typebulb 0.24.3 → 0.26.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -27
- package/dist/agents/claude/client.js +343 -273
- package/dist/agents/claude/styles.css +79 -11
- package/dist/agents/pi/client.js +319 -249
- package/dist/agents/pi/matchu-patchu.ts +1 -1
- package/dist/agents/pi/styles.css +79 -11
- package/dist/ai/index.d.ts +1 -0
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +2 -0
- package/dist/ai/index.js.map +1 -1
- package/dist/ai/inference.d.ts +40 -0
- package/dist/ai/inference.d.ts.map +1 -0
- package/dist/ai/inference.js +301 -0
- package/dist/ai/inference.js.map +1 -0
- package/dist/ai/providers/gemini.d.ts +11 -1
- package/dist/ai/providers/gemini.d.ts.map +1 -1
- package/dist/ai/providers/gemini.js +24 -16
- package/dist/ai/providers/gemini.js.map +1 -1
- package/dist/format/config.d.ts +5 -0
- package/dist/format/config.d.ts.map +1 -1
- package/dist/format/config.js +20 -0
- package/dist/format/config.js.map +1 -1
- package/dist/format/parse.d.ts +3 -0
- package/dist/format/parse.d.ts.map +1 -1
- package/dist/format/parse.js +7 -3
- package/dist/format/parse.js.map +1 -1
- package/dist/format/serialize.d.ts +8 -0
- package/dist/format/serialize.d.ts.map +1 -1
- package/dist/format/serialize.js +42 -7
- package/dist/format/serialize.js.map +1 -1
- package/dist/index.js +626 -228
- package/dist/render.js +151 -86
- package/dist/servers.js +101 -101
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,160 +1,169 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);
|
|
3
|
-
var
|
|
4
|
-
`),t=0;if(e[t]?.trim()!=="---")return null;t++;let n=[];for(;t<e.length&&e[t]?.trim()!=="---";)n.push(e[t]),t++;if(e[t]?.trim()!=="---")return null;t++;let s=
|
|
5
|
-
`)),a=t}else t++}return{frontmatter:s,files:i,warnings:o,bodyEndLine:a}}catch{return null}}function
|
|
6
|
-
|
|
7
|
-
${
|
|
8
|
-
${
|
|
9
|
-
${
|
|
10
|
-
`)}
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
`)}
|
|
14
|
-
|
|
3
|
+
var Kg=Object.create;var co=Object.defineProperty;var Hg=Object.getOwnPropertyDescriptor;var Wg=Object.getOwnPropertyNames;var Vg=Object.getPrototypeOf,Yg=Object.prototype.hasOwnProperty;var jn=(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 O=(r,e)=>()=>(r&&(e=r(r=0)),e);var A=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Il=(r,e)=>{for(var t in e)co(r,t,{get:e[t],enumerable:!0})},Gg=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Wg(e))!Yg.call(r,s)&&s!==t&&co(r,s,{get:()=>e[s],enumerable:!(n=Hg(e,s))||n.enumerable});return r};var zg=(r,e,t)=>(t=r!=null?Kg(Vg(r)):{},Gg(e||!r||!r.__esModule?co(t,"default",{value:r,enumerable:!0}):t,r));function Kl(r){return Ut.find(e=>pt[e].path===r)}function Wl(r){return!!r?.startsWith("typebulb")}var pt,Ut,Hl,Fn=O(()=>{pt={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"}},Ut=["code","css","html","data","infer","insight","config","notes"];Hl="typebulb/v1"});function po(r){return/[:\n"']/.test(r)||r.startsWith(" ")||r.endsWith(" ")?`"${r.replace(/"/g,'\\"')}"`:r}function mo(r){return r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1).replace(/\\"/g,'"'):r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}var qn=O(()=>{});function Re(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=cy(n);if(!s)return null;let i=new Map,o=[],a=t;for(;t<e.length;){let l=e[t]?.trim()?.match(Vl);if(l){let d=l[1].trim();for(t++;t<e.length&&e[t]?.trim()==="";)t++;let u=e[t]?.match(Un);if(!u){o.push(`**${d}** has no code fence \u2014 block skipped`);continue}let f=u[1];t++;let p=[],b=ho(f);for(;t<e.length&&!e[t]?.match(b);)p.push(e[t]),t++;let h=t<e.length;t++,o.push(...oy(d,p,h)),i.set(d,p.join(`
|
|
5
|
+
`)),a=t}else t++}return{frontmatter:s,files:i,warnings:o,bodyEndLine:a}}catch{return null}}function oy(r,e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s]?.trim().match(Vl);i&&iy.has(i[1].trim())&&ay(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 ay(r,e){let t=e+1;for(;t<r.length&&r[t]?.trim()==="";)t++;return!!r[t]?.match(Un)}function cy(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=mo(i);break}}return!Wl(e.format)||!e.name?null:e}function Yl(r){return Re(r)?.warnings??[]}function Gl(r){let e=Object.fromEntries(Ut.map(t=>[t,r.files.get(pt[t].path)||""]));return{name:r.frontmatter.name,...e}}var Vl,Un,iy,ho,go=O(()=>{Fn();qn();Vl=/^\*\*(.+)\*\*$/,Un=/^(`{3,})(\w*)\s*$/,iy=new Set(Ut.map(r=>pt[r].path)),ho=r=>new RegExp(`^${r}\\s*$`)});function zl(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 Ql(r,e){let{path:t}=pt[r],n=t.split(".").pop(),s=zl(e);return`**${t}**
|
|
6
|
+
|
|
7
|
+
${s}${n}
|
|
8
|
+
${e}
|
|
9
|
+
${s}`}function Xl(r){let e=Ut.filter(t=>r[t]).map(t=>Ql(t,r[t]));return["---",`format: ${Hl}`,`name: ${po(r.name)}`,"---","",...e].join(`
|
|
10
|
+
`)}function yo(r,e,t){let{path:n}=pt[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(Un);if(!a)continue;let c=ho(a[1]),l=o+1;for(;l<s.length&&!s[l]?.match(c);)l++;if(l>=s.length)return r;let d=zl(t),u=d.length>a[1].length?d:a[1];return[...s.slice(0,o),u+a[2],...t.split(`
|
|
12
|
+
`),u,...s.slice(l+1)].join(`
|
|
13
|
+
`)}return`${r.replace(/\s*$/,"")}
|
|
14
|
+
|
|
15
|
+
${Ql(e,t)}
|
|
16
|
+
`}var Zl=O(()=>{Fn();go();qn()});function Jn(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}var eu=O(()=>{});var tu=O(()=>{});function bo(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index:-1}var ru=O(()=>{});function Or(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index+s[0].length-1:-1}var nu=O(()=>{});function Kn(r,e){let t=new RegExp(e,"g"),n=r.match(t);return n?n.length:0}var su=O(()=>{});function Cr(r,e,t){let n=t&&t.debug||!1,s=!(t&&typeof t.nested===!1),i=t&&t.startIndex||0;n&&console.log("[xml-utils] starting findTagByName with",e," and ",t);let o=bo(r,`<${e}[
|
|
17
|
+
>/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=Or(a,"^[^<]*[ /]>",0),l=c!==-1&&a[c-1]==="/";if(n&&console.log("[xml-utils] selfClosing:",l),l===!1)if(s){let p=0,b=1,h=0;for(;(c=Or(a,"[ /]"+e+">",p))!==-1;){let w=a.substring(p,c+1);if(b+=Kn(w,"<"+e+`[
|
|
18
|
+
>]`),h+=Kn(w,"</"+e+">"),h>=b)break;p=c}}else c=Or(a,"[ /]"+e+">",0);let d=o+e.length+c+1;if(n&&console.log("[xml-utils] end:",d),d===-1)return;let u=r.slice(o,d),f;return l?f=null:f=u.slice(u.indexOf(">")+1,u.lastIndexOf("<")),{inner:f,outer:u,start:o,end:d}}var wo=O(()=>{ru();nu();su()});var vo=O(()=>{wo()});var So=O(()=>{vo()});var iu=O(()=>{So()});var ou=O(()=>{});var au=O(()=>{tu();wo();vo();iu();So();ou()});var D=A(Q=>{"use strict";var ko=Symbol.for("yaml.alias"),cu=Symbol.for("yaml.document"),Hn=Symbol.for("yaml.map"),lu=Symbol.for("yaml.pair"),xo=Symbol.for("yaml.scalar"),Wn=Symbol.for("yaml.seq"),Ne=Symbol.for("yaml.node.type"),fy=r=>!!r&&typeof r=="object"&&r[Ne]===ko,dy=r=>!!r&&typeof r=="object"&&r[Ne]===cu,py=r=>!!r&&typeof r=="object"&&r[Ne]===Hn,my=r=>!!r&&typeof r=="object"&&r[Ne]===lu,uu=r=>!!r&&typeof r=="object"&&r[Ne]===xo,hy=r=>!!r&&typeof r=="object"&&r[Ne]===Wn;function fu(r){if(r&&typeof r=="object")switch(r[Ne]){case Hn:case Wn:return!0}return!1}function gy(r){if(r&&typeof r=="object")switch(r[Ne]){case ko:case Hn:case xo:case Wn:return!0}return!1}var yy=r=>(uu(r)||fu(r))&&!!r.anchor;Q.ALIAS=ko;Q.DOC=cu;Q.MAP=Hn;Q.NODE_TYPE=Ne;Q.PAIR=lu;Q.SCALAR=xo;Q.SEQ=Wn;Q.hasAnchor=yy;Q.isAlias=fy;Q.isCollection=fu;Q.isDocument=dy;Q.isMap=py;Q.isNode=gy;Q.isPair=my;Q.isScalar=uu;Q.isSeq=hy});var _r=A(Eo=>{"use strict";var G=D(),se=Symbol("break visit"),du=Symbol("skip children"),xe=Symbol("remove node");function Vn(r,e){let t=pu(e);G.isDocument(r)?Jt(null,r.contents,t,Object.freeze([r]))===xe&&(r.contents=null):Jt(null,r,t,Object.freeze([]))}Vn.BREAK=se;Vn.SKIP=du;Vn.REMOVE=xe;function Jt(r,e,t,n){let s=mu(r,e,t,n);if(G.isNode(s)||G.isPair(s))return hu(r,n,s),Jt(r,s,t,n);if(typeof s!="symbol"){if(G.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=Jt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===se)return se;o===xe&&(e.items.splice(i,1),i-=1)}}}else if(G.isPair(e)){n=Object.freeze(n.concat(e));let i=Jt("key",e.key,t,n);if(i===se)return se;i===xe&&(e.key=null);let o=Jt("value",e.value,t,n);if(o===se)return se;o===xe&&(e.value=null)}}return s}async function Yn(r,e){let t=pu(e);G.isDocument(r)?await Kt(null,r.contents,t,Object.freeze([r]))===xe&&(r.contents=null):await Kt(null,r,t,Object.freeze([]))}Yn.BREAK=se;Yn.SKIP=du;Yn.REMOVE=xe;async function Kt(r,e,t,n){let s=await mu(r,e,t,n);if(G.isNode(s)||G.isPair(s))return hu(r,n,s),Kt(r,s,t,n);if(typeof s!="symbol"){if(G.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=await Kt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===se)return se;o===xe&&(e.items.splice(i,1),i-=1)}}}else if(G.isPair(e)){n=Object.freeze(n.concat(e));let i=await Kt("key",e.key,t,n);if(i===se)return se;i===xe&&(e.key=null);let o=await Kt("value",e.value,t,n);if(o===se)return se;o===xe&&(e.value=null)}}return s}function pu(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 mu(r,e,t,n){if(typeof t=="function")return t(r,e,n);if(G.isMap(e))return t.Map?.(r,e,n);if(G.isSeq(e))return t.Seq?.(r,e,n);if(G.isPair(e))return t.Pair?.(r,e,n);if(G.isScalar(e))return t.Scalar?.(r,e,n);if(G.isAlias(e))return t.Alias?.(r,e,n)}function hu(r,e,t){let n=e[e.length-1];if(G.isCollection(n))n.items[r]=t;else if(G.isPair(n))r==="key"?n.key=t:n.value=t;else if(G.isDocument(n))n.contents=t;else{let s=G.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}Eo.visit=Vn;Eo.visitAsync=Yn});var Ao=A(yu=>{"use strict";var gu=D(),by=_r(),wy={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},vy=r=>r.replace(/[!,[\]{}]/g,e=>wy[e]),Rr=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+vy(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&&gu.isNode(e.contents)){let i={};by.visit(e.contents,(o,a)=>{gu.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
|
+
`)}};Rr.defaultYaml={explicit:!1,version:"1.2"};Rr.defaultTags={"!!":"tag:yaml.org,2002:"};yu.Directives=Rr});var Gn=A(Nr=>{"use strict";var bu=D(),Sy=_r();function ky(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 wu(r){let e=new Set;return Sy.visit(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function vu(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function xy(r,e){let t=[],n=new Map,s=null;return{onAnchor:i=>{t.push(i),s??(s=wu(r));let o=vu(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(bu.isScalar(o.node)||bu.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}}Nr.anchorIsValid=ky;Nr.anchorNames=wu;Nr.createNodeAnchors=xy;Nr.findNewAnchor=vu});var To=A(Su=>{"use strict";function Ir(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let s=0,i=n.length;s<i;++s){let o=n[s],a=Ir(r,n,String(s),o);a===void 0?delete n[s]:a!==o&&(n[s]=a)}else if(n instanceof Map)for(let s of Array.from(n.keys())){let i=n.get(s),o=Ir(r,n,s,i);o===void 0?n.delete(s):o!==i&&n.set(s,o)}else if(n instanceof Set)for(let s of Array.from(n)){let i=Ir(r,n,s,s);i===void 0?n.delete(s):i!==s&&(n.delete(s),n.add(i))}else for(let[s,i]of Object.entries(n)){let o=Ir(r,n,s,i);o===void 0?delete n[s]:o!==i&&(n[s]=o)}return r.call(e,t,n)}Su.applyReviver=Ir});var Ke=A(xu=>{"use strict";var Ey=D();function ku(r,e,t){if(Array.isArray(r))return r.map((n,s)=>ku(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!Ey.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}xu.toJS=ku});var zn=A(Au=>{"use strict";var Ay=To(),Eu=D(),Ty=Ke(),Po=class{constructor(e){Object.defineProperty(this,Eu.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:s,reviver:i}={}){if(!Eu.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=Ty.toJS(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?Ay.applyReviver(i,{"":a},"",a):a}};Au.NodeBase=Po});var Lr=A(Tu=>{"use strict";var Py=Gn(),Oy=_r(),Ht=D(),Cy=zn(),_y=Ke(),Oo=class extends Cy.NodeBase{constructor(e){super(Ht.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=[],Oy.visit(e,{Node:(i,o)=>{(Ht.isAlias(o)||Ht.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||(_y.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=Qn(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(Py.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 Qn(r,e,t){if(Ht.isAlias(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(Ht.isCollection(e)){let n=0;for(let s of e.items){let i=Qn(r,s,t);i>n&&(n=i)}return n}else if(Ht.isPair(e)){let n=Qn(r,e.key,t),s=Qn(r,e.value,t);return Math.max(n,s)}return 1}Tu.Alias=Oo});var H=A(Co=>{"use strict";var Ry=D(),Ny=zn(),Iy=Ke(),Ly=r=>!r||typeof r!="function"&&typeof r!="object",He=class extends Ny.NodeBase{constructor(e){super(Ry.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:Iy.toJS(this.value,e,t)}toString(){return String(this.value)}};He.BLOCK_FOLDED="BLOCK_FOLDED";He.BLOCK_LITERAL="BLOCK_LITERAL";He.PLAIN="PLAIN";He.QUOTE_DOUBLE="QUOTE_DOUBLE";He.QUOTE_SINGLE="QUOTE_SINGLE";Co.Scalar=He;Co.isScalarValue=Ly});var $r=A(Ou=>{"use strict";var $y=Lr(),mt=D(),Pu=H(),My="tag:yaml.org,2002:";function Dy(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 By(r,e,t){if(mt.isDocument(r)&&(r=r.contents),mt.isNode(r))return r;if(mt.isPair(r)){let u=t.schema[mt.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 $y.Alias(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=My+e.slice(2));let l=Dy(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let u=new Pu.Scalar(r);return c&&(c.node=u),u}l=r instanceof Map?o[mt.MAP]:Symbol.iterator in Object(r)?o[mt.SEQ]:o[mt.MAP]}i&&(i(l),delete t.onTagObj);let d=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new Pu.Scalar(r);return e?d.tag=e:l.default||(d.tag=l.tag),c&&(c.node=d),d}Ou.createNode=By});var Zn=A(Xn=>{"use strict";var jy=$r(),Ee=D(),Fy=zn();function _o(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 jy.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 Cu=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,Ro=class extends Fy.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=>Ee.isNode(n)||Ee.isPair(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Cu(e))this.add(t);else{let[n,...s]=e,i=this.get(n,!0);if(Ee.isCollection(i))i.addIn(s,t);else if(i===void 0&&this.schema)this.set(n,_o(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(Ee.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&&Ee.isScalar(i)?i.value:i:Ee.isCollection(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!Ee.isPair(t))return!1;let n=t.value;return n==null||e&&Ee.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 Ee.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(Ee.isCollection(i))i.setIn(s,t);else if(i===void 0&&this.schema)this.set(n,_o(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}};Xn.Collection=Ro;Xn.collectionFromPath=_o;Xn.isEmptyPath=Cu});var Mr=A(es=>{"use strict";var qy=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function No(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var Uy=(r,e,t)=>r.endsWith(`
|
|
20
|
+
`)?No(t,e):t.includes(`
|
|
15
21
|
`)?`
|
|
16
|
-
`+
|
|
17
|
-
`)t===
|
|
18
|
-
`&&p!==" "){let
|
|
19
|
-
`&&
|
|
20
|
-
${e}${r.slice(0,
|
|
21
|
-
${e}${r.slice(
|
|
22
|
-
`);n=e,s=e+1,i=r[s]}return n}
|
|
23
|
-
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function
|
|
22
|
+
`+No(t,e):(r.endsWith(" ")?"":" ")+t;es.indentComment=No;es.lineComment=Uy;es.stringifyComment=qy});var Ru=A(Dr=>{"use strict";var Jy="flow",Io="block",ts="quoted";function Ky(r,e,t="flow",{indentAtStart:n,lineWidth:s=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!s||s<0)return r;s<i&&(i=0);let c=Math.max(1+i,1+s-e.length);if(r.length<=c)return r;let l=[],d={},u=s-e.length;typeof n=="number"&&(n>s-Math.max(2,i)?l.push(0):u=s-n);let f,p,b=!1,h=-1,w=-1,x=-1;t===Io&&(h=_u(r,h,e.length),h!==-1&&(u=h+c));for(let T;T=r[h+=1];){if(t===ts&&T==="\\"){switch(w=h,r[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}x=h}if(T===`
|
|
23
|
+
`)t===Io&&(h=_u(r,h,e.length)),u=h+e.length+c,f=void 0;else{if(T===" "&&p&&p!==" "&&p!==`
|
|
24
|
+
`&&p!==" "){let P=r[h+1];P&&P!==" "&&P!==`
|
|
25
|
+
`&&P!==" "&&(f=h)}if(h>=u)if(f)l.push(f),u=f+c,f=void 0;else if(t===ts){for(;p===" "||p===" ";)p=T,T=r[h+=1],b=!0;let P=h>x+1?h-2:w-1;if(d[P])return r;l.push(P),d[P]=!0,u=P+c,f=void 0}else b=!0}p=T}if(b&&a&&a(),l.length===0)return r;o&&o();let E=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?E=`
|
|
26
|
+
${e}${r.slice(0,C)}`:(t===ts&&d[P]&&(E+=`${r[P]}\\`),E+=`
|
|
27
|
+
${e}${r.slice(P+1,C)}`)}return E}function _u(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}Dr.FOLD_BLOCK=Io;Dr.FOLD_FLOW=Jy;Dr.FOLD_QUOTED=ts;Dr.foldFlowLines=Ky});var jr=A(Nu=>{"use strict";var me=H(),We=Ru(),ns=(r,e)=>({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),ss=r=>/^(%|---|\.\.\.)/m.test(r);function Hy(r,e,t){if(!e||e<0)return!1;let n=e-t,s=r.length;if(s<=n)return!1;for(let i=0,o=0;i<s;++i)if(r[i]===`
|
|
29
|
+
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function Br(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(ss(r)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let d=t.substr(c+2,4);switch(d){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length<s)c+=1;else{for(o+=t.slice(a,c)+`
|
|
24
30
|
|
|
25
31
|
`;t[c+2]==="\\"&&t[c+3]==="n"&&t[c+4]!=='"';)o+=`
|
|
26
|
-
`,c+=2;o+=i,t[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+t.slice(a):t,n?o:
|
|
27
|
-
`)||/[ \t]\n|\n[ \t]/.test(r))return
|
|
28
|
-
${t}`)+"'";return e.implicitKey?n:
|
|
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:We.foldFlowLines(o,i,We.FOLD_QUOTED,ns(e,!1))}function Lo(r,e){if(e.options.singleQuote===!1||e.implicitKey&&r.includes(`
|
|
33
|
+
`)||/[ \t]\n|\n[ \t]/.test(r))return Br(r,e);let t=e.indent||(ss(r)?" ":""),n="'"+r.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
34
|
+
${t}`)+"'";return e.implicitKey?n:We.foldFlowLines(n,t,We.FOLD_FLOW,ns(e,!1))}function Wt(r,e){let{singleQuote:t}=e.options,n;if(t===!1)n=Br;else{let s=r.includes('"'),i=r.includes("'");s&&!i?n=Lo:i&&!s?n=Br:n=t?Lo:Br}return n(r,e)}var $o;try{$o=new RegExp(`(^|(?<!
|
|
29
35
|
))
|
|
30
36
|
+(?!
|
|
31
|
-
|$)`,"g")}catch{
|
|
37
|
+
|$)`,"g")}catch{$o=/\n+(?!\n|$)/g}function rs({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 Wt(t,n);let l=n.indent||(n.forceBlockIndent||ss(t)?" ":""),d=o==="literal"?!0:o==="folded"||e===me.Scalar.BLOCK_FOLDED?!1:e===me.Scalar.BLOCK_LITERAL?!0:!Hy(t,c,l.length);if(!t)return d?`|
|
|
32
38
|
`:`>
|
|
33
|
-
`;let u,f;for(f=t.length;f>0;--f){let
|
|
34
|
-
`&&
|
|
35
|
-
`);
|
|
36
|
-
`&&(p=p.slice(0,-1)),p=p.replace(
|
|
37
|
-
`)x=
|
|
38
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),
|
|
39
|
-
${l}${
|
|
40
|
-
${l}${
|
|
41
|
-
`)||d&&/[[\]{},]/.test(i))return
|
|
42
|
-
`)?
|
|
43
|
-
`))return
|
|
44
|
-
${c}`);if(o){let f=
|
|
45
|
-
${e.indent}${a}`:a}
|
|
46
|
-
${a}:`):(
|
|
47
|
-
`:"",
|
|
48
|
-
${
|
|
49
|
-
`&&
|
|
50
|
-
|
|
51
|
-
`):
|
|
52
|
-
${t.indent}`}else if(!p&&
|
|
53
|
-
`),
|
|
54
|
-
${t.indent}`)}}else(
|
|
55
|
-
`)&&(
|
|
56
|
-
${c}${
|
|
39
|
+
`;let u,f;for(f=t.length;f>0;--f){let C=t[f-1];if(C!==`
|
|
40
|
+
`&&C!==" "&&C!==" ")break}let p=t.substring(f),b=p.indexOf(`
|
|
41
|
+
`);b===-1?u="-":t===p||b!==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($o,`$&${l}`));let h=!1,w,x=-1;for(w=0;w<t.length;++w){let C=t[w];if(C===" ")h=!0;else if(C===`
|
|
43
|
+
`)x=w;else break}let E=t.substring(0,x<w?x+1:w);E&&(t=t.substring(E.length),E=E.replace(/\n+/g,`$&${l}`));let P=(h?l?"2":"1":"")+u;if(r&&(P+=" "+a(r.replace(/ ?[\r\n]+/g," ")),s&&s()),!d){let C=t.replace(/\n+/g,`
|
|
44
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),m=!1,y=ns(n,!0);o!=="folded"&&e!==me.Scalar.BLOCK_FOLDED&&(y.onOverflow=()=>{m=!0});let v=We.foldFlowLines(`${E}${C}${p}`,l,We.FOLD_BLOCK,y);if(!m)return`>${P}
|
|
45
|
+
${l}${v}`}return t=t.replace(/\n+/g,`$&${l}`),`|${P}
|
|
46
|
+
${l}${E}${t}${p}`}function Wy(r,e,t,n){let{type:s,value:i}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:d}=e;if(a&&i.includes(`
|
|
47
|
+
`)||d&&/[[\]{},]/.test(i))return Wt(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||d||!i.includes(`
|
|
48
|
+
`)?Wt(i,e):rs(r,e,t,n);if(!a&&!d&&s!==me.Scalar.PLAIN&&i.includes(`
|
|
49
|
+
`))return rs(r,e,t,n);if(ss(i)){if(c==="")return e.forceBlockIndent=!0,rs(r,e,t,n);if(a&&c===l)return Wt(i,e)}let u=i.replace(/\n+/g,`$&
|
|
50
|
+
${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:p,tags:b}=e.doc.schema;if(b.some(f)||p?.some(f))return Wt(i,e)}return a?u:We.foldFlowLines(u,c,We.FOLD_FLOW,ns(e,!1))}function Vy(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!==me.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=me.Scalar.QUOTE_DOUBLE);let c=d=>{switch(d){case me.Scalar.BLOCK_FOLDED:case me.Scalar.BLOCK_LITERAL:return s||i?Wt(o.value,e):rs(o,e,t,n);case me.Scalar.QUOTE_DOUBLE:return Br(o.value,e);case me.Scalar.QUOTE_SINGLE:return Lo(o.value,e);case me.Scalar.PLAIN:return Wy(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:d,defaultStringType:u}=e.options,f=s&&d||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Nu.stringifyString=Vy});var Fr=A(Mo=>{"use strict";var Yy=Gn(),Ve=D(),Gy=Mr(),zy=jr();function Qy(r,e){let t=Object.assign({blockQuote:!0,commentString:Gy.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 Xy(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(Ve.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 Zy(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let s=[],i=(Ve.isScalar(r)||Ve.isCollection(r))&&r.anchor;i&&Yy.anchorIsValid(i)&&(t.add(i),s.push(`&${i}`));let o=r.tag??(e.default?null:e.tag);return o&&s.push(n.directives.tagString(o)),s.join(" ")}function eb(r,e,t,n){if(Ve.isPair(r))return r.toString(e,t,n);if(Ve.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=Ve.isNode(r)?r:e.doc.createNode(r,{onTagObj:c=>s=c});s??(s=Xy(e.doc.schema.tags,i));let o=Zy(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):Ve.isScalar(i)?zy.stringifyString(i,e,t,n):i.toString(e,t,n);return o?Ve.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
51
|
+
${e.indent}${a}`:a}Mo.createStringifyContext=Qy;Mo.stringify=eb});var Mu=A($u=>{"use strict";var Ie=D(),Iu=H(),Lu=Fr(),qr=Mr();function tb({key:r,value:e},t,n,s){let{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=t,f=Ie.isNode(r)&&r.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Ie.isCollection(r)||!Ie.isNode(r)&&typeof r=="object"){let y="With simple keys, collection cannot be used as a key value";throw new Error(y)}}let p=!u&&(!r||f&&e==null&&!t.inFlow||Ie.isCollection(r)||(Ie.isScalar(r)?r.type===Iu.Scalar.BLOCK_FOLDED||r.type===Iu.Scalar.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(u||!i),indent:a+c});let b=!1,h=!1,w=Lu.stringify(r,t,()=>b=!0,()=>h=!0);if(!p&&!t.inFlow&&w.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(i||e==null)return b&&n&&n(),w===""?"?":p?`? ${w}`:w}else if(i&&!u||e==null&&p)return w=`? ${w}`,f&&!b?w+=qr.lineComment(w,t.indent,l(f)):h&&s&&s(),w;b&&(f=null),p?(f&&(w+=qr.lineComment(w,t.indent,l(f))),w=`? ${w}
|
|
52
|
+
${a}:`):(w=`${w}:`,f&&(w+=qr.lineComment(w,t.indent,l(f))));let x,E,T;Ie.isNode(e)?(x=!!e.spaceBefore,E=e.commentBefore,T=e.comment):(x=!1,E=null,T=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&Ie.isScalar(e)&&(t.indentAtStart=w.length+1),h=!1,!d&&c.length>=2&&!t.inFlow&&!p&&Ie.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let P=!1,C=Lu.stringify(e,t,()=>P=!0,()=>h=!0),m=" ";if(f||x||E){if(m=x?`
|
|
53
|
+
`:"",E){let y=l(E);m+=`
|
|
54
|
+
${qr.indentComment(y,t.indent)}`}C===""&&!t.inFlow?m===`
|
|
55
|
+
`&&T&&(m=`
|
|
56
|
+
|
|
57
|
+
`):m+=`
|
|
58
|
+
${t.indent}`}else if(!p&&Ie.isCollection(e)){let y=C[0],v=C.indexOf(`
|
|
59
|
+
`),R=v!==-1,I=t.inFlow??e.flow??e.items.length===0;if(R||!I){let J=!1;if(R&&(y==="&"||y==="!")){let B=C.indexOf(" ");y==="&"&&B!==-1&&B<v&&C[B+1]==="!"&&(B=C.indexOf(" ",B+1)),(B===-1||v<B)&&(J=!0)}J||(m=`
|
|
60
|
+
${t.indent}`)}}else(C===""||C[0]===`
|
|
61
|
+
`)&&(m="");return w+=m+C,t.inFlow?P&&n&&n():T&&!P?w+=qr.lineComment(w,t.indent,l(T)):h&&s&&s(),w}$u.stringifyPair=tb});var Bo=A(Do=>{"use strict";var Du=jn("process");function rb(r,...e){r==="debug"&&console.log(...e)}function nb(r,e){(r==="debug"||r==="warn")&&(typeof Du.emitWarning=="function"?Du.emitWarning(e):console.warn(e))}Do.debug=rb;Do.warn=nb});var cs=A(as=>{"use strict";var Ur=D(),Bu=H(),is="<<",os={identify:r=>r===is||typeof r=="symbol"&&r.description===is,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Bu.Scalar(Symbol(is)),{addToJSMap:ju}),stringify:()=>is},sb=(r,e)=>(os.identify(e)||Ur.isScalar(e)&&(!e.type||e.type===Bu.Scalar.PLAIN)&&os.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===os.tag&&t.default);function ju(r,e,t){if(t=r&&Ur.isAlias(t)?t.resolve(r.doc):t,Ur.isSeq(t))for(let n of t.items)jo(r,e,n);else if(Array.isArray(t))for(let n of t)jo(r,e,n);else jo(r,e,t)}function jo(r,e,t){let n=r&&Ur.isAlias(t)?t.resolve(r.doc):t;if(!Ur.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}as.addMergeToJSMap=ju;as.isMergeKey=sb;as.merge=os});var qo=A(Uu=>{"use strict";var ib=Bo(),Fu=cs(),ob=Fr(),qu=D(),Fo=Ke();function ab(r,e,{key:t,value:n}){if(qu.isNode(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(Fu.isMergeKey(r,t))Fu.addMergeToJSMap(r,e,n);else{let s=Fo.toJS(t,"",r);if(e instanceof Map)e.set(s,Fo.toJS(n,s,r));else if(e instanceof Set)e.add(s);else{let i=cb(t,s,r),o=Fo.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 cb(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(qu.isNode(r)&&t?.doc){let n=ob.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)+'..."'),ib.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)}Uu.addPairToJSMap=ab});var Ye=A(Uo=>{"use strict";var Ju=$r(),lb=Mu(),ub=qo(),ls=D();function fb(r,e,t){let n=Ju.createNode(r,void 0,t),s=Ju.createNode(e,void 0,t);return new us(n,s)}var us=class r{constructor(e,t=null){Object.defineProperty(this,ls.NODE_TYPE,{value:ls.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return ls.isNode(t)&&(t=t.clone(e)),ls.isNode(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return ub.addPairToJSMap(t,n,this)}toString(e,t,n){return e?.doc?lb.stringifyPair(this,e,t,n):JSON.stringify(this)}};Uo.Pair=us;Uo.createPair=fb});var Jo=A(Hu=>{"use strict";var ht=D(),Ku=Fr(),fs=Mr();function db(r,e,t){return(e.inFlow??r.flow?mb:pb)(r,e,t)}function pb({comment:r,items:e},t,{blockItemPrefix:n,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,d=Object.assign({},t,{indent:i,type:null}),u=!1,f=[];for(let b=0;b<e.length;++b){let h=e[b],w=null;if(ht.isNode(h))!u&&h.spaceBefore&&f.push(""),ds(t,f,h.commentBefore,u),h.comment&&(w=h.comment);else if(ht.isPair(h)){let E=ht.isNode(h.key)?h.key:null;E&&(!u&&E.spaceBefore&&f.push(""),ds(t,f,E.commentBefore,u))}u=!1;let x=Ku.stringify(h,d,()=>w=null,()=>u=!0);w&&(x+=fs.lineComment(x,i,l(w))),u&&w&&(u=!1),f.push(n+x)}let p;if(f.length===0)p=s.start+s.end;else{p=f[0];for(let b=1;b<f.length;++b){let h=f[b];p+=h?`
|
|
62
|
+
${c}${h}`:`
|
|
57
63
|
`}}return r?(p+=`
|
|
58
|
-
`+
|
|
59
|
-
`))&&(l=!0),u.push(x),d=u.length}let{start:f,end:p}=t;if(u.length===0)return f+p;if(!l){let
|
|
60
|
-
${i}${s}${
|
|
61
|
-
`;return`${
|
|
62
|
-
${s}${p}`}else return`${f}${o}${u.join(" ")}${o}${p}`}function
|
|
63
|
-
`:" ")}return
|
|
64
|
+
`+fs.indentComment(l(r),c),a&&a()):u&&o&&o(),p}function mb({items:r},e,{flowChars:t,itemIndent:n}){let{indent:s,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;n+=i;let c=Object.assign({},e,{indent:n,inFlow:!0,type:null}),l=!1,d=0,u=[];for(let b=0;b<r.length;++b){let h=r[b],w=null;if(ht.isNode(h))h.spaceBefore&&u.push(""),ds(e,u,h.commentBefore,!1),h.comment&&(w=h.comment);else if(ht.isPair(h)){let E=ht.isNode(h.key)?h.key:null;E&&(E.spaceBefore&&u.push(""),ds(e,u,E.commentBefore,!1),E.comment&&(l=!0));let T=ht.isNode(h.value)?h.value:null;T?(T.comment&&(w=T.comment),T.commentBefore&&(l=!0)):h.value==null&&E?.comment&&(w=E.comment)}w&&(l=!0);let x=Ku.stringify(h,c,()=>w=null);b<r.length-1&&(x+=","),w&&(x+=fs.lineComment(x,n,a(w))),!l&&(u.length>d||x.includes(`
|
|
65
|
+
`))&&(l=!0),u.push(x),d=u.length}let{start:f,end:p}=t;if(u.length===0)return f+p;if(!l){let b=u.reduce((h,w)=>h+w.length+2,2);l=e.options.lineWidth>0&&b>e.options.lineWidth}if(l){let b=f;for(let h of u)b+=h?`
|
|
66
|
+
${i}${s}${h}`:`
|
|
67
|
+
`;return`${b}
|
|
68
|
+
${s}${p}`}else return`${f}${o}${u.join(" ")}${o}${p}`}function ds({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=fs.indentComment(e(n),r);t.push(i.trimStart())}}Hu.stringifyCollection=db});var ze=A(Ho=>{"use strict";var hb=Jo(),gb=qo(),yb=Zn(),Ge=D(),ps=Ye(),bb=H();function Jr(r,e){let t=Ge.isScalar(e)?e.value:e;for(let n of r)if(Ge.isPair(n)&&(n.key===e||n.key===t||Ge.isScalar(n.key)&&n.key.value===t))return n}var Ko=class extends yb.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ge.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(ps.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;Ge.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new ps.Pair(e,e?.value):n=new ps.Pair(e.key,e.value);let s=Jr(this.items,n.key),i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);Ge.isScalar(s.value)&&bb.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=Jr(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let s=Jr(this.items,e)?.value;return(!t&&Ge.isScalar(s)?s.value:s)??void 0}has(e){return!!Jr(this.items,e)}set(e,t){this.add(new ps.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)gb.addPairToJSMap(t,s,i);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(let s of this.items)if(!Ge.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})),hb.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};Ho.YAMLMap=Ko;Ho.findPair=Jr});var Vt=A(Vu=>{"use strict";var wb=D(),Wu=ze(),vb={collection:"map",default:!0,nodeClass:Wu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(r,e){return wb.isMap(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Wu.YAMLMap.from(r,e,t)};Vu.map=vb});var Qe=A(Yu=>{"use strict";var Sb=$r(),kb=Jo(),xb=Zn(),hs=D(),Eb=H(),Ab=Ke(),Wo=class extends xb.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(hs.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=ms(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=ms(e);if(typeof n!="number")return;let s=this.items[n];return!t&&hs.isScalar(s)?s.value:s}has(e){let t=ms(e);return typeof t=="number"&&t<this.items.length}set(e,t){let n=ms(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let s=this.items[n];hs.isScalar(s)&&Eb.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(Ab.toJS(i,String(s++),t));return n}toString(e,t,n){return e?kb.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(Sb.createNode(a,void 0,n))}}return i}};function ms(r){let e=hs.isScalar(r)?r.value:r;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Yu.YAMLSeq=Wo});var Yt=A(zu=>{"use strict";var Tb=D(),Gu=Qe(),Pb={collection:"seq",default:!0,nodeClass:Gu.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Tb.isSeq(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Gu.YAMLSeq.from(r,e,t)};zu.seq=Pb});var Kr=A(Qu=>{"use strict";var Ob=jr(),Cb={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),Ob.stringifyString(r,e,t,n)}};Qu.string=Cb});var gs=A(ef=>{"use strict";var Xu=H(),Zu={identify:r=>r==null,createNode:()=>new Xu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Xu.Scalar(null),stringify:({source:r},e)=>typeof r=="string"&&Zu.test.test(r)?r:e.options.nullStr};ef.nullTag=Zu});var Vo=A(rf=>{"use strict";var _b=H(),tf={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new _b.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&tf.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};rf.boolTag=tf});var Gt=A(nf=>{"use strict";function Rb({format:r,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);let s=typeof n=="number"?n:Number(n);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let i=Object.is(n,-0)?"-0":JSON.stringify(n);if(!r&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(i)){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=e-(i.length-o-1);for(;a-- >0;)i+="0"}return i}nf.stringifyNumber=Rb});var Go=A(ys=>{"use strict";var Nb=H(),Yo=Gt(),Ib={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:Yo.stringifyNumber},Lb={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():Yo.stringifyNumber(r)}},$b={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(r){let e=new Nb.Scalar(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:Yo.stringifyNumber};ys.float=$b;ys.floatExp=Lb;ys.floatNaN=Ib});var Qo=A(ws=>{"use strict";var sf=Gt(),bs=r=>typeof r=="bigint"||Number.isInteger(r),zo=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function of(r,e,t){let{value:n}=r;return bs(n)&&n>=0?t+n.toString(e):sf.stringifyNumber(r)}var Mb={identify:r=>bs(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>zo(r,2,8,t),stringify:r=>of(r,8,"0o")},Db={identify:bs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>zo(r,0,10,t),stringify:sf.stringifyNumber},Bb={identify:r=>bs(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>zo(r,2,16,t),stringify:r=>of(r,16,"0x")};ws.int=Db;ws.intHex=Bb;ws.intOct=Mb});var cf=A(af=>{"use strict";var jb=Vt(),Fb=gs(),qb=Yt(),Ub=Kr(),Jb=Vo(),Xo=Go(),Zo=Qo(),Kb=[jb.map,qb.seq,Ub.string,Fb.nullTag,Jb.boolTag,Zo.intOct,Zo.int,Zo.intHex,Xo.floatNaN,Xo.floatExp,Xo.float];af.schema=Kb});var ff=A(uf=>{"use strict";var Hb=H(),Wb=Vt(),Vb=Yt();function lf(r){return typeof r=="bigint"||Number.isInteger(r)}var vs=({value:r})=>JSON.stringify(r),Yb=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:vs},{identify:r=>r==null,createNode:()=>new Hb.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:vs},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:vs},{identify:lf,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})=>lf(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:vs}],Gb={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},zb=[Wb.map,Vb.seq].concat(Yb,Gb);uf.schema=zb});var ta=A(df=>{"use strict";var Hr=jn("buffer"),ea=H(),Qb=jr(),Xb={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof Hr.Buffer=="function")return Hr.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 Hr.Buffer=="function")a=o instanceof Hr.Buffer?o.toString("base64"):Hr.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=ea.Scalar.BLOCK_LITERAL),e!==ea.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(a.length/c),d=new Array(l);for(let u=0,f=0;u<l;++u,f+=c)d[u]=a.substr(f,c);a=d.join(e===ea.Scalar.BLOCK_LITERAL?`
|
|
69
|
+
`:" ")}return Qb.stringifyString({comment:r,type:e,value:a},n,s,i)}};df.binary=Xb});var xs=A(ks=>{"use strict";var Ss=D(),ra=Ye(),Zb=H(),ew=Qe();function pf(r,e){if(Ss.isSeq(r))for(let t=0;t<r.items.length;++t){let n=r.items[t];if(!Ss.isPair(n)){if(Ss.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let s=n.items[0]||new ra.Pair(new Zb.Scalar(null));if(n.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${n.commentBefore}
|
|
64
70
|
${s.key.commentBefore}`:n.commentBefore),n.comment){let i=s.value??s.key;i.comment=i.comment?`${n.comment}
|
|
65
|
-
${i.comment}`:n.comment}n=s}r.items[t]=us.isPair(n)?n:new Fo.Pair(n)}}else e("Expected a sequence for this tag");return r}function Yu(r,e,t){let{replacer:n}=t,s=new _b.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(Fo.createPair(a,c,t))}return s}var Cb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Vu,createNode:Yu};fs.createPairs=Yu;fs.pairs=Cb;fs.resolvePairs=Vu});var Jo=O(Uo=>{"use strict";var Gu=M(),qo=je(),Dr=We(),Nb=He(),zu=ds(),ct=class r extends Nb.YAMLSeq{constructor(){super(),this.add=Dr.YAMLMap.prototype.add.bind(this),this.delete=Dr.YAMLMap.prototype.delete.bind(this),this.get=Dr.YAMLMap.prototype.get.bind(this),this.has=Dr.YAMLMap.prototype.has.bind(this),this.set=Dr.YAMLMap.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let s of this.items){let i,o;if(Gu.isPair(s)?(i=qo.toJS(s.key,"",t),o=qo.toJS(s.value,i,t)):i=qo.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=zu.createPairs(e,t,n),i=new this;return i.items=s.items,i}};ct.tag="tag:yaml.org,2002:omap";var Ib={collection:"seq",identify:r=>r instanceof Map,nodeClass:ct,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=zu.resolvePairs(r,e),n=[];for(let{key:s}of t.items)Gu.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new ct,t)},createNode:(r,e,t)=>ct.from(r,e,t)};Uo.YAMLOMap=ct;Uo.omap=Ib});var tf=O(Ko=>{"use strict";var Qu=J();function Xu({value:r,source:e},t){return e&&(r?Zu:ef).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Zu={identify:r=>r===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Qu.Scalar(!0),stringify:Xu},ef={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 Qu.Scalar(!1),stringify:Xu};Ko.falseTag=ef;Ko.trueTag=Zu});var rf=O(ps=>{"use strict";var Lb=J(),Wo=Jt(),Mb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Wo.stringifyNumber},$b={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Wo.stringifyNumber(r)}},Db={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 Lb.Scalar(parseFloat(r.replace(/_/g,""))),t=r.indexOf(".");if(t!==-1){let n=r.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:Wo.stringifyNumber};ps.float=Db;ps.floatExp=$b;ps.floatNaN=Mb});var sf=O(jr=>{"use strict";var nf=Jt(),Br=r=>typeof r=="bigint"||Number.isInteger(r);function ms(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 Ho(r,e,t){let{value:n}=r;if(Br(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return nf.stringifyNumber(r)}var Bb={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>ms(r,2,2,t),stringify:r=>Ho(r,2,"0b")},jb={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>ms(r,1,8,t),stringify:r=>Ho(r,8,"0")},Fb={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>ms(r,0,10,t),stringify:nf.stringifyNumber},qb={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>ms(r,2,16,t),stringify:r=>Ho(r,16,"0x")};jr.int=Fb;jr.intBin=Bb;jr.intHex=qb;jr.intOct=jb});var Yo=O(Vo=>{"use strict";var ys=M(),hs=Je(),gs=We(),lt=class r extends gs.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;ys.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new hs.Pair(e.key,null):t=new hs.Pair(e,null),gs.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=gs.findPair(this.items,e);return!t&&ys.isPair(n)?ys.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=gs.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new hs.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(hs.createPair(o,null,n));return i}};lt.tag="tag:yaml.org,2002:set";var Ub={collection:"map",identify:r=>r instanceof Set,nodeClass:lt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>lt.from(r,e,t),resolve(r,e){if(ys.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new lt,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Vo.YAMLSet=lt;Vo.set=Ub});var zo=O(bs=>{"use strict";var Jb=Jt();function Go(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 of(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Jb.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 Kb={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})=>Go(r,t),stringify:of},Wb={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=>Go(r,!1),stringify:of},af={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(af.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,s,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,s,i||0,o||0,a||0,c),d=e[8];if(d&&d!=="Z"){let u=Go(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};bs.floatTime=Wb;bs.intTime=Kb;bs.timestamp=af});var uf=O(lf=>{"use strict";var Hb=qt(),Vb=is(),Yb=Ut(),Gb=Mr(),zb=jo(),cf=tf(),Qo=rf(),ws=sf(),Qb=Qn(),Xb=Jo(),Zb=ds(),ew=Yo(),Xo=zo(),tw=[Hb.map,Yb.seq,Gb.string,Vb.nullTag,cf.trueTag,cf.falseTag,ws.intBin,ws.intOct,ws.int,ws.intHex,Qo.floatNaN,Qo.floatExp,Qo.float,zb.binary,Qb.merge,Xb.omap,Zb.pairs,ew.set,Xo.intTime,Xo.floatTime,Xo.timestamp];lf.schema=tw});var vf=O(ta=>{"use strict";var mf=qt(),rw=is(),hf=Ut(),nw=Mr(),sw=Co(),Zo=Io(),ea=Mo(),iw=Uu(),ow=Wu(),gf=jo(),Fr=Qn(),yf=Jo(),bf=ds(),ff=uf(),wf=Yo(),vs=zo(),df=new Map([["core",iw.schema],["failsafe",[mf.map,hf.seq,nw.string]],["json",ow.schema],["yaml11",ff.schema],["yaml-1.1",ff.schema]]),pf={binary:gf.binary,bool:sw.boolTag,float:Zo.float,floatExp:Zo.floatExp,floatNaN:Zo.floatNaN,floatTime:vs.floatTime,int:ea.int,intHex:ea.intHex,intOct:ea.intOct,intTime:vs.intTime,map:mf.map,merge:Fr.merge,null:rw.nullTag,omap:yf.omap,pairs:bf.pairs,seq:hf.seq,set:wf.set,timestamp:vs.timestamp},aw={"tag:yaml.org,2002:binary":gf.binary,"tag:yaml.org,2002:merge":Fr.merge,"tag:yaml.org,2002:omap":yf.omap,"tag:yaml.org,2002:pairs":bf.pairs,"tag:yaml.org,2002:set":wf.set,"tag:yaml.org,2002:timestamp":vs.timestamp};function cw(r,e,t){let n=df.get(e);if(n&&!r)return t&&!n.includes(Fr.merge)?n.concat(Fr.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(df.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(r))for(let i of r)s=s.concat(i);else typeof r=="function"&&(s=r(s.slice()));return t&&(s=s.concat(Fr.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?pf[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(pf).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}ta.coreKnownTags=aw;ta.getTags=cw});var sa=O(Sf=>{"use strict";var ra=M(),lw=qt(),uw=Ut(),fw=Mr(),Ss=vf(),dw=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,na=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Ss.getTags(e,"compat"):e?Ss.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?Ss.coreKnownTags:{},this.tags=Ss.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,ra.MAP,{value:lw.map}),Object.defineProperty(this,ra.SCALAR,{value:fw.string}),Object.defineProperty(this,ra.SEQ,{value:uw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?dw:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Sf.Schema=na});var xf=O(kf=>{"use strict";var pw=M(),ia=Cr(),qr=Pr();function mw(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=ia.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(qr.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(pw.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let d=i(r.contents.commentBefore);t.push(qr.indentComment(d,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=ia.stringify(r.contents,s,()=>a=null,c);a&&(l+=qr.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(ia.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
66
|
-
`)?(t.push("..."),t.push(
|
|
71
|
+
${i.comment}`:n.comment}n=s}r.items[t]=Ss.isPair(n)?n:new ra.Pair(n)}}else e("Expected a sequence for this tag");return r}function mf(r,e,t){let{replacer:n}=t,s=new ew.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(ra.createPair(a,c,t))}return s}var tw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:pf,createNode:mf};ks.createPairs=mf;ks.pairs=tw;ks.resolvePairs=pf});var ia=A(sa=>{"use strict";var hf=D(),na=Ke(),Wr=ze(),rw=Qe(),gf=xs(),gt=class r extends rw.YAMLSeq{constructor(){super(),this.add=Wr.YAMLMap.prototype.add.bind(this),this.delete=Wr.YAMLMap.prototype.delete.bind(this),this.get=Wr.YAMLMap.prototype.get.bind(this),this.has=Wr.YAMLMap.prototype.has.bind(this),this.set=Wr.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(hf.isPair(s)?(i=na.toJS(s.key,"",t),o=na.toJS(s.value,i,t)):i=na.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=gf.createPairs(e,t,n),i=new this;return i.items=s.items,i}};gt.tag="tag:yaml.org,2002:omap";var nw={collection:"seq",identify:r=>r instanceof Map,nodeClass:gt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=gf.resolvePairs(r,e),n=[];for(let{key:s}of t.items)hf.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new gt,t)},createNode:(r,e,t)=>gt.from(r,e,t)};sa.YAMLOMap=gt;sa.omap=nw});var Sf=A(oa=>{"use strict";var yf=H();function bf({value:r,source:e},t){return e&&(r?wf:vf).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var wf={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 yf.Scalar(!0),stringify:bf},vf={identify:r=>r===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new yf.Scalar(!1),stringify:bf};oa.falseTag=vf;oa.trueTag=wf});var kf=A(Es=>{"use strict";var sw=H(),aa=Gt(),iw={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:aa.stringifyNumber},ow={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():aa.stringifyNumber(r)}},aw={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 sw.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:aa.stringifyNumber};Es.float=aw;Es.floatExp=ow;Es.floatNaN=iw});var Ef=A(Yr=>{"use strict";var xf=Gt(),Vr=r=>typeof r=="bigint"||Number.isInteger(r);function As(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(Vr(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return xf.stringifyNumber(r)}var cw={identify:Vr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>As(r,2,2,t),stringify:r=>ca(r,2,"0b")},lw={identify:Vr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>As(r,1,8,t),stringify:r=>ca(r,8,"0")},uw={identify:Vr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>As(r,0,10,t),stringify:xf.stringifyNumber},fw={identify:Vr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>As(r,2,16,t),stringify:r=>ca(r,16,"0x")};Yr.int=uw;Yr.intBin=cw;Yr.intHex=fw;Yr.intOct=lw});var ua=A(la=>{"use strict";var Os=D(),Ts=Ye(),Ps=ze(),yt=class r extends Ps.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;Os.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Ts.Pair(e.key,null):t=new Ts.Pair(e,null),Ps.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=Ps.findPair(this.items,e);return!t&&Os.isPair(n)?Os.isScalar(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=Ps.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Ts.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(Ts.createPair(o,null,n));return i}};yt.tag="tag:yaml.org,2002:set";var dw={collection:"map",identify:r=>r instanceof Set,nodeClass:yt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>yt.from(r,e,t),resolve(r,e){if(Os.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new yt,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};la.YAMLSet=yt;la.set=dw});var da=A(Cs=>{"use strict";var pw=Gt();function fa(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 Af(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return pw.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 mw={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})=>fa(r,t),stringify:Af},hw={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=>fa(r,!1),stringify:Af},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),d=e[8];if(d&&d!=="Z"){let u=fa(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Cs.floatTime=hw;Cs.intTime=mw;Cs.timestamp=Tf});var Cf=A(Of=>{"use strict";var gw=Vt(),yw=gs(),bw=Yt(),ww=Kr(),vw=ta(),Pf=Sf(),pa=kf(),_s=Ef(),Sw=cs(),kw=ia(),xw=xs(),Ew=ua(),ma=da(),Aw=[gw.map,bw.seq,ww.string,yw.nullTag,Pf.trueTag,Pf.falseTag,_s.intBin,_s.intOct,_s.int,_s.intHex,pa.floatNaN,pa.floatExp,pa.float,vw.binary,Sw.merge,kw.omap,xw.pairs,Ew.set,ma.intTime,ma.floatTime,ma.timestamp];Of.schema=Aw});var jf=A(ya=>{"use strict";var If=Vt(),Tw=gs(),Lf=Yt(),Pw=Kr(),Ow=Vo(),ha=Go(),ga=Qo(),Cw=cf(),_w=ff(),$f=ta(),Gr=cs(),Mf=ia(),Df=xs(),_f=Cf(),Bf=ua(),Rs=da(),Rf=new Map([["core",Cw.schema],["failsafe",[If.map,Lf.seq,Pw.string]],["json",_w.schema],["yaml11",_f.schema],["yaml-1.1",_f.schema]]),Nf={binary:$f.binary,bool:Ow.boolTag,float:ha.float,floatExp:ha.floatExp,floatNaN:ha.floatNaN,floatTime:Rs.floatTime,int:ga.int,intHex:ga.intHex,intOct:ga.intOct,intTime:Rs.intTime,map:If.map,merge:Gr.merge,null:Tw.nullTag,omap:Mf.omap,pairs:Df.pairs,seq:Lf.seq,set:Bf.set,timestamp:Rs.timestamp},Rw={"tag:yaml.org,2002:binary":$f.binary,"tag:yaml.org,2002:merge":Gr.merge,"tag:yaml.org,2002:omap":Mf.omap,"tag:yaml.org,2002:pairs":Df.pairs,"tag:yaml.org,2002:set":Bf.set,"tag:yaml.org,2002:timestamp":Rs.timestamp};function Nw(r,e,t){let n=Rf.get(e);if(n&&!r)return t&&!n.includes(Gr.merge)?n.concat(Gr.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(Rf.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(Gr.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?Nf[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Nf).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}ya.coreKnownTags=Rw;ya.getTags=Nw});var va=A(Ff=>{"use strict";var ba=D(),Iw=Vt(),Lw=Yt(),$w=Kr(),Ns=jf(),Mw=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,wa=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Ns.getTags(e,"compat"):e?Ns.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?Ns.coreKnownTags:{},this.tags=Ns.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,ba.MAP,{value:Iw.map}),Object.defineProperty(this,ba.SCALAR,{value:$w.string}),Object.defineProperty(this,ba.SEQ,{value:Lw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Mw:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Ff.Schema=wa});var Uf=A(qf=>{"use strict";var Dw=D(),Sa=Fr(),zr=Mr();function Bw(r,e){let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let c=r.directives.toString(r);c?(t.push(c),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let s=Sa.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(zr.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(Dw.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let d=i(r.contents.commentBefore);t.push(zr.indentComment(d,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Sa.stringify(r.contents,s,()=>a=null,c);a&&(l+=zr.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Sa.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
72
|
+
`)?(t.push("..."),t.push(zr.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(zr.indentComment(i(c),"")))}return t.join(`
|
|
67
73
|
`)+`
|
|
68
|
-
`}
|
|
74
|
+
`}qf.stringifyDocument=Bw});var Qr=A(Jf=>{"use strict";var jw=Lr(),zt=Zn(),le=D(),Fw=Ye(),qw=Ke(),Uw=va(),Jw=Uf(),ka=Gn(),Kw=To(),Hw=$r(),xa=Ao(),Ea=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,le.NODE_TYPE,{value:le.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 xa.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,{[le.NODE_TYPE]:{value:le.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=le.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Qt(this.contents)&&this.contents.add(e)}addIn(e,t){Qt(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 jw.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 w=E=>typeof E=="number"||E instanceof String||E instanceof Number,x=t.filter(w).map(String);x.length>0&&(t=t.concat(x)),s=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:d}=n??{},{onAnchor:u,setAnchors:f,sourceObjects:p}=ka.createNodeAnchors(this,o||"a"),b={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:p},h=Hw.createNode(e,d,b);return a&&le.isCollection(h)&&(h.flow=!0),f(),h}createPair(e,t,n={}){let s=this.createNode(e,null,n),i=this.createNode(t,null,n);return new Fw.Pair(s,i)}delete(e){return Qt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return zt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Qt(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return le.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return zt.isEmptyPath(e)?!t&&le.isScalar(this.contents)?this.contents.value:this.contents:le.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return le.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return zt.isEmptyPath(e)?this.contents!==void 0:le.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=zt.collectionFromPath(this.schema,[e],t):Qt(this.contents)&&this.contents.set(e,t)}setIn(e,t){zt.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=zt.collectionFromPath(this.schema,Array.from(e),t):Qt(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 xa.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 xa.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 Uw.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=qw.toJS(this.contents,t??"",a);if(typeof i=="function")for(let{count:l,res:d}of a.anchors.values())i(d,l);return typeof o=="function"?Kw.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 Jw.stringifyDocument(this,e)}};function Qt(r){if(le.isCollection(r))return!0;throw new Error("Expected a YAML collection as document contents")}Jf.Document=Ea});var en=A(Zr=>{"use strict";var Xr=class extends Error{constructor(e,t,n,s){super(),this.name=e,this.code=n,this.message=s,this.pos=t}},Aa=class extends Xr{constructor(e,t,n){super("YAMLParseError",e,t,n)}},Ta=class extends Xr{constructor(e,t,n){super("YAMLWarning",e,t,n)}},Ww=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:s}=t.linePos[0];t.message+=` at line ${n}, column ${s}`;let i=s-1,o=r.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){let a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,i))){let a=r.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
|
|
69
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+=`:
|
|
70
76
|
|
|
71
77
|
${o}
|
|
72
78
|
${l}
|
|
73
|
-
`}};
|
|
74
|
-
`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(
|
|
75
|
-
`+
|
|
76
|
-
`+
|
|
77
|
-
`+
|
|
78
|
-
`+
|
|
79
|
-
`+
|
|
80
|
-
`+
|
|
81
|
-
`.repeat(Math.max(1,o.length-1)):"",
|
|
82
|
-
`;for(let
|
|
83
|
-
`):
|
|
79
|
+
`}};Zr.YAMLError=Xr;Zr.YAMLParseError=Aa;Zr.YAMLWarning=Ta;Zr.prettifyError=Ww});var tn=A(Kf=>{"use strict";function Vw(r,{flow:e,indicator:t,next:n,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,d=a,u="",f="",p=!1,b=!1,h=null,w=null,x=null,E=null,T=null,P=null,C=null;for(let v of r)switch(b&&(v.type!=="space"&&v.type!=="newline"&&v.type!=="comma"&&i(v.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),b=!1),h&&(l&&v.type!=="comment"&&v.type!=="newline"&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),v.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&v.source.includes(" ")&&(h=v),d=!0;break;case"comment":{d||i(v,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let R=v.source.substring(1)||" ";u?u+=f+R:u=R,f="",l=!1;break}case"newline":l?u?u+=v.source:(!P||t!=="seq-item-ind")&&(c=!0):f+=v.source,l=!0,p=!0,(w||x)&&(E=v),d=!0;break;case"anchor":w&&i(v,"MULTIPLE_ANCHORS","A node can have at most one anchor"),v.source.endsWith(":")&&i(v.offset+v.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),w=v,C??(C=v.offset),l=!1,d=!1,b=!0;break;case"tag":{x&&i(v,"MULTIPLE_TAGS","A node can have at most one tag"),x=v,C??(C=v.offset),l=!1,d=!1,b=!0;break}case t:(w||x)&&i(v,"BAD_PROP_ORDER",`Anchors and tags must be after the ${v.source} indicator`),P&&i(v,"UNEXPECTED_TOKEN",`Unexpected ${v.source} in ${e??"collection"}`),P=v,l=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){T&&i(v,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),T=v,l=!1,d=!1;break}default:i(v,"UNEXPECTED_TOKEN",`Unexpected ${v.type} token`),l=!1,d=!1}let m=r[r.length-1],y=m?m.offset+m.source.length:s;return b&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&i(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:T,found:P,spaceBefore:c,comment:u,hasNewline:p,anchor:w,tag:x,newlineAfterProp:E,end:y,start:C??y}}Kf.resolveProps=Vw});var Is=A(Hf=>{"use strict";function Pa(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(Pa(e.key)||Pa(e.value))return!0}return!1;default:return!0}}Hf.containsNewline=Pa});var Oa=A(Wf=>{"use strict";var Yw=Is();function Gw(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&Yw.containsNewline(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Wf.flowIndentCheck=Gw});var Ca=A(Yf=>{"use strict";var Vf=D();function zw(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let s=typeof n=="function"?n:(i,o)=>i===o||Vf.isScalar(i)&&Vf.isScalar(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}Yf.mapIncludes=zw});var ed=A(Zf=>{"use strict";var Gf=Ye(),Qw=ze(),zf=tn(),Xw=Is(),Qf=Oa(),Zw=Ca(),Xf="All mapping items must start at the same column";function ev({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??Qw.YAMLMap,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let d of n.items){let{start:u,key:f,sep:p,value:b}=d,h=zf.resolveProps(u,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0}),w=!h.found;if(w){if(f&&(f.type==="block-seq"?s(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&s(c,"BAD_INDENT",Xf)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(a.comment?a.comment+=`
|
|
81
|
+
`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||Xw.containsNewline(f))&&s(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&s(c,"BAD_INDENT",Xf);t.atKey=!0;let x=h.end,E=f?r(t,f,h,s):e(t,x,u,null,h,s);t.schema.compat&&Qf.flowIndentCheck(n.indent,f,s),t.atKey=!1,Zw.mapIncludes(t,a.items,E)&&s(x,"DUPLICATE_KEY","Map keys must be unique");let T=zf.resolveProps(p??[],{indicator:"map-value-ind",next:b,offset:E.range[2],onError:s,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=T.end,T.found){w&&(b?.type==="block-map"&&!T.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&h.start<T.found.offset-1024&&s(E.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let P=b?r(t,b,T,s):e(t,c,p,null,T,s);t.schema.compat&&Qf.flowIndentCheck(n.indent,b,s),c=P.range[2];let C=new Gf.Pair(E,P);t.options.keepSourceTokens&&(C.srcToken=d),a.items.push(C)}else{w&&s(E.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),T.comment&&(E.comment?E.comment+=`
|
|
82
|
+
`+T.comment:E.comment=T.comment);let P=new Gf.Pair(E);t.options.keepSourceTokens&&(P.srcToken=d),a.items.push(P)}}return l&&l<c&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,l??c],a}Zf.resolveBlockMap=ev});var rd=A(td=>{"use strict";var tv=Qe(),rv=tn(),nv=Oa();function sv({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??tv.YAMLSeq,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let c=n.offset,l=null;for(let{start:d,value:u}of n.items){let f=rv.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u?.type==="block-seq"?s(f.end,"BAD_INDENT","All sequence items must start at the same column"):s(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(a.comment=f.comment);continue}let p=u?r(t,u,f,s):e(t,f.end,d,null,f,s);t.schema.compat&&nv.flowIndentCheck(n.indent,u,s),c=p.range[2],a.items.push(p)}return a.range=[n.offset,c,l??c],a}td.resolveBlockSeq=sv});var Xt=A(nd=>{"use strict";function iv(r,e,t,n){let s="";if(r){let i=!1,o="";for(let a of r){let{source:c,type:l}=a;switch(l){case"space":i=!0;break;case"comment":{t&&!i&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";s?s+=o+d:s=d,o="";break}case"newline":s&&(o+=c),i=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:s,offset:e}}nd.resolveEnd=iv});var ad=A(od=>{"use strict";var ov=D(),av=Ye(),sd=ze(),cv=Qe(),lv=Xt(),id=tn(),uv=Is(),fv=Ca(),_a="Block collections are not allowed within flow collections",Ra=r=>r&&(r.type==="block-map"||r.type==="block-seq");function dv({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?sd.YAMLMap:cv.YAMLSeq),l=new c(t.schema);l.flow=!0;let d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=n.offset+n.start.source.length;for(let w=0;w<n.items.length;++w){let x=n.items[w],{start:E,key:T,sep:P,value:C}=x,m=id.resolveProps(E,{flow:a,indicator:"explicit-key-ind",next:T??P?.[0],offset:u,onError:s,parentIndent:n.indent,startOnNewline:!1});if(!m.found){if(!m.anchor&&!m.tag&&!P&&!C){w===0&&m.comma?s(m.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):w<n.items.length-1&&s(m.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),m.comment&&(l.comment?l.comment+=`
|
|
83
|
+
`+m.comment:l.comment=m.comment),u=m.end;continue}!o&&t.options.strict&&uv.containsNewline(T)&&s(T,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(w===0)m.comma&&s(m.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(m.comma||s(m.start,"MISSING_CHAR",`Missing , between ${a} items`),m.comment){let y="";e:for(let v of E)switch(v.type){case"comma":case"space":break;case"comment":y=v.source.substring(1);break e;default:break e}if(y){let v=l.items[l.items.length-1];ov.isPair(v)&&(v=v.value??v.key),v.comment?v.comment+=`
|
|
84
|
+
`+y:v.comment=y,m.comment=m.comment.substring(y.length+1)}}if(!o&&!P&&!m.found){let y=C?r(t,C,m,s):e(t,m.end,P,null,m,s);l.items.push(y),u=y.range[2],Ra(C)&&s(y.range,"BLOCK_IN_FLOW",_a)}else{t.atKey=!0;let y=m.end,v=T?r(t,T,m,s):e(t,y,E,null,m,s);Ra(T)&&s(v.range,"BLOCK_IN_FLOW",_a),t.atKey=!1;let R=id.resolveProps(P??[],{flow:a,indicator:"map-value-ind",next:C,offset:v.range[2],onError:s,parentIndent:n.indent,startOnNewline:!1});if(R.found){if(!o&&!m.found&&t.options.strict){if(P)for(let B of P){if(B===R.found)break;if(B.type==="newline"){s(B,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}m.start<R.found.offset-1024&&s(R.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(R.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let I=C?r(t,C,R,s):R.found?e(t,R.end,P,null,R,s):null;I?Ra(C)&&s(I.range,"BLOCK_IN_FLOW",_a):R.comment&&(v.comment?v.comment+=`
|
|
85
|
+
`+R.comment:v.comment=R.comment);let J=new av.Pair(v,I);if(t.options.keepSourceTokens&&(J.srcToken=x),o){let B=l;fv.mapIncludes(t,B.items,v)&&s(y,"DUPLICATE_KEY","Map keys must be unique"),B.items.push(J)}else{let B=new sd.YAMLMap(t.schema);B.flow=!0,B.items.push(J);let pe=(I??v).range;B.range=[v.range[0],pe[1],pe[2]],l.items.push(B)}u=I?I.range[2]:R.end}}let f=o?"}":"]",[p,...b]=n.end,h=u;if(p?.source===f)h=p.offset+p.source.length;else{let w=a[0].toUpperCase()+a.substring(1),x=d?`${w} must end with a ${f}`:`${w} in block collection must be sufficiently indented and end with a ${f}`;s(u,d?"MISSING_CHAR":"BAD_INDENT",x),p&&p.source.length!==1&&b.unshift(p)}if(b.length>0){let w=lv.resolveEnd(b,h,t.options.strict,s);w.comment&&(l.comment?l.comment+=`
|
|
86
|
+
`+w.comment:l.comment=w.comment),l.range=[n.offset,h,w.offset]}else l.range=[n.offset,h,h];return l}od.resolveFlowCollection=dv});var ld=A(cd=>{"use strict";var pv=D(),mv=H(),hv=ze(),gv=Qe(),yv=ed(),bv=rd(),wv=ad();function Na(r,e,t,n,s,i){let o=t.type==="block-map"?yv.resolveBlockMap(r,e,t,n,i):t.type==="block-seq"?bv.resolveBlockSeq(r,e,t,n,i):wv.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 vv(r,e,t,n,s){let i=n.tag,o=i?e.directives.tagName(i.source,f=>s(i,"TAG_RESOLVE_FAILED",f)):null;if(t.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=n,b=f&&i?f.offset>i.offset?f:i:f??i;b&&(!p||p.offset<b.offset)&&s(b,"MISSING_CHAR","Missing newline after block sequence props")}let a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===hv.YAMLMap.tagName&&a==="map"||o===gv.YAMLSeq.tagName&&a==="seq")return Na(r,e,t,s,o);let c=e.schema.tags.find(f=>f.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?s(i,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Na(r,e,t,s,o)}let l=Na(r,e,t,s,o,c),d=c.resolve?.(l,f=>s(i,"TAG_RESOLVE_FAILED",f),e.options)??l,u=pv.isNode(d)?d:new mv.Scalar(d);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}cd.composeCollection=vv});var La=A(ud=>{"use strict";var Ia=H();function Sv(r,e,t){let n=e.offset,s=kv(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let i=s.mode===">"?Ia.Scalar.BLOCK_FOLDED:Ia.Scalar.BLOCK_LITERAL,o=e.source?xv(e.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let w=o[h][1];if(w===""||w==="\r")a=h;else break}if(a===0){let h=s.chomp==="+"&&o.length>0?`
|
|
87
|
+
`.repeat(Math.max(1,o.length-1)):"",w=n+s.length;return e.source&&(w+=e.source.length),{value:h,type:i,comment:s.comment,range:[n,w,w]}}let c=e.indent+s.indent,l=e.offset+s.length,d=0;for(let h=0;h<a;++h){let[w,x]=o[h];if(x===""||x==="\r")s.indent===0&&w.length>c&&(c=w.length);else{w.length<c&&t(l+w.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(c=w.length),d=h,c===0&&!r.atRoot&&t(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=w.length+x.length+1}for(let h=o.length-1;h>=a;--h)o[h][0].length>c&&(a=h+1);let u="",f="",p=!1;for(let h=0;h<d;++h)u+=o[h][0].slice(c)+`
|
|
88
|
+
`;for(let h=d;h<a;++h){let[w,x]=o[h];l+=w.length+x.length+1;let E=x[x.length-1]==="\r";if(E&&(x=x.slice(0,-1)),x&&w.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-(E?2:1),"BAD_INDENT",P),w=""}i===Ia.Scalar.BLOCK_LITERAL?(u+=f+w.slice(c)+x,f=`
|
|
89
|
+
`):w.length>c||x[0]===" "?(f===" "?f=`
|
|
84
90
|
`:!p&&f===`
|
|
85
91
|
`&&(f=`
|
|
86
92
|
|
|
87
|
-
`),u+=f+
|
|
93
|
+
`),u+=f+w.slice(c)+x,f=`
|
|
88
94
|
`,p=!0):x===""?f===`
|
|
89
95
|
`?u+=`
|
|
90
96
|
`:f=`
|
|
91
|
-
`:(u+=f+x,f=" ",p=!1)}switch(s.chomp){case"-":break;case"+":for(let
|
|
92
|
-
`+o[
|
|
97
|
+
`:(u+=f+x,f=" ",p=!1)}switch(s.chomp){case"-":break;case"+":for(let h=a;h<o.length;++h)u+=`
|
|
98
|
+
`+o[h][0].slice(c);u[u.length-1]!==`
|
|
93
99
|
`&&(u+=`
|
|
94
100
|
`);break;default:u+=`
|
|
95
|
-
`}let
|
|
101
|
+
`}let b=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,b,b]}}function kv({offset:r,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:s}=e[0],i=s[0],o=0,a="",c=-1;for(let f=1;f<s.length;++f){let p=s[f];if(!a&&(p==="-"||p==="+"))a=p;else{let b=Number(p);!o&&b?o=b:c===-1&&(c=r+f)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,d="",u=s.length;for(let f=1;f<e.length;++f){let p=e[f];switch(p.type){case"space":l=!0;case"newline":u+=p.source.length;break;case"comment":t&&!l&&n(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=p.source.length,d=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),u+=p.source.length;break;default:{let b=`Unexpected token in block scalar header: ${p.type}`;n(p,"UNEXPECTED_TOKEN",b);let h=p.source;h&&typeof h=="string"&&(u+=h.length)}}}return{mode:i,indent:o,chomp:a,comment:d,length:u}}function xv(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}ud.resolveBlockScalar=Sv});var Ma=A(dd=>{"use strict";var $a=H(),Ev=Xt();function Av(r,e,t){let{offset:n,type:s,source:i,end:o}=r,a,c,l=(f,p,b)=>t(n+f,p,b);switch(s){case"scalar":a=$a.Scalar.PLAIN,c=Tv(i,l);break;case"single-quoted-scalar":a=$a.Scalar.QUOTE_SINGLE,c=Pv(i,l);break;case"double-quoted-scalar":a=$a.Scalar.QUOTE_DOUBLE,c=Ov(i,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[n,n+i.length,n+i.length]}}let d=n+i.length,u=Ev.resolveEnd(o,d,e,t);return{value:c,type:a,comment:u.comment,range:[n,d,u.offset]}}function Tv(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}`),fd(r)}function Pv(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),fd(r.slice(1,-1)).replace(/''/g,"'")}function fd(r){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
96
102
|
`,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
97
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===`
|
|
98
104
|
`?s+=i:i=`
|
|
99
|
-
`:(s+=i+n[1],i=" "),o=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(r),s+i+(n?.[1]??"")}function
|
|
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 Ov(r,e){let t="";for(let n=1;n<r.length-1;++n){let s=r[n];if(!(s==="\r"&&r[n+1]===`
|
|
100
106
|
`))if(s===`
|
|
101
|
-
`){let{fold:i,offset:o}=
|
|
107
|
+
`){let{fold:i,offset:o}=Cv(r,n);t+=i,n=o}else if(s==="\\"){let i=r[++n],o=_v[i];if(o)t+=o;else if(i===`
|
|
102
108
|
`)for(i=r[n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="\r"&&r[n+1]===`
|
|
103
|
-
`)for(i=r[++n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];t+=
|
|
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+=Rv(r,n+1,a,e),n+=a}else{let a=r.substr(n-1,2);e(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(s===" "||s===" "){let i=n,o=r[n+1];for(;o===" "||o===" ";)o=r[++n+1];o!==`
|
|
104
110
|
`&&!(o==="\r"&&r[n+2]===`
|
|
105
|
-
`)&&(t+=n>i?r.slice(i,n+1):s)}else t+=s}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function
|
|
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 Cv(r,e){let t="",n=r[e+1];for(;(n===" "||n===" "||n===`
|
|
106
112
|
`||n==="\r")&&!(n==="\r"&&r[e+2]!==`
|
|
107
113
|
`);)n===`
|
|
108
114
|
`&&(t+=`
|
|
109
|
-
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var
|
|
110
|
-
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
115
|
+
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var _v={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 Rv(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)}dd.resolveFlowScalar=Av});var hd=A(md=>{"use strict";var bt=D(),pd=H(),Nv=La(),Iv=Ma();function Lv(r,e,t,n){let{value:s,type:i,comment:o,range:a}=e.type==="block-scalar"?Nv.resolveBlockScalar(r,e,n):Iv.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[bt.SCALAR]:c?l=$v(r.schema,s,c,t,n):e.type==="scalar"?l=Mv(r,s,e,n):l=r.schema[bt.SCALAR];let d;try{let u=l.resolve(s,f=>n(t??e,"TAG_RESOLVE_FAILED",f),r.options);d=bt.isScalar(u)?u:new pd.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);n(t??e,"TAG_RESOLVE_FAILED",f),d=new pd.Scalar(s)}return d.range=a,d.source=s,i&&(d.type=i),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function $v(r,e,t,n,s){if(t==="!")return r[bt.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[bt.SCALAR])}function Mv({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[bt.SCALAR];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[bt.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),d=`Value may be parsed as either ${c} or ${l}`;i(s,"TAG_RESOLVE_FAILED",d,!0)}}return o}md.composeScalar=Lv});var yd=A(gd=>{"use strict";function Dv(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}gd.emptyScalarPosition=Dv});var vd=A(Ba=>{"use strict";var Bv=Lr(),jv=D(),Fv=ld(),bd=hd(),qv=Xt(),Uv=yd(),Jv={composeNode:wd,composeEmptyNode:Da};function wd(r,e,t,n){let s=r.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=t,l,d=!0;switch(e.type){case"alias":l=Kv(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=bd.composeScalar(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=Fv.composeCollection(Jv,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=Da(r,e.offset,void 0,null,t,n),d=!1}}return a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&r.options.stringKeys&&(!jv.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&d&&(l.srcToken=e),l}function Da(r,e,t,n,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let d={type:"scalar",offset:Uv.emptyScalarPosition(e,t,n),indent:-1,source:""},u=bd.composeScalar(r,d,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=c),u}function Kv({options:r},{offset:e,source:t,end:n},s){let i=new Bv.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=qv.resolveEnd(n,o,r.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}Ba.composeEmptyNode=Da;Ba.composeNode=wd});var xd=A(kd=>{"use strict";var Hv=Qr(),Sd=vd(),Wv=Xt(),Vv=tn();function Yv(r,e,{offset:t,start:n,value:s,end:i},o){let a=Object.assign({_directives:e},r),c=new Hv.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=Vv.resolveProps(n,{indicator:"doc-start",next:s??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?Sd.composeNode(l,s,d,o):Sd.composeEmptyNode(l,d.end,n,null,d,o);let u=c.contents.range[2],f=Wv.resolveEnd(i,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,u,f.offset],c}kd.composeDoc=Yv});var Fa=A(Td=>{"use strict";var Gv=jn("process"),zv=Ao(),Qv=Qr(),rn=en(),Ed=D(),Xv=xd(),Zv=Xt();function nn(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 Ad(r){let e="",t=!1,n=!1;for(let s=0;s<r.length;++s){let i=r[s];switch(i[0]){case"#":e+=(e===""?"":n?`
|
|
111
117
|
|
|
112
118
|
`:`
|
|
113
|
-
`)+(i.substring(1)||" "),t=!0,n=!1;break;case"%":r[s+1]?.[0]!=="#"&&(s+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var
|
|
114
|
-
${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(
|
|
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 ja=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,s,i)=>{let o=nn(t);i?this.warnings.push(new rn.YAMLWarning(o,n,s)):this.errors.push(new rn.YAMLParseError(o,n,s))},this.directives=new zv.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:s}=Ad(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(Ed.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];Ed.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n}
|
|
115
121
|
${a}`:n}else{let o=i.commentBefore;i.commentBefore=o?`${n}
|
|
116
|
-
${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
117
|
-
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new
|
|
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:Ad(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(Gv.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,n,s)=>{let i=nn(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,s)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=Xv.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 rn.YAMLParseError(nn(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 rn.YAMLParseError(nn(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=Zv.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 rn.YAMLParseError(nn(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 Qv.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}}};Td.Composer=ja});var Cd=A(Ls=>{"use strict";var eS=La(),tS=Ma(),rS=en(),Pd=jr();function nS(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 rS.YAMLParseError([a,a+1],i,o)};switch(r.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return tS.resolveFlowScalar(r,e,n);case"block-scalar":return eS.resolveBlockScalar({options:{strict:e}},r,n)}}return null}function sS(r,e){let{implicitKey:t=!1,indent:n,inFlow:s=!1,offset:i=-1,type:o="PLAIN"}=e,a=Pd.stringifyString({type:o,value:r},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:`
|
|
118
124
|
`}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
|
|
119
125
|
`),d=a.substring(0,l),u=a.substring(l+1)+`
|
|
120
|
-
`,f=[{type:"block-scalar-header",offset:i,indent:n,source:d}];return
|
|
121
|
-
`}),{type:"block-scalar",offset:i,indent:n,props:f,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:n,source:a,end:c};default:return{type:"scalar",offset:i,indent:n,source:a,end:c}}}function
|
|
126
|
+
`,f=[{type:"block-scalar-header",offset:i,indent:n,source:d}];return Od(f,c)||f.push({type:"newline",offset:-1,indent:n,source:`
|
|
127
|
+
`}),{type:"block-scalar",offset:i,indent:n,props:f,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:n,source:a,end:c};default:return{type:"scalar",offset:i,indent:n,source:a,end:c}}}function iS(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=Pd.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">":oS(r,c);break;case'"':qa(r,c,"double-quoted-scalar");break;case"'":qa(r,c,"single-quoted-scalar");break;default:qa(r,c,"scalar")}}function oS(r,e){let t=e.indexOf(`
|
|
122
128
|
`),n=e.substring(0,t),s=e.substring(t+1)+`
|
|
123
|
-
`;if(r.type==="block-scalar"){let i=r.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=n,r.source=s}else{let{offset:i}=r,o="indent"in r?r.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:n}];
|
|
124
|
-
`});for(let c of Object.keys(r))c!=="type"&&c!=="offset"&&delete r[c];Object.assign(r,{type:"block-scalar",indent:o,props:a,source:s})}}function
|
|
125
|
-
`};delete r.items,Object.assign(r,{type:t,source:e,end:[s]});break}default:{let n="indent"in r?r.indent:-1,s="end"in r&&Array.isArray(r.end)?r.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(r))i!=="type"&&i!=="offset"&&delete r[i];Object.assign(r,{type:t,indent:n,source:e,end:s})}}}
|
|
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}];Od(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 Od(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 qa(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})}}}Ls.createScalarToken=sS;Ls.resolveAsScalar=nS;Ls.setScalarValue=iS});var Rd=A(_d=>{"use strict";var aS=r=>"type"in r?Ms(r):$s(r);function Ms(r){switch(r.type){case"block-scalar":{let e="";for(let t of r.props)e+=Ms(t);return e+r.source}case"block-map":case"block-seq":{let e="";for(let t of r.items)e+=$s(t);return e}case"flow-collection":{let e=r.start.source;for(let t of r.items)e+=$s(t);for(let t of r.end)e+=t.source;return e}case"document":{let e=$s(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 $s({start:r,key:e,sep:t,value:n}){let s="";for(let i of r)s+=i.source;if(e&&(s+=Ms(e)),t)for(let i of t)s+=i.source;return n&&(s+=Ms(n)),s}_d.stringify=aS});var $d=A(Ld=>{"use strict";var Ua=Symbol("break visit"),cS=Symbol("skip children"),Nd=Symbol("remove item");function wt(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),Id(Object.freeze([]),r,e)}wt.BREAK=Ua;wt.SKIP=cS;wt.REMOVE=Nd;wt.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};wt.parentCollection=(r,e)=>{let t=wt.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 Id(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=Id(Object.freeze(r.concat([[s,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===Ua)return Ua;a===Nd&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&s==="key"&&(n=n(e,r))}}return typeof n=="function"?n(e,r):n}Ld.visit=wt});var Ds=A(ie=>{"use strict";var Ja=Cd(),lS=Rd(),uS=$d(),Ka="\uFEFF",Ha="",Wa="",Va="",fS=r=>!!r&&"items"in r,dS=r=>!!r&&(r.type==="scalar"||r.type==="single-quoted-scalar"||r.type==="double-quoted-scalar"||r.type==="block-scalar");function pS(r){switch(r){case Ka:return"<BOM>";case Ha:return"<DOC>";case Wa:return"<FLOW_END>";case Va:return"<SCALAR>";default:return JSON.stringify(r)}}function mS(r){switch(r){case Ka:return"byte-order-mark";case Ha:return"doc-mode";case Wa:return"flow-error-end";case Va:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
126
132
|
`:case`\r
|
|
127
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(r[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}
|
|
128
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
129
|
-
\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}ie.createScalarToken=Ja.createScalarToken;ie.resolveAsScalar=Ja.resolveAsScalar;ie.setScalarValue=Ja.setScalarValue;ie.stringify=lS.stringify;ie.visit=uS.visit;ie.BOM=Ka;ie.DOCUMENT=Ha;ie.FLOW_END=Wa;ie.SCALAR=Va;ie.isCollection=fS;ie.isScalar=dS;ie.prettyToken=pS;ie.tokenType=mS});var za=A(Dd=>{"use strict";var sn=Ds();function he(r){switch(r){case void 0:case" ":case`
|
|
134
|
+
`:case"\r":case" ":return!0;default:return!1}}var Md=new Set("0123456789ABCDEFabcdef"),hS=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Bs=new Set(",[]{}"),gS=new Set(` ,[]{}
|
|
135
|
+
\r `),Ya=r=>!r||gS.has(r),Ga=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
|
|
130
136
|
`?!0:t==="\r"?this.buffer[e+1]===`
|
|
131
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===`
|
|
132
138
|
`||!s&&!this.atEnd)return e+n+1}return t===`
|
|
133
|
-
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&
|
|
134
|
-
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===
|
|
139
|
+
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&he(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]===sn.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 sn.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==="...")&&he(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&&!he(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===":")&&he(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(Ya),"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("..."))&&he(s[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield sn.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(Ya),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||he(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let i=0;for(;this.buffer[t-1-i]==="\\";)i+=1;if(i%2===0)break;t=this.buffer.indexOf('"',t+1)}let n=this.buffer.substring(0,t),s=n.indexOf(`
|
|
135
141
|
`,this.pos);if(s!==-1){for(;s!==-1;){let i=this.continueScalar(s+1);if(i===-1)break;s=n.indexOf(`
|
|
136
|
-
`,i)}s!==-1&&(t=s-(n[s-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>
|
|
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=>he(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let i=this.pos;n=this.buffer[i];++i)switch(n){case" ":t+=1;break;case`
|
|
137
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===`
|
|
138
144
|
`)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let i=this.continueScalar(e+1);if(i===-1)break;e=this.buffer.indexOf(`
|
|
139
145
|
`,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let s=e+1;for(n=this.buffer[s];n===" ";)n=this.buffer[++s];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
|
|
140
146
|
`;)n=this.buffer[++s];e=s-1}else if(!this.blockScalarKeep)do{let i=e-1,o=this.buffer[i];o==="\r"&&(o=this.buffer[--i]);let a=i;for(;o===" ";)o=this.buffer[--i];if(o===`
|
|
141
|
-
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield
|
|
147
|
+
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield sn.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(he(i)||e&&Bs.has(i))break;t=n}else if(he(s)){let i=this.buffer[n+1];if(s==="\r"&&(i===`
|
|
142
148
|
`?(n+=1,s=`
|
|
143
|
-
`,i=this.buffer[n+1]):t=n),i==="#"||e&&
|
|
144
|
-
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&
|
|
149
|
+
`,i=this.buffer[n+1]):t=n),i==="#"||e&&Bs.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&&Bs.has(s))break;t=n}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield sn.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(Ya))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(he(t)||e&&Bs.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(;!he(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(hS.has(t))t=this.buffer[++e];else if(t==="%"&&Md.has(this.buffer[e+1])&&Md.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
145
151
|
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
146
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");let s=t-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=t),s}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};
|
|
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)}};Dd.Lexer=Ga});var Xa=A(Bd=>{"use strict";var Qa=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let i=t+n>>1;this.lineStarts[i]<e?t=i+1:n=i}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let s=this.lineStarts[t-1];return{line:t,col:e-s+1}}}};Bd.LineCounter=Qa});var ec=A(Jd=>{"use strict";var yS=jn("process"),jd=Ds(),bS=za();function Xe(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function Fd(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 Ud(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 js(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 Zt(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 qd(r){if(r.start.type==="flow-seq-start")for(let e of r.items)e.sep&&!e.value&&!Xe(e.start,"explicit-key-ind")&&!Xe(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Ud(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 Za=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 bS.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,yS.env.LOG_TOKENS&&console.log("|",jd.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=jd.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"&&qd(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&&Fd(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":{Fd(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=js(this.peek(2)),n=Zt(t),s;e.end?(s=e.end,s.push(this.sourceToken),delete e.end):s=[this.sourceToken];let i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
|
|
147
153
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
148
|
-
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,s=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&t.sep&&!t.value){let o=[];for(let a=0;a<t.sep.length;++a){let c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(
|
|
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(Xe(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(Ud(t.key)&&!Xe(t.sep,"newline")){let o=Zt(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(Xe(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=Zt(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]}):Xe(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&&!Xe(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||Xe(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=js(n),i=Zt(s);qd(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
|
149
155
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
150
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=
|
|
151
|
-
`),t=e.trim();if(
|
|
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=js(e),n=Zt(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=js(e),n=Zt(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())}}};Jd.Parser=Za});var Yd=A(an=>{"use strict";var Kd=Fa(),wS=Qr(),on=en(),vS=Bo(),SS=D(),kS=Xa(),Hd=ec();function Wd(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new kS.LineCounter||null,prettyErrors:e}}function xS(r,e={}){let{lineCounter:t,prettyErrors:n}=Wd(e),s=new Hd.Parser(t?.addNewLine),i=new Kd.Composer(e),o=Array.from(i.compose(s.parse(r)));if(n&&t)for(let a of o)a.errors.forEach(on.prettifyError(r,t)),a.warnings.forEach(on.prettifyError(r,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Vd(r,e={}){let{lineCounter:t,prettyErrors:n}=Wd(e),s=new Hd.Parser(t?.addNewLine),i=new Kd.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 on.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(on.prettifyError(r,t)),o.warnings.forEach(on.prettifyError(r,t))),o}function ES(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=Vd(r,t);if(!s)return null;if(s.warnings.forEach(i=>vS.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 AS(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 SS.isDocument(r)&&!n?r.toString(t):new wS.Document(r,n,t).toString(t)}an.parse=ES;an.parseAllDocuments=xS;an.parseDocument=Vd;an.stringify=AS});var zd=A(j=>{"use strict";var TS=Fa(),PS=Qr(),OS=va(),tc=en(),CS=Lr(),Ze=D(),_S=Ye(),RS=H(),NS=ze(),IS=Qe(),LS=Ds(),$S=za(),MS=Xa(),DS=ec(),Fs=Yd(),Gd=_r();j.Composer=TS.Composer;j.Document=PS.Document;j.Schema=OS.Schema;j.YAMLError=tc.YAMLError;j.YAMLParseError=tc.YAMLParseError;j.YAMLWarning=tc.YAMLWarning;j.Alias=CS.Alias;j.isAlias=Ze.isAlias;j.isCollection=Ze.isCollection;j.isDocument=Ze.isDocument;j.isMap=Ze.isMap;j.isNode=Ze.isNode;j.isPair=Ze.isPair;j.isScalar=Ze.isScalar;j.isSeq=Ze.isSeq;j.Pair=_S.Pair;j.Scalar=RS.Scalar;j.YAMLMap=NS.YAMLMap;j.YAMLSeq=IS.YAMLSeq;j.CST=LS;j.Lexer=$S.Lexer;j.LineCounter=MS.LineCounter;j.Parser=DS.Parser;j.parse=Fs.parse;j.parseAllDocuments=Fs.parseAllDocuments;j.parseDocument=Fs.parseDocument;j.stringify=Fs.stringify;j.visit=Gd.visit;j.visitAsync=Gd.visitAsync});function jS(r){try{return JSON.parse(r.trim()),!0}catch{return!1}}function FS(r){let e=r.trim();if(!e.startsWith("<"))return!1;let t=e.match(BS);return t?Cr(e,t[1])!==null:!1}function qS(r){let e=r.trim();if(!e.match(/^(---|#|\w+:|-)/)||"[{<".includes(e[0]))return!1;try{let t=Qd.parse(e);return t!==null&&typeof t=="object"}catch{return!1}}function Xd(r){return jS(r)||FS(r)||qS(r)}var Qd,BS,rc=O(()=>{au();Qd=zg(zd(),1),BS=/<([a-zA-Z_][\w.-]*)/});function US(r){if(!r?.trim())return[];let e=r.replace(/\r\n/g,`
|
|
157
|
+
`),t=e.trim();if(Xd(t))return[{text:t,startLine:1,endLine:e.split(`
|
|
152
158
|
`).length}];let n=e.split(`
|
|
153
159
|
`),s=[],i=0,o=-1,a=0,c=()=>{if(o>=i){let l=n.slice(i,o+1).join(`
|
|
154
|
-
`).trim();l&&s.push({text:l,startLine:i+1,endLine:o+1})}};for(let l=0;l<n.length;l++)n[l].trim()?(a>=2&&o>=i&&(c(),i=l),a=0,o=l):a++;return c(),s}function
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
`)
|
|
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 qs(r){return US(r).map(e=>e.text)}var Zd,ep=O(()=>{rc();Zd=`
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
`});var vt=O(()=>{Fn();go();Zl();eu();rc();ep();qn()});function er(r){return{...Gl(r),server:r.files.get("server.ts")??""}}function Us(r){return!!r.server&&!r.code}var cn=O(()=>{vt();vt()});function WS(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 tp(r){let e=[];for(let s of HS)for(let i of r.matchAll(s)){let o=WS(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 rp(r){return tp(r).map(e=>e.root)}function ln(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 KS)l.targets.includes(t)&&l.pattern.test(a)&&s.push({type:l.type,severity:"error",message:GS(l.type,c),lineNumber:c,lineContent:a})}return t==="client"&&n&&s.push(...VS(i,n)),s}function VS(r,e){let t=new Set(Object.keys(e));return tp(r.join(`
|
|
166
|
+
`)).filter(({root:n})=>!t.has(n)).map(({root:n,lineIndex:s})=>({type:"UNDECLARED_IMPORT",severity:"error",message:YS(n,s+1),lineNumber:s+1,lineContent:r[s]}))}function YS(r,e){return`Import "${r}" is not declared in config.json dependencies! Found on line ${e}.
|
|
158
167
|
|
|
159
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.
|
|
160
169
|
|
|
@@ -168,7 +177,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
168
177
|
}
|
|
169
178
|
\`\`\`
|
|
170
179
|
|
|
171
|
-
**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 GS(r,e){return r==="URL_IMPORT"?`Direct URL imports are not supported! Found on line ${e}.
|
|
172
181
|
|
|
173
182
|
**CRITICAL**: Import packages by name only. Do NOT use CDN URLs:
|
|
174
183
|
|
|
@@ -322,40 +331,58 @@ import { something } from 'module-name'
|
|
|
322
331
|
const something = require('module-name') // NOT SUPPORTED!
|
|
323
332
|
\`\`\`
|
|
324
333
|
|
|
325
|
-
**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 St,kt,KS,HS,Js=O(()=>{St=["client"],kt=["client","server"],KS=[{type:"DYNAMIC_IMPORT",pattern:/\bimport\s*\(\s*['"`]/,targets:St},{type:"COMMONJS_REQUIRE",pattern:/\brequire\s*\(\s*['"`]/,targets:kt},{type:"JS_EXTENSION_IMPORT",pattern:/from\s+['"][^'"]*\/[^'"]*\.js['"]/,targets:St},{type:"URL_IMPORT",pattern:/from\s+['"]https?:\/\//,targets:St},{type:"VERSION_SPECIFIER_IMPORT",pattern:/from\s+['"][^'"]*@[\d^~]/,targets:St},{type:"REDUNDANT_TB_DECLARATION",pattern:/declare\s+(const|var|let)\s+tb\b/,targets:kt},{type:"CONST_ENUM",pattern:/\bconst\s+enum\b/,targets:kt},{type:"NAMESPACE_DECLARATION",pattern:/\bnamespace\s+\w+/,targets:kt},{type:"COMMONJS_EXPORT_EQUALS",pattern:/\bexport\s*=/,targets:kt},{type:"COMMONJS_IMPORT_EQUALS",pattern:/\bimport\s+\w+\s*=/,targets:kt},{type:"MODULE_DECLARATION",pattern:/\bmodule\s+\w+\s*\{/,targets:kt},{type:"CSS_FILE_IMPORT",pattern:/(?:from|import)\s+['"][^'"]*\.css['"]/,targets:St},{type:"NAVIGATION",pattern:/window\.(location\.(reload|assign|replace)\s*\(|open\s*\()/,targets:St},{type:"NAVIGATION",pattern:/window\.location(\.href)?\s*=[^=]/,targets:St}],HS=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});var xp=O(()=>{});var ce,be,ir=O(()=>{ce=class extends Error{constructor(e,t="unknown",n=!1){super(e),this.code=t,this.retryable=n}},be=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=`
|
|
326
335
|
|
|
327
|
-
`){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
|
|
328
|
-
`)),!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
|
|
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 ce(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 ce(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 si,uc=O(()=>{ir();si=class extends be{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
|
+
`)),!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 ce(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(`
|
|
329
338
|
|
|
330
|
-
`)}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 or,ii=O(()=>{ir();or=class extends be{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 oi,fc=O(()=>{ii();oi=class extends or{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 ai,dc=O(()=>{ir();ai=class extends be{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(`
|
|
331
340
|
|
|
332
|
-
`);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
|
|
333
|
-
`),c={contents:o.map(d=>({role:d.role==="assistant"?"model":"user",parts:[{text:d.content}]}))};n?.webSearch!==!1&&(c.tools=[{google_search:{}}]),i&&(c.systemInstruction={role:"system",parts:[{text:i}]});let l=n?.effort;if(l!==void 0){let u={
|
|
334
|
-
`)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkAndThrowError(e),this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractParts(e).text||"",n=e.candidates?.[0]?.finishReason,s="complete";return n==="MAX_TOKENS"?s="interrupted":(n==="SAFETY"||n==="RECITATION")&&(s="failed"),{text:t,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let t=this.extractParts(e);return t.text||t.reasoning?t:null}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractParts(e){let t=e.candidates?.[0]?.content?.parts;if(!t)return{};let n="",s="";for(let i of t)i.text&&(i.thought?s+=i.text:n+=i.text);return{text:n||void 0,reasoning:s||void 0}}checkGeminiError(e){if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new
|
|
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 ci,pc=O(()=>{ir();ci=class extends be{constructor(){super(...arguments),this.providerName="Gemini",this.defaultBaseUrl="https://generativelanguage.googleapis.com",this.path="/v1beta/models",this.budgetMap={0:0,1:1024,2:8192,3:-1}}getPath(e,t){return`/v1beta/models/${e}:${t?"streamGenerateContent":"generateContent"}${t?"?alt=sse":""}`}buildHeaders(e){return{"Content-Type":"application/json","x-goog-api-key":e}}buildPayload(e,t,n,s){let{system:i,conversationMessages:o}=this.extractSystemMessages(e,`
|
|
342
|
+
`),c={contents:o.map(d=>({role:d.role==="assistant"?"model":"user",parts:[{text:d.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 d=this.geminiVersion(t),u=d!==null&&d>=3?{thinkingLevel:this.thinkingLevelFor(d,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 ce(`Prompt blocked: ${t}`)}}}});var li,mc=O(()=>{ii();li=class extends or{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 Tt(r){let e=wk.get(r);if(!e)throw new Error(`Unsupported protocol: ${r}`);return e}function vk(r,e){return r.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function hc(r,e){let t=Tt(r.protocol),n=t.getPath(r.model,e.stream),s=vk(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 Sk(r){return/prompt is too long|context[_ ](length|window)|maximum context|token count exceeds|too many tokens/i.test(r)}async function ar(r,e){let t=Tt(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||Sk(s))&&(o="context_exceeded"),{code:o,message:s,retryable:i===429||i>=500}}var Ep,wk,gc=O(()=>{uc();fc();dc();pc();mc();Ep=new li,wk=new Map([["openai",new si],["openrouter",new oi],["anthropic",new ai],["gemini",new ci],["ollama",Ep],["openai-compat",Ep]])});function Ap(r){let e=r.indexOf(`\r
|
|
335
344
|
\r
|
|
336
345
|
`),t=r.indexOf(`
|
|
337
346
|
|
|
338
|
-
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function
|
|
339
|
-
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
347
|
+
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function yc(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*Tp(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=yc(s);u!==null&&u!=="done"&&(yield u)}return}t?.(),s+=n.decode(c,{stream:!0});let{pos:l,len:d}=Ap(s);for(;l!==-1;){let u=s.slice(0,l);s=s.slice(l+d);let f=yc(u);if(f==="done")return;f!==null&&(yield f),{pos:l,len:d}=Ap(s)}}}finally{i&&e?.removeEventListener("abort",i);try{await r.cancel()}catch{}}}async function Pt(r,e){if(!r.body)throw new Error("Response body is missing");let t="";for await(let n of Ot(r,e))n.kind==="text"&&(t+=n.text);return t}async function*Ot(r,e){let t=e??(r.headers.get("X-Provider-Protocol")||"openai"),n=Tt(t);if(!r.body)return;let s=r.body.getReader();for await(let i of Tp(s)){let o=n.parseStreamChunk(i);o?.reasoning&&(yield{kind:"reasoning",text:o.reasoning}),o?.text&&(yield{kind:"text",text:o.text})}}var Pp=O(()=>{gc()});import{strToU8 as kk,strFromU8 as xk,deflateSync as Ek,inflateSync as Ak}from"fflate";function wc(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
|
+
|
|
350
|
+
---
|
|
351
|
+
Instructions:
|
|
352
|
+
${r.infer||"Process the data and return a JSON object."}`),r.insight&&t.push(`---
|
|
353
|
+
Example output:
|
|
354
|
+
${r.insight}`),r.code&&t.push(`---
|
|
355
|
+
Code that will consume your output:
|
|
356
|
+
${r.code}`),e.length>0){let n=e.length===1?e[0]:e.map((s,i)=>`[Chunk ${i+1}]
|
|
357
|
+
${s}`).join(`
|
|
358
|
+
|
|
359
|
+
`);t.push(`---
|
|
360
|
+
Data to process:
|
|
361
|
+
<data>
|
|
362
|
+
${n}
|
|
363
|
+
</data>`)}return t.push(`
|
|
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
|
+
|
|
366
|
+
`)}function yn(r){try{return JSON.parse(r)}catch{return null}}function Pk(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 Ok(r){let e=Pk(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 Ck(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 _k(r){let e=null,t=0;for(;t<r.length;){let n=r[t];if(n==="{"||n==="["){let s=Ck(r,t);if(s!==-1){let i=r.slice(t,s+1),o=yn(i);o!==null&&(e={parsed:o,json:i}),t=s+1;continue}}t++}return e}function vc(r){let e=[],t=r.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*\n?/,"").replace(/\n?```\s*$/,""),e.push("markdown fences"));let n=yn(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=yn(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=yn(t),n!==null))return{parsed:n,json:t,fixesApplied:e}}for(let[o,a]of Tk){let c=a(t);if(c!==null){let l=yn(c);if(l!==null)return{parsed:l,json:c,fixesApplied:[...e,o]}}}let i=_k(r);return i!==null?{...i,fixesApplied:[...e,"extracted last JSON value"]}:{parsed:null,json:t,fixesApplied:e}}function Sc(r){try{let e={i:r.insight,d:r.data},t=JSON.stringify(e),n=Ek(kk(t),{level:9}),s=Nk(n),i=`${Op}:${s}`;return i.length>Rk?"":"#"+bc+i}catch{return""}}function kc(r){try{let e=r.startsWith("#")?r.slice(1):r;if(!e.startsWith(bc))return null;let t=e.slice(bc.length),n=t.indexOf(":");if(n===-1||t.slice(0,n)!==Op)return null;let s=Ik(t.slice(n+1)),i=JSON.parse(xk(Ak(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 Nk(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 Ik(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 Tk,bc,Op,Rk,Cp=O(()=>{Tk=[["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",Ok]];bc="tb=",Op="1",Rk=6e4});var cr=O(()=>{xp();ir();gc();Pp();Cp();ii();dc();pc();uc();fc();mc()});function ur(r){return(r.includes("://")?r:`http://${r}`).replace(/\/+$/,"")}function xc(){return wn}async function Me(){let[r,e]=await Promise.all([Rp(),Bk()]);return[...jk(e),...r]}async function _p(){let r;try{r=await fetch(Lk,{signal:AbortSignal.timeout(Mk)})}catch(e){return wn=`catalog fetch failed: ${e?.message??e}`,null}if(!r.ok)return wn=`catalog fetch failed: HTTP ${r.status}`,null;try{return await r.json()}catch(e){return wn=`catalog returned an unreadable body: ${e?.message??e}`,null}}async function Bk(){if(bn&&Date.now()-bn.fetchedAt<=$k)return bn.models;let r=await _p()??await _p();return r?(bn={models:r,fetchedAt:Date.now()},wn=null,r):bn?.models??[]}async function Rp(){if(ui&&Date.now()-ui.fetchedAt<=Dk)return ui.models;let r=ur(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 ui={models:e,fetchedAt:Date.now()},e}function jk(r){let e=new Set(Object.entries(lr).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function Ec(){return Object.values(lr).some(r=>!!process.env[r])}async function fi(){return Ec()||process.env.TB_AI_BASE_URL?!0:(await Rp()).length>0}function Np(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 lr,Lk,$k,Mk,Dk,bn,ui,wn,Ct=O(()=>{lr={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};Lk="https://api.typebulb.com/api/models",$k=1440*60*1e3,Mk=5e3,Dk=60*1e3,bn=null,ui=null,wn=null});function De(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=Tt(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${ur(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=lr[t];if(!i)return`Unknown provider '${t}'.`;let o=process.env[i];return o?{apiKey:o,baseUrl:s.defaultBaseUrl,protocol:t,model:n,isFreeModel:!1}:`No API key for '${t}'. Set ${i} in your .env file.`}function st(r,e){let t=[...e.system?[{role:"system",content:e.system}]:[],...e.messages.map(s=>({role:s.role,content:s.content}))],n=e.effort;return hc(r,{messages:t,stream:!0,effort:n!=null&&n>=0&&n<=3?n:void 0,webSearch:e.webSearch??!0,signal:e.signal})}var di=O(()=>{cr();Ct()});import{realpathSync as Jk}from"fs";import{join as Pc,resolve as Kk}from"path";import{homedir as Hk}from"os";function pi(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?Pc(r,".."):Pc(Hk(),".typebulb")}function je(){return process.env.TYPEBULB_SERVERS_DIR||Pc(pi(),"servers")}function X(r){let e=Kk(r),t=e;try{t=Jk.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function Mp(r,e){let t=X(r),n=X(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var mi=O(()=>{});import{readFileSync as Wk,writeFileSync as Vk,mkdirSync as Yk}from"fs";import{join as Gk}from"path";function Dp(){return Gk(pi(),"trust.json")}function Oc(){try{let r=JSON.parse(Wk(Dp(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function zk(r){Yk(pi(),{recursive:!0}),Vk(Dp(),JSON.stringify([...r]))}function _t(r){return Oc().has(X(r))}function fr(r,e){let t=Oc(),n=X(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),zk(t))}function Cc(){return[...Oc()]}var Sn=O(()=>{mi()});function Ae(r){return r.length>5e4?r.slice(0,5e4)+`
|
|
368
|
+
\u2026[${r.length-5e4} more characters truncated]`:r}function Fe(r){let e=r.replace(Qk,"").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 Qk,hi,gi=O(()=>{Qk=/\u001b\[[0-9;]*m/g;hi=(r,e)=>``});import{existsSync as Xk,readdirSync as Zk,statSync as ex}from"fs";import{join as tx}from"path";function yi(r){if(!Xk(r))return[];let e;try{e=Zk(r)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(".jsonl"))continue;let s=tx(r,n);try{let i=ex(s);i.isFile()&&t.push({sessionId:n.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var _c=O(()=>{});var dr,Rc=O(()=>{dr=class{ensureHarnessSupport(){}}});import{openSync as rx,readSync as nx,closeSync as sx,statSync as ix,readdirSync as ox,readFileSync as ax,existsSync as cx}from"fs";import{join as xn}from"path";import{homedir as Lc}from"os";function lx(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function bi(r){let e=r?.type==="image"?r.source:void 0;return e?.type==="base64"&&e.data?hi(e.data,e.media_type):""}function Nc(r){return typeof r=="string"?Ae(r):Array.isArray(r)?r.map(e=>{if(typeof e=="string")return Ae(e);let t=e;return typeof t?.text=="string"?Ae(t.text):t?.content!=null?Nc(t.content):bi(t)}).join(`
|
|
370
|
+
`):r==null?"":Ae(JSON.stringify(r))}function fx(r){let e=r.trim();return!!e&&qp.some(t=>t.test(e))}function dx(r){let e=r.trim();return e?qp.some(t=>{let n=t.exec(e);return!!n&&n.index===0}):!0}function mx(r){return r.replace(px,"")}function hx(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 ot(r){let e=mx(r).trim();return e?hx(e)??(fx(e)?"":e):""}function Ic(r){return r?.type==="text"&&typeof r.text=="string"?ot(r.text):""}function $c(r,e){if(typeof r=="string")return Fe(r);if(!r||typeof r!="object")return Fe(e);let t=r;if(t.type==="text"&&typeof t.file?.numLines=="number")return ve(t.file.numLines,"line");if(t.type==="image"){let n=jp(t.file?.originalSize);return n?`image (${n})`:"image"}if(t.type==="pdf"){let n=jp(t.file?.originalSize);return n?`PDF (${n})`:"PDF"}if(t.type==="parts"&&typeof t.file?.count=="number")return ve(t.file.count,"page");if(t.type==="file_unchanged")return"unchanged since last read";if(t.type==="create"&&typeof t.content=="string")return`created, ${ve(t.content.split(`
|
|
371
|
+
`).length,"line")}`;if(t.mode==="content")return ve(t.numLines??0,"line");if(t.mode==="count")return`${ve(t.numMatches??0,"match","matches")} (${ve(t.numFiles??0,"file")})`;if(t.mode==="files_with_matches")return ve(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":Fe(t.stdout||t.stderr||"")||"no output":typeof t.code=="number"&&typeof t.codeText=="string"?`${t.code} ${t.codeText}`:typeof t.searchCount=="number"?ve(t.searchCount,"search","searches"):Array.isArray(t.matches)&&typeof t.total_deferred_tools=="number"?ve(t.matches.length,"tool"):Array.isArray(t.newTodos)?ve(t.newTodos.length,"todo"):typeof t.numFiles=="number"?ve(t.numFiles,"file"):Fe(e)}function kn(r){return!!r.isSidechain||!!r.isMeta}function gx(r){let e;try{e=rx(r,"r")}catch{return""}try{let n=65536;try{n=ix(r).size}catch{}let s=(l,d)=>{if(d<=0)return"";let u=Buffer.alloc(d),f=nx(e,u,0,d,l);return u.subarray(0,f).toString("utf8")},i=(l,d,u)=>{let f="";for(let p of l.split(`
|
|
372
|
+
`)){if(!p.includes(`"${d}"`))continue;let b;try{b=JSON.parse(p)}catch{continue}let h=b?.[u];b?.type===d&&typeof h=="string"&&h&&(f=h)}return f},o=s(0,Math.min(65536,n)),a=n>65536?s(n-65536,65536):"",c=i(a,"custom-title","customTitle")||i(o,"custom-title","customTitle")||i(a,"ai-title","aiTitle")||i(o,"ai-title","aiTitle");if(c)return c.replace(/\s+/g," ").trim().slice(0,200);for(let l of o.split(`
|
|
373
|
+
`)){if(!l.trim())continue;let d;try{d=JSON.parse(l)}catch{continue}if(!d||kn(d)||d.type!=="user")continue;let u=d.message?.content,f="";typeof u=="string"?f=ot(u):Array.isArray(u)&&(f=u.map(Ic).filter(Boolean).join(" "));let p=f.replace(/\s+/g," ").trim();if(p)return(p.replace(/^Continuing from a prior session\. Here is the summary of our work so far:\s*/i,"").trim()||p).slice(0,200)}return""}finally{sx(e)}}function yx(r){let e;try{e=ox(Fp)}catch{return!1}for(let t of e)if(t.endsWith(".json"))try{let n=JSON.parse(ax(xn(Fp,t),"utf8"));if(n?.sessionId!==r)continue;return process.kill(n.pid,0),!0}catch{}return!1}var ux,Bp,qp,px,ve,jp,Fp,pr,wi=O(()=>{gi();_c();Rc();ux=xn(Lc(),".claude","projects"),Bp=r=>xn(ux,lx(r));qp=[/\[Request interrupted by user\b/i,/\[Tool use was interrupted\]/i,/Claude Code returned an error/i,/\[ede_diagnostic\]/i,/^No response requested\.?$/i,/^<task-notification\b/i,/^<system-reminder\b/i,/^<local-command-stdout\b/i,/^<local-command-stderr\b/i];px=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;ve=(r,e,t=e+"s")=>`${r} ${r===1?e:t}`,jp=r=>typeof r!="number"?"":r<1024?`${r}B`:r<1048576?`${Math.round(r/1024)}KB`:`${(r/1048576).toFixed(1)}MB`;Fp=xn(Lc(),".claude","sessions");pr=class extends dr{displayName="Claude Mirror";detectsSelf(){return process.env.CLAUDECODE==="1"}detectsInstalled(){return cx(xn(Lc(),".claude"))}sessionsDir(e){return Bp(e)}listSessionFiles(e){return yi(Bp(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(kn(e))return{events:[]};let n=[];if(e.type==="user"){let s=e.message?.content;if(typeof s=="string"){let i=ot(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=Nc(i.content);n.push({type:"tool_result",id:i.tool_use_id??"",content:o,isError:!!i.is_error,digest:$c(e.toolUseResult,o)})}else{let o=Ic(i)||bi(i);o&&n.push({type:"user",text:o})}return{events:n}}if(e.type==="attachment"&&e.attachment?.type==="queued_command"){let s=ot(Nc(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=>!dx(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??""),f=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:f})}let l=e.message?.usage??e.usage,d=l&&{in:l.input_tokens??0,out:l.output_tokens??0,cached:l.cache_read_input_tokens??0,cacheCreate:l.cache_creation_input_tokens??0};return{events:n,usage:d,model:e.message?.model}}return{events:n}}chainWorking(e){let t;for(let o of e)(o.type==="user"||o.type==="assistant")&&(t=o);if(!t)return!1;if(t.type==="user"){try{let o=t.message?.content,a=typeof o=="string"?o:Array.isArray(o)?o.filter(l=>l&&l.type==="text").map(l=>l.text??"").join(""):"";if(!(Array.isArray(o)&&o.some(l=>l&&l.type==="tool_result"))&&a.trim()&&ot(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 yx(e)}readPreview(e){return gx(e)}searchText(e){if(!e||kn(e)||e.type!=="user"&&e.type!=="assistant")return"";let t=e.message?.content,n="";if(typeof t=="string")n=ot(t);else if(Array.isArray(t)){let s=t;n=e.type==="user"?s.map(Ic).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 Up}from"child_process";import{readdir as bx,readFile as Kp,writeFile as Hp,unlink as Mc,mkdir as wx}from"fs/promises";import{mkdirSync as Wp,writeFileSync as vi,appendFileSync as vx,readFileSync as Dc}from"fs";import*as fe from"path";import{fileURLToPath as Sx}from"url";function Bc(r){return fe.join(je(),`${r}.json`)}function An(r){return fe.join(je(),`${r}.log`)}function jc(r){return fe.join(je(),`${r}.wait.json`)}function Vp(r){try{let e=JSON.parse(Dc(jc(r),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function Fc(r,e=""){let t=Vp(r)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Si(r,e,t=""){try{Wp(je(),{recursive:!0});let n=Vp(r);n[t]=e,vi(jc(r),JSON.stringify({cursors:n}))}catch{}}function ki(r){let e=An(r);try{Wp(je(),{recursive:!0}),vi(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(vx(e,c),s+=c.length,s>2*Jp){let l=Dc(e),d=l.subarray(Math.max(0,l.length-Jp));vi(e,d),s=d.length}}catch{i=!0}};return process.stdout.write=((a,...c)=>(o(a),t(a,...c))),process.stderr.write=((a,...c)=>(o(a),n(a,...c))),()=>{process.stdout.write=t,process.stderr.write=n}}function Yp(r){try{vi(An(r),"")}catch{}}function Te(r,e=0){try{let t=Dc(An(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 qc(r){return`\u2500\u2500 run ${r} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function xx(r){let e=kx.exec(r);return e?Number(e[1]):void 0}function Gp(r,e){let t=r.split(`
|
|
375
|
+
`),n=[];if(t.forEach((o,a)=>{let c=xx(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 Uc(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function zp(r){await wx(je(),{recursive:!0}),await Hp(Bc(r.pid),JSON.stringify(r))}async function Qp(r,e){let t=Bc(r);try{let n=JSON.parse(await Kp(t,"utf8"));if(n.denied===e)return;n.denied=e,await Hp(t,JSON.stringify(n))}catch{}}async function En(r){await Mc(Bc(r)).catch(()=>{}),await Mc(An(r)).catch(()=>{}),await Mc(jc(r)).catch(()=>{})}async function W(r){let e;try{e=await bx(je())}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 Kp(fe.join(je(),s),"utf8"))}catch{await En(i);return}o&&typeof o.pid=="number"&&Uc(o.pid)?t.push(o):await En(i)})),(r?t.filter(s=>s.agent==null&&Mp(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function Jc(r,e){let t=X(r);return(await W()).find(n=>n.cwd!=null&&X(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function Rt(r){try{process.kill(r,"SIGTERM")}catch{}await En(r)}function mr(r,e){let t=X(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&X(n.file)===t)}async function Kc(r){let e=mr(await W(),r);for(let t of e)await Rt(t.pid);return e}function Ax(r,e,t){(process.platform==="win32"?Up("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):Up(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function Xp(){return fe.join(fe.dirname(Sx(import.meta.url)),"index.js")}function Tx(r,e={}){return{command:process.execPath,args:[Xp(),...e.trust?["--trust"]:[],r,...e.open===!1?["--no-open"]:[]]}}function Px(r){return{command:process.execPath,args:[Xp(),`agent:${r}`,"--no-open"]}}async function Zp(r,e,t,n){let s=await r();if(s)return s;Ax(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await Ex(150);let o=await r();if(o)return o}throw new Error(`Launched ${n} but it did not register within 20s.`)}async function xi(r,e={}){let t=e.cwd??process.cwd(),n=fe.resolve(t,r);return await Kc(n),Zp(async()=>mr(await W(),n)[0],Tx(r,e),t,fe.basename(r))}async function em(r,e=process.cwd()){return Zp(()=>Jc(e,r),Px(r),e,`the ${r} mirror`)}var Jp,kx,Ex,Pe=O(()=>{mi();Jp=1e6;kx=/^── run (\d+) ── /;Ex=r=>new Promise(e=>setTimeout(e,r))});function Ei(r){let e=/^---[^\n]*\n([\s\S]*?)\n---/.exec(r),t=e?/^\s*name:\s*(.+?)\s*$/m.exec(e[1]):null;return t?t[1].replace(/^["']|["']$/g,""):void 0}function Hc(r){return(Ei(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var Wc=O(()=>{});import{readdirSync as Ox,readFileSync as Cx,statSync as _x}from"fs";import{join as tm,basename as Rx}from"path";function rm(r,e,t){if(e>8)return t;let n;try{n=Ox(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;rm(tm(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(tm(r,s.name));return t}function Ai(r){return rm(r,0,[]).map(e=>{let t=0;try{t=_x(e).mtimeMs}catch{}let n,s=!1;try{let i=Cx(e,"utf8");n=Ei(i.slice(0,1024));let o=Re(i);s=!!o&&Us(er(o))}catch{}return{path:e,name:n??Rx(e).replace(/\.bulb\.md$/,""),mtime:t,serverOnly:s}})}var nm=O(()=>{vt();cn();Wc()});function hr(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 Ti=O(()=>{});import{readFile as Nx}from"fs/promises";async function Vc(r){try{let e=Re(await Nx(r,"utf-8"));return e?hr(er(e)):void 0}catch{return}}var sm=O(()=>{cn();Ti()});function Yc(r){let e=Re(r);if(!e)return r;let t=e.files.get("code.tsx");if(!t)return r;let n=rp(t);if(!n.length)return r;let s=e.files.get("config.json"),i={};if(s)try{let l=JSON.parse(s);l&&typeof l=="object"&&(i=l)}catch{}let o=i.dependencies&&typeof i.dependencies=="object"?{...i.dependencies}:{},a=n.filter(l=>!(l in o));if(!a.length)return r;for(let l of a)o[l]="latest";i.dependencies=o;let c={name:e.frontmatter.name};for(let[l,d]of e.files){let u=Kl(l);u&&(c[u]=d)}return c.config=JSON.stringify(i,null,2),Xl(c)}var im=O(()=>{vt();Js()});import{spawn as om}from"child_process";import{basename as Ix}from"path";function Lx(){return process.env.TYPEBULB_EDITOR||"code"}function Mx(r,e,t){return t==null?[e]:$x.test(Ix(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function Dx(r,e){let t=Lx();return{command:t,args:Mx(t,r,e)}}function Gc(r,e){let{command:t,args:n}=Dx(r,e),s=process.platform==="win32"?om("cmd.exe",["/d","/s","/c",t,...n],{detached:!0,stdio:"ignore",windowsHide:!0}):om(t,n,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var $x,am=O(()=>{$x=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as Bx,existsSync as jx}from"fs";import*as Nt from"path";import{fileURLToPath as Fx}from"url";function cm(){let r=Nt.dirname(Fx(import.meta.url));for(;!jx(Nt.join(r,"package.json"));){let e=Nt.dirname(r);if(e===r)break;r=e}return r}function It(){return Nt.join(cm(),"README.md")}function gr(){return Nt.join(cm(),"description.md")}function qx(r){let e=Bx(gr(),"utf8").trim().replace(/\s+/g," ");return`---
|
|
350
377
|
name: typebulb
|
|
351
378
|
description: ${JSON.stringify(e)}
|
|
352
379
|
version: ${r}
|
|
353
|
-
---`}function
|
|
380
|
+
---`}function Ux(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 lm(r,e){return`${qx(e)}
|
|
354
381
|
|
|
355
|
-
${
|
|
382
|
+
${Ux(e)}
|
|
356
383
|
|
|
357
384
|
${r.trim()}
|
|
358
|
-
`}var
|
|
385
|
+
`}var Pi=O(()=>{});var yr=O(()=>{Pe();nm();sm();Wc();im();am();Sn();Ct();Ct();di();Pi()});import{copyFileSync as Jx,existsSync as um,mkdirSync as fm,rmSync as Kx,writeFileSync as Hx}from"fs";import{homedir as Wx}from"os";import*as Oe from"path";import{fileURLToPath as Vx}from"url";function Zx(){return Xx.replace('"__TB_DESCRIPTION_PATH__"',JSON.stringify(gr())).replace('"__TB_README_PATH__"',JSON.stringify(It()))}function dm(){try{if(!um(Oi()))return}catch{return}try{let r=Yx();fm(Oe.dirname(r),{recursive:!0}),Hx(r,Zx()),Kx(Gx(),{force:!0})}catch{}try{let r=zx();if(!um(r))return;let e=Qx();fm(Oe.dirname(e),{recursive:!0}),Jx(r,e)}catch{}}var Oi,Yx,Gx,zx,Qx,Xx,pm=O(()=>{yr();Oi=()=>Oe.join(Wx(),".pi","agent"),Yx=()=>Oe.join(Oi(),"extensions","typebulb.ts"),Gx=()=>Oe.join(Oi(),"extensions","typebulb-wait.ts"),zx=()=>Oe.join(Oe.dirname(Vx(import.meta.url)),"agents","pi","matchu-patchu.ts"),Qx=()=>Oe.join(Oi(),"extensions","matchu-patchu.ts"),Xx=String.raw`// Generated by typebulb — do not edit; overwritten on each run.
|
|
359
386
|
import { spawn } from "node:child_process";
|
|
360
387
|
import { existsSync } from "node:fs";
|
|
361
388
|
|
|
@@ -504,29 +531,30 @@ export default function (pi) {
|
|
|
504
531
|
try { pi.on("session_shutdown", () => { for (const c of pending) { try { c.kill(); } catch (e) {} } pending.clear(); }); } catch (e) {}
|
|
505
532
|
} catch (e) { logErr("load", e && e.message); }
|
|
506
533
|
}
|
|
507
|
-
`});function q(r){return r?.message??String(r)}var
|
|
508
|
-
`))>=0;){let o=n.slice(0,i);n=n.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var
|
|
509
|
-
`)}catch{}await Promise.race([this.#v,
|
|
510
|
-
`)}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"?
|
|
534
|
+
`});function q(r){return r?.message??String(r)}var V,at=O(()=>{V=process.cwd()});import{spawn as mm}from"child_process";import{StringDecoder as e0}from"string_decoder";function c0(r,e){let t=new e0("utf8"),n="";r.on("data",s=>{n+=typeof s=="string"?s:t.write(s);let i;for(;(i=n.indexOf(`
|
|
535
|
+
`))>=0;){let o=n.slice(0,i);n=n.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var t0,r0,hm,n0,s0,i0,o0,a0,Ci,_i,gm,ym=O(()=>{at();t0=3e4,r0=5e3,hm=2e3,n0=2e3,s0=12e4,i0=8e3,o0=15e3,a0=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"]),Ci=new Set;process.on("exit",()=>{for(let r of Ci)try{r.kill()}catch{}});_i=class{#e;#a=!1;#c=0;#i=!1;#l=null;#m=null;#t=null;#n=null;#u=new Map;#r=[];#h=null;#w=null;#g=null;#f;#d;#y="";#A=1;#s=new Map;#v;#b;constructor(e,t,n=(s,i)=>mm(s,{cwd:i,shell:!0,stdio:["pipe","pipe","pipe"],env:{...process.env,TYPEBULB_MIRROR:"1"}})){if(this.#v=new Promise(o=>{this.#b=o}),t?.includes('"')){this.#d="session path contains a quote \u2014 cannot drive it",this.#b();return}let s=t?`pi --mode rpc --session "${t}"`:"pi --mode rpc",i;try{i=n(s,e)}catch(o){this.#d=`could not start pi: ${q(o)}`,this.#b();return}this.#e=i,this.#f=t,Ci.add(i),i.stdout&&c0(i.stdout,o=>this.#T(o)),i.stderr&&i.stderr.on("data",o=>{this.#y=(this.#y+o.toString()).slice(-n0)}),i.on("error",o=>this.#x(`could not start pi: ${o.message}`)),i.on("exit",o=>{this.#e===i&&this.#x(o?`pi exited (code ${o})${this.#y.trim()?`: ${this.#y.trim()}`:""}`:"pi exited"),Ci.delete(i),this.#b()}),this.#o({type:"get_state"}).then(o=>{let a=o.data?.sessionFile;typeof a=="string"&&a&&(this.#f=a);let c=o.data?.model;c&&typeof c.id=="string"&&c.id&&(this.#g=c.id)}).catch(()=>{}),this.#S()}get streaming(){return this.#a||Date.now()<this.#c}get draft(){return this.#l}get echo(){return this.#m}get queue(){return this.#h}get stats(){return this.#w}get model(){return this.#g}get sessionFile(){return this.#f}get error(){return this.#d}get status(){if(this.#t)return this.#t;if(this.#n){if(Date.now()<this.#n.until)return{text:this.#n.text,kind:this.#n.kind};this.#n=null}return this.#u.size?{text:[...this.#u.values()].join(" \xB7 "),kind:"info"}:null}get dialog(){let e=Date.now();for(;this.#r.length;){let t=this.#r[0];if(e<t.until)return t.req;this.#r.shift(),t.ownTimeout||this.#k({type:"extension_ui_response",id:t.req.id,cancelled:!0})}return null}notice(e,t){this.#p(e,t)}respondUi(e,t){let n=this.#r.findIndex(o=>o.req.id===e);if(n<0)return{ok:!1,error:"dialog expired or already answered"};let[s]=this.#r.splice(n,1),i={type:"extension_ui_response",id:e};return t.cancelled?i.cancelled=!0:s.req.method==="confirm"?i.confirmed=!!t.confirmed:i.value=t.value??"",this.#k(i),{ok:!0}}async rpc(e){if(!a0.has(e.type))return{ok:!1,error:`command not allowed: ${e.type}`};try{let t=await this.#o(e);if(t.success&&e.type==="set_model"){let n=t.data?.id;typeof n=="string"&&n&&(this.#g=n)}if(t.success&&(e.type==="fork"||e.type==="clone")){try{let s=(await this.#o({type:"get_state"})).data?.sessionFile;typeof s=="string"&&s&&(this.#f=s)}catch{}return{ok:!0,data:{...t.data??{},sessionFile:this.#f}}}return t.success?{ok:!0,data:t.data}:{ok:!1,error:t.error??`pi rejected ${e.type}`}}catch(t){return{ok:!1,error:q(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:q(o)}}return i.success&&!n&&(this.#c=Date.now()+r0),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"})+`
|
|
536
|
+
`)}catch{}await Promise.race([this.#v,gm(hm)])}try{e.stdin?.end()}catch{}if(await Promise.race([this.#v,gm(hm)]),e.exitCode===null&&!e.killed)if(process.platform==="win32"&&e.pid)try{mm("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}else try{e.kill("SIGKILL")}catch{}Ci.delete(e),this.#r=[],this.#E("pi was shut down")}}#k(e){try{this.#e?.stdin?.write(JSON.stringify(e)+`
|
|
537
|
+
`)}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"?i0:o0)})}#S(){this.#o({type:"get_session_stats"}).then(e=>{if(!e.success||!e.data)return;let t=e.data;this.#w={cost:typeof t.cost=="number"?t.cost:0,contextTokens:typeof t.contextUsage?.tokens=="number"?t.contextUsage.tokens:null,contextPercent:typeof t.contextUsage?.percent=="number"?t.contextUsage.percent:null}}).catch(()=>{})}#o(e){let t=this.#e;if(!t?.stdin?.writable)return Promise.reject(new Error(this.#d??"pi is not running"));let n=`tb-${this.#A++}`;return new Promise((s,i)=>{let o=setTimeout(()=>{this.#s.delete(n),i(new Error("pi did not respond (30s)"))},t0);o.unref?.(),this.#s.set(n,{resolve:s,timer:o});try{t.stdin.write(JSON.stringify({id:n,...e})+`
|
|
511
538
|
`)}catch(a){clearTimeout(o),this.#s.delete(n),i(new Error(q(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(`
|
|
512
|
-
`)};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??
|
|
513
|
-
`),c=i.filter(f=>f.type==="toolCall").map(f=>({id:f.id??"",name:f.name??"",input:f.arguments??{}}));if(o||a||c.length){let f=Date.parse(e.timestamp??""),p=!isNaN(f)&&f>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:p})}let l=s.usage,d=l?(l.input??0)+(l.output??0)+(l.cacheRead??0)+(l.cacheWrite??0):0,u=l&&d>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)
|
|
514
|
-
`))if(p.includes('"session_info"'))try{let
|
|
515
|
-
`))if(!(l||!u.includes('"type"')))try{let f=JSON.parse(u);f?.type==="message"&&f.message?.role==="user"&&(l=this.contentText(f.message.content).replace(/\s+/g," ").trim())}catch{}let d=c(a)||c(o)||l;return d?d.slice(0,200):""}finally{
|
|
516
|
-
`):""}}});var
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
`).
|
|
521
|
-
`)){
|
|
522
|
-
`)){if(!
|
|
523
|
-
`)){let
|
|
524
|
-
`)}function
|
|
539
|
+
`)};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??s0),ownTimeout:s!==void 0})}else if(n==="notify"){let s=t.notifyType==="warning"?"warning":t.notifyType==="error"?"error":"info";this.#p(String(t.message??""),s),console.log(`[composer] pi extension: ${String(t.message??"")}`)}else if(n==="setStatus"){let s=String(t.statusKey??"");typeof t.statusText=="string"&&t.statusText?this.#u.set(s,t.statusText):this.#u.delete(s)}return}default:return}}#x(e){this.#d=e,this.#a=!1,this.#c=0,this.#i=!1,this.#l=null,this.#m=null,this.#t=null,this.#n=null,this.#u.clear(),this.#r=[],this.#h=null,this.#w=null,this.#g=null,this.#e=void 0,this.#E(e)}#E(e){for(let[,t]of this.#s)clearTimeout(t.timer),t.resolve({type:"response",success:!1,error:e});this.#s.clear()}},gm=r=>new Promise(e=>{setTimeout(e,r).unref?.()})});import{existsSync as bm,readFileSync as l0,realpathSync as u0}from"fs";import{join as Lt,dirname as km,resolve as f0}from"path";import{homedir as wm}from"os";function p0(r,e){let t=Lt(r,".pi");if(d0.some(s=>bm(Lt(t,s))))return!0;let n=Lt(e,".agents","skills");for(let s=r;;){let i=Lt(s,".agents","skills");if(i!==n&&bm(i))return!0;let o=km(s);if(o===s)return!1;s=o}}function m0(r,e){for(let t=e;;){if(r[t]===!0||r[t]===!1)return!0;let n=km(t);if(n===t)return!1;t=n}}function xm(r,e){try{let t=e?.agentDir??Lt(wm(),".pi","agent"),n=vm(e?.home??process.env.HOME??wm()),s=vm(f0(r));if(!p0(s,n))return null;let i=Sm(Lt(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||m0(Sm(Lt(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 d0,vm,Sm,Em=O(()=>{d0=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],vm=r=>{try{return u0(r)}catch{return r}},Sm=r=>{try{return JSON.parse(l0(r,"utf8"))}catch{return{}}}});import{statSync as h0,openSync as g0,readSync as y0,closeSync as b0,existsSync as w0}from"fs";import{join as zc}from"path";import{homedir as Tm}from"os";function S0(r){return`--${r.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function Am(r){return r.type==="message"?k0(r.message?.role):r.type==="custom_message"?r.display!==!1:!1}var v0,k0,br,Qc=O(()=>{gi();_c();Rc();pm();ym();Em();v0=zc(Tm(),".pi","agent","sessions");k0=r=>r==="user"||r==="assistant"||r==="toolResult"||r==="bashExecution";br=class extends dr{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}detectsInstalled(){return w0(zc(Tm(),".pi","agent"))}ensureHarnessSupport(){dm()}createDriver(e,t){let n=new _i(e,t),s=xm(e);return s&&n.notice(s,"warning"),n}sessionsDir(e){return zc(v0,S0(e))}listSessionFiles(e){return yi(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 Am(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:Fe(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(f=>f.type==="text").map(f=>f.text??"").join(""),a=i.filter(f=>f.type==="thinking").map(f=>f.thinking??"").join(`
|
|
540
|
+
`),c=i.filter(f=>f.type==="toolCall").map(f=>({id:f.id??"",name:f.name??"",input:f.arguments??{}}));if(o||a||c.length){let f=Date.parse(e.timestamp??""),p=!isNaN(f)&&f>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:p})}let l=s.usage,d=l?(l.input??0)+(l.output??0)+(l.cacheRead??0)+(l.cacheWrite??0):0,u=l&&d>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)Am(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=g0(e,"r")}catch{return""}try{let s=65536;try{s=h0(e).size}catch{}let i=(u,f)=>{let p=Buffer.alloc(f),b=y0(t,p,0,f,u);return p.subarray(0,b).toString("utf8")},o=i(0,Math.min(65536,s)),a=s>65536?i(s-65536,65536):"",c=u=>{let f="";for(let p of u.split(`
|
|
541
|
+
`))if(p.includes('"session_info"'))try{let b=JSON.parse(p);b?.type==="session_info"&&typeof b.name=="string"&&b.name&&(f=b.name)}catch{}return f},l="";for(let u of o.split(`
|
|
542
|
+
`))if(!(l||!u.includes('"type"')))try{let f=JSON.parse(u);f?.type==="message"&&f.message?.role==="user"&&(l=this.contentText(f.message.content).replace(/\s+/g," ").trim())}catch{}let d=c(a)||c(o)||l;return d?d.slice(0,200):""}finally{b0(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"?Ae(e):Array.isArray(e)?e.map(t=>typeof t?.text=="string"?Ae(t.text):t?.type==="image"&&t.data?hi(t.data,t.mimeType):"").filter(Boolean).join(`
|
|
543
|
+
`):""}}});var Ri,Pm=O(()=>{Ri=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});import{execFile as x0}from"child_process";import{promisify as E0}from"util";import{readFile as A0}from"fs/promises";import{resolve as Om,sep as T0}from"path";async function wr(r,e){let{stdout:t}=await P0("git",r,{cwd:e,maxBuffer:67108864});return t}async function vr(){if(Ni)return Ni;try{Ni=(await wr(["rev-parse","--show-toplevel"],V)).trim()}catch{}return Ni}function O0(r,e){let t=e===" "?r:e;return t==="?"?"U":t}async function _m(){let r=await vr();if(!r)return{repo:!1,root:"",files:[]};try{let e=await wr(["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:O0(i[0],i[1])}))}try{let s=await wr(["diff","--numstat","HEAD"],r),i=new Map;for(let o of s.split(`
|
|
544
|
+
`)){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:q(e)}}}async function Rm(r){let e=await vr();if(!e)return{ok:!1,error:"not a git repository"};try{if((await wr(["status","--porcelain","-z","--",r],e)).startsWith("??")){let s=Om(e,r);if(!s.startsWith(Om(e)+T0))return{ok:!1,error:"outside repository"};let i=await A0(s);return i.includes(0)?Xc("Binary file (not shown)",!1):Xc(i.toString("utf8"),!0)}let n;try{n=await wr(["diff","--no-color","--unified=999999","HEAD","--",r],e)}catch{n=await wr(["diff","--no-color","--unified=999999","--",r],e)}return Xc(n,!1)}catch(t){return{ok:!1,error:q(t)}}}var P0,Cm,Ni,Xc,Ii=O(()=>{at();P0=E0(x0),Cm=2e6;Xc=(r,e)=>({ok:!0,text:r.slice(0,Cm),untracked:e,truncated:r.length>Cm})});function Li(r,e){let t=0,n="";for(let s of r){let i=s.lower.indexOf(e);if(!(i<0)&&(t++,!n)){let o=Math.max(0,i-110),a=Math.min(s.text.length,i+e.length+110);n=(o>0?"\u2026":"")+s.text.slice(o,a)+(a<s.text.length?"\u2026":"")}}return{hitCount:t,snippet:n}}var Zc=O(()=>{});var $i,Mi,Nm=O(()=>{$i=".typebulb/paste",Mi={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 C0,mkdirSync as _0,writeFileSync as R0,readFileSync as N0}from"fs";import{join as Di}from"path";function Im(){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 M0(r){return r.trim().toLowerCase().replace(/\.[a-z0-9]{1,4}$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function D0(r){let e=AbortSignal.timeout(I0);for(let[t,n]of $0){let s=De(t,n);if(typeof s!="string"){try{let i=await st(s,{messages:[{role:"user",content:`Reply with ONLY a short kebab-case filename (2-5 words, lowercase, no extension) describing this text:
|
|
545
|
+
|
|
546
|
+
${r.slice(0,L0)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=M0(await Pt(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function Lm(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=Di(r,$i);try{_0(t,{recursive:!0})}catch(a){return{ok:!1,error:q(a)}}let n,s,i;if(e.kind==="image"){if(n=`img-${Im()}`,s=Object.keys(Mi).find(a=>Mi[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else n=await D0(e.data)??`paste-${Im()}`,s="md",i=e.data;let o=`${n}.${s}`;for(let a=2;C0(Di(t,o));a++)o=`${n}-${a}.${s}`;try{R0(Di(t,o),i)}catch(a){return{ok:!1,error:q(a)}}return{ok:!0,path:`${$i}/${o}`}}function $m(r,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),n=Mi[t];if(!n)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:n,base64:N0(Di(r,$i,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var I0,L0,$0,Mm=O(()=>{cr();yr();at();Nm();I0=4e3,L0=4e3,$0=[["openrouter","google/gemini-3.1-flash-lite-preview"],["gemini","gemini-3.1-flash-lite"]]});import{existsSync as Dm,openSync as B0,readSync as j0,closeSync as F0,statSync as Sr,readdirSync as Bm,watchFile as q0,unwatchFile as jm,mkdirSync as U0,writeFileSync as J0,readFileSync as Bi,unlinkSync as K0,rmSync as H0}from"fs";import{stat as W0}from"fs/promises";import{dirname as V0,join as $t,resolve as Fm}from"path";import{execFile as Y0}from"child_process";function X0(r){if(!Number.isInteger(r))return!0;try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}function ji(r){let e={cwd:V,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 k={d:r.createDriver(e.cwd,g),file:g};return t.add(k),e.file||(n=k),k}async function o(g){t.delete(g),n===g&&(n=void 0);try{await g.d.dispose()}catch(k){console.error("[composer] dispose:",q(k))}}function a(){let g=s();for(let k of[...t])k!==g&&(k.d.streaming||k.d.queue||k.d.error||o(k))}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(k=>k.file===n.file);g&&C(g)}}let l=g=>$t(g,z0),d=(g,k)=>$t(l(g),`${k}.lock`);function u(g,k){try{let S=d(g,k);if(Date.now()-Sr(S).mtimeMs>=qm)return!1;try{let _=parseInt(Bi(S,"utf8").trim(),10);if(_===process.pid||!X0(_))return!1}catch{}return!0}catch{return!1}}function f(g,k){if(k)try{U0(l(g),{recursive:!0}),J0(d(g,k),String(process.pid))}catch(S){console.error("[lock] claim failed:",q(S))}}function p(g){try{H0($t(g,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function b(g){let k=l(g);if(!Dm(k))return;let S;try{S=Bm(k)}catch{return}let _=Date.now();for(let L of S){if(!L.endsWith(".lock"))continue;let M=$t(k,L);try{let N=Sr(M);_-N.mtimeMs>Q0&&K0(M)}catch{}}}function h(g){try{return Sr(g),!1}catch(k){return k.code==="ENOENT"}}function w(){let g=e;if(g.file&&!h(g.file)){f(g.cwd,g.sessionId);return}let k=x(g);k&&C(k)}function x(g){if(!g.everAttached)return E(g.cwd)??T(g.cwd,()=>!0)}function E(g){let k=l(g);if(!Dm(k))return;let S;try{S=Bm(k)}catch{return}let _;for(let M of S)if(M.endsWith(".lock"))try{let N=Sr($t(k,M));if(Date.now()-N.mtimeMs>=qm||parseInt(Bi($t(k,M),"utf8").trim(),10)!==process.pid)continue;(!_||N.mtimeMs>_.mtime)&&(_={sessionId:M.slice(0,-5),mtime:N.mtimeMs})}catch{}if(!_)return;let L=r.listSessionFiles(g).find(M=>M.sessionId===_.sessionId);if(!(!L||h(L.file)))return L}function T(g,k){return r.listSessionFiles(g).sort((S,_)=>_.mtime-S.mtime).find(S=>!u(g,S.sessionId)&&k(S))}function P(g,k){let S=e;if(S.file)try{jm(S.file)}catch{}S.file=g,S.sessionId=k,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:k})}function C(g){let k=e;n=void 0,P(g.file,g.sessionId),k.everAttached=!0,f(k.cwd,g.sessionId),y();try{jm(g.file)}catch{}q0(g.file,{interval:200},()=>y())}function m(){P(void 0,"")}function y(){let g=e;if(!g.file)return;let k;try{k=Sr(g.file).size}catch{return}if(k<=g.offset)return;let S;try{S=B0(g.file,"r")}catch{return}try{let F=k-g.offset,ae=Buffer.alloc(F),z=0;for(;z<F;){let Nl=j0(S,ae,z,F-z,g.offset+z);if(!Nl)break;z+=Nl}g.offset+=z,g.partial+=ae.subarray(0,z).toString("utf8")}finally{F0(S)}let _,L;for(;(L=g.partial.indexOf(`
|
|
547
|
+
`))>=0;){let F=g.partial.slice(0,L);if(g.partial=g.partial.slice(L+1),!F.trim())continue;let ae=r.parseEntry(F);if(!ae)continue;let z=r.idOf(ae);z&&(g.entries.set(z,ae),!r.isSidechain(ae)&&r.isLeafType(ae)&&(_=z))}if(!_)return;let M=[],N=g.entries.get(_),U=!1;for(;N;){if(M.push(N),r.idOf(N)===g.chainLastId){U=!0;break}let F=r.parentOf(N);N=F?g.entries.get(F):void 0}if(U)for(let F=M.length-2;F>=0;F--)J(M[F]);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 F=new Set(M.map(z=>r.idOf(z))),ae=v(g.entries);for(let z=M.length-1;z>=0;z--)J(M[z]),R(r.idOf(M[z]),ae,F)}g.chainLastId=_}function v(g){let k=new Map;for(let S of g.values()){let _=r.parentOf(S);if(!_)continue;let L=k.get(_);L?L.push(S):k.set(_,[S])}return k}function R(g,k,S){if(!g)return;let _=k.get(g);if(!_)return;let L=_.filter(F=>!r.isSidechain(F));if(L.length<2)return;let M=L.filter(F=>!S.has(r.idOf(F)));if(!M.length)return;let N=[],U=0;for(let F of M){let ae=I(F,k);N.push(...ae.events),U+=ae.count}U>0&&e.buffer.push({type:"fork",atId:g,count:U,events:N})}function I(g,k){let S=[],_=[g];for(;_.length;){let N=_.pop();if(r.isSidechain(N))continue;S.push(N);let U=k.get(r.idOf(N)??"");if(U)for(let F of U)_.push(F)}S.sort((N,U)=>(Date.parse(r.timestampOf(N)??"")||0)-(Date.parse(r.timestampOf(U)??"")||0));let L=[];for(let N of S)r.isRecoveryNoise(N)||L.push(...r.apply(N,e.sessionStartMs).events);return{count:L.reduce((N,U)=>N+(U.type==="user"||U.type==="assistant"?1:0),0),events:L}}function J(g){try{let{events:k,usage:S,model:_,cost:L}=r.apply(g,e.sessionStartMs);for(let M of k)e.buffer.push(M);k.some(M=>M.type==="assistant")&&s()?.d.clearCompletedDraft(),k.some(M=>M.type==="user")&&s()?.d.clearEcho(),_&&(e.latestModel=_),S&&(e.latest=S),(S||L)&&e.buffer.push({type:"usage",...e.latest,cost:L})}catch(k){console.error("[mirror] skipped malformed entry:",q(k))}}async function B(){return{cwd:e.cwd,pid:process.pid,composer:!!r.createDriver,elsewhere:await pe()}}async function pe(){if(r.listSessionFiles(e.cwd).length)return;let g=await vr();if(!g)return;let k=Fm(g).toLowerCase();for(let S=Fm(e.cwd);S.toLowerCase()!==k;){let _=V0(S);if(_===S)return;S=_;let L=r.listSessionFiles(S).length;if(L)return{dir:S,count:L}}}pe().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 Z=new Ri;async function ee(g,k){Z.accept(g,k)&&console.log(k)}function dt(){let g=r.sessionAlive(e.sessionId,e.cwd);if(g!==void 0)return g;if(!e.file)return!1;try{return Date.now()-Sr(e.file).mtimeMs<1e4}catch{return!1}}function ke(){return r.chainWorking([...e.entries.values()])&&dt()}function Pg(){!r.createDriver||s()||e.latestModel||ke()||i(e.file)}async function Og(g){let k=e;w(),c(),Pg(),a();let S=s();for(let N of t)N!==S&&N.d.dialog;let _=new Set([...t].filter(N=>N.d.streaming&&N.file).map(N=>N.file)),L=_.size?r.listSessionFiles(k.cwd).filter(N=>_.has(N.file)).map(N=>N.sessionId):[],M=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:k.buffer.slice(g),cursor:k.buffer.length,working:!!S?.d.streaming||ke(),latestModel:k.latestModel,composer:M,busy:L}}async function Ol(){w(),c();let g=s();if(g?.d.error&&!g.d.streaming&&(await o(g),g=void 0),!g){if(ke())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 Cg(g,k){if(!r.createDriver)return{ok:!1,error:"not supported"};let S=String(g??"").trim();if(!S)return{ok:!1,error:"empty message"};let _=await Ol();return _.ok?_.d.send(S,k):_}async function _g(g,k){let S=s();return S?S.d.respondUi(String(g??""),k??{}):{ok:!1,error:"no dialog pending"}}async function Rg(g,k){if(!r.createDriver)return{ok:!1,error:"not supported"};if(!g||typeof g.type!="string")return{ok:!1,error:"bad command"};if(k?.spawn){let _=await Ol();return _.ok?_.d.rpc(g):_}let S=s();return!S||S.d.error?{ok:!1,error:"not running"}:S.d.rpc(g)}async function Ng(){let g=s();if(g)try{await g.d.stop()}catch(k){console.error("[composer] stop:",q(k))}return{ok:!0}}async function Ig(){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&&m(),i(void 0),a(),{ok:!0})):{ok:!1,error:"not supported"}}async function Lg(){if(!r.createDriver)return[];let g=await new Promise(S=>{Y0("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e.cwd,maxBuffer:64*1024*1024},(_,L)=>S(_?"":L))});return(await Promise.all(g.split(`
|
|
548
|
+
`).filter(Boolean).map(async S=>{try{return{f:S,m:(await W0($t(e.cwd,S))).mtimeMs}}catch{return{f:S,m:0}}}))).sort((S,_)=>_.m-S.m).map(S=>S.f)}function $g(){for(let g of[...t])o(g)}async function Mg(g){return r.createDriver?Lm(e.cwd,g):{ok:!1,error:"not supported"}}async function Dg(g){return $m(e.cwd,String(g??""))}async function Bg(){return r.listSessionFiles(e.cwd).sort((g,k)=>k.mtime-g.mtime).map(({sessionId:g,file:k,mtime:S})=>({sessionId:g,mtime:S,preview:r.readPreview(k)}))}let Cl=new Map;function jg(g,k){let S=Cl.get(g);if(S&&S.mtime===k)return S.turns;let _=[],L="";try{L=Bi(g,"utf8")}catch{return[]}for(let M of L.split(`
|
|
549
|
+
`)){if(!M.trim())continue;let N=r.parseEntry(M);if(!N)continue;let U=r.searchText(N);U&&_.push({text:U,lower:U.toLowerCase()})}return Cl.set(g,{mtime:k,turns:_}),_}async function Fg(g){let k=g.toLowerCase(),S=[];for(let{sessionId:_,file:L,mtime:M}of r.listSessionFiles(e.cwd).sort((N,U)=>U.mtime-N.mtime)){let{hitCount:N,snippet:U}=Li(jg(L,M),k);if(N&&(S.push({sessionId:_,mtime:M,preview:r.readPreview(L),hitCount:N,snippet:U}),S.length>=Z0))break}return S}let _l=800,Rl=new Map;function qg(g,k){let S=Rl.get(g);if(S&&S.mtime===k)return S.text;let _="";try{_=Bi(g,"utf8")}catch{return""}let L="";for(let N of _.split(`
|
|
550
|
+
`)){if(!N.trim())continue;let U=r.parseEntry(N);if(U)for(let F of r.apply(U,e.sessionStartMs).events)F.type==="assistant"&&F.text.trim()&&(L=F.text.trim())}let M=L.length>_l?L.slice(0,_l).trimEnd()+"\u2026":L;return Rl.set(g,{mtime:k,text:M}),M}async function Ug(g){let k=r.listSessionFiles(e.cwd).find(S=>S.sessionId===g);return{text:k?qg(k.file,k.mtime):""}}async function Jg(g){let k=e,S=r.listSessionFiles(k.cwd).find(_=>_.sessionId===g);return S?S.file===k.file?{ok:!0}:(C(S),c(),a(),{ok:!0}):{ok:!1,error:"session not found"}}return p(e.cwd),b(e.cwd),w(),{info:B,poll:Og,logEmbedStatus:ee,listSessions:Bg,searchSessions:Fg,sessionPeek:Ug,attach:Jg,composerSend:Cg,composerStop:Ng,composerNew:Ig,composerFiles:Lg,composerUiRespond:_g,composerRpc:Rg,composerPaste:Mg,composerPasteRead:Dg,shutdownComposer:$g}}var G0,z0,qm,Q0,Z0,el=O(()=>{at();Pm();Ii();Zc();Mm();G0=".typebulb",z0=`${G0}/locks`,qm=5e3,Q0=6e4;Z0=50});import{existsSync as tl,mkdirSync as eE,readFileSync as Um,writeFileSync as tE}from"fs";import{join as kr,isAbsolute as rE}from"path";async function Jm(r,e){let t=rE(r)?r:kr(V,r);return tl(t)?(Gc(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function Km(r){let e=V,t=Yc(r),n=kr(e,"typebulbs");eE(n,{recursive:!0});let s=Hc(t),i=`${s}.bulb.md`;for(let l=2;tl(kr(n,i))&&Um(kr(n,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=kr(n,i);tl(o)||tE(o,t);let a=kr("typebulbs",i),c=await xi(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function Hm(){return W(V)}async function Wm(r){return await Rt(r),{ok:!0}}async function Vm(){return Ai(V).filter(r=>!r.serverOnly).map(r=>({...r,trusted:_t(r.path)}))}async function Ym(r){let e=r.toLowerCase(),t=[];for(let n of Ai(V).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=Um(n.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
|
|
551
|
+
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=Li(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function Gm(r,e){let t=V;e!=null&&fr(r,e);let n=await xi(r,{cwd:t,open:!1,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function zm(r){return{cap:await Vc(r)}}async function Qm(r,e){return fr(r,e),{ok:!0}}async function Xm(r,e){return Te(r,e)}var rl=O(()=>{yr();at();Zc()});import{readFileSync as il,writeFileSync as eh,mkdirSync as nE,appendFileSync as th,rmSync as Zm}from"fs";import{join as Ui,dirname as sE}from"path";import{createServer as iE}from"http";function ct(r){try{return JSON.parse(il(r,"utf8"))}catch{return null}}function qi(r,e){nE(sE(r),{recursive:!0}),eh(r,JSON.stringify(e,null,2)+`
|
|
552
|
+
`)}function nh(r,e,t){let n=Ui(r,".gitignore"),s="";try{s=il(n,"utf8")}catch{}let i=new Set(s.split(/\r?\n/).map(c=>c.trim())),o=e.filter(c=>!i.has(c));if(!o.length)return;let a=s&&!s.endsWith(`
|
|
525
553
|
`)?`
|
|
526
|
-
`:"";try{
|
|
554
|
+
`:"";try{th(n,a+t+`
|
|
527
555
|
`+o.join(`
|
|
528
556
|
`)+`
|
|
529
|
-
`)}catch(c){console.error("[switcher] .gitignore update failed",q(c))}}function
|
|
557
|
+
`)}catch(c){console.error("[switcher] .gitignore update failed",q(c))}}function uE(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?On="live":s>lE&&(On="uncached")}function ih(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 fE(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 oh(r){let e;try{e=JSON.parse(r)}catch{return r}Pn=typeof e?.model=="string"?e.model:null,Ce&&(e.model=Ce),Dt&&(e.provider=sh(Dt));let t=/haiku/i.test(Pn||"");return Cn!=null&&!t&&(e.reasoning={effort:nl[Cn]}),delete e.thinking,e.output_config&&delete e.output_config.effort,fE(e),JSON.stringify(e)}function dE(){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}
|
|
530
558
|
data: ${JSON.stringify(a)}
|
|
531
559
|
|
|
532
560
|
`}case"content_block_delta":case"content_block_stop":{let c=t.get(a.index);return c==null?null:(a.index=c,`event: ${a.type}
|
|
@@ -534,11 +562,11 @@ data: ${JSON.stringify(a)}
|
|
|
534
562
|
|
|
535
563
|
`)}default:return i}};return i=>{r+=i;let o="",a;for(;(a=r.indexOf(`
|
|
536
564
|
|
|
537
|
-
`))!==-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
|
|
565
|
+
`))!==-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 pE(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 Tn(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 mE(r,e,t){if(!Ce){Tn(e,400,"invalid_request_error",cE);return}let n=process.env.OPENROUTER_API_KEY;if(!n){Tn(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(ol,{method:"POST",headers:ih(r,n),body:oh(t),signal:s.signal})}catch(u){Tn(e,502,"api_error",`proxy upstream failed: ${q(u)}`);return}let o=i.headers.get("content-type")||"application/json";if(e.writeHead(i.status,{"content-type":o}),!i.body){e.end();return}let a=o.includes("event-stream"),c=i.body.getReader(),l=new TextDecoder,d=a?dE():null;try{for(;;){let{done:u,value:f}=await c.read();if(u)break;if(f)if(d){let p=l.decode(f,{stream:!0});uE(p);let b=d(p);b&&e.write(b)}else e.write(Buffer.from(f))}}catch{}finally{e.writableEnded||e.end()}}async function hE(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(!Ce||!n)return s();try{let i=await fetch(`${ol}/count_tokens`,{method:"POST",headers:ih(r,n),body:oh(t)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function gE(r,e){let t=r.url||"/";if(r.method==="HEAD"){e.writeHead(200),e.end();return}if(r.method!=="POST"){Tn(e,404,"not_found_error",t);return}pE(r).then(n=>{if(t.includes("count_tokens"))return hE(r,e,n);if(t.includes("/v1/messages"))return mE(r,e,n);Tn(e,404,"not_found_error",t)})}function yE(){return xr&&Mt?Promise.resolve(Mt):new Promise((r,e)=>{let t=iE(gE);t.on("error",e),t.listen(0,"127.0.0.1",()=>{xr=t,Mt=t.address().port,console.log(`[switcher] wire proxy listening on ${Fi(Mt)}`),r(Mt)})})}function bE(){try{xr?.close()}catch{}xr=null,Mt=null}function wE(r,e){let t=Ji(r),n=ct(t),s=n||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===Fi(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=Ki(r);if(!ct(i)){let a={};for(let c of rh)a[c]=c in s.env?s.env[c]:null;qi(i,{managedBy:"agent-switcher",fileExisted:n!==null,snapshot:a,active:null})}s.env.ANTHROPIC_BASE_URL=Fi(e),s.env.ANTHROPIC_AUTH_TOKEN=aE,qi(t,s),nh(r,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function vE(r,e,t){let n=Ki(r),s=ct(n)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:t},qi(n,s)}function ah(r){let e=Ji(r),t=Ki(r),n=ct(t),s=ct(e);if(s?.env){let i=n?.snapshot||{};for(let o of rh){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{Zm(e,{force:!0})}catch{}else qi(e,s)}try{Zm(t,{force:!0})}catch{}}async function SE(){let r=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await Me()).filter(n=>n.provider==="openrouter"&&!al(n.name)).map(n=>({id:n.name,label:n.friendlyName||n.name}))}catch(n){console.error("[switcher] model list failed",q(n))}let t=e.length?void 0:xc()??void 0;return{hasKey:r,models:e,error:t}}async function kE(){if(xr&&Ce)return{active:!0,managed:!0,model:Ce,port:Mt,provider:Dt,routedModel:Pn,caching:On,reasoning:Cn,externalBaseUrl:null};let r=ct(Ji(V))?.env||{};return{active:!1,managed:!1,model:null,port:null,provider:null,routedModel:null,caching:"unknown",reasoning:Cn,externalBaseUrl:r.ANTHROPIC_BASE_URL||null}}async function ch(r,e){let t=await yE();return Ce=r,Dt=e,wE(V,t),t}async function xE({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(al(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 ch(r,cl[r]??null),Pn=null,On="unknown",vE(V,r,Dt)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${q(e)}`}}return{ok:!0}}async function EE({level:r}){return r!=null&&(!Number.isInteger(r)||r<0||r>=nl.length)?{ok:!1,error:`reasoning level must be 0\u2013${nl.length-1} or null`}:(Cn=r,{ok:!0,level:r})}async function AE(){return ah(V),Ce=null,Dt=null,Pn=null,On="unknown",{ok:!0}}async function TE({key:r}){let e=(r||"").trim();if(!e)return{ok:!1,error:"empty key"};let t=V,n=Ui(t,".env"),s="";try{s=il(n,"utf8")}catch{}try{if(/^\s*OPENROUTER_API_KEY\s*=/m.test(s))eh(n,s.replace(/^\s*OPENROUTER_API_KEY\s*=.*$/m,`OPENROUTER_API_KEY=${e}`));else{let i=s&&!s.endsWith(`
|
|
538
566
|
`)?`
|
|
539
|
-
`:"";
|
|
540
|
-
`)}}catch(i){return{ok:!1,error:q(i)}}return process.env.OPENROUTER_API_KEY=e,
|
|
541
|
-
`)}catch(o){return{ok:!1,error:`could not write ${r}: ${q(o)}`}}return{ok:!0,count:e.length}}var
|
|
567
|
+
`:"";th(n,i+`OPENROUTER_API_KEY=${e}
|
|
568
|
+
`)}}catch(i){return{ok:!1,error:q(i)}}return process.env.OPENROUTER_API_KEY=e,nh(t,[".env"],"# secrets"),{ok:!0}}function PE(){if(!(!xr&&!Ce)){try{ah(V)}catch{}bE()}}function OE(r,e){return lh.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 CE(r){if(lh.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 _E(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=sl(e?.cache_read_input_tokens)||sl(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 RE({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(al(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 d=JSON.stringify(a?{...i,provider:sh(a)}:i),u=await fetch(ol,{method:"POST",signal:c.signal,headers:s,body:d}),f=await u.json().catch(()=>({}));return{r:u,j:f}}finally{clearTimeout(l)}};try{let{r:a,j:c}=await o();if(!a.ok){let x=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:OE(a.status,x),restriction:CE(x)}}let l=typeof c?.provider=="string"?c.provider:void 0,d=c?.content?.find?.(x=>x.type==="text")?.text??c?.content?.[0]?.text??"ok",u=sl(c?.usage?.cache_creation_input_tokens),{r:f,j:p}=await o(l),{works:b,read:h,note:w}=_E(f.ok,p?.usage,l);return b===!0&&l&&(cl[r]=l,Ce===r&&(Dt=l)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-t,provider:l,sample:String(d).trim().slice(0,60),cache:{works:b,created:u,read:h,note:w}}}catch(a){let c=q(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(c)?"timed out (20s)":c}}}var oE,ol,aE,cE,rh,lE,nl,Ji,Ki,Fi,al,xr,Mt,Ce,Dt,Pn,On,Cn,cl,sl,sh,lh,uh=O(()=>{yr();at();oE="https://openrouter.ai/api",ol=`${oE}/v1/messages`,aE="typebulb-proxy-managed",cE="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.",rh=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],lE=5e3,nl=["low","medium","high"],Ji=r=>Ui(r,".claude","settings.local.json"),Ki=r=>Ui(r,".claude",".cc-switcher.json"),Fi=r=>`http://127.0.0.1:${r}`;al=r=>/^anthropic\//i.test(r)||/claude/i.test(r),xr=null,Mt=null,Ce=null,Dt=null,Pn=null,On="unknown",Cn=1,cl={},sl=r=>typeof r=="number"?r:0,sh=r=>({order:[r],allow_fallbacks:!1});lh=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=ct(Ki(V)),t=e?.active?.model;if(!t)return;let s=(ct(Ji(V))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await ch(t,e.active.provider??cl[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${Fi(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",q(e))}})()});var dh={};Il(dh,{attach:()=>jE,blockToMarkdown:()=>bi,breakout:()=>Km,capText:()=>Ae,cleanUserText:()=>ot,clearSwitchModel:()=>AE,composerPasteRead:()=>FE,displayName:()=>NE,firstLineDigest:()=>Fe,gitChangedFiles:()=>_m,gitDiff:()=>Rm,info:()=>IE,isHiddenTurn:()=>kn,launchBulb:()=>Gm,listBreakouts:()=>Hm,listBulbFiles:()=>Vm,listSessions:()=>ME,listSwitchModels:()=>SE,logEmbedStatus:()=>$E,openFile:()=>Jm,poll:()=>LE,predictTrustOf:()=>zm,probeModel:()=>RE,readBulbLog:()=>Xm,repoRoot:()=>vr,saveOpenRouterKey:()=>TE,searchBulbs:()=>Ym,searchSessions:()=>DE,sessionPeek:()=>BE,setBulbTrust:()=>Qm,setReasoning:()=>EE,setSwitchModel:()=>xE,shutdownSwitcher:()=>PE,stopBreakout:()=>Wm,switchState:()=>kE,toolResultDigest:()=>$c});var fh,NE,IE,LE,$E,ME,DE,BE,jE,FE,ph=O(()=>{el();wi();rl();Ii();uh();wi();gi();fh=new pr,NE=fh.displayName,{info:IE,poll:LE,logEmbedStatus:$E,listSessions:ME,searchSessions:DE,sessionPeek:BE,attach:jE,composerPasteRead:FE}=ji(fh)});import{readFileSync as qE,writeFileSync as UE,mkdirSync as JE}from"fs";import{homedir as KE}from"os";import*as Hi from"path";async function gh(){try{let r=await fetch(new URL("/api/tags",hh()).toString(),{signal:AbortSignal.timeout(HE)});return r.ok?((await r.json()).models??[]).map(t=>t.name).filter(t=>!!t):[]}catch{return[]}}function yh(r){let e;try{e=qE(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&&!ll(n)}}}catch{}return{json:void 0,unreadable:!0}}function ll(r){let e=r?.providers;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function WE(r){let e=ll(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 bh(){let{json:r,unreadable:e}=yh(mh());return e?{installed:[],configured:null}:{installed:await gh(),configured:WE(r)}}async function wh(){let r=await gh();return r.length?VE(mh(),r,hh()):{ok:!1,error:"Ollama is not running (or has no models installed)"}}function VE(r,e,t){let{json:n,unreadable:s}=yh(r);if(s)return{ok:!1,error:`could not parse ${r} \u2014 edit the ollama provider there yourself`};let i={...n??{},providers:{...ll(n)??{},ollama:{baseUrl:`${t}/v1`,api:"openai-completions",apiKey:"ollama",models:e.map(o=>({id:o}))}}};try{JE(Hi.dirname(r),{recursive:!0}),UE(r,JSON.stringify(i,null,2)+`
|
|
569
|
+
`)}catch(o){return{ok:!1,error:`could not write ${r}: ${q(o)}`}}return{ok:!0,count:e.length}}var HE,mh,hh,vh=O(()=>{at();yr();HE=1500,mh=()=>Hi.join(KE(),".pi","agent","models.json"),hh=()=>ur(process.env.OLLAMA_HOST??"http://localhost:11434")});var kh={};Il(kh,{attach:()=>tA,breakout:()=>Km,composerFiles:()=>iA,composerNew:()=>sA,composerPaste:()=>cA,composerPasteRead:()=>lA,composerRpc:()=>aA,composerSend:()=>rA,composerStop:()=>nA,composerUiRespond:()=>oA,displayName:()=>YE,gitChangedFiles:()=>_m,gitDiff:()=>Rm,info:()=>GE,launchBulb:()=>Gm,listBreakouts:()=>Hm,listBulbFiles:()=>Vm,listSessions:()=>XE,logEmbedStatus:()=>QE,ollamaOffer:()=>bh,ollamaSync:()=>wh,openFile:()=>Jm,poll:()=>zE,predictTrustOf:()=>zm,readBulbLog:()=>Xm,repoRoot:()=>vr,searchBulbs:()=>Ym,searchSessions:()=>ZE,sessionPeek:()=>eA,setBulbTrust:()=>Qm,shutdownComposer:()=>uA,stopBreakout:()=>Wm});var Sh,YE,GE,zE,QE,XE,ZE,eA,tA,rA,nA,sA,iA,oA,aA,cA,lA,uA,xh=O(()=>{el();Qc();rl();Ii();vh();Sh=new br,YE=Sh.displayName,{info:GE,poll:zE,logEmbedStatus:QE,listSessions:XE,searchSessions:ZE,sessionPeek:eA,attach:tA,composerSend:rA,composerStop:nA,composerNew:sA,composerFiles:iA,composerUiRespond:oA,composerRpc:aA,composerPaste:cA,composerPasteRead:lA,shutdownComposer:uA}=ji(Sh)});import*as Tg from"fs/promises";import*as Ft from"path";import*as $l from"fs/promises";import{existsSync as qt,readFileSync as Qg}from"fs";import*as Y from"path";import{pathToFileURL as Xg}from"url";import{resolve as uo}from"resolve.exports";import{init as Ml,parse as Dl}from"es-module-lexer";function Bl(r,e){let t=Y.join(r,"package.json");try{return JSON.parse(Qg(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var lo=["browser","import","default"],Ll=["node","import","default"];function jl(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:Y.resolve(n)}}async function Fl(r){let{name:e,dir:t}=r;if(!qt(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=Bl(t,e),s=Zg(n,e),i=Y.resolve(t,s);if(!qt(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=Y.dirname(i),a=`/local/${e}/${Y.basename(i)}`,c=ey(n,t);return await ty(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function Zg(r,e){if(r.exports!==void 0){let n;try{n=uo(r,".",{browser:!0,conditions:lo})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${lo.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=fo(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${lo.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 ey(r,e){if(r.exports!==void 0)try{let n=uo(r,".",{conditions:["types"]}),s=fo(n);if(s){let i=Y.resolve(e,s);if(qt(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=Y.resolve(e,t);if(qt(n))return n}}function fo(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function ty(r,e,t){await Ml;let n=Y.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 $l.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=Dl(a,o)}catch{continue}if(o===e&&!l)throw new Error(`override package '${r}' entry is not an ES module (no import/export syntax); CommonJS or non-module entries aren't supported (esm.sh would have to transform it).`);for(let d of c){if(d.d===-2)continue;let u=d.n;if(u&&!u.startsWith("node:")){if(u.startsWith("./")||u.startsWith("../")||u.startsWith("/")){let f=ry(o,u,n);f&&!s.has(f)&&i.push(f);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${r} externalizes '${u}'`)}}}}function ry(r,e,t){let n=e.replace(/[?#].*$/,""),s=Y.resolve(Y.dirname(r),n),i=[s,s+".js",s+".mjs",Y.join(s,"index.js"),Y.join(s,"index.mjs")];for(let o of i)if(Y.normalize(o).startsWith(t)&&qt(o))return o}function ny(r,e,t){let n=Bl(r,e),s;if(n.exports!==void 0)try{s=fo(uo(n,t,{conditions:Ll}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${Ll.join(", ")}): ${o instanceof Error?o.message:o}`)}else t==="."&&(s=n.main??n.module);if(!s)throw new Error(`--replace package '${e}' has no node export for '${t}'.`);let i=Y.resolve(r,s);if(!qt(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return Xg(i).href}async function ql(r,e){await Ml;let t;try{[t]=Dl(r)}catch{return r}let n="",s=0;for(let i of t){if(i.d!==-1)continue;let o=i.n;if(!o||o!==e.name&&!o.startsWith(e.name+"/"))continue;let a=o===e.name?".":"."+o.slice(e.name.length),c=ny(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var sy=5e3;function Ul(r){let t={subcommand:"run",file:"",port:3e3,watch:!0,open:!(process.env.TERM_PROGRAM==="vscode"),server:!1,trust:!1,noTrust:!1,follow:!1,clear:!1,help:!1,version:!1,callArgs:[],hasArgsFlag:!1},n=["call","check","predict","logs","wait","stop","trust","untrust","skill","models","send"],s=r[0];if(s==="agent"||s?.startsWith("agent:")){t.subcommand="agent";let o=s.indexOf(":");if(o!==-1){let a=s.slice(o+1);a&&(t.agentTarget=a)}r=r.slice(1)}else s&&n.includes(s)&&(t.subcommand=s,r=r.slice(1));let i=[];for(let o=0;o<r.length;o++){let a=r[o];if(a==="--help"||a==="-h")t.help=!0;else if(a==="--version"||a==="-V")t.version=!0;else if(a==="--no-watch")t.watch=!1;else if(a==="--open")t.open=!0;else if(a==="--no-open")t.open=!1;else if(a==="--server")t.server=!0;else if(a==="--trust")t.trust=!0;else if(a==="--no-trust")t.noTrust=!0;else if(a==="--mode"){let c=r[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),t.mode=c}else if(a==="--follow"||a==="-f")t.follow=!0;else if(a==="--clear")t.clear=!0;else if(a==="--run"){let c=r[++o];if(c==="latest")t.run="latest";else{let l=parseInt(c,10);(isNaN(l)||l<1)&&(console.error(`Invalid --run value: ${c} (a run number, or 'latest')`),process.exit(1)),t.run=l}}else if(a==="--bulbs")t.stopScope="bulbs";else if(a==="--agent")t.stopScope="agent";else if(a==="--global")t.stopScope="global";else if(a==="--match"){let c=r[++o];c===void 0&&(console.error("Missing value for --match (a literal substring new log lines must contain)"),process.exit(1)),t.match=c}else if(a==="--timeout"){let c=parseInt(r[++o],10);(isNaN(c)||c<=0)&&(console.error(`Invalid --timeout value: ${r[o]} (seconds)`),process.exit(1)),t.timeoutSec=c}else if(a==="--wait"||a.startsWith("--wait="))if(a.startsWith("--wait=")){let c=parseInt(a.slice(7),10);(isNaN(c)||c<=0)&&(console.error(`Invalid --wait value: ${a.slice(7)} (milliseconds)`),process.exit(1)),t.sendWaitMs=c}else t.sendWaitMs=sy;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=jl(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 Jl(){console.log(`
|
|
542
570
|
typebulb - Local bulb runner for Typebulb
|
|
543
571
|
|
|
544
572
|
Usage:
|
|
@@ -667,11 +695,11 @@ Examples:
|
|
|
667
695
|
typebulb my-editor.bulb.md
|
|
668
696
|
typebulb --no-watch --port 8080 my-editor.bulb.md
|
|
669
697
|
typebulb .
|
|
670
|
-
`)}
|
|
698
|
+
`)}cn();import*as it from"fs/promises";import*as Be from"path";import{pathToFileURL as Uk}from"url";import{transform as JS}from"sucrase";function nc(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=JS(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}Js();function zS(r){return r.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
|
|
671
699
|
`)[0]}`).join(`
|
|
672
|
-
`)}function
|
|
673
|
-
${TS(t)}`)}var Ge="https://esm.sh",tn="https://cdn.jsdelivr.net/npm/",Ua="https://data.jsdelivr.com/v1/package/npm/";function jd(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var N=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=Gt(t??s.version),this.subpath=Gt(n??s.subpath)}static parse(e){let t=jd(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=Fd(t[1]??""),a=Gt(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=Fd(t[0]),o=Gt(t.slice(1).join("/"));return new r({name:s,version:i,subpath:o})}}static fromUrl(e){try{let t=new URL(e),n=new URL(Ge).host,s=new URL(tn).host;if(t.host===n){let i=jd(t.pathname.replace(/^\/v\d+\//,"/"));if(!i.length)return;let o=i[0].startsWith("@")?`${i[0]}/${i[1]??""}`:i[0];return r.parse(o)}if(t.host===s){let i=t.pathname.split("/npm/")[1];if(!i)return;let o=i.split("/")[0]||"";return r.parse(o)}return}catch{return}}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return r.parse(e).name}withVersion(e){return new r({name:this.name,version:Gt(e),subpath:this.subpath})}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},Gt=r=>r&&r.length?r:void 0,Fd=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),Gt(r.slice(e+1))]};async function se(r){try{return await r()}catch{return}}function mt(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function Ja(r){return r.startsWith("./")?r:`./${r}`}var rn=class{constructor(e,t){this.cache=e,this.http=t,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}baseDir(e){let t=typeof e=="string"?new N(e):e;return`${tn}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(mt(t),this.baseDir(e)).toString()}packageJson(e){return this.file(e,"package.json")}buildEsmUrl(e,t={}){let{target:n="es2022",bundle:s=!1,external:i}=t,o=new URLSearchParams({target:n});return s&&o.append("bundle",""),i?.length&&o.append("external",i.join(",")),`${Ge}/${e}?${o.toString()}`}async resolveExactVersion(e){let t=Date.now(),n=this.pinCache.get(e);if(n&&t-n.ts<this.pinMs)return n.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${Ge}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await se(()=>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 se(()=>this.http.getJson(`${Ua}${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=N.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let n=await this.cache.getMeta(e,t);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:d,peerDependencies:u,peerDependenciesMeta:f}=n;return{name:e,version:t,dependencies:d,peerDependencies:u,peerDependenciesMeta:f}}let s=this.packageJson(new N(`${e}@${t}`)),i=await se(()=>this.http.getJson(s));if(!i)return;let o=d=>d&&Object.keys(d).length?d:void 0,a=o(i.dependencies),c=o(i.peerDependencies),l=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}};var qd=r=>r.startsWith("@types/"),nn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!qd(e)),Ka=r=>Object.keys(r?.dependencies||{}).filter(e=>!qd(e)),PS=r=>nn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),sn=class{constructor(e){this.cdn=e}async resolve(e,t){let n=await this.fetchMeta(e),{allRoots:s,autoAddedPeers:i}=await this.expandWithPeers(n,t),o=this.computeFlags(s);return{allRoots:s,flags:o,autoAddedPeers:i}}async fetchMeta(e){return Promise.all(e.map(async({name:t,version:n})=>({name:t,version:n,meta:await this.cdn.fetchPackageMeta(t,n)})))}async expandWithPeers(e,t){let n=new Map(e.map(i=>[i.name,i])),s=[];for(let i of e)for(let o of PS(i.meta))!n.has(o)&&!s.some(a=>a.name===o)&&s.push({name:o,requiredBy:i.name});for(let{name:i,requiredBy:o}of s)try{let a=await t(i),c=await this.cdn.fetchPackageMeta(i,a);n.set(i,{name:i,version:a,meta:c})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${i}" for "${o}":`,a)}return{allRoots:[...n.values()],autoAddedPeers:s.filter(i=>n.has(i.name))}}computeFlags(e){let t=new Set(e.flatMap(i=>nn(i.meta))),n=new Map;for(let i of e)for(let o of Ka(i.meta))n.set(o,(n.get(o)||0)+1);let s=new Set([...n.entries()].filter(([,i])=>i>=2).map(([i])=>i));return new Map(e.map(i=>[i.name,{isPeerRoot:t.has(i.name),hasPeers:nn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var on=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await se(()=>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 se(()=>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 se(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=await s(this.semver.selectBestVersion(a.versions,{range:t,distTags:a.distTags}));if(c)return c}}}return s(await this.cdn.resolveExactVersion(`${e}@${t}`))}async effectivePackage(e,t){let n=new N(e),s=n.root(),i=t[s],o=i?await se(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as OS,parse as RS}from"es-module-lexer";var zt=class r{constructor(e,t,n){this.version=e,this.cdn=t,this.peer=n}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))N.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{N.isBare(s)&&t.add(s)};try{await OS;let[s]=RS(e);s.forEach(i=>n(e.slice(i.s,i.e).trim()))}catch{return this.extractImportsSync(e)}return Array.from(t)}async buildImportMap(e,t,n){let s=(await this.extractImports(e)).filter(u=>!n?.has(N.rootOf(u))),i=[...new Set(s.map(N.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),d=this.buildEntries([...s,...l.map(u=>u.name)],a,c);return{importMap:{imports:Object.fromEntries(d)},prefetchUrls:d.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=await this.version.resolveExactForRoot(e,n);if(!s)throw new Error(`Cannot resolve ${n?`${e}@${n}`:e}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);return s}buildEntries(e,t,n){let s=new Map(t.map(p=>[p.name,p])),i=p=>{let y=s.get(N.rootOf(p));return new N(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!==N.rootOf(p)).map(N.rootOf)),c=[],l=new Set,d=new Set(e.filter(p=>p===N.rootOf(p))),u=new Set;for(let p of e){let y=N.rootOf(p),m=s.get(y),{isPeerRoot:b,hasPeers:x,isSharedDep:A}=n.get(y),g=a.has(y),w=p!==y,E=!(b||A)&&(g||!x),T=this.singletonDepsOf(m,o),P=w&&d.has(y);P&&u.add(y);let D=P?[...T,y]:T.length?T:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:E,external:D})]),l.add(p)}let f=new Set([...o,...u]);for(let p of f)s.has(p)&&(l.has(p)||c.push([p,this.cdn.buildEsmUrl(i(p),{})]),c.push([`${p}/`,`${Ge}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...nn(e.meta),...Ka(e.meta)])].filter(n=>t.has(n))}};zt.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as Ud,satisfies as _S,maxSatisfying as Jd,major as CS,valid as NS}from"semver";var Ns=class{cmp(e,t){return e===t?0:Ud(e,t)?1:Ud(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!_S(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=Jd(e,n,{includePrerelease:!1});if(a)return a}return Jd(e,n,{includePrerelease:!0})??void 0}majorOf(e){return CS(e)}isExactVersion(e){return NS(e)!==null}},ht=new Ns;var gt=class{constructor(e){this.store=e}async isNegative(e){let t=await se(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await se(()=>this.store.get(e)))?.attempts||0)+1;await se(()=>this.store.set(e,{until:Date.now()+IS(n),attempts:n}))}async clearNegative(e){await se(()=>this.store.delete(e))}};function IS(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}function Kd(r,e){let t=new rn(r,e),n=new sn(t),s=new on(r,t,ht);return{packageService:new zt(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as Qd from"fs/promises";import*as pe from"path";import*as Qe from"fs/promises";import*as Ce from"path";import*as Vd from"os";import*as Wa from"fs/promises";import*as Wd from"crypto";function de(r){return Wd.createHash("sha1").update(r).digest("hex")}async function _e(r){try{return JSON.parse(await Wa.readFile(r,"utf8"))}catch{return}}async function Is(r){try{return await Wa.readFile(r,"utf8")}catch{return}}var Hd=1,ze=Ce.join(Vd.homedir(),".typebulb","cache"),an=Ce.join(ze,"packages"),cn=Ce.join(ze,"proxy"),Ls=Ce.join(ze,"dts"),LS=Ce.join(ze,"emit"),Ha;function U(){return Ha||(Ha=MS()),Ha}function Ms(r,e){return Ce.join(LS,de(r),e)}async function MS(){await Qe.mkdir(ze,{recursive:!0});let r=Ce.join(ze,"version.json");if((await _e(r))?.version===Hd)return;let t=await Qe.readdir(ze).catch(()=>[]);await Promise.all(t.map(n=>Qe.rm(Ce.join(ze,n),{recursive:!0,force:!0}))),await Qe.writeFile(r,JSON.stringify({version:Hd})+`
|
|
674
|
-
`,"utf8")}import*as
|
|
700
|
+
`)}function np(r,e){let t=ln(r,{target:"client",dependencies:e}).filter(n=>n.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
701
|
+
${zS(t)}`)}var et="https://esm.sh",un="https://cdn.jsdelivr.net/npm/",sc="https://data.jsdelivr.com/v1/package/npm/";function sp(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var $=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=tr(t??s.version),this.subpath=tr(n??s.subpath)}static parse(e){let t=sp(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=ip(t[1]??""),a=tr(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=ip(t[0]),o=tr(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(et).host,s=new URL(un).host;if(t.host===n){let i=sp(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:tr(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://")}},tr=r=>r&&r.length?r:void 0,ip=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),tr(r.slice(e+1))]};async function oe(r){try{return await r()}catch{return}}function xt(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function ic(r){return r.startsWith("./")?r:`./${r}`}var fn=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 $(e):e;return`${un}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(xt(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(",")),`${et}/${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),`${et}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await oe(()=>this.http.head(t)),s=this.parseVersionFromUrl(n?.url||t);if(s)return s}}async fetchVersionsIndex(e){if(await this.cache.isNegative(e))return;let t=await this.cache.getIndex(e);if(t&&Date.now()-t.updatedAt<this.versionsIndexMs)return{versions:t.versions,distTags:t.distTags};let n=await oe(()=>this.http.getJson(`${sc}${encodeURIComponent(e)}`));if(!n?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=n.tags&&Object.keys(n.tags).length?n.tags:void 0;return await this.cache.setIndex(e,n.versions,s),{versions:n.versions,distTags:s}}parseVersionFromUrl(e){let t=$.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let n=await this.cache.getMeta(e,t);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:d,peerDependencies:u,peerDependenciesMeta:f}=n;return{name:e,version:t,dependencies:d,peerDependencies:u,peerDependenciesMeta:f}}let s=this.packageJson(new $(`${e}@${t}`)),i=await oe(()=>this.http.getJson(s));if(!i)return;let o=d=>d&&Object.keys(d).length?d:void 0,a=o(i.dependencies),c=o(i.peerDependencies),l=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}};var op=r=>r.startsWith("@types/"),dn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!op(e)),oc=r=>Object.keys(r?.dependencies||{}).filter(e=>!op(e)),QS=r=>dn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),pn=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 QS(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=>dn(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:dn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var mn=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await oe(()=>this.cdn.fetchVersionsIndex(e));if(t?.versions?.length){let n=this.semver.selectBestVersion(t.versions,{distTags:t.distTags});if(n)return n}return this.cdn.resolveExactVersion(e)}async resolveExactForRoot(e,t){if(!t)return this.learnExactVersion(e);let n=await this.cache.getPinnedExact(e,t);if(n){if(this.semver.isExactVersion(n))return n;console.debug("[typebulb] cached version for",e,"is not exact (",n,"); re-resolving from registry")}let s=async o=>{if(o&&this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o},i=await oe(()=>this.cdn.fetchVersionsIndex(e));if(i?.versions?.length){let o=this.semver.selectBestVersion(i.versions,{range:t,distTags:i.distTags});if(o){let a=await s(o);if(a)return a}else{console.debug("[typebulb] refreshing version cache for",e,"(",t,"not in cached set \u2014 likely a new release)"),await this.cache.invalidateVersionsCache(e);let a=await oe(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=await s(this.semver.selectBestVersion(a.versions,{range:t,distTags:a.distTags}));if(c)return c}}}return s(await this.cdn.resolveExactVersion(`${e}@${t}`))}async effectivePackage(e,t){let n=new $(e),s=n.root(),i=t[s],o=i?await oe(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as XS,parse as ZS}from"es-module-lexer";var rr=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))$.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{$.isBare(s)&&t.add(s)};try{await XS;let[s]=ZS(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($.rootOf(u))),i=[...new Set(s.map($.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),d=this.buildEntries([...s,...l.map(u=>u.name)],a,c);return{importMap:{imports:Object.fromEntries(d)},prefetchUrls:d.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=await this.version.resolveExactForRoot(e,n);if(!s)throw new Error(`Cannot resolve ${n?`${e}@${n}`:e}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);return s}buildEntries(e,t,n){let s=new Map(t.map(p=>[p.name,p])),i=p=>{let b=s.get($.rootOf(p));return new $(p).withVersion(b.version).format()},o=new Set([...n.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==$.rootOf(p)).map($.rootOf)),c=[],l=new Set,d=new Set(e.filter(p=>p===$.rootOf(p))),u=new Set;for(let p of e){let b=$.rootOf(p),h=s.get(b),{isPeerRoot:w,hasPeers:x,isSharedDep:E}=n.get(b),T=a.has(b),P=p!==b,m=!(w||E)&&(T||!x),y=this.singletonDepsOf(h,o),v=P&&d.has(b);v&&u.add(b);let R=v?[...y,b]:y.length?y:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:m,external:R})]),l.add(p)}let f=new Set([...o,...u]);for(let p of f)s.has(p)&&(l.has(p)||c.push([p,this.cdn.buildEsmUrl(i(p),{})]),c.push([`${p}/`,`${et}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...dn(e.meta),...oc(e.meta)])].filter(n=>t.has(n))}};rr.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as ap,satisfies as ek,maxSatisfying as cp,major as tk,valid as rk}from"semver";var Ks=class{cmp(e,t){return e===t?0:ap(e,t)?1:ap(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!ek(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=cp(e,n,{includePrerelease:!1});if(a)return a}return cp(e,n,{includePrerelease:!0})??void 0}majorOf(e){return tk(e)}isExactVersion(e){return rk(e)!==null}},Et=new Ks;var At=class{constructor(e){this.store=e}async isNegative(e){let t=await oe(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await oe(()=>this.store.get(e)))?.attempts||0)+1;await oe(()=>this.store.set(e,{until:Date.now()+nk(n),attempts:n}))}async clearNegative(e){await oe(()=>this.store.delete(e))}};function nk(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}function lp(r,e){let t=new fn(r,e),n=new pn(t),s=new mn(r,t,Et);return{packageService:new rr(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as gp from"fs/promises";import*as ye from"path";import*as rt from"fs/promises";import*as $e from"path";import*as dp from"os";import*as ac from"fs/promises";import*as up from"crypto";function ge(r){return up.createHash("sha1").update(r).digest("hex")}async function Le(r){try{return JSON.parse(await ac.readFile(r,"utf8"))}catch{return}}async function Hs(r){try{return await ac.readFile(r,"utf8")}catch{return}}var fp=1,tt=$e.join(dp.homedir(),".typebulb","cache"),hn=$e.join(tt,"packages"),gn=$e.join(tt,"proxy"),Ws=$e.join(tt,"dts"),sk=$e.join(tt,"emit"),cc;function K(){return cc||(cc=ik()),cc}function Vs(r,e){return $e.join(sk,ge(r),e)}async function ik(){await rt.mkdir(tt,{recursive:!0});let r=$e.join(tt,"version.json");if((await Le(r))?.version===fp)return;let t=await rt.readdir(tt).catch(()=>[]);await Promise.all(t.map(n=>rt.rm($e.join(tt,n),{recursive:!0,force:!0}))),await rt.writeFile(r,JSON.stringify({version:fp})+`
|
|
702
|
+
`,"utf8")}import*as nt from"fs/promises";import*as pp from"path";async function ue(r,e){await nt.mkdir(pp.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await nt.writeFile(t,e,"utf8"),await nt.rename(t,r).catch(async n=>{throw await nt.rm(t,{force:!0}).catch(()=>{}),n})}var nr=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=Le(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 ue(this.filePath,JSON.stringify(Object.fromEntries(e)))}};var lc=ye.join(hn,"indexes"),mp=ye.join(hn,"pinned"),ok=ye.join(hn,"meta"),ak=ye.join(hn,"negative.json"),Gs=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new At(new nr(ak));async getPinnedExact(e,t){let n=`${e}@${t}`;if(this.pinnedMem.has(n))return this.pinnedMem.get(n);await K();let s=await Hs(ye.join(mp,ge(n)+".txt"));return this.pinnedMem.set(n,s),s}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await K(),await ue(ye.join(mp,ge(s)+".txt"),n)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await K();let t=await Le(ye.join(lc,Ys(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 K(),await ue(ye.join(lc,Ys(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await gp.rm(ye.join(lc,Ys(e)+".json"),{force:!0})}async isNegative(e){return await K(),this.negativeCache.isNegative(e)}async recordNegative(e){await K(),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 K();let s=await Le(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 K(),await ue(hp(e,t),JSON.stringify(o))}};function hp(r,e){return ye.join(ok,Ys(r),encodeURIComponent(e)+".json")}function Ys(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 ck=new Gs,{packageService:zs,versionResolver:bp,cdnClient:wp,peerResolver:XC}=lp(ck,yp);var vp=`
|
|
675
703
|
(() => {
|
|
676
704
|
// Embedded (bulb-in-a-bulb): runs inside a sandboxed iframe with no parent
|
|
677
705
|
// bridge, so privileged tb.* (AI, fs, server RPC) can't reach a host and would
|
|
@@ -700,6 +728,28 @@ ${TS(t)}`)}var Ge="https://esm.sh",tn="https://cdn.jsdelivr.net/npm/",Ua="https:
|
|
|
700
728
|
// Read from window each time so updates are visible
|
|
701
729
|
const getData = () => window.__TB_DATA__ || [];
|
|
702
730
|
|
|
731
|
+
// #tb= fragment restore (TB-Inference.md "Sharing a local run"): a refreshed or pasted share
|
|
732
|
+
// URL re-injects its run before the bulb code reads tb.insight()/tb.data() \u2014 the template's
|
|
733
|
+
// module script awaits __tbBoot, so the async decode still lands ahead of synchronous startup
|
|
734
|
+
// reads. Decode failure falls through to the file's own blocks with a console note.
|
|
735
|
+
if (!isEmbedded && location.protocol.indexOf('http') === 0 && location.hash.indexOf('#tb=') === 0) {
|
|
736
|
+
globalThis.__tbBoot = fetch('/__infer-decode', {
|
|
737
|
+
method: 'POST',
|
|
738
|
+
headers: { 'Content-Type': 'application/json' },
|
|
739
|
+
body: JSON.stringify({ hash: location.hash })
|
|
740
|
+
})
|
|
741
|
+
.then((r) => r.json())
|
|
742
|
+
.then((res) => {
|
|
743
|
+
if (res && Array.isArray(res.data)) {
|
|
744
|
+
window.__TB_INSIGHT__ = res.insightJson;
|
|
745
|
+
window.__TB_DATA__ = res.data;
|
|
746
|
+
} else {
|
|
747
|
+
console.warn('[typebulb] The #tb= fragment could not be decoded (incomplete or corrupted link) \u2014 using the bulb file state.');
|
|
748
|
+
}
|
|
749
|
+
})
|
|
750
|
+
.catch(() => {});
|
|
751
|
+
}
|
|
752
|
+
|
|
703
753
|
// tb.onMessage subscribers, fed by the events-SSE 'message' channel (typebulb send). A message is
|
|
704
754
|
// JSON-or-string: parse as JSON, else hand back the raw string; '' (a bare \`send\`) \u21D2 undefined.
|
|
705
755
|
const messageHandlers = new Set();
|
|
@@ -853,6 +903,52 @@ ${TS(t)}`)}var Ge="https://esm.sh",tn="https://cdn.jsdelivr.net/npm/",Ua="https:
|
|
|
853
903
|
})();
|
|
854
904
|
const ai = Object.assign(aiCall, { stream: aiStream });
|
|
855
905
|
|
|
906
|
+
// tb.infer() \u2014 the local inference layer (TB-Inference.md). The UI and network live in the
|
|
907
|
+
// lazy-imported modal module (/__infer-ui.js \u2014 zero bytes here until the first call); the shim
|
|
908
|
+
// stays the state machine and globals writer. The promise settles once: a modal retry after a
|
|
909
|
+
// rejected promise still updates runtime state on success, for tb.insight() readers.
|
|
910
|
+
let inferState = 'idle';
|
|
911
|
+
let dataOverrides = null;
|
|
912
|
+
const infer = (opts = {}) => {
|
|
913
|
+
if (isEmbedded) return Promise.reject(embedErr('tb.infer()'));
|
|
914
|
+
if (inferState === 'running') return Promise.reject(new Error('Inference already in progress'));
|
|
915
|
+
inferState = 'running';
|
|
916
|
+
// Data priority (matching the .com sandbox): explicit arg > setData overrides > undefined \u2014
|
|
917
|
+
// the modal then seeds from the SOURCE chunks (/__infer-info), the local Data tab, exactly as
|
|
918
|
+
// .com's IDE modal reseeds from the Data tab rather than post-run runtime state.
|
|
919
|
+
let data = opts.data;
|
|
920
|
+
if (data === undefined && dataOverrides) data = Object.values(dataOverrides);
|
|
921
|
+
if (data !== undefined && !Array.isArray(data)) data = [data];
|
|
922
|
+
return new Promise((resolve, reject) => {
|
|
923
|
+
let settled = false;
|
|
924
|
+
const settle = (fn, v) => { if (!settled) { settled = true; fn(v); } };
|
|
925
|
+
import('/__infer-ui.js').then((ui) => {
|
|
926
|
+
ui.runInference({
|
|
927
|
+
data,
|
|
928
|
+
// The transport reader is the shim's \u2014 one NDJSON decoder per page, never two
|
|
929
|
+
// drifting copies (TB-Streaming.md envelope: payload-side, so drift is not tolerable).
|
|
930
|
+
readStream,
|
|
931
|
+
onComplete: (final) => {
|
|
932
|
+
// Runtime state only, never the file (TB-Inference.md Invariant 2).
|
|
933
|
+
window.__TB_INSIGHT__ = final.insightJson;
|
|
934
|
+
if (final.data && final.data.length) window.__TB_DATA__ = final.data;
|
|
935
|
+
if (final.hash) history.replaceState(null, '', location.pathname + location.search + final.hash);
|
|
936
|
+
inferState = 'complete';
|
|
937
|
+
settle(resolve, final.insight);
|
|
938
|
+
},
|
|
939
|
+
onError: (err) => {
|
|
940
|
+
inferState = 'error';
|
|
941
|
+
const e = new Error(err.message); e.code = err.code; e.retryable = !!err.retryable;
|
|
942
|
+
settle(reject, e);
|
|
943
|
+
},
|
|
944
|
+
onCancel: () => {
|
|
945
|
+
if (!settled) { inferState = 'idle'; settle(resolve, undefined); }
|
|
946
|
+
}
|
|
947
|
+
});
|
|
948
|
+
}).catch((e) => { inferState = 'error'; settle(reject, e); });
|
|
949
|
+
});
|
|
950
|
+
};
|
|
951
|
+
|
|
856
952
|
// tb.server.<fn>(...) \u2014 one call object that is both awaitable (single result) and async-iterable
|
|
857
953
|
// (a streamed async-generator export). The server picks by export kind; this stays graceful if
|
|
858
954
|
// they're mismatched (await a stream \u2192 array of chunks; for-await a normal result \u2192 one value).
|
|
@@ -896,15 +992,11 @@ ${TS(t)}`)}var Ge="https://esm.sh",tn="https://cdn.jsdelivr.net/npm/",Ua="https:
|
|
|
896
992
|
json: (index) => parseJson(getData()[index]),
|
|
897
993
|
insight: () => window.__TB_INSIGHT__ ? parseJson(window.__TB_INSIGHT__) : undefined,
|
|
898
994
|
|
|
899
|
-
// Inference
|
|
900
|
-
infer
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
},
|
|
905
|
-
inferenceState: () => 'idle',
|
|
906
|
-
setData: () => {},
|
|
907
|
-
resetInferenceState: () => {},
|
|
995
|
+
// Inference (TB-Inference.md) \u2014 modal-hosted one-shot LLM call over the bulb's own blocks
|
|
996
|
+
infer,
|
|
997
|
+
inferenceState: () => inferState,
|
|
998
|
+
setData: (index, content) => { if (!dataOverrides) dataOverrides = {}; dataOverrides[index] = content; },
|
|
999
|
+
resetInferenceState: () => { inferState = 'idle'; dataOverrides = null; },
|
|
908
1000
|
|
|
909
1001
|
// AI - tb.ai() proxies to the provider via the local server; tb.ai.stream() streams AiChunks.
|
|
910
1002
|
ai,
|
|
@@ -1007,18 +1099,18 @@ ${TS(t)}`)}var Ge="https://esm.sh",tn="https://cdn.jsdelivr.net/npm/",Ua="https:
|
|
|
1007
1099
|
};
|
|
1008
1100
|
}
|
|
1009
1101
|
})();
|
|
1010
|
-
`;var
|
|
1102
|
+
`;var sr=r=>r.replace(/<\/script/gi,"<\\/script");function Qs(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}var Xs=` *, *::before, *::after { box-sizing: border-box; }
|
|
1011
1103
|
canvas { max-width: 100%; }
|
|
1012
1104
|
body { margin: 0; display: flow-root; font-family: system-ui, -apple-system, sans-serif; }
|
|
1013
1105
|
html[data-theme="dark"] { color-scheme: dark; }
|
|
1014
|
-
html[data-theme="light"] { color-scheme: light; }`;function
|
|
1106
|
+
html[data-theme="light"] { color-scheme: light; }`;function Zs(r,e){return` <script>
|
|
1015
1107
|
(function() {
|
|
1016
1108
|
try {
|
|
1017
|
-
var KEY = ${
|
|
1109
|
+
var KEY = ${sr(JSON.stringify("tb-theme:"+r))};
|
|
1018
1110
|
var doc = document.documentElement;
|
|
1019
1111
|
var mq = window.matchMedia('(prefers-color-scheme: dark)');
|
|
1020
1112
|
var os = function() { return mq.matches ? 'dark' : 'light'; };
|
|
1021
|
-
var FORCED = ${
|
|
1113
|
+
var FORCED = ${sr(JSON.stringify(e??null))};
|
|
1022
1114
|
var stored = function() {
|
|
1023
1115
|
try { var v = localStorage.getItem(KEY); return (v === 'dark' || v === 'light') ? v : undefined; }
|
|
1024
1116
|
catch (e) { return undefined; }
|
|
@@ -1046,19 +1138,19 @@ ${TS(t)}`)}var Ge="https://esm.sh",tn="https://cdn.jsdelivr.net/npm/",Ua="https:
|
|
|
1046
1138
|
});
|
|
1047
1139
|
} catch (e) {}
|
|
1048
1140
|
})();
|
|
1049
|
-
</script>`}function
|
|
1050
|
-
html, body { height: 100%; }`,f={imports:
|
|
1141
|
+
</script>`}function Sp(r){let{name:e,code:t,css:n,html:s,data:i,insight:o,importMap:a,theme:c,embedded:l}=r,d=s.trim()||'<div id="app"></div>',u=l?"":`
|
|
1142
|
+
html, body { height: 100%; }`,f={imports:uk(a.imports)};return`<!DOCTYPE html>
|
|
1051
1143
|
<html>
|
|
1052
1144
|
<head>
|
|
1053
1145
|
<meta charset="utf-8">
|
|
1054
1146
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1055
|
-
<title>${
|
|
1056
|
-
${
|
|
1147
|
+
<title>${Qs(e)} - typebulb</title>
|
|
1148
|
+
${Zs(e,c)}
|
|
1057
1149
|
<script type="importmap">
|
|
1058
1150
|
${JSON.stringify(f,null,2)}
|
|
1059
1151
|
</script>
|
|
1060
1152
|
<style>
|
|
1061
|
-
${
|
|
1153
|
+
${Xs}${u}
|
|
1062
1154
|
</style>
|
|
1063
1155
|
<style>
|
|
1064
1156
|
${n}
|
|
@@ -1067,21 +1159,22 @@ ${n}
|
|
|
1067
1159
|
<body>
|
|
1068
1160
|
${d}
|
|
1069
1161
|
|
|
1070
|
-
${i.length>0?`<script>window.__TB_DATA__ = ${
|
|
1071
|
-
${o?`<script>window.__TB_INSIGHT__ = ${
|
|
1162
|
+
${i.length>0?`<script>window.__TB_DATA__ = ${sr(JSON.stringify(i))};</script>`:""}
|
|
1163
|
+
${o?`<script>window.__TB_INSIGHT__ = ${sr(JSON.stringify(o))};</script>`:""}
|
|
1072
1164
|
|
|
1073
1165
|
<script>
|
|
1074
|
-
${
|
|
1166
|
+
${vp}
|
|
1075
1167
|
</script>
|
|
1076
1168
|
|
|
1077
|
-
${
|
|
1169
|
+
${lk}
|
|
1078
1170
|
|
|
1079
1171
|
<script type="module">
|
|
1080
|
-
|
|
1081
|
-
globalThis.
|
|
1172
|
+
globalThis.__tbEntryRan = true; /* import graph resolved \u2014 the load-failure backstop's signal (imports hoist above this line) */
|
|
1173
|
+
await globalThis.__tbBoot; /* #tb= fragment restore, set by the shim when present (TB-Inference.md) */
|
|
1174
|
+
${sr(t)}
|
|
1082
1175
|
</script>
|
|
1083
1176
|
</body>
|
|
1084
|
-
</html>`}var
|
|
1177
|
+
</html>`}var lk=`<script>
|
|
1085
1178
|
(function () {
|
|
1086
1179
|
var framed = window.parent !== window;
|
|
1087
1180
|
var post = function (m) { try { parent.postMessage(m, '*'); } catch (e) {} }; /* framed only */
|
|
@@ -1177,8 +1270,8 @@ globalThis.__tbEntryRan = true; /* load-failure backstop \u2014 see embedProtoco
|
|
|
1177
1270
|
}
|
|
1178
1271
|
});
|
|
1179
1272
|
})();
|
|
1180
|
-
</script>`;function
|
|
1181
|
-
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await
|
|
1273
|
+
</script>`;function uk(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}import*as ti from"fs/promises";import*as ei from"path";import{existsSync as kp,readFileSync as fk}from"fs";import{execFile as dk}from"child_process";import{promisify as pk}from"util";import{satisfies as mk}from"semver";var hk=pk(dk),gk=/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+(@[a-zA-Z0-9.^~*x-]+)?$/i;async function ri(r,e,t,n){let i=r.map(l=>yk(l,t)).filter(l=>!bk(l,e));if(i.length===0)return;let o=i.filter(l=>!gk.test(l));if(o.length)throw new Error(`Refusing to install npm spec(s) with unsupported characters: ${o.join(", ")}
|
|
1274
|
+
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await ti.mkdir(e,{recursive:!0});let a=ei.join(e,"package.json");kp(a)||await ti.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 hk("npm",["install",...c,...i],{cwd:e,shell:!0})}function yk(r,e){if(!e||$.parse(r).version)return r;let t=e[r];return t?`${r}@${t}`:r}function bk(r,e){let{name:t,version:n}=$.parse(r),s=ei.join(e,"node_modules",t);if(!kp(s))return!1;if(!n)return!0;try{let i=JSON.parse(fk(ei.join(s,"package.json"),"utf-8")).version;return mk(i,n)}catch{return!1}}function ni(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($.rootOf(s))}return[...e]}cr();di();Ct();async function Ip(r){let e=De(r.provider,r.model);if(typeof e=="string")throw new Error(e);let t=await st(e,r);if(!t.ok){let n=await ar(t,e.protocol);throw new Error(n.message)}return{response:t,protocol:e.protocol}}async function Fk(r){let{response:e,protocol:t}=await Ip(r);return{text:await Pt(e,t)}}async function*qk(r){let{response:e,protocol:t}=await Ip(r);yield*Ot(e,t)}function Lp(){let r=Object.assign(Fk,{stream:qk});globalThis.tb=Object.freeze({ai:r,models:()=>Me(),hasOwnKeys:fi,mode:"local"})}async function $p(r){let t=(await it.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?Be.join(r,t):null}async function we(r){let e=await it.readFile(r,"utf-8"),t=Re(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=er(t);return{bulb:n,config:Jn(n.config),warnings:Yl(e)}}function Ac(r){let e=Be.basename(r).replace(/\.bulb\.md$/i,"");return Be.join(Be.dirname(r),".typebulb",`${e}.server.mjs`)}async function vn(r,e,t,n){let s=nc(r,{serverOnly:!0});if(s.error)throw new Error(`Server compilation error: ${s.error}`);let i=s.code;t&&(i=await ql(i,t));let o=Be.join(Be.dirname(e),".typebulb");await it.mkdir(o,{recursive:!0});let a=ni(i);a.length>0&&await ri(a,o,n);let c=Ac(e);return await it.writeFile(c,i,"utf-8"),Lp(),await import(`${Uk(c).href}?t=${Date.now()}`)}async function Tc(r,e,t,n){let{bulb:s,config:i}=await we(r),o=qs(s.data);np(s.code,i.dependencies??{});let a=nc(s.code,{jsxImportSource:i.ts?.jsxImportSource});a.error&&console.error("Compilation error:",a.error);let{importMap:c}=await zs.buildImportMap(a.code,i.dependencies??{},n?new Set([n.name]):void 0);n&&(c.imports[n.name]=n.entryUrl);let l=Sp({name:s.name,code:a.code,css:s.css,html:s.html,data:o,insight:s.insight,importMap:c,watch:e}),d=null;return s.server&&t&&(d=await vn(s.server,r,n,i.dependencies)),{html:l,bulb:s,serverExports:d}}cn();Sn();wi();Qc();var Wi={claude:{adapter:()=>new pr,server:()=>Promise.resolve().then(()=>(ph(),dh))},pi:{adapter:()=>new br,server:()=>Promise.resolve().then(()=>(xh(),kh))}};function Eh(r){return r in Wi}function Er(){return Object.keys(Wi)}function Ah(){return Object.fromEntries(Object.entries(Wi).map(([r,e])=>[r,e.adapter]))}function Th(r){return Wi[r].server()}import*as ut from"path";import{spawn as MA,execSync as DA}from"child_process";import{createRequire as BA}from"module";import{existsSync as jA}from"fs";import*as ne from"fs/promises";import*as te from"path";var ul=[{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"}],fl=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function dl(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 fA=`
|
|
1182
1275
|
/**
|
|
1183
1276
|
* Get raw data chunk from the Data tab.
|
|
1184
1277
|
* @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
|
|
@@ -1189,7 +1282,7 @@ globalThis.__tbEntryRan = true; /* load-failure backstop \u2014 see embedProtoco
|
|
|
1189
1282
|
* @param index - Chunk index (0-based)
|
|
1190
1283
|
* @throws If chunk is not valid JSON/JSON-ish
|
|
1191
1284
|
*/
|
|
1192
|
-
json<T = unknown>(index: number): T;`,
|
|
1285
|
+
json<T = unknown>(index: number): T;`,dA=`
|
|
1193
1286
|
/**
|
|
1194
1287
|
* Get the insight data produced by the inference layer.
|
|
1195
1288
|
*
|
|
@@ -1198,7 +1291,7 @@ globalThis.__tbEntryRan = true; /* load-failure backstop \u2014 see embedProtoco
|
|
|
1198
1291
|
*
|
|
1199
1292
|
* @returns The parsed insight JSON, or undefined if no insight is available
|
|
1200
1293
|
*/
|
|
1201
|
-
insight<T = unknown>(): T | undefined;`,
|
|
1294
|
+
insight<T = unknown>(): T | undefined;`,Ph=`options: {
|
|
1202
1295
|
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
1203
1296
|
system?: string;
|
|
1204
1297
|
/** 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. */
|
|
@@ -1209,12 +1302,12 @@ globalThis.__tbEntryRan = true; /* load-failure backstop \u2014 see embedProtoco
|
|
|
1209
1302
|
webSearch?: boolean;
|
|
1210
1303
|
/** Abort the request. On abort the promise rejects / the stream ends. */
|
|
1211
1304
|
signal?: AbortSignal;
|
|
1212
|
-
}`,
|
|
1305
|
+
}`,Oh=`
|
|
1213
1306
|
/** A single streamed delta from \`tb.ai.stream()\`. Discriminated by \`kind\`. */
|
|
1214
1307
|
type AiChunk =
|
|
1215
1308
|
| { kind: "text"; text: string }
|
|
1216
1309
|
| { kind: "reasoning"; text: string };
|
|
1217
|
-
`,
|
|
1310
|
+
`,Ch=`
|
|
1218
1311
|
/**
|
|
1219
1312
|
* General-purpose AI call. \`tb.ai(opts)\` resolves with the full text; \`tb.ai.stream(opts)\`
|
|
1220
1313
|
* returns an async iterable of {@link AiChunk} deltas you consume with \`for await\`.
|
|
@@ -1223,7 +1316,7 @@ type AiChunk =
|
|
|
1223
1316
|
* @throws On rate limit, network error, or provider error
|
|
1224
1317
|
*/
|
|
1225
1318
|
ai: {
|
|
1226
|
-
(${
|
|
1319
|
+
(${Ph}): Promise<{ text: string }>;
|
|
1227
1320
|
/**
|
|
1228
1321
|
* Streaming counterpart of \`tb.ai()\`. Yields \`{ kind: "text" | "reasoning", text }\` deltas
|
|
1229
1322
|
* as they arrive; break the loop (or abort \`signal\`) to cancel and stop the upstream.
|
|
@@ -1237,8 +1330,8 @@ type AiChunk =
|
|
|
1237
1330
|
* if (c.kind === "text") answer += c.text;
|
|
1238
1331
|
* }
|
|
1239
1332
|
*/
|
|
1240
|
-
stream(${
|
|
1241
|
-
};`,
|
|
1333
|
+
stream(${Ph}): AsyncIterable<AiChunk>;
|
|
1334
|
+
};`,_h=`
|
|
1242
1335
|
/**
|
|
1243
1336
|
* Returns AI models available to the current user.
|
|
1244
1337
|
* Models are filtered by the user's configured API keys.
|
|
@@ -1260,7 +1353,7 @@ type AiChunk =
|
|
|
1260
1353
|
* making many AI calls should check this and show a "use your own keys"
|
|
1261
1354
|
* notice instead of running.
|
|
1262
1355
|
*/
|
|
1263
|
-
hasOwnKeys(): Promise<boolean>;`,
|
|
1356
|
+
hasOwnKeys(): Promise<boolean>;`,pA="\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;",Rh=`
|
|
1264
1357
|
/**
|
|
1265
1358
|
* The mode this bulb is running in.
|
|
1266
1359
|
*
|
|
@@ -1270,7 +1363,7 @@ type AiChunk =
|
|
|
1270
1363
|
* - \`'embedded'\` \u2014 Running as a bulb embedded inside another bulb (sandboxed,
|
|
1271
1364
|
* client-only: AI, filesystem, and server RPC are unavailable)
|
|
1272
1365
|
*/
|
|
1273
|
-
mode: 'local' | 'editor' | 'published' | 'embedded';`,
|
|
1366
|
+
mode: 'local' | 'editor' | 'published' | 'embedded';`,mA=`
|
|
1274
1367
|
/**
|
|
1275
1368
|
* Local filesystem access (CLI only).
|
|
1276
1369
|
*
|
|
@@ -1285,7 +1378,7 @@ type AiChunk =
|
|
|
1285
1378
|
readBytes(path: string): Promise<Uint8Array>;
|
|
1286
1379
|
/** Write text or raw bytes to a file. Creates parent directories if needed. */
|
|
1287
1380
|
write(path: string, content: string | Uint8Array): Promise<boolean>;
|
|
1288
|
-
};`,
|
|
1381
|
+
};`,hA=`
|
|
1289
1382
|
/**
|
|
1290
1383
|
* Async value inspector for tensor-like objects.
|
|
1291
1384
|
*
|
|
@@ -1352,7 +1445,7 @@ type AiChunk =
|
|
|
1352
1445
|
*
|
|
1353
1446
|
* @returns The full canonical URL
|
|
1354
1447
|
*/
|
|
1355
|
-
url(): Promise<string>;`,
|
|
1448
|
+
url(): Promise<string>;`,gA=`
|
|
1356
1449
|
/**
|
|
1357
1450
|
* Subscribe to a value pushed from the terminal via \`typebulb send <file> [message]\`.
|
|
1358
1451
|
*
|
|
@@ -1367,49 +1460,354 @@ type AiChunk =
|
|
|
1367
1460
|
* @param handler - Called with each pushed message.
|
|
1368
1461
|
* @returns An unsubscribe function.
|
|
1369
1462
|
*/
|
|
1370
|
-
onMessage(handler: (message: any) => void): () => void;`,
|
|
1463
|
+
onMessage(handler: (message: any) => void): () => void;`,yA="\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>>;",pl=`${Oh}
|
|
1371
1464
|
/**
|
|
1372
1465
|
* Typebulb utilities namespace.
|
|
1373
1466
|
* Type \`tb.\` to discover available helpers.
|
|
1374
1467
|
*/
|
|
1375
|
-
declare const tb: {${
|
|
1468
|
+
declare const tb: {${fA}${hA}${dA}${yA}${gA}${Ch}${mA}${_h}${pA}${Rh}
|
|
1376
1469
|
};
|
|
1377
|
-
`,
|
|
1470
|
+
`,ml=`${Oh}
|
|
1378
1471
|
/**
|
|
1379
1472
|
* Typebulb utilities namespace (server-side).
|
|
1380
1473
|
* Type \`tb.\` to discover available helpers.
|
|
1381
1474
|
*/
|
|
1382
|
-
declare const tb: {${
|
|
1475
|
+
declare const tb: {${Ch}${_h}${Rh}
|
|
1383
1476
|
};
|
|
1384
|
-
`;import
|
|
1477
|
+
`;import SA from"p-limit";import{resolve as Ih}from"resolve.exports";var qe={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},_n=["index.d.ts","index.d.mts"],hl=/\.d\.(ts|mts|cts)$/i;function Vi(r){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(r)||/[?&]dts(?:[&#]|$)/i.test(r)}function Nh(r){return[`${r}.d.ts`,`${r}.d.mts`]}function lt(r){if(!r||r==="./"||r==="/")return[..._n];let e=r.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=Nh(e),n=e.endsWith("/")?e:`${e}/`;return t.push(...Nh(`${n}index`)),t}async function Ar(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(bA(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function bA(r){return r===408||r===429||r>=500&&r<600}var Yi=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)||Vi(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 $({name:e,version:t})),s=await Ar(n);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new $({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=xt(e.path);if(!o||o==="/"||o===".")return this.tryUntilSuccess([..._n],t);if(!hl.test(o)){let a=await this.tryUntilSuccess(lt(o),t);if(a)return a}return t(o)}let s=lt(e.path),i=n?.subpath?[...s,..._n]:[..._n,...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(Ih(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(Ih(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=$.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 $(i).format(),a=new $({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=ic(t.subpath),f=this.resolveExportsPath(n,u);if(f){let b=await this.resolveFromSelected(this.toResolutionResult(f),c,{subpath:!0});if(b)return{...b,resolvedPkg:a}}let p=await this.tryUntilSuccess(lt(u),c);if(p)return{...p,resolvedPkg:a}}let l=n.types??n.typings;if(l){let u=await this.resolveFromSelected({kind:"types",path:l},c);if(u)return{...u,resolvedPkg:o}}let d=this.resolveExportsPath(n,".");if(d){let u=await this.resolveFromSelected(this.toResolutionResult(d),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=xt(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 wA}from"fflate";var Gi=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Ar(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=wA(e),s=new TextDecoder("utf-8"),i=0;for(;i<n.length-512;){let o=n.slice(i,i+512);if(o[0]===0)break;let a=o.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),d=o.slice(124,136),u=s.decode(d).trim().replace(/\0/g,""),f=parseInt(u,8)||0,p=String.fromCharCode(o[156]);if(i+=512,(p==="0"||p==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let b=n.slice(i,i+f);t.set(this.normalizeTarPath(l),s.decode(b))}i+=Math.ceil(f/512)*512}}catch{}return t}};var zi=class{constructor(e,t,n=new Gi){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=Et.majorOf(n),o=e.filter(a=>Et.majorOf(a)===i);if(o.length)return o.sort((a,c)=>Et.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=lt(e);return t!==e&&n.push(`${e}.d.ts`,`${e}/index.d.ts`),n}async fetchFromVersionedRoot(e,t){let n=new $(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 $(t).format():t.name}}}async resolve(e){let t=$.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 Qi=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(`
|
|
1385
1478
|
`).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
|
|
1386
|
-
`),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
|
|
1387
|
-
`);await this.prefetchBareDeps(
|
|
1388
|
-
`,"utf8"),await
|
|
1389
|
-
`,"utf8"),{dir:e}}function
|
|
1390
|
-
`))console.log(`${e} ${n}`);return r.length>0}function
|
|
1479
|
+
`),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 Lh="file:///node_modules",Xi=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${Lh}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=xt(t);return`${Lh}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as vA}from"lru-cache";function $h(r){let e=new vA({ttl:qe.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 Ar(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(),d=c.url||s;return await r.clearNegative(s),await r.setCachedFile(d,l),{dts:l,url:d}})();return t.set(s,a),await a.finally(()=>t.delete(s))}catch{return}}}var Rn=class{constructor(e){this.inFlight=new Map,this.scanner=new Qi,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=$h(e.cache),this.typescriptProvider=new Yi(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new zi(e.cdnClient,e.cache),this.virtualFs=new Xi}withInFlight(e,t){let n=this.inFlight.get(e);if(n)return n;let s=t().finally(()=>this.inFlight.delete(e));return this.inFlight.set(e,s),s}invalidate(){this.virtualFs.bumpEpoch(),this.inFlight.clear()}pushFileIfNew(e,t,n){e.some(s=>s.path===t)||e.push({path:t,content:n})}createStubDef(e){let t=this.virtualFs.pathForMain(e);return{pkg:e,mainPath:t,files:[{path:t,content:"export const _shim: any; export default _shim;"}],shims:[{module:e,path:t}]}}async fetchViaProviders(e){for(let t of[this.typescriptProvider,this.definitelyTypedProvider])try{let n=await t.resolve(e);if(n?.dts)return n}catch{}}async fetchRootDts(e,t){let{effectivePackage:n,root:s,pinned:i}=await this.versionResolver.effectivePackage(e,t),o=await this.cache.getCachedDts(n);if(o?.content){let c=o.url??this.cdnClient.file(i?`${s}@${i}`:s,"index.d.ts");return{dts:o.content,url:c,resolvedPkg:n}}let a;try{a=await this.fetchViaProviders(n)}catch{return}if(!(!a?.dts||!a.url)&&new $(n).subpath===new $(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>qe.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.scanner.collectRelativeTypeRefs(e).slice(0,qe.maxRelativeTypeRefs);for(let d of l)await this.tryRelativeRef(d,c,o,n,s,i)}catch{}}async tryRelativeRef(e,t,n,s,i,o){try{let a=new URL(e,t),c=a.pathname+a.search,l=Vi(c)?[c]:lt(c);for(let d of l){let f=new URL(d,a).toString();if(o.has(f))return;let p=await this.fetchDts(f);if(p?.dts){let b=this.toVirtualPath(n,new URL(p.url),s);this.pushFileIfNew(i,b,p.dts),await this.expandRelativeRefs(p.dts,p.url,s,i,o,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new $(e).name!==new $(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,qe.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=SA(qe.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,qe.maxBareDepth,a,i).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,i,o){if(s<=0||i.has(e))return;i.add(e);let a=await this.fetchRootDts(e,o);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):n.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let d=this.scanner.collectBareModuleRefs(a.dts).slice(0,qe.maxBareDeps).filter(u=>!i.has(u));for(let u of d)await this.prefetchBareDepsRecursive(u,t,n,s-1,i,o)}async resolve(e,t,n){let s=await this.packageService.extractImports(e),i=n?[...s,...n]:s;return(await Promise.all(i.map(a=>this.resolveOne(a,t)))).filter(a=>!!a)}async resolveOne(e,t){let{effectivePackage:n}=await this.versionResolver.effectivePackage(e,t);return this.withInFlight(n,async()=>{let s=new $(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 $(a||n),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:d,packageRootUrl:u}=this.computeEntryPath(o,l),f=[{path:d,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,f,void 0,u);let b=f.map(E=>E.content).join(`
|
|
1480
|
+
`);await this.prefetchBareDeps(b,l,f,p,s);let h=c.format(),w=e===h?[e]:[e,h],x=w.some(E=>this.ambientlyDeclares(i,E));return x?this.markFileAmbient(f,d):p.push(...w.map(E=>({module:E,path:d}))),{pkg:e,mainPath:d,files:f,shims:p,ambient:x}}};import*as Tr from"path";var kA=Tr.join(Ws,"pkg"),xA=Tr.join(Ws,"files"),EA=Tr.join(Ws,"negative.json"),eo=class{pkgMem=new Map;fileMem=new Map;negativeCache=new At(new nr(EA));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await K();let t=await Le(Mh(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 Zi(async()=>{await K(),await ue(Mh(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await K();let t=await Hs(Dh(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await Zi(async()=>{await K(),await ue(Dh(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await Zi(async()=>{await K(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return Zi(()=>this.negativeCache.clearNegative(e))}};async function Zi(r){try{await r()}catch{}}function Mh(r){return Tr.join(kA,ge(r)+".json")}function Dh(r){return Tr.join(xA,ge(r)+".txt")}var gl;function AA(){return gl||(gl=new Rn({cache:new eo,cdnClient:wp,packageService:zs,versionResolver:bp})),gl}var Bh="file:///node_modules/";async function jh(r){let e=Vs(r.emitKey,"typecheck");await K(),await ne.rm(e,{recursive:!0,force:!0}),await ne.mkdir(e,{recursive:!0});let t=CA(r.jsxImportSource,r.dependencies),n=await AA().resolve(r.code,r.dependencies,t),s=r.local?.name,i=s?n.filter(d=>d.pkg!==s):n,o=new Set;for(let d of i)for(let u of d.files){let f=to(u.path);if(!f||o.has(f))continue;o.add(f);let p=te.join(e,"node_modules",f);await ne.mkdir(te.dirname(p),{recursive:!0}),await ne.writeFile(p,u.content,"utf8")}let a={};for(let d of i)for(let u of d.shims){let f=to(u.path);f&&(a[u.module]=[`./node_modules/${f}`])}for(let d of i){if(d.ambient)continue;let u=to(d.mainPath);u&&(a[d.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let d of i)for(let u of d.files){if(!u.ambient)continue;let f=to(u.path);f&&c.add(`node_modules/${f}`)}if(r.local){delete a[r.local.name];let d=await _A(r.local,e);d?a[r.local.name]=[`./node_modules/${r.local.name}/${d}`]:console.warn(` local: '${r.local.name}' ships no type defs; check cannot type against it.`)}let l=TA(r.jsxImportSource,a,[...c]);return await ne.writeFile(te.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
|
|
1481
|
+
`,"utf8"),await ne.writeFile(te.join(e,"code.tsx"),r.code,"utf8"),await ne.writeFile(te.join(e,"tb.d.ts"),pl,"utf8"),{dir:e}}var yl={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function TA(r,e,t=[]){return{compilerOptions:{...yl,lib:PA([...ul,...fl]),jsx:"react-jsx",jsxImportSource:r??"react",paths:e},include:["code.tsx","tb.d.ts",...t]}}function PA(r){return dl(r).map(e=>OA(e.name))}function OA(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 CA(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function to(r){if(!r.startsWith(Bh))return;let e=r.slice(Bh.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function _A(r,e){if(!r.typesAbs)return;let t=te.dirname(r.typesAbs),n=te.join(e,"node_modules",r.name);for(let s of await RA(t)){let i=te.join(n,te.relative(t,s));await ne.mkdir(te.dirname(i),{recursive:!0}),await ne.copyFile(s,i)}return te.basename(r.typesAbs)}async function RA(r){let e=[];async function t(n){let s=await ne.readdir(n,{withFileTypes:!0});for(let i of s){let o=te.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 de from"fs/promises";import*as Ue from"path";import{existsSync as NA}from"fs";var IA="^22";async function Fh(r){let e=Vs(r.emitKey,"typecheck-server");await K(),await de.rm(e,{recursive:!0,force:!0}),await de.mkdir(e,{recursive:!0});let t=Ue.join(r.bulbDir,".typebulb"),n=ni(r.server).filter(o=>o!==r.local?.name);await ri([`@types/node@${IA}`,...n],t,r.dependencies,{ignoreScripts:!0});let s=Ue.join(t,"node_modules"),i=Ue.join(e,"node_modules");return await $A(s,i),await de.writeFile(Ue.join(e,"server.ts"),r.server,"utf8"),await de.writeFile(Ue.join(e,"tb.d.ts"),ml,"utf8"),await de.writeFile(Ue.join(e,"tsconfig.json"),JSON.stringify(LA(r.local),null,2)+`
|
|
1482
|
+
`,"utf8"),{dir:e}}function LA(r){let e={...yl,lib:["ES2023"],types:["node"]};if(r?.typesAbs){let t=i=>i.replace(/\\/g,"/"),n=t(Ue.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 $A(r,e){if(!NA(r)){await de.mkdir(e,{recursive:!0});return}await de.rm(e,{recursive:!0,force:!0});let t=process.platform==="win32"?"junction":"dir";await de.symlink(r,e,t)}Js();async function Uh(r,e){let{bulb:t,config:n,warnings:s}=await we(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=qh(ln(t.code,{target:"client",dependencies:n.dependencies??{}}),"client")||i),t.server&&(i=qh(ln(t.server,{target:"server"}),"server")||i);let o=UA([process.cwd(),ut.dirname(r)]);if(!o){let l=ut.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 jh({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 Fh({server:t.server,bulbDir:ut.dirname(r),emitKey:r,local:e?{name:e.name,typesAbs:e.typesAbs}:void 0,dependencies:n.dependencies});a.push({role:"server",dir:l})}for(let{role:l,dir:d}of a){let{stdout:u,exitCode:f}=await FA(o,d);for(let p of u.split(/\r?\n/))p.trim()&&console.log(`${l} ${p}`);f!==0&&(i=!0)}i&&process.exit(1);let c=[t.code&&"code.tsx",t.server&&"server.ts"].filter(Boolean).join(", ");console.error(`\u2713 no issues (${c})`)}function qh(r,e){for(let t of r)for(let n of t.message.split(`
|
|
1483
|
+
`))console.log(`${e} ${n}`);return r.length>0}function FA(r,e){return new Promise(t=>{let n=MA(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 qA=BA(import.meta.url);function UA(r){let e=n=>{try{let s=qA.resolve("typescript/package.json",{paths:n}),i=ut.join(ut.dirname(s),"lib","tsc.js");return jA(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=DA("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}Ti();Sn();async function Jh(r,e){let{bulb:t}=await we(r),n=hr(t);if(_t(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.)")}Sn();import*as Nn from"path";async function Kh(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=Cc();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=Nn.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),fr(t,e),console.log(e?`Trusted ${Nn.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${Nn.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}Pe();import*as Yh from"readline";var In=Ah();function Hh(){for(let r of Object.values(In))try{r().ensureHarnessSupport()}catch{}}function Ln(){for(let r of Object.keys(In))try{if(In[r]().detectsSelf())return r}catch{}}function Wh(r){let e=Er(),t=new Map(e.filter(i=>In[i]).map(i=>[i,In[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)))}}Pi();function bl(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 Gh(r){let e=Wh(process.cwd());if("ambiguous"in e){let t=await JA(r,e.ambiguous);return t?Vh(r,t):KA(r,e.ambiguous)}return Vh(r,e.name)}async function Vh(r,e){let t,n;try{t=await em(e)}catch(d){n=d instanceof Error?d.message:String(d)}let{lit:s,litLink:i,brand:o}=bl(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(gr())}`,` ${s(It())}`],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(`
|
|
1391
1484
|
`)+`
|
|
1392
|
-
`)}async function
|
|
1485
|
+
`)}async function JA(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:n}=bl(!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(`
|
|
1393
1486
|
`)+`
|
|
1394
|
-
`);let i=
|
|
1487
|
+
`);let i=Yh.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 KA(r,e){let{lit:t,brand:n}=bl(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(`
|
|
1395
1488
|
`)+`
|
|
1396
|
-
`)}import{readFileSync as
|
|
1397
|
-
`)){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
|
|
1398
|
-
`+e)}function
|
|
1489
|
+
`)}import{readFileSync as HA,existsSync as WA}from"fs";import*as Je from"path";function VA(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function _e(r,e=process.cwd()){let t={},n=[];for(let s of VA(r)){let i;try{i=HA(Je.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[o,a]of YA(i))process.env[o]===void 0&&(process.env[o]=a,t[o]=s)}return{mode:r,sources:t,loaded:n}}function*YA(r){for(let e of r.split(`
|
|
1490
|
+
`)){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 GA(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 ft(r,e,t){let{sources:n,mode:s,loaded:i}=r,o=process.cwd(),a=Je.dirname(e),c=`(mode: ${s??"none"})`,l=t?GA(t):[],d=l.filter(p=>n[p]).map(p=>`${p} \u2190 ${n[p]}`);d.length?console.log(`env: ${d.join(", ")} ${c}`):i.length&&console.log(`env: loaded ${i.join(", ")} ${c}`),s&&!i.some(p=>p===`.env.${s}`||p===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let u=Je.resolve(a)!==Je.resolve(o);if(u)for(let p of[".env.local",".env"])WA(Je.join(a,p))&&console.log(`env: ${Je.join(a,p)} present but not loaded (cwd is ${o})`);let f=l.filter(p=>process.env[p]===void 0);if(f.length){let p=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${f.join(", ")} but ${f.length>1?"they are":"it's"} unset${p}`)}}Ct();async function zh(r){_e(r);let e=await Me();if(e.length>0){console.log(Np(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!Ec()){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(lr))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.")}Pi();import*as Qh from"fs/promises";async function Xh(r){let e=It(),t;try{t=await Qh.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(lm(t,r))}mi();import*as Zh from"path";Pe();function zA(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&&X(o.cwd)===X(t));return n&&i.find(o=>o.agent===n)||i[0]}return r.find(i=>X(i.file)===X(e))}var $n=r=>r.agent??Zh.basename(r.file);function eg(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"} ${t.file}`)}function wl(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),eg(r,t=>console.log(t)),console.log(`
|
|
1491
|
+
`+e)}function vl(r,e,t,n,s){let i=zA(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>\`):`),eg(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function tg(r,e){if(!r){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),wl(await W(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=vl(await W(),r,"logs",process.cwd(),Ln());if(e.clear){Yp(t.pid),console.log(`Cleared log for ${$n(t)} (pid ${t.pid}).`);return}let n=Te(t.pid),s=n.text;if(e.run!==void 0&&(s=Gp(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(`
|
|
1399
1492
|
`);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
|
|
1400
1493
|
`)}if(process.stdout.write(s),s&&!s.endsWith(`
|
|
1401
1494
|
`)&&process.stdout.write(`
|
|
1402
|
-
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=
|
|
1403
|
-
`);
|
|
1404
|
-
|
|
1495
|
+
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=Te(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 QA=r=>new Promise(e=>setTimeout(e,r));async function rg(r,e){if(!r){wl(await W(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=vl(await W(),r,"wait",process.cwd(),Ln()),n=t.agent!=null,i=process.env.TYPEBULB_WAIT_SHIM==="1",o=e.timeoutSec??1800,a=e.match??"",c=Te(t.pid).offset,l=Fc(t.pid,a)??(a?Fc(t.pid):void 0),d=l!==void 0&&l<=c?l:a?0:c,u=Date.now()+o*1e3,f=n?1e4:1e3,p=2e3,b,h="",w=0;for(;;){let x=Te(t.pid,d);if(d=x.offset,x.text){h+=x.text;let E=h.split(`
|
|
1496
|
+
`);h=E.pop()??"";for(let T of E)T.trim()&&(e.match&&!T.includes(e.match)||(console.log(T),b??=Date.now()+f,n&&(T.includes("] compile error")||T.includes("] runtime error"))&&(b=Math.min(b,Date.now()+p))))}if(b&&Date.now()>=b)break;if(!i&&!b&&Date.now()>=u){console.error(`timeout: no ${e.match?`line matching '${e.match}'`:"new output"} from ${$n(t)} within ${o}s`),w=2;break}if(!Uc(t.pid)){b||(console.error(`server ${$n(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await QA(400)}Si(t.pid,d,a),process.exit(w)}async function ng(r){if(!r){wl(await W(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=vl(await W(),r,"stop",process.cwd(),Ln());await Rt(e.pid),console.log(`Stopped ${$n(e)} (pid ${e.pid}, ${e.url}).`)}async function sg(r){let e=process.cwd(),t=r==="agent"?Ln():void 0,n=r==="global"?await W():r==="bulbs"?await W(e):(await W()).filter(i=>i.agent!=null&&i.cwd!=null&&X(i.cwd)===X(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=>Rt(i.pid))),console.log(`Stopped ${n.length} ${s}${n.length===1?"":"s"}:`);for(let i of n)console.log(` ${i.url} pid ${i.pid} ${$n(i)}`)}Pe();import*as ig from"path";async function og(r,e,t=0){let n=ig.resolve(r),s=mr(await W(),n)[0];s||(console.error(`No running server for '${r}'. Start it first: npx typebulb ${r}`),process.exit(1));let i=async()=>{let a=await fetch(`${s.url}/__send`,{method:"POST",headers:{"Content-Type":"text/plain"},body:e??""});return a.ok||(console.error(`send failed: HTTP ${a.status} from ${s.url}/__send`),process.exit(1)),(await a.json().catch(()=>({}))).clients??0},o=0;try{let a=Date.now()+t;do{if(o=await i(),o>0||Date.now()>=a)break;await new Promise(c=>setTimeout(c,150))}while(!0)}catch(a){console.error(`send failed: ${a instanceof Error?a.message:String(a)}`),process.exit(1)}o>0?console.log(`Sent to ${o} page${o===1?"":"s"}.`):t>0?console.log(`No page connected after ${t/1e3}s \u2014 is the bulb open?`):console.log("Sent, but no page is connected yet \u2014 open the bulb and retry.")}import*as Pr from"fs/promises";import*as pg from"path";import{EventEmitter as dg}from"events";vt();Ti();import pT from"open";cr();vt();import{Hono as nT}from"hono";import{serve as sT}from"@hono/node-server";import{streamSSE as iT}from"hono/streaming";import*as Bt from"fs/promises";import*as Se from"path";import*as Sl from"fs/promises";import*as Mn from"path";var ro=class{async get(e){let t=ge(e),n=Mn.join(gn,t+".bin"),s=Mn.join(gn,t+".json");try{let[i,o]=await Promise.all([Sl.readFile(n),Sl.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await K();let n=ge(e),s=Mn.join(gn,n+".bin"),i=Mn.join(gn,n+".json"),o={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([ue(s,t.body),ue(i,JSON.stringify(o))])}};var ag=`
|
|
1497
|
+
const CSS = '\\n' +
|
|
1498
|
+
/* The agent mirror's token set, verbatim (agents/core/client/styles.css) \u2014 one system across CLI
|
|
1499
|
+
chrome: app chrome sits on --panel, content wells paint --veil, grays ride one neutral tint.
|
|
1500
|
+
The lone extension is --accent-contrast (text on a filled accent; the mirror never fills a
|
|
1501
|
+
button, and the dark theme's lighter accent needs dark text). */
|
|
1502
|
+
'.overlay { --fg: rgb(28, 28, 30); --muted: rgb(96, 96, 100); --panel: rgb(242, 242, 242);\\n' +
|
|
1503
|
+
' --border: rgb(221, 221, 221); --accent: rgb(58, 125, 232); --accent-contrast: #fff;\\n' +
|
|
1504
|
+
' --veil: rgba(0, 0, 0, 0.05); --err: rgb(206, 60, 60); }\\n' +
|
|
1505
|
+
'.dark .overlay { --fg: rgb(190, 190, 190); --muted: rgb(150, 150, 150); --panel: rgb(32, 32, 32);\\n' +
|
|
1506
|
+
' --border: rgb(52, 52, 52); --accent: rgb(122, 162, 250); --accent-contrast: #1c1e21;\\n' +
|
|
1507
|
+
' --veil: rgba(255, 255, 255, 0.06); --err: rgb(230, 60, 60); }\\n' +
|
|
1508
|
+
'.overlay { position: fixed; inset: 0; background: rgba(0,0,0,.45); z-index: 2147483000;\\n' +
|
|
1509
|
+
' display: flex; align-items: center; justify-content: center; padding: 16px;\\n' +
|
|
1510
|
+
' font: 14px/1.45 system-ui, sans-serif; color: var(--fg); }\\n' +
|
|
1511
|
+
'.card { background: var(--panel); border-radius: 10px; box-shadow: 0 12px 40px rgba(0,0,0,.35);\\n' +
|
|
1512
|
+
' width: min(560px, 100%); max-height: min(80vh, 640px); display: flex; flex-direction: column; }\\n' +
|
|
1513
|
+
'.head { display: flex; align-items: center; gap: 8px; padding: 14px 16px 10px; }\\n' +
|
|
1514
|
+
'.head h1 { font-size: 18px; font-weight: 600; margin: 0; flex: 1; color: var(--accent); }\\n' +
|
|
1515
|
+
'.x { border: 0; background: none; color: inherit; font-size: 18px; cursor: pointer; opacity: .6; padding: 2px 6px; }\\n' +
|
|
1516
|
+
'.x:hover { opacity: 1; }\\n' +
|
|
1517
|
+
'.body { padding: 0 16px; overflow-y: auto; flex: 1; display: flex; flex-direction: column; gap: 10px; }\\n' +
|
|
1518
|
+
'.model { color: var(--muted); }\\n' +
|
|
1519
|
+
'.model.err { color: var(--err); }\\n' +
|
|
1520
|
+
'label { font-weight: 600; }\\n' +
|
|
1521
|
+
'.tabs { display: flex; gap: 4px; }\\n' +
|
|
1522
|
+
'.tab { font: inherit; padding: 4px 10px; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; color: inherit; cursor: pointer; opacity: .6; }\\n' +
|
|
1523
|
+
'.tab.on { opacity: 1; border-bottom-color: var(--accent); }\\n' +
|
|
1524
|
+
'.tab .cnt { opacity: .6; font-size: 12px; margin-left: 4px; }\\n' +
|
|
1525
|
+
'textarea { width: 100%; box-sizing: border-box; min-height: 160px; max-height: 320px; resize: vertical;\\n' +
|
|
1526
|
+
' font: 13px/1.4 ui-monospace, monospace; padding: 8px; border-radius: 6px;\\n' +
|
|
1527
|
+
' border: 1px solid var(--border); background: var(--veil); color: inherit; }\\n' +
|
|
1528
|
+
'pre.stream { font: 13px/1.4 ui-monospace, monospace; white-space: pre-wrap; word-break: break-word;\\n' +
|
|
1529
|
+
' background: var(--veil); border-radius: 6px; padding: 10px; margin: 0; min-height: 120px; }\\n' +
|
|
1530
|
+
'.error { color: var(--err); white-space: pre-wrap; }\\n' +
|
|
1531
|
+
'.foot { display: flex; gap: 8px; padding: 12px 16px 14px; justify-content: flex-end; align-items: center; }\\n' +
|
|
1532
|
+
'.leftgrp { margin-right: auto; display: flex; gap: 8px; }\\n' +
|
|
1533
|
+
'button { font: inherit; padding: 6px 14px; border-radius: 6px; cursor: pointer;\\n' +
|
|
1534
|
+
' border: 1px solid var(--border); background: transparent; color: inherit; }\\n' +
|
|
1535
|
+
'button.run { background: var(--accent); border-color: var(--accent); color: var(--accent-contrast); }\\n' +
|
|
1536
|
+
'button.run:disabled { opacity: .5; cursor: default; }\\n' +
|
|
1537
|
+
'@keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }\\n' +
|
|
1538
|
+
'.shimmer { display: inline-block; background-image: linear-gradient(90deg, var(--muted), var(--fg), var(--muted));\\n' +
|
|
1539
|
+
' background-size: 200% 100%; -webkit-background-clip: text; background-clip: text;\\n' +
|
|
1540
|
+
' -webkit-text-fill-color: transparent; color: transparent; animation: shimmer 2s linear infinite; }\\n';
|
|
1541
|
+
|
|
1542
|
+
function isDark() {
|
|
1543
|
+
var t = document.documentElement.getAttribute('data-theme');
|
|
1544
|
+
if (t) return t === 'dark';
|
|
1545
|
+
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
function el(tag, cls, text) {
|
|
1549
|
+
var e = document.createElement(tag);
|
|
1550
|
+
if (cls) e.className = cls;
|
|
1551
|
+
if (text != null) e.textContent = text;
|
|
1552
|
+
return e;
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
// Per-chunk label: config dataTitle (comma-delimited) > a #/// comment-header first line > Data N.
|
|
1556
|
+
// The same fallback chain as .com's DataChunkEditor.
|
|
1557
|
+
function chunkLabel(chunk, i, titles) {
|
|
1558
|
+
if (titles[i]) return titles[i];
|
|
1559
|
+
var first = (chunk.split('\\n')[0] || '').trim();
|
|
1560
|
+
if (first.charAt(0) === '#' && first.length > 1 && first.length < 40) return first.replace(/^#+\\s*/, '');
|
|
1561
|
+
if (first.indexOf('//') === 0 && first.length > 2 && first.length < 40) return first.replace(/^\\/\\/\\s*/, '');
|
|
1562
|
+
return 'Data ' + (i + 1);
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
/**
|
|
1566
|
+
* Open the inference modal. ctx: { data: string[], readStream(resp), onComplete(final),
|
|
1567
|
+
* onError(err), onCancel() }. readStream is the SHIM's NDJSON reader (an async iterable of chunk
|
|
1568
|
+
* values that throws error envelopes as Error with code/retryable) \u2014 passed in so the page has
|
|
1569
|
+
* exactly one copy of the transport decoder. onComplete fires on every successful run (a retry
|
|
1570
|
+
* after an error included); onError on each displayed terminal error; onCancel when the user
|
|
1571
|
+
* closes before any completion.
|
|
1572
|
+
*/
|
|
1573
|
+
export function runInference(ctx) {
|
|
1574
|
+
var host = document.createElement('div');
|
|
1575
|
+
var root = host.attachShadow({ mode: 'closed' });
|
|
1576
|
+
var style = document.createElement('style');
|
|
1577
|
+
style.textContent = CSS;
|
|
1578
|
+
root.appendChild(style);
|
|
1579
|
+
|
|
1580
|
+
var wrap = el('div', isDark() ? 'dark' : '');
|
|
1581
|
+
root.appendChild(wrap);
|
|
1582
|
+
var overlay = el('div', 'overlay');
|
|
1583
|
+
wrap.appendChild(overlay);
|
|
1584
|
+
var card = el('div', 'card');
|
|
1585
|
+
overlay.appendChild(card);
|
|
1586
|
+
|
|
1587
|
+
var completed = false;
|
|
1588
|
+
var canceled = false;
|
|
1589
|
+
var aborter = null;
|
|
1590
|
+
var inferCfg = {};
|
|
1591
|
+
var dataTitles = function () {
|
|
1592
|
+
return String(inferCfg.dataTitle || '').split(',').map(function (s) { return s.trim(); }).filter(Boolean);
|
|
1593
|
+
};
|
|
1594
|
+
|
|
1595
|
+
function close(kind) {
|
|
1596
|
+
if (kind === 'cancel') canceled = true;
|
|
1597
|
+
if (aborter) { aborter.abort(); aborter = null; }
|
|
1598
|
+
host.remove();
|
|
1599
|
+
if (kind === 'cancel' && !completed) ctx.onCancel();
|
|
1600
|
+
}
|
|
1601
|
+
overlay.addEventListener('click', function (e) { if (e.target === overlay) close('cancel'); });
|
|
1602
|
+
|
|
1603
|
+
var head = el('div', 'head');
|
|
1604
|
+
var title = el('h1', '', 'Run AI inference');
|
|
1605
|
+
head.appendChild(title);
|
|
1606
|
+
var x = el('button', 'x', '\\u00d7');
|
|
1607
|
+
x.addEventListener('click', function () { close('cancel'); });
|
|
1608
|
+
head.appendChild(x);
|
|
1609
|
+
card.appendChild(head);
|
|
1610
|
+
|
|
1611
|
+
var body = el('div', 'body');
|
|
1612
|
+
card.appendChild(body);
|
|
1613
|
+
var foot = el('div', 'foot');
|
|
1614
|
+
card.appendChild(foot);
|
|
1615
|
+
|
|
1616
|
+
// \u2500\u2500 Confirmation state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1617
|
+
var areas = [];
|
|
1618
|
+
function showConfirm() {
|
|
1619
|
+
body.textContent = ''; foot.textContent = ''; areas = [];
|
|
1620
|
+
|
|
1621
|
+
var model = el('div', 'model');
|
|
1622
|
+
model.appendChild(el('span', 'shimmer', 'Resolving model\\u2026'));
|
|
1623
|
+
body.appendChild(model);
|
|
1624
|
+
var cancel = el('button', '', 'Cancel');
|
|
1625
|
+
cancel.addEventListener('click', function () { close('cancel'); });
|
|
1626
|
+
foot.appendChild(cancel);
|
|
1627
|
+
|
|
1628
|
+
// Build the whole view once the seed arrives (a localhost roundtrip; the shimmer covers it).
|
|
1629
|
+
// Seeding is explicit ctx.data (an arg / setData / a retry's edits) > the bulb's SOURCE
|
|
1630
|
+
// chunks from the server \u2014 never the page's post-run runtime data.
|
|
1631
|
+
fetch('/__infer-info').then(function (r) { return r.json(); })
|
|
1632
|
+
.catch(function () { return {}; })
|
|
1633
|
+
.then(function (info) { buildConfirm(info || {}); });
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
function buildConfirm(info) {
|
|
1637
|
+
body.textContent = ''; foot.textContent = ''; areas = [];
|
|
1638
|
+
inferCfg = info.inference || {};
|
|
1639
|
+
if (inferCfg.title) title.textContent = inferCfg.title;
|
|
1640
|
+
|
|
1641
|
+
var model = el('div', 'model');
|
|
1642
|
+
var runBtn = el('button', 'run', inferCfg.submitTitle || 'Run');
|
|
1643
|
+
if (info.error) { model.textContent = info.error; model.className = 'model err'; runBtn.disabled = true; }
|
|
1644
|
+
else if (info.model) model.textContent = info.model + ' \\u00b7 ' + info.provider;
|
|
1645
|
+
else model.textContent = 'Model info unavailable';
|
|
1646
|
+
|
|
1647
|
+
var chunks = ctx.data && ctx.data.length ? ctx.data
|
|
1648
|
+
: (info.data && info.data.length ? info.data : ['']);
|
|
1649
|
+
var titles = dataTitles();
|
|
1650
|
+
// Multi-chunk: .com's shape \u2014 a tab per chunk (label + live char count), one textarea visible.
|
|
1651
|
+
var multi = chunks.length > 1;
|
|
1652
|
+
var tabBtns = [];
|
|
1653
|
+
var counts = [];
|
|
1654
|
+
var strip = multi ? el('div', 'tabs') : null;
|
|
1655
|
+
if (strip) body.appendChild(strip);
|
|
1656
|
+
function formatCount(n) { return n < 10000 ? String(n) : Math.round(n / 1000) + 'K'; }
|
|
1657
|
+
function selectTab(i) {
|
|
1658
|
+
tabBtns.forEach(function (b, j) { b.className = j === i ? 'tab on' : 'tab'; });
|
|
1659
|
+
areas.forEach(function (a, j) { a.style.display = j === i ? '' : 'none'; });
|
|
1660
|
+
}
|
|
1661
|
+
chunks.forEach(function (chunk, i) {
|
|
1662
|
+
if (multi) {
|
|
1663
|
+
var tab = el('button', 'tab');
|
|
1664
|
+
tab.appendChild(el('span', '', chunkLabel(chunk, i, titles)));
|
|
1665
|
+
var cnt = el('span', 'cnt', '(' + formatCount(chunk.length) + ')');
|
|
1666
|
+
counts.push(cnt);
|
|
1667
|
+
tab.appendChild(cnt);
|
|
1668
|
+
tab.addEventListener('click', function () { selectTab(i); });
|
|
1669
|
+
tabBtns.push(tab);
|
|
1670
|
+
strip.appendChild(tab);
|
|
1671
|
+
} else {
|
|
1672
|
+
body.appendChild(el('label', '', titles[0] || 'Data to process'));
|
|
1673
|
+
}
|
|
1674
|
+
var ta = document.createElement('textarea');
|
|
1675
|
+
ta.value = chunk;
|
|
1676
|
+
if (!chunk) ta.placeholder = 'Paste data to process (optional)\\u2026';
|
|
1677
|
+
ta.addEventListener('input', function () {
|
|
1678
|
+
// 2 blank lines IS the chunk separator \u2014 collapse pasted 3+ so text can't silently split (.com parity)
|
|
1679
|
+
var v = ta.value.replace(/\\n{3,}/g, '\\n\\n');
|
|
1680
|
+
if (v !== ta.value) ta.value = v;
|
|
1681
|
+
if (multi) counts[i].textContent = '(' + formatCount(ta.value.length) + ')';
|
|
1682
|
+
});
|
|
1683
|
+
areas.push(ta);
|
|
1684
|
+
body.appendChild(ta);
|
|
1685
|
+
});
|
|
1686
|
+
if (multi) selectTab(0);
|
|
1687
|
+
// The model line reads as a footnote to the action, not a header to the data \u2014 under the
|
|
1688
|
+
// textareas, above the buttons.
|
|
1689
|
+
body.appendChild(model);
|
|
1690
|
+
|
|
1691
|
+
// Fragment-driven actions (TB-Inference.md): the address bar holds the last completed run, so
|
|
1692
|
+
// both appear exactly when one exists. Copy = share it; Save = promote it to the bulb's source.
|
|
1693
|
+
if (location.hash.indexOf('tb=') !== -1) {
|
|
1694
|
+
var grp = el('div', 'leftgrp');
|
|
1695
|
+
var share = el('button', '', 'Copy share URL');
|
|
1696
|
+
share.title = 'Copies this page URL with the #tb= result fragment \\u2014 paste the fragment onto the published bulb\\u2019s URL to share the last run';
|
|
1697
|
+
share.addEventListener('click', function () {
|
|
1698
|
+
navigator.clipboard.writeText(location.href).then(function () {
|
|
1699
|
+
share.textContent = 'Copied \\u2713';
|
|
1700
|
+
setTimeout(function () { share.textContent = 'Copy share URL'; }, 1500);
|
|
1701
|
+
});
|
|
1702
|
+
});
|
|
1703
|
+
grp.appendChild(share);
|
|
1704
|
+
var save = el('button', '', 'Save to bulb');
|
|
1705
|
+
save.title = 'Write this run\\u2019s data + insight into the .bulb.md as its new defaults';
|
|
1706
|
+
save.addEventListener('click', function () {
|
|
1707
|
+
save.disabled = true;
|
|
1708
|
+
fetch('/__infer-save', {
|
|
1709
|
+
method: 'POST',
|
|
1710
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1711
|
+
body: JSON.stringify({ hash: location.hash })
|
|
1712
|
+
}).then(async function (r) {
|
|
1713
|
+
if (!r.ok) { var t = await r.text(); var err; try { err = JSON.parse(t).message; } catch (e) { err = t; } throw new Error(err || 'Save failed'); }
|
|
1714
|
+
}).then(function () {
|
|
1715
|
+
// The run is source now \u2014 clear the runtime layer. Under watch, the file write is about
|
|
1716
|
+
// to hot-reload the page onto its new defaults anyway.
|
|
1717
|
+
history.replaceState(null, '', location.pathname + location.search);
|
|
1718
|
+
save.textContent = 'Saved \\u2713';
|
|
1719
|
+
}).catch(function (e) {
|
|
1720
|
+
save.textContent = 'Save failed'; save.title = e.message; save.disabled = false;
|
|
1721
|
+
});
|
|
1722
|
+
});
|
|
1723
|
+
grp.appendChild(save);
|
|
1724
|
+
foot.appendChild(grp);
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
var cancel = el('button', '', 'Cancel');
|
|
1728
|
+
cancel.addEventListener('click', function () { close('cancel'); });
|
|
1729
|
+
foot.appendChild(cancel);
|
|
1730
|
+
runBtn.addEventListener('click', run);
|
|
1731
|
+
foot.appendChild(runBtn);
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
// \u2500\u2500 Streaming / error states \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1735
|
+
function run() {
|
|
1736
|
+
var data = areas.map(function (a) { return a.value.trim(); }).filter(function (v) { return v !== ''; });
|
|
1737
|
+
ctx.data = data; // a retry's confirm re-seeds from the edited chunks, not the originals
|
|
1738
|
+
body.textContent = ''; foot.textContent = '';
|
|
1739
|
+
|
|
1740
|
+
var pre = el('pre', 'stream', '');
|
|
1741
|
+
var waiting = el('span', 'shimmer', 'Waiting for response\\u2026');
|
|
1742
|
+
pre.appendChild(waiting);
|
|
1743
|
+
var textNode = null;
|
|
1744
|
+
body.appendChild(pre);
|
|
1745
|
+
var cancel = el('button', '', 'Cancel');
|
|
1746
|
+
cancel.addEventListener('click', function () { close('cancel'); });
|
|
1747
|
+
foot.appendChild(cancel);
|
|
1748
|
+
|
|
1749
|
+
aborter = new AbortController();
|
|
1750
|
+
(async function () {
|
|
1751
|
+
var resp = await fetch('/__infer', {
|
|
1752
|
+
method: 'POST',
|
|
1753
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1754
|
+
body: JSON.stringify({ data: data }),
|
|
1755
|
+
signal: aborter.signal
|
|
1756
|
+
});
|
|
1757
|
+
if (resp.headers.get('X-TB-Stream') !== '1') {
|
|
1758
|
+
// Non-stream response: a 403 trust denial (plain text) or a 400/500 JSON error.
|
|
1759
|
+
var text = await resp.text();
|
|
1760
|
+
var err; try { err = JSON.parse(text); } catch (e) { err = { message: text, code: 'unknown', retryable: false }; }
|
|
1761
|
+
var e2 = new Error(err.message || 'Inference failed'); e2.code = err.code; e2.retryable = !!err.retryable;
|
|
1762
|
+
throw e2;
|
|
1763
|
+
}
|
|
1764
|
+
var final = null;
|
|
1765
|
+
for await (var v of ctx.readStream(resp)) {
|
|
1766
|
+
if (v.kind === 'delta') {
|
|
1767
|
+
if (waiting) { waiting.remove(); waiting = null; textNode = document.createTextNode(''); pre.appendChild(textNode); }
|
|
1768
|
+
textNode.appendData(v.text); pre.scrollTop = pre.scrollHeight;
|
|
1769
|
+
}
|
|
1770
|
+
else if (v.kind === 'complete') final = v;
|
|
1771
|
+
}
|
|
1772
|
+
if (!final) { var e3 = new Error('Stream ended without a result'); e3.code = 'network'; e3.retryable = true; throw e3; }
|
|
1773
|
+
completed = true;
|
|
1774
|
+
ctx.onComplete(final);
|
|
1775
|
+
close('complete');
|
|
1776
|
+
})().catch(function (err) {
|
|
1777
|
+
if (canceled) return; // user canceled; close() already ran and the abort rejection is expected
|
|
1778
|
+
showError(err);
|
|
1779
|
+
});
|
|
1780
|
+
}
|
|
1781
|
+
|
|
1782
|
+
function showError(err) {
|
|
1783
|
+
body.textContent = ''; foot.textContent = '';
|
|
1784
|
+
body.appendChild(el('div', 'error', err.message || 'Inference failed'));
|
|
1785
|
+
ctx.onError({ message: err.message, code: err.code || 'unknown', retryable: !!err.retryable });
|
|
1786
|
+
|
|
1787
|
+
var closeBtn = el('button', '', 'Close');
|
|
1788
|
+
closeBtn.addEventListener('click', function () { close('cancel'); });
|
|
1789
|
+
foot.appendChild(closeBtn);
|
|
1790
|
+
if (err.retryable) {
|
|
1791
|
+
var retry = el('button', 'run', 'Retry');
|
|
1792
|
+
retry.addEventListener('click', showConfirm);
|
|
1793
|
+
foot.appendChild(retry);
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
showConfirm();
|
|
1798
|
+
document.body.appendChild(host);
|
|
1799
|
+
}
|
|
1800
|
+
`;Pe();Ct();di();cr();import{stream as XA}from"hono/streaming";var ZA="X-TB-Stream";function Dn(r){return r instanceof ce?{message:r.message,code:r.code,retryable:r.retryable}:{message:r instanceof Error?r.message:"Unknown error",code:"unknown",retryable:!1}}function no(r,e){return r.header("Content-Type","application/x-ndjson; charset=utf-8"),r.header("Cache-Control","no-cache"),r.header(ZA,"1"),XA(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:Dn(s)}))}finally{try{await n.return?.()}catch{}}})}var so={log:(...r)=>console.log(...r)};function io(r,e){let t=r?.[e]??(Object.hasOwn(so,e)?so[e]:void 0);return typeof t=="function"?t:void 0}function oo(r){return r.constructor?.name==="AsyncGeneratorFunction"}var eT=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,tT=/[?&]target=/,rT=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function cg(r,e=""){return eT.test(r)?!0:rT.test(r)&&tT.test(e)}var ug="127.0.0.1",oT=new Set(["localhost","127.0.0.1","::1"]);function aT(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function cT(r){let e=aT(r);return!!e&&oT.has(e)}function lT(r,e){if(!e)return!1;try{return new URL(r).host===e}catch{return!1}}function kl(r){return r instanceof Error?r.message:"Unknown error"}async function fg(r){let{getHtml:e,basePath:t,port:n,reloadEmitter:s,messageEmitter:i,getServerExports:o,getBulbBlocks:a,saveInferenceResult:c,localOverride:l,trusted:d=!1,trustHint:u,staticAssets:f}=r,p=new nT;p.use("*",async(m,y)=>{if(!cT(m.req.header("host")))return m.text("Forbidden: untrusted Host",403);await y()}),p.use("*",async(m,y)=>{await y(),m.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),m.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"]],h=async(m,y)=>{if(!d){let v=new URL(m.req.url).pathname,R=b.find(([J])=>J.endsWith("/*")?v.startsWith(J.slice(0,-2)):v===J)?.[1]??"server-side code (server.ts)";Qp(process.pid,R);let I=u?`
|
|
1801
|
+
${u}`:"";return m.text(`Forbidden: this capability requires --trust.${I}`,403)}await y()},w=async(m,y)=>{let v=m.req.header("sec-fetch-site");if(v){if(v!=="same-origin")return m.text(`Forbidden: ${v} request`,403)}else{let R=m.req.header("origin");if(R&&!lT(R,m.req.header("host")))return m.text("Forbidden: cross-origin request",403)}await y()};for(let[m]of b)p.use(m,h),p.use(m,w);p.use("/__log",w),p.post("/__log",async m=>{try{let{args:y}=await m.req.json();console.log(...y||[])}catch{}return m.json({ok:!0})}),i&&(p.use("/__send",w),p.post("/__send",async m=>{let y="";try{y=await m.req.text()}catch{}let v=i.listenerCount("message");return i.emit("message",y),m.json({clients:v})})),p.get("/",m=>m.html(e())),p.post("/__fs/read",async m=>{try{let{path:y}=await m.req.json(),v=El(y,t),R=await Bt.readFile(v);return new Response(new Uint8Array(R),{headers:{"Content-Type":"application/octet-stream"}})}catch(y){let v=kl(y);return m.json({error:v},400)}}),p.post("/__fs/write",async m=>{try{let y=m.req.query("path");if(!y)return m.json({error:"Missing path"},400);let v=El(y,t);return await Bt.mkdir(Se.dirname(v),{recursive:!0}),await Bt.writeFile(v,Buffer.from(await m.req.arrayBuffer())),m.json({success:!0})}catch(y){let v=kl(y);return m.json({error:v},400)}}),p.post("/__api/:name",async m=>{try{let y=m.req.param("name"),v=io(o?.(),y);if(!v)return m.json({error:`API function '${y}' not found`},404);let{args:R}=await m.req.json();if(oo(v))return no(m,v(...R||[]));let I=await v(...R||[]);return m.json({result:I})}catch(y){let v=kl(y);return m.json({error:v},500)}}),p.post("/__ai",async m=>{try{let{messages:y,system:v,effort:R,provider:I,model:J,webSearch:B,stream:pe}=await m.req.json();if(!y||!Array.isArray(y)||y.length===0)return m.json({message:"messages array is required",code:"unknown",retryable:!1},400);let Z=De(I,J);if(typeof Z=="string")return m.json({message:Z,code:"unknown",retryable:!1},400);let ee=await st(Z,{messages:y,system:v,effort:R,webSearch:B,signal:m.req.raw.signal});if(!ee.ok){let ke=await ar(ee,Z.protocol);return m.json(ke,ee.status)}if(pe)return no(m,Ot(ee,Z.protocol));let dt=await Pt(ee,Z.protocol);return dt||console.warn("[tb.ai] Empty response from provider"),m.json({text:dt})}catch(y){return m.json(Dn(y),500)}}),p.post("/__infer",async m=>{try{let{data:y}=await m.req.json().catch(()=>({})),v=a?.();if(!v?.infer.trim())return m.json({message:"This bulb has no infer.md block.",code:"unknown",retryable:!1},400);let R=De();if(typeof R=="string")return m.json({message:R,code:"unknown",retryable:!1},400);let I=Array.isArray(y)?y.map(String):[],J=wc(v,I),B=await st(R,{messages:[{role:"user",content:J}],signal:m.req.raw.signal});if(!B.ok){let Z=await ar(B,R.protocol);return m.json(Z,B.status)}let pe=(async function*(){let Z="";for await(let ke of Ot(B,R.protocol))ke.kind!=="text"||!ke.text||(Z+=ke.text,yield{kind:"delta",text:ke.text});let ee=vc(Z);if(ee.parsed===null)throw console.warn(`[tb.infer] output not valid JSON after sanitize; raw output (last 4000 chars):
|
|
1802
|
+
`+Z.slice(-4e3)),new ce("LLM output is not valid JSON","parse_error",!0);ee.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",ee.fixesApplied.join(", "));let dt={insight:ee.parsed,insightJson:ee.json,data:I};yield{kind:"complete",...dt,fixesApplied:ee.fixesApplied,hash:Sc(dt)}})();return no(m,pe)}catch(y){return m.json(Dn(y),500)}});let x=async m=>{let{hash:y}=await m.req.json().catch(()=>({}));return typeof y=="string"?kc(y):null};p.post("/__infer-save",async m=>{try{if(!c)return m.json({message:"Save is not available for this server.",code:"unknown",retryable:!1},400);let y=await x(m);return y?(await c(y.data,y.insightJson),m.json({ok:!0})):m.json({message:"No decodable #tb= fragment to save.",code:"unknown",retryable:!1},400)}catch(y){return m.json(Dn(y),500)}}),p.get("/__infer-info",m=>{let y=a?.(),v=Jn(y?.config??"").inference,R=qs(y?.data??""),I=De();return typeof I=="string"?m.json({error:I,inference:v,data:R}):m.json({provider:I.protocol,model:I.model,inference:v,data:R})}),p.use("/__infer-decode",w),p.post("/__infer-decode",async m=>m.json(await x(m)??{error:"invalid fragment"})),p.get("/__infer-ui.js",m=>m.body(ag,200,{"Content-Type":"text/javascript; charset=utf-8"})),p.get("/__models",async m=>{try{let y=await Me();return m.json(y)}catch{return m.json([],200)}}),p.get("/__has-own-keys",async m=>{try{return m.json(await fi())}catch{return m.json(!1,200)}});let E=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],T=new ro;p.get("/proxy/*",async m=>{let y=new URL(m.req.url),R=(y.pathname+y.search).slice(7),I=R.lastIndexOf("https://");return I===-1?m.text("Invalid proxy URL",400):P(m,R.slice(I))}),l&&lg(p,`/local/${l.name}/`,l.serveDir),f&&lg(p,f.mount,f.dir);async function P(m,y){let v;try{v=new URL(y)}catch{return m.text("Invalid URL",400)}if(v.protocol!=="https:")return m.text("HTTPS only",400);if(!E.includes(v.hostname))return m.text("Host not allowed",403);let R=await T.get(y);if(R)return new Response(R.body,{status:200,headers:xl(R.contentType,R.cacheControl)});try{let I=await fetch(y,{headers:{Accept:m.req.header("Accept")||"*/*"},redirect:"follow"});if(!I.ok)return m.text(`Upstream ${I.status}`,I.status);let J=I.headers.get("Content-Type")||void 0,B=I.headers.get("Cache-Control")||void 0;if(I.body){let[pe,Z]=I.body.tee();return(async()=>{try{let ee=await new Response(Z).arrayBuffer();await T.set(y,{body:Buffer.from(ee),contentType:J,cacheControl:B})}catch{}})(),new Response(pe,{status:I.status,headers:xl(J,B)})}return new Response(null,{status:I.status,headers:xl(J,B)})}catch(I){return m.text(`Proxy fetch failed: ${I instanceof Error?I.message:I}`,502)}}(s||i)&&p.get("/__reload",m=>iT(m,async y=>{let v=()=>{y.writeSSE({event:"reload",data:""})},R=I=>{y.writeSSE({event:"message",data:JSON.stringify(I)})};for(s?.on("reload",v),i?.on("message",R),y.onAbort(()=>{s?.removeListener("reload",v),i?.removeListener("message",R)});!y.aborted;)await y.sleep(3e4)})),p.notFound(async m=>{if(m.req.method!=="GET")return m.text("Not Found",404);let y=new URL(m.req.url);return cg(y.pathname,y.search)?P(m,"https://esm.sh"+y.pathname+y.search):m.text("Not Found",404)});let C=sT({fetch:p.fetch,port:n,hostname:ug});return{port:n,close:()=>C.close()}}function xl(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 lg(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=El(i,t),a=await Bt.readFile(o);return new Response(a,{headers:{"Content-Type":uT(o)}})}catch{return n.text("Not Found",404)}})}function uT(r){switch(Se.extname(r).toLowerCase()){case".js":case".mjs":return"text/javascript";case".wasm":return"application/wasm";case".json":case".map":return"application/json";default:return"application/octet-stream"}}function El(r,e){let t=Se.resolve(e,r),n=Se.normalize(e),s=Se.normalize(t);if(s!==n&&!s.startsWith(n+Se.sep))throw new Error("Path traversal detected - access denied");return t}async function Al(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,ug,()=>{let s=n.address(),i=typeof s=="object"&&s?s.port:r;n.close(()=>t(i))}),n.on("error",()=>{t(Al(r+1))})})}Pe();async function ao(r){let{portPreference:e,makeServerOptions:t,makeEntry:n,displayName:s,stopLog:i}=r,o=await Al(e),a=await fg(t(o)),c=`http://localhost:${o}`;await zp(n(o,c)),console.log(`
|
|
1405
1803
|
${s}`),console.log(` ${c}`),o!==e&&console.log(` (port ${e} was busy)`);let l=[],d=async()=>{console.log(`
|
|
1406
|
-
Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await
|
|
1804
|
+
Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await En(process.pid),process.exit(0)};return process.on("SIGINT",d),process.on("SIGTERM",d),{port:o,url:c,onCleanup(u){l.push(u)}}}import fT from"chokidar";var dT={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function jt(r){let{target:e,onChange:t,events:n="change",debounceMs:s=150}=r,i,o=fT.watch(e,dT),a=()=>{i&&clearTimeout(i),i=setTimeout(t,s)};return n==="all"?o.on("all",a):o.on("change",a),()=>{i&&clearTimeout(i),o.close()}}Pe();async function mg(r,e,t,n){let s=process.cwd(),i=ki(process.pid),o=e.watch?new dg:void 0,a=new dg;a.setMaxListeners(0);let c=_e(e.mode),l=await Kc(r);l.length&&console.log(`Replacing the running server for this bulb (pid ${l.map(P=>P.pid).join(", ")})`);let d=1;console.log(qc(d)),console.log(`Loading ${pg.basename(r)}...`);let{html:u,bulb:f,serverExports:p}=await Tc(r,e.watch,e.trust,n);ft(c,r,f.server);let b=e.trust?void 0:hr(f),{port:h,url:w,onCleanup:x}=await ao({portPreference:e.port,displayName:f.name,stopLog:i,makeServerOptions:P=>({getHtml:()=>u,basePath:s,port:P,reloadEmitter:o,messageEmitter:a,getServerExports:()=>p,getBulbBlocks:()=>({infer:f.infer,insight:f.insight,code:f.code,config:f.config,data:f.data}),saveInferenceResult:async(C,m)=>{let y=await Pr.readFile(r,"utf-8");y=yo(y,"data",C.join(Zd)),y=yo(y,"insight",m),await Pr.writeFile(r,y)},localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,trusted:e.trust,trustHint:t}),makeEntry:(P,C)=>({pid:process.pid,port:P,url:C,file:r,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,predicted:b})});e.trust?console.log(" trust: granted (filesystem, AI, server.ts enabled)"):console.log(b?` trust: restricted \u2014 this bulb appears to use ${b}; re-run with --trust to enable it:
|
|
1407
1805
|
${t}
|
|
1408
1806
|
`:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
|
|
1409
1807
|
`),e.watch&&console.log(` Watching for changes...
|
|
1410
|
-
`);let
|
|
1411
|
-
`),o.emit("reload")}})}}
|
|
1412
|
-
`):await
|
|
1808
|
+
`);let E,T;if(e.watch&&o){let P=0,C=Promise.resolve();if(E=jt({target:r,onChange:()=>{let m=++P;C=C.then(async()=>{if(m===P)try{console.log("Recompiling...");let y=await Tc(r,!0,e.trust,n);u=y.html,p=y.serverExports,f=y.bulb,d++,console.log(qc(d)),o.emit("reload")}catch(y){console.error("Compile error:",y)}})}}),n){let{name:m,serveDir:y}=n;T=jt({target:y,events:"all",onChange:()=>{console.log(`Local package '${m}' changed. Browser reloading...
|
|
1809
|
+
`),o.emit("reload")}})}}E&&x(E),T&&x(T),x(()=>Pr.rm(Ac(r),{force:!0})),e.open&&(l.some(P=>P.port===h)?console.log(` Reusing the open browser tab.
|
|
1810
|
+
`):await pT(w))}import{readFileSync as gg,copyFileSync as hT,existsSync as gT}from"fs";import*as re from"path";import{fileURLToPath as yT}from"url";import{EventEmitter as bT}from"events";import yg from"open";Pe();var Tl=r=>`/agents/${r}/client.js`,mT=`
|
|
1413
1811
|
(() => {
|
|
1414
1812
|
const api = async (name, ...args) => {
|
|
1415
1813
|
const resp = await fetch('/__api/' + name, {
|
|
@@ -1444,15 +1842,15 @@ Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await gn(pr
|
|
|
1444
1842
|
es.onerror = () => { es.close(); };
|
|
1445
1843
|
}
|
|
1446
1844
|
})();
|
|
1447
|
-
`;function
|
|
1845
|
+
`;function hg(r){let{name:e,agent:t,styles:n,mountHtml:s,watch:i,theme:o}=r,a=Tl(t);return`<!DOCTYPE html>
|
|
1448
1846
|
<html>
|
|
1449
1847
|
<head>
|
|
1450
1848
|
<meta charset="utf-8">
|
|
1451
1849
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1452
|
-
<title>${
|
|
1453
|
-
${
|
|
1850
|
+
<title>${Qs(e)} - typebulb</title>
|
|
1851
|
+
${Zs(e,o)}
|
|
1454
1852
|
<style>
|
|
1455
|
-
${
|
|
1853
|
+
${Xs}
|
|
1456
1854
|
</style>
|
|
1457
1855
|
<style>
|
|
1458
1856
|
${n}
|
|
@@ -1464,17 +1862,17 @@ ${s}
|
|
|
1464
1862
|
${i?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
|
|
1465
1863
|
|
|
1466
1864
|
<script>
|
|
1467
|
-
${
|
|
1865
|
+
${mT}
|
|
1468
1866
|
</script>
|
|
1469
1867
|
|
|
1470
1868
|
<script type="module" src="${a}"></script>
|
|
1471
1869
|
</body>
|
|
1472
|
-
</html>`}async function
|
|
1473
|
-
${n.url}`),r.open&&await
|
|
1474
|
-
`);let
|
|
1475
|
-
`),i.emit("reload")}catch(
|
|
1476
|
-
`);let a=0,c=Promise.resolve();
|
|
1477
|
-
`)}catch(f){
|
|
1478
|
-
`),
|
|
1479
|
-
`),process.exit(1)}function
|
|
1480
|
-
${e}`),process.exit(1))}async function
|
|
1870
|
+
</html>`}async function bg(r){let e=process.cwd(),t=r.agentTarget;Eh(t)||(console.error(`Unknown agent '${t}'. Known: ${Er().join(", ")}.`),process.exit(1));let n=await Jc(e,t);if(n){console.log(`Mirror '${t}' is already running for this project:
|
|
1871
|
+
${n.url}`),r.open&&await yg(n.url);return}let s=ki(process.pid),i=r.watch?new bT:void 0,o=_e(r.mode),a=await Th(t),c=a.displayName||`${t} mirror`;ft(o,re.join(e,"mirror"));let l=re.dirname(yT(import.meta.url)),d=re.join(l,"agents",t),u=re.join(l,"..","cli","agents"),f=re.join(d,"styles.css"),p=re.join(d,"index.html"),b=()=>hg({name:c,agent:t,styles:gg(f,"utf8"),mountHtml:gg(p,"utf8"),watch:r.watch}),{port:h,url:w,onCleanup:x}=await ao({portPreference:r.port,displayName:c,stopLog:s,makeServerOptions:m=>({getHtml:b,basePath:e,port:m,reloadEmitter:i,getServerExports:()=>a,trusted:!0,staticAssets:{mount:`${re.posix.dirname(Tl(t))}/`,dir:d}}),makeEntry:(m,y)=>({pid:process.pid,port:m,url:y,file:`agent:${t}`,cwd:e,startedAt:Date.now(),trust:!0,agent:t})});r.watch&&console.log(` Watching for changes...
|
|
1872
|
+
`);let E=re.join(u,t,"client"),T=re.join(u,"core","client");async function P(){await(await import("esbuild")).build({entryPoints:[re.join(E,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:re.join(d,"client.js")});for(let y of["styles.css","index.html","typebulb.png","typebulb-inv.png"])hT(re.join(T,y),re.join(d,y))}let C;if(r.watch&&i){let m=gT(E),y=!1;C=jt({target:m?u:d,events:"all",onChange:async()=>{if(!y){y=!0;try{m&&await P(),console.log(`Mirror rebuilt. Browser reloading...
|
|
1873
|
+
`),i.emit("reload")}catch(v){console.error("Mirror rebuild failed:",v instanceof Error?v.message:v)}finally{y=!1}}}})}r.open&&await yg(w),x(()=>a.shutdownSwitcher?.()),x(()=>a.shutdownComposer?.()),C&&x(C)}import*as wg from"path";async function vg(r,e,t,n){let s=_e(t),i=!1,o=async()=>{let{bulb:a,config:c}=await we(r);i||(ft(s,r,a.server),i=!0),await vn(a.server,r,n,c.dependencies)};if(console.log(`Running ${wg.basename(r)}...`),await o(),e){console.log(`Watching for changes...
|
|
1874
|
+
`);let a=0,c=Promise.resolve();jt({target:r,onChange:()=>{let l=++a;c=c.then(async()=>{if(l===a)try{console.log("Re-running..."),await o()}catch(d){console.error("Error:",d)}})}})}}import{Console as wT}from"node:console";Pe();async function xg(r,e,t,n){ET();try{let f=mr(await W(),r)[0];f&&(Si(f.pid,Te(f.pid).offset),console.error(`note: 'call' boots a fresh server.ts instance; the running server (${f.url}) is not contacted \u2014 state shared with it must live on disk.`))}catch{}let s=_e(t),{bulb:i,config:o}=await we(r);i.server||Bn("This bulb has no **server.ts** block; nothing to call."),ft(s,r,i.server);let a;try{a=await vn(i.server,r,n,o.dependencies)}catch(f){Bn(f instanceof Error?f.message:String(f))}let c=io(a,e.fn);if(!c){let f=[...Object.keys(a).filter(p=>typeof a[p]=="function"),...Object.keys(so)];Bn(`Function '${e.fn}' not found. Available: ${f.length?f.join(", "):"(none)"}.`)}let l=await vT(e);if(oo(c)){try{for await(let f of c(...l))await kg(JSON.stringify(f,Eg)+`
|
|
1875
|
+
`)}catch(f){Bn(f instanceof Error?f.stack??f.message:String(f))}return Sg(0)}let d;try{d=await c(...l)}catch(f){Bn(f instanceof Error?f.stack??f.message:String(f))}let u=xT(d);u!==void 0&&await kg(u+`
|
|
1876
|
+
`),Sg(0)}function Sg(r){process.exitCode=r,setTimeout(()=>process.exit(r),2e3).unref?.()}async function vT(r){if(r.hasArgsFlag){let e=r.argsJson??"";return e==="-"&&(e=await AT()),kT(e)}return ST(r.positional)}function ST(r){return r.map(e=>{try{return JSON.parse(e)}catch{return e}})}function kT(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 xT(r){if(r!==void 0)return JSON.stringify(r,Eg,2)}function Eg(r,e){return typeof e=="bigint"?e.toString():e}function Bn(r){process.stderr.write(r+`
|
|
1877
|
+
`),process.exit(1)}function ET(){let r=new wT(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 kg(r){return new Promise((e,t)=>{process.stdout.write(r,n=>n?t(n):e())})}async function AT(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}var Pl="0.26.1";function Ag(r,e){r||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
|
|
1878
|
+
${e}`),process.exit(1))}async function TT(){let r=Ul(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${Pl}`),process.exit(0)),r.help&&(Jl(),process.exit(0)),Hh(),r.subcommand==="logs"){await tg(r.file||void 0,{follow:r.follow,clear:r.clear,run:r.run,lines:r.lines});return}if(r.subcommand==="wait"){await rg(r.file||void 0,{match:r.match,timeoutSec:r.timeoutSec});return}if(r.subcommand==="stop"){r.stopScope?await sg(r.stopScope):await ng(r.file||void 0);return}if(r.subcommand==="send"){await og(r.file,r.sendMessage,r.sendWaitMs??0);return}if(r.subcommand==="skill"){await Xh(Pl);return}if(r.subcommand==="models"){await zh(r.mode);return}if(r.subcommand==="agent"){await(r.agentTarget?bg(r):Gh(Pl));return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await Kh(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let c=await $p(process.cwd());c||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=c}else e=Ft.resolve(r.file);await Tg.access(e).then(()=>!0,()=>!1)||(Er().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:Ft.relative(process.cwd(),e)||Ft.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await Jh(e,s);return}let i=!r.noTrust&&_t(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 we(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 Fl(r.local)}catch(c){console.error(c instanceof Error?c.message:String(c)),process.exit(1)}console.error(`replace: ${a.name} \u2192 ${Ft.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await Uh(e,a);return}if(r.subcommand==="call"){Ag(r.trust,s),await xg(e,{fn:r.fn,positional:r.callArgs,argsJson:r.argsJson,hasArgsFlag:r.hasArgsFlag},r.mode,a);return}if(o&&o.bulb.server&&(Us(o.bulb)||r.server)){Ag(r.trust,s),await vg(e,r.watch,r.mode,a);return}await mg(e,r,s,a)}TT().catch(r=>{console.error("Error:",r.message),process.exit(1)});
|