typebulb 0.31.3 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/dist/agents/claude/client.js +80 -80
- package/dist/agents/pi/client.js +79 -79
- package/dist/agents/pi/matchu-patchu.ts +1 -1
- package/dist/format/config.d.ts +5 -0
- package/dist/format/config.d.ts.map +1 -1
- package/dist/format/config.js +16 -0
- package/dist/format/config.js.map +1 -1
- package/dist/index.js +1027 -1026
- package/dist/servers.js +275 -137
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,169 +1,169 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);
|
|
3
|
-
var
|
|
4
|
-
`),t=0;if(e[t]?.trim()!=="---")return null;t++;let n=[];for(;t<e.length&&e[t]?.trim()!=="---";)n.push(e[t]),t++;if(e[t]?.trim()!=="---")return null;t++;let s=
|
|
5
|
-
`)),a=t}else t++}return{frontmatter:s,files:i,warnings:o,bodyEndLine:a}}catch{return null}}function
|
|
3
|
+
var mb=Object.create;var Jo=Object.defineProperty;var hb=Object.getOwnPropertyDescriptor;var gb=Object.getOwnPropertyNames;var yb=Object.getPrototypeOf,bb=Object.prototype.hasOwnProperty;var cs=(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 S=(r,e)=>()=>(r&&(e=r(r=0)),e);var T=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ru=(r,e)=>{for(var t in e)Jo(r,t,{get:e[t],enumerable:!0})},wb=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of gb(e))!bb.call(r,s)&&s!==t&&Jo(r,s,{get:()=>e[s],enumerable:!(n=hb(e,s))||n.enumerable});return r};var vb=(r,e,t)=>(t=r!=null?mb(yb(r)):{},wb(e||!r||!r.__esModule?Jo(t,"default",{value:r,enumerable:!0}):t,r));import*as Iu from"fs/promises";import{existsSync as nr,readFileSync as Sb}from"fs";import*as Z from"path";import{pathToFileURL as kb}from"url";import{resolve as Ho}from"resolve.exports";import{init as $u,parse as Lu}from"es-module-lexer";function Mu(r,e){let t=Z.join(r,"package.json");try{return JSON.parse(Sb(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}function Du(r){let e=r.indexOf("=");if(e===-1)throw new Error(`--replace must be <name>=<path> (got '${r}')`);let t=r.slice(0,e).trim(),n=r.slice(e+1).trim();if(!t)throw new Error(`--replace missing package name (got '${r}')`);if(!n)throw new Error(`--replace missing path for '${t}'`);if(t.startsWith("@"))throw new Error(`--replace does not support scoped names yet; '${t}' is scoped`);return{name:t,dir:Z.resolve(n)}}async function Bu(r){let{name:e,dir:t}=r;if(!nr(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=Mu(t,e),s=xb(n,e),i=Z.resolve(t,s);if(!nr(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=Z.dirname(i),a=`/local/${e}/${Z.basename(i)}`,c=Eb(n,t);return await Ab(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function xb(r,e){if(r.exports!==void 0){let n;try{n=Ho(r,".",{browser:!0,conditions:Ko})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${Ko.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=Wo(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${Ko.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 Eb(r,e){if(r.exports!==void 0)try{let n=Ho(r,".",{conditions:["types"]}),s=Wo(n);if(s){let i=Z.resolve(e,s);if(nr(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=Z.resolve(e,t);if(nr(n))return n}}function Wo(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function Ab(r,e,t){await $u;let n=Z.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 Iu.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=Lu(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=Tb(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 Tb(r,e,t){let n=e.replace(/[?#].*$/,""),s=Z.resolve(Z.dirname(r),n),i=[s,s+".js",s+".mjs",Z.join(s,"index.js"),Z.join(s,"index.mjs")];for(let o of i)if(Z.normalize(o).startsWith(t)&&nr(o))return o}function Pb(r,e,t){let n=Mu(r,e),s;if(n.exports!==void 0)try{s=Wo(Ho(n,t,{conditions:Nu}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${Nu.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=Z.resolve(r,s);if(!nr(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return kb(i).href}async function ju(r,e){await $u;let t;try{[t]=Lu(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=Pb(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var Ko,Nu,ls=S(()=>{Ko=["browser","import","default"],Nu=["node","import","default"]});function Ju(r){return tt.find(e=>Oe[e].path===r)}function Hu(r){return!!r?.startsWith("typebulb")}var Oe,tt,Ku,us=S(()=>{Oe={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"}},tt=["code","css","html","data","infer","insight","config","notes"];Ku="typebulb/v1"});function Vo(r){return/[:\n"']/.test(r)||r.startsWith(" ")||r.endsWith(" ")?`"${r.replace(/"/g,'\\"')}"`:r}function Go(r){return r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1).replace(/\\"/g,'"'):r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}var fs=S(()=>{});function ce(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=Rb(n);if(!s)return null;let i=new Map,o=[],a=t;for(;t<e.length;){let l=e[t]?.trim()?.match(Wu);if(l){let d=l[1].trim();for(t++;t<e.length&&e[t]?.trim()==="";)t++;let u=e[t]?.match(ds);if(!u){o.push(`**${d}** has no code fence \u2014 block skipped`);continue}let f=u[1];t++;let p=[],b=zo(f);for(;t<e.length&&!e[t]?.match(b);)p.push(e[t]),t++;let m=t<e.length;t++,o.push(...Cb(d,p,m)),i.set(d,p.join(`
|
|
5
|
+
`)),a=t}else t++}return{frontmatter:s,files:i,warnings:o,bodyEndLine:a}}catch{return null}}function Cb(r,e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s]?.trim().match(Wu);i&&Ob.has(i[1].trim())&&_b(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 _b(r,e){let t=e+1;for(;t<r.length&&r[t]?.trim()==="";)t++;return!!r[t]?.match(ds)}function Rb(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=Go(i);break}}return!Hu(e.format)||!e.name?null:e}function Yu(r){return ce(r)?.warnings??[]}function Vu(r){let e=Object.fromEntries(tt.map(t=>[t,r.files.get(Oe[t].path)||""]));return{name:r.frontmatter.name,...e}}var Wu,ds,Ob,zo,Xo=S(()=>{us();fs();Wu=/^\*\*(.+)\*\*$/,ds=/^(`{3,})(\w*)\s*$/,Ob=new Set(tt.map(r=>Oe[r].path)),zo=r=>new RegExp(`^${r}\\s*$`)});function Gu(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 zu(r,e){let{path:t}=Oe[r],n=t.split(".").pop(),s=Gu(e);return`**${t}**
|
|
6
6
|
|
|
7
7
|
${s}${n}
|
|
8
8
|
${e}
|
|
9
|
-
${s}`}function
|
|
10
|
-
`)}function
|
|
11
|
-
`);for(let i=0;i<s.length;i++){if(s[i]?.trim()!==`**${n}**`)continue;let o=i+1;for(;o<s.length&&s[o]?.trim()==="";)o++;let a=s[o]?.match(
|
|
9
|
+
${s}`}function Xu(r){let e=tt.filter(t=>r[t]).map(t=>zu(t,r[t]));return["---",`format: ${Ku}`,`name: ${Vo(r.name)}`,"---","",...e].join(`
|
|
10
|
+
`)}function Qo(r,e,t){let{path:n}=Oe[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(ds);if(!a)continue;let c=zo(a[1]),l=o+1;for(;l<s.length&&!s[l]?.match(c);)l++;if(l>=s.length)return r;let d=Gu(t),u=d.length>a[1].length?d:a[1];return[...s.slice(0,o),u+a[2],...t.split(`
|
|
12
12
|
`),u,...s.slice(l+1)].join(`
|
|
13
13
|
`)}return`${r.replace(/\s*$/,"")}
|
|
14
14
|
|
|
15
|
-
${
|
|
16
|
-
`}var
|
|
17
|
-
>/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=
|
|
18
|
-
>]`),m+=
|
|
19
|
-
`)}};
|
|
20
|
-
`)?
|
|
15
|
+
${zu(e,t)}
|
|
16
|
+
`}var Qu=S(()=>{us();Xo();fs()});function rt(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}function Ur(r){let e=rt(r??"").assets?.trim();if(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")return}catch{return}return e.endsWith("/")?e:e+"/"}}function Ib(r){return r.replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"")}function Zo(r){let e=rt(r??"").description?.trim();if(!e)return Nb;let t=Ib(e);return(t.length>200?t.slice(0,197)+"...":t).replace(/\n/g," ")}var Nb,Zu=S(()=>{Nb="A Typebulb bulb."});var ef=S(()=>{});function ea(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index:-1}var tf=S(()=>{});function Jr(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index+s[0].length-1:-1}var rf=S(()=>{});function ps(r,e){let t=new RegExp(e,"g"),n=r.match(t);return n?n.length:0}var nf=S(()=>{});function Kr(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=ea(r,`<${e}[
|
|
17
|
+
>/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=Jr(a,"^[^<]*[ /]>",0),l=c!==-1&&a[c-1]==="/";if(n&&console.log("[xml-utils] selfClosing:",l),l===!1)if(s){let p=0,b=1,m=0;for(;(c=Jr(a,"[ /]"+e+">",p))!==-1;){let g=a.substring(p,c+1);if(b+=ps(g,"<"+e+`[
|
|
18
|
+
>]`),m+=ps(g,"</"+e+">"),m>=b)break;p=c}}else c=Jr(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 ta=S(()=>{tf();rf();nf()});var ra=S(()=>{ta()});var na=S(()=>{ra()});var sf=S(()=>{na()});var of=S(()=>{});var af=S(()=>{ef();ta();ra();sf();na();of()});var F=T(re=>{"use strict";var sa=Symbol.for("yaml.alias"),cf=Symbol.for("yaml.document"),ms=Symbol.for("yaml.map"),lf=Symbol.for("yaml.pair"),ia=Symbol.for("yaml.scalar"),hs=Symbol.for("yaml.seq"),Ue=Symbol.for("yaml.node.type"),Mb=r=>!!r&&typeof r=="object"&&r[Ue]===sa,Db=r=>!!r&&typeof r=="object"&&r[Ue]===cf,Bb=r=>!!r&&typeof r=="object"&&r[Ue]===ms,jb=r=>!!r&&typeof r=="object"&&r[Ue]===lf,uf=r=>!!r&&typeof r=="object"&&r[Ue]===ia,Fb=r=>!!r&&typeof r=="object"&&r[Ue]===hs;function ff(r){if(r&&typeof r=="object")switch(r[Ue]){case ms:case hs:return!0}return!1}function qb(r){if(r&&typeof r=="object")switch(r[Ue]){case sa:case ms:case ia:case hs:return!0}return!1}var Ub=r=>(uf(r)||ff(r))&&!!r.anchor;re.ALIAS=sa;re.DOC=cf;re.MAP=ms;re.NODE_TYPE=Ue;re.PAIR=lf;re.SCALAR=ia;re.SEQ=hs;re.hasAnchor=Ub;re.isAlias=Mb;re.isCollection=ff;re.isDocument=Db;re.isMap=Bb;re.isNode=qb;re.isPair=jb;re.isScalar=uf;re.isSeq=Fb});var Hr=T(oa=>{"use strict";var ee=F(),le=Symbol("break visit"),df=Symbol("skip children"),Ce=Symbol("remove node");function gs(r,e){let t=pf(e);ee.isDocument(r)?sr(null,r.contents,t,Object.freeze([r]))===Ce&&(r.contents=null):sr(null,r,t,Object.freeze([]))}gs.BREAK=le;gs.SKIP=df;gs.REMOVE=Ce;function sr(r,e,t,n){let s=mf(r,e,t,n);if(ee.isNode(s)||ee.isPair(s))return hf(r,n,s),sr(r,s,t,n);if(typeof s!="symbol"){if(ee.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=sr(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===le)return le;o===Ce&&(e.items.splice(i,1),i-=1)}}}else if(ee.isPair(e)){n=Object.freeze(n.concat(e));let i=sr("key",e.key,t,n);if(i===le)return le;i===Ce&&(e.key=null);let o=sr("value",e.value,t,n);if(o===le)return le;o===Ce&&(e.value=null)}}return s}async function ys(r,e){let t=pf(e);ee.isDocument(r)?await ir(null,r.contents,t,Object.freeze([r]))===Ce&&(r.contents=null):await ir(null,r,t,Object.freeze([]))}ys.BREAK=le;ys.SKIP=df;ys.REMOVE=Ce;async function ir(r,e,t,n){let s=await mf(r,e,t,n);if(ee.isNode(s)||ee.isPair(s))return hf(r,n,s),ir(r,s,t,n);if(typeof s!="symbol"){if(ee.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=await ir(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===le)return le;o===Ce&&(e.items.splice(i,1),i-=1)}}}else if(ee.isPair(e)){n=Object.freeze(n.concat(e));let i=await ir("key",e.key,t,n);if(i===le)return le;i===Ce&&(e.key=null);let o=await ir("value",e.value,t,n);if(o===le)return le;o===Ce&&(e.value=null)}}return s}function pf(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 mf(r,e,t,n){if(typeof t=="function")return t(r,e,n);if(ee.isMap(e))return t.Map?.(r,e,n);if(ee.isSeq(e))return t.Seq?.(r,e,n);if(ee.isPair(e))return t.Pair?.(r,e,n);if(ee.isScalar(e))return t.Scalar?.(r,e,n);if(ee.isAlias(e))return t.Alias?.(r,e,n)}function hf(r,e,t){let n=e[e.length-1];if(ee.isCollection(n))n.items[r]=t;else if(ee.isPair(n))r==="key"?n.key=t:n.value=t;else if(ee.isDocument(n))n.contents=t;else{let s=ee.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}oa.visit=gs;oa.visitAsync=ys});var aa=T(yf=>{"use strict";var gf=F(),Jb=Hr(),Kb={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Hb=r=>r.replace(/[!,[\]{}]/g,e=>Kb[e]),Wr=class r{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},r.defaultYaml,e),this.tags=Object.assign({},r.defaultTags,t)}clone(){let e=new r(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new r(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:r.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},r.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:r.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},r.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),s=n.shift();switch(s){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[i,o]=n;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let o=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${s}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}let[,n,s]=e.match(/^(.*!)([^!]*)$/s);s||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(s)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+Hb(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),s;if(e&&n.length>0&&gf.isNode(e.contents)){let i={};Jb.visit(e.contents,(o,a)=>{gf.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
|
+
`)}};Wr.defaultYaml={explicit:!1,version:"1.2"};Wr.defaultTags={"!!":"tag:yaml.org,2002:"};yf.Directives=Wr});var bs=T(Yr=>{"use strict";var bf=F(),Wb=Hr();function Yb(r){if(/[\x00-\x19\s,[\]{}]/.test(r)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(r)}`;throw new Error(t)}return!0}function wf(r){let e=new Set;return Wb.visit(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function vf(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function Vb(r,e){let t=[],n=new Map,s=null;return{onAnchor:i=>{t.push(i),s??(s=wf(r));let o=vf(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(bf.isScalar(o.node)||bf.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}}Yr.anchorIsValid=Yb;Yr.anchorNames=wf;Yr.createNodeAnchors=Vb;Yr.findNewAnchor=vf});var ca=T(Sf=>{"use strict";function Vr(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=Vr(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=Vr(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=Vr(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=Vr(r,n,s,i);o===void 0?delete n[s]:o!==i&&(n[s]=o)}return r.call(e,t,n)}Sf.applyReviver=Vr});var nt=T(xf=>{"use strict";var Gb=F();function kf(r,e,t){if(Array.isArray(r))return r.map((n,s)=>kf(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!Gb.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}xf.toJS=kf});var ws=T(Af=>{"use strict";var zb=ca(),Ef=F(),Xb=nt(),la=class{constructor(e){Object.defineProperty(this,Ef.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(!Ef.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=Xb.toJS(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?zb.applyReviver(i,{"":a},"",a):a}};Af.NodeBase=la});var Gr=T(Tf=>{"use strict";var Qb=bs(),Zb=Hr(),or=F(),ew=ws(),tw=nt(),ua=class extends ew.NodeBase{constructor(e){super(or.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=[],Zb.visit(e,{Node:(i,o)=>{(or.isAlias(o)||or.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||(tw.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=vs(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(Qb.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 vs(r,e,t){if(or.isAlias(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(or.isCollection(e)){let n=0;for(let s of e.items){let i=vs(r,s,t);i>n&&(n=i)}return n}else if(or.isPair(e)){let n=vs(r,e.key,t),s=vs(r,e.value,t);return Math.max(n,s)}return 1}Tf.Alias=ua});var X=T(fa=>{"use strict";var rw=F(),nw=ws(),sw=nt(),iw=r=>!r||typeof r!="function"&&typeof r!="object",st=class extends nw.NodeBase{constructor(e){super(rw.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:sw.toJS(this.value,e,t)}toString(){return String(this.value)}};st.BLOCK_FOLDED="BLOCK_FOLDED";st.BLOCK_LITERAL="BLOCK_LITERAL";st.PLAIN="PLAIN";st.QUOTE_DOUBLE="QUOTE_DOUBLE";st.QUOTE_SINGLE="QUOTE_SINGLE";fa.Scalar=st;fa.isScalarValue=iw});var zr=T(Of=>{"use strict";var ow=Gr(),Rt=F(),Pf=X(),aw="tag:yaml.org,2002:";function cw(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 lw(r,e,t){if(Rt.isDocument(r)&&(r=r.contents),Rt.isNode(r))return r;if(Rt.isPair(r)){let u=t.schema[Rt.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 ow.Alias(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=aw+e.slice(2));let l=cw(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let u=new Pf.Scalar(r);return c&&(c.node=u),u}l=r instanceof Map?o[Rt.MAP]:Symbol.iterator in Object(r)?o[Rt.SEQ]:o[Rt.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 Pf.Scalar(r);return e?d.tag=e:l.default||(d.tag=l.tag),c&&(c.node=d),d}Of.createNode=lw});var ks=T(Ss=>{"use strict";var uw=zr(),_e=F(),fw=ws();function da(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 uw.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 Cf=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,pa=class extends fw.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>_e.isNode(n)||_e.isPair(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Cf(e))this.add(t);else{let[n,...s]=e,i=this.get(n,!0);if(_e.isCollection(i))i.addIn(s,t);else if(i===void 0&&this.schema)this.set(n,da(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let s=this.get(t,!0);if(_e.isCollection(s))return s.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...s]=e,i=this.get(n,!0);return s.length===0?!t&&_e.isScalar(i)?i.value:i:_e.isCollection(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!_e.isPair(t))return!1;let n=t.value;return n==null||e&&_e.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let s=this.get(t,!0);return _e.isCollection(s)?s.hasIn(n):!1}setIn(e,t){let[n,...s]=e;if(s.length===0)this.set(n,t);else{let i=this.get(n,!0);if(_e.isCollection(i))i.setIn(s,t);else if(i===void 0&&this.schema)this.set(n,da(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}};Ss.Collection=pa;Ss.collectionFromPath=da;Ss.isEmptyPath=Cf});var Xr=T(xs=>{"use strict";var dw=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function ma(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var pw=(r,e,t)=>r.endsWith(`
|
|
20
|
+
`)?ma(t,e):t.includes(`
|
|
21
21
|
`)?`
|
|
22
|
-
`+
|
|
23
|
-
`)t===
|
|
24
|
-
`&&p!==" "){let
|
|
25
|
-
`&&
|
|
26
|
-
${e}${r.slice(0,
|
|
27
|
-
${e}${r.slice(
|
|
28
|
-
`);n=e,s=e+1,i=r[s]}return n}
|
|
29
|
-
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function
|
|
22
|
+
`+ma(t,e):(r.endsWith(" ")?"":" ")+t;xs.indentComment=ma;xs.lineComment=pw;xs.stringifyComment=dw});var Rf=T(Qr=>{"use strict";var mw="flow",ha="block",Es="quoted";function hw(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,m=-1,g=-1,x=-1;t===ha&&(m=_f(r,m,e.length),m!==-1&&(u=m+c));for(let P;P=r[m+=1];){if(t===Es&&P==="\\"){switch(g=m,r[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}x=m}if(P===`
|
|
23
|
+
`)t===ha&&(m=_f(r,m,e.length)),u=m+e.length+c,f=void 0;else{if(P===" "&&p&&p!==" "&&p!==`
|
|
24
|
+
`&&p!==" "){let R=r[m+1];R&&R!==" "&&R!==`
|
|
25
|
+
`&&R!==" "&&(f=m)}if(m>=u)if(f)l.push(f),u=f+c,f=void 0;else if(t===Es){for(;p===" "||p===" ";)p=P,P=r[m+=1],b=!0;let R=m>x+1?m-2:g-1;if(d[R])return r;l.push(R),d[R]=!0,u=R+c,f=void 0}else b=!0}p=P}if(b&&a&&a(),l.length===0)return r;o&&o();let A=r.slice(0,l[0]);for(let P=0;P<l.length;++P){let R=l[P],N=l[P+1]||r.length;R===0?A=`
|
|
26
|
+
${e}${r.slice(0,N)}`:(t===Es&&d[R]&&(A+=`${r[R]}\\`),A+=`
|
|
27
|
+
${e}${r.slice(R+1,N)}`)}return A}function _f(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}Qr.FOLD_BLOCK=ha;Qr.FOLD_FLOW=mw;Qr.FOLD_QUOTED=Es;Qr.foldFlowLines=hw});var en=T(Nf=>{"use strict";var ve=X(),it=Rf(),Ts=(r,e)=>({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),Ps=r=>/^(%|---|\.\.\.)/m.test(r);function gw(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 Zr(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(Ps(r)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let 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)+`
|
|
30
30
|
|
|
31
31
|
`;t[c+2]==="\\"&&t[c+3]==="n"&&t[c+4]!=='"';)o+=`
|
|
32
|
-
`,c+=2;o+=i,t[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+t.slice(a):t,n?o:
|
|
33
|
-
`)||/[ \t]\n|\n[ \t]/.test(r))return
|
|
34
|
-
${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:it.foldFlowLines(o,i,it.FOLD_QUOTED,Ts(e,!1))}function ga(r,e){if(e.options.singleQuote===!1||e.implicitKey&&r.includes(`
|
|
33
|
+
`)||/[ \t]\n|\n[ \t]/.test(r))return Zr(r,e);let t=e.indent||(Ps(r)?" ":""),n="'"+r.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
34
|
+
${t}`)+"'";return e.implicitKey?n:it.foldFlowLines(n,t,it.FOLD_FLOW,Ts(e,!1))}function ar(r,e){let{singleQuote:t}=e.options,n;if(t===!1)n=Zr;else{let s=r.includes('"'),i=r.includes("'");s&&!i?n=ga:i&&!s?n=Zr:n=t?ga:Zr}return n(r,e)}var ya;try{ya=new RegExp(`(^|(?<!
|
|
35
35
|
))
|
|
36
36
|
+(?!
|
|
37
|
-
|$)`,"g")}catch{
|
|
37
|
+
|$)`,"g")}catch{ya=/\n+(?!\n|$)/g}function As({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 ar(t,n);let l=n.indent||(n.forceBlockIndent||Ps(t)?" ":""),d=o==="literal"?!0:o==="folded"||e===ve.Scalar.BLOCK_FOLDED?!1:e===ve.Scalar.BLOCK_LITERAL?!0:!gw(t,c,l.length);if(!t)return d?`|
|
|
38
38
|
`:`>
|
|
39
|
-
`;let u,
|
|
40
|
-
`&&
|
|
41
|
-
`);
|
|
42
|
-
`&&(p=p.slice(0,-1)),p=p.replace(
|
|
43
|
-
`)x=
|
|
44
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),
|
|
45
|
-
${l}${
|
|
46
|
-
${l}${
|
|
47
|
-
`)||
|
|
48
|
-
`)?
|
|
49
|
-
`))return
|
|
50
|
-
${c}`);if(o){let
|
|
51
|
-
${e.indent}${a}`:a}
|
|
52
|
-
${a}:`):(
|
|
53
|
-
`:"",
|
|
54
|
-
${
|
|
55
|
-
`&&
|
|
56
|
-
|
|
57
|
-
`):
|
|
58
|
-
${t.indent}`}else if(!p&&
|
|
59
|
-
`),
|
|
60
|
-
${t.indent}`)}}else(
|
|
61
|
-
`)&&(
|
|
39
|
+
`;let u,f;for(f=t.length;f>0;--f){let N=t[f-1];if(N!==`
|
|
40
|
+
`&&N!==" "&&N!==" ")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(ya,`$&${l}`));let m=!1,g,x=-1;for(g=0;g<t.length;++g){let N=t[g];if(N===" ")m=!0;else if(N===`
|
|
43
|
+
`)x=g;else break}let A=t.substring(0,x<g?x+1:g);A&&(t=t.substring(A.length),A=A.replace(/\n+/g,`$&${l}`));let R=(m?l?"2":"1":"")+u;if(r&&(R+=" "+a(r.replace(/ ?[\r\n]+/g," ")),s&&s()),!d){let N=t.replace(/\n+/g,`
|
|
44
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),O=!1,$=Ts(n,!0);o!=="folded"&&e!==ve.Scalar.BLOCK_FOLDED&&($.onOverflow=()=>{O=!0});let E=it.foldFlowLines(`${A}${N}${p}`,l,it.FOLD_BLOCK,$);if(!O)return`>${R}
|
|
45
|
+
${l}${E}`}return t=t.replace(/\n+/g,`$&${l}`),`|${R}
|
|
46
|
+
${l}${A}${t}${p}`}function yw(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 ar(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||d||!i.includes(`
|
|
48
|
+
`)?ar(i,e):As(r,e,t,n);if(!a&&!d&&s!==ve.Scalar.PLAIN&&i.includes(`
|
|
49
|
+
`))return As(r,e,t,n);if(Ps(i)){if(c==="")return e.forceBlockIndent=!0,As(r,e,t,n);if(a&&c===l)return ar(i,e)}let u=i.replace(/\n+/g,`$&
|
|
50
|
+
${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(u),{compat:p,tags:b}=e.doc.schema;if(b.some(f)||p?.some(f))return ar(i,e)}return a?u:it.foldFlowLines(u,c,it.FOLD_FLOW,Ts(e,!1))}function bw(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!==ve.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=ve.Scalar.QUOTE_DOUBLE);let c=d=>{switch(d){case ve.Scalar.BLOCK_FOLDED:case ve.Scalar.BLOCK_LITERAL:return s||i?ar(o.value,e):As(o,e,t,n);case ve.Scalar.QUOTE_DOUBLE:return Zr(o.value,e);case ve.Scalar.QUOTE_SINGLE:return ga(o.value,e);case ve.Scalar.PLAIN:return yw(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}Nf.stringifyString=bw});var tn=T(ba=>{"use strict";var ww=bs(),ot=F(),vw=Xr(),Sw=en();function kw(r,e){let t=Object.assign({blockQuote:!0,commentString:vw.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 xw(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(ot.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 Ew(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let s=[],i=(ot.isScalar(r)||ot.isCollection(r))&&r.anchor;i&&ww.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 Aw(r,e,t,n){if(ot.isPair(r))return r.toString(e,t,n);if(ot.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=ot.isNode(r)?r:e.doc.createNode(r,{onTagObj:c=>s=c});s??(s=xw(e.doc.schema.tags,i));let o=Ew(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):ot.isScalar(i)?Sw.stringifyString(i,e,t,n):i.toString(e,t,n);return o?ot.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
51
|
+
${e.indent}${a}`:a}ba.createStringifyContext=kw;ba.stringify=Aw});var Mf=T(Lf=>{"use strict";var Je=F(),If=X(),$f=tn(),rn=Xr();function Tw({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=Je.isNode(r)&&r.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Je.isCollection(r)||!Je.isNode(r)&&typeof r=="object"){let $="With simple keys, collection cannot be used as a key value";throw new Error($)}}let p=!u&&(!r||f&&e==null&&!t.inFlow||Je.isCollection(r)||(Je.isScalar(r)?r.type===If.Scalar.BLOCK_FOLDED||r.type===If.Scalar.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(u||!i),indent:a+c});let b=!1,m=!1,g=$f.stringify(r,t,()=>b=!0,()=>m=!0);if(!p&&!t.inFlow&&g.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(),g===""?"?":p?`? ${g}`:g}else if(i&&!u||e==null&&p)return g=`? ${g}`,f&&!b?g+=rn.lineComment(g,t.indent,l(f)):m&&s&&s(),g;b&&(f=null),p?(f&&(g+=rn.lineComment(g,t.indent,l(f))),g=`? ${g}
|
|
52
|
+
${a}:`):(g=`${g}:`,f&&(g+=rn.lineComment(g,t.indent,l(f))));let x,A,P;Je.isNode(e)?(x=!!e.spaceBefore,A=e.commentBefore,P=e.comment):(x=!1,A=null,P=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&Je.isScalar(e)&&(t.indentAtStart=g.length+1),m=!1,!d&&c.length>=2&&!t.inFlow&&!p&&Je.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let R=!1,N=$f.stringify(e,t,()=>R=!0,()=>m=!0),O=" ";if(f||x||A){if(O=x?`
|
|
53
|
+
`:"",A){let $=l(A);O+=`
|
|
54
|
+
${rn.indentComment($,t.indent)}`}N===""&&!t.inFlow?O===`
|
|
55
|
+
`&&P&&(O=`
|
|
56
|
+
|
|
57
|
+
`):O+=`
|
|
58
|
+
${t.indent}`}else if(!p&&Je.isCollection(e)){let $=N[0],E=N.indexOf(`
|
|
59
|
+
`),y=E!==-1,k=t.inFlow??e.flow??e.items.length===0;if(y||!k){let I=!1;if(y&&($==="&"||$==="!")){let _=N.indexOf(" ");$==="&"&&_!==-1&&_<E&&N[_+1]==="!"&&(_=N.indexOf(" ",_+1)),(_===-1||E<_)&&(I=!0)}I||(O=`
|
|
60
|
+
${t.indent}`)}}else(N===""||N[0]===`
|
|
61
|
+
`)&&(O="");return g+=O+N,t.inFlow?R&&n&&n():P&&!R?g+=rn.lineComment(g,t.indent,l(P)):m&&s&&s(),g}Lf.stringifyPair=Tw});var va=T(wa=>{"use strict";var Df=cs("process");function Pw(r,...e){r==="debug"&&console.log(...e)}function Ow(r,e){(r==="debug"||r==="warn")&&(typeof Df.emitWarning=="function"?Df.emitWarning(e):console.warn(e))}wa.debug=Pw;wa.warn=Ow});var Rs=T(_s=>{"use strict";var nn=F(),Bf=X(),Os="<<",Cs={identify:r=>r===Os||typeof r=="symbol"&&r.description===Os,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Bf.Scalar(Symbol(Os)),{addToJSMap:jf}),stringify:()=>Os},Cw=(r,e)=>(Cs.identify(e)||nn.isScalar(e)&&(!e.type||e.type===Bf.Scalar.PLAIN)&&Cs.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===Cs.tag&&t.default);function jf(r,e,t){if(t=r&&nn.isAlias(t)?t.resolve(r.doc):t,nn.isSeq(t))for(let n of t.items)Sa(r,e,n);else if(Array.isArray(t))for(let n of t)Sa(r,e,n);else Sa(r,e,t)}function Sa(r,e,t){let n=r&&nn.isAlias(t)?t.resolve(r.doc):t;if(!nn.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}_s.addMergeToJSMap=jf;_s.isMergeKey=Cw;_s.merge=Cs});var xa=T(Uf=>{"use strict";var _w=va(),Ff=Rs(),Rw=tn(),qf=F(),ka=nt();function Nw(r,e,{key:t,value:n}){if(qf.isNode(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(Ff.isMergeKey(r,t))Ff.addMergeToJSMap(r,e,n);else{let s=ka.toJS(t,"",r);if(e instanceof Map)e.set(s,ka.toJS(n,s,r));else if(e instanceof Set)e.add(s);else{let i=Iw(t,s,r),o=ka.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 Iw(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(qf.isNode(r)&&t?.doc){let n=Rw.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)+'..."'),_w.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)}Uf.addPairToJSMap=Nw});var at=T(Ea=>{"use strict";var Jf=zr(),$w=Mf(),Lw=xa(),Ns=F();function Mw(r,e,t){let n=Jf.createNode(r,void 0,t),s=Jf.createNode(e,void 0,t);return new Is(n,s)}var Is=class r{constructor(e,t=null){Object.defineProperty(this,Ns.NODE_TYPE,{value:Ns.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return Ns.isNode(t)&&(t=t.clone(e)),Ns.isNode(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return Lw.addPairToJSMap(t,n,this)}toString(e,t,n){return e?.doc?$w.stringifyPair(this,e,t,n):JSON.stringify(this)}};Ea.Pair=Is;Ea.createPair=Mw});var Aa=T(Hf=>{"use strict";var Nt=F(),Kf=tn(),$s=Xr();function Dw(r,e,t){return(e.inFlow??r.flow?jw:Bw)(r,e,t)}function Bw({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 m=e[b],g=null;if(Nt.isNode(m))!u&&m.spaceBefore&&f.push(""),Ls(t,f,m.commentBefore,u),m.comment&&(g=m.comment);else if(Nt.isPair(m)){let A=Nt.isNode(m.key)?m.key:null;A&&(!u&&A.spaceBefore&&f.push(""),Ls(t,f,A.commentBefore,u))}u=!1;let x=Kf.stringify(m,d,()=>g=null,()=>u=!0);g&&(x+=$s.lineComment(x,i,l(g))),u&&g&&(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 m=f[b];p+=m?`
|
|
62
62
|
${c}${m}`:`
|
|
63
63
|
`}}return r?(p+=`
|
|
64
|
-
|
|
65
|
-
`))&&(l=!0),u.push(x),
|
|
64
|
+
`+$s.indentComment(l(r),c),a&&a()):u&&o&&o(),p}function jw({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 m=r[b],g=null;if(Nt.isNode(m))m.spaceBefore&&u.push(""),Ls(e,u,m.commentBefore,!1),m.comment&&(g=m.comment);else if(Nt.isPair(m)){let A=Nt.isNode(m.key)?m.key:null;A&&(A.spaceBefore&&u.push(""),Ls(e,u,A.commentBefore,!1),A.comment&&(l=!0));let P=Nt.isNode(m.value)?m.value:null;P?(P.comment&&(g=P.comment),P.commentBefore&&(l=!0)):m.value==null&&A?.comment&&(g=A.comment)}g&&(l=!0);let x=Kf.stringify(m,c,()=>g=null);b<r.length-1&&(x+=","),g&&(x+=$s.lineComment(x,n,a(g))),!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((m,g)=>m+g.length+2,2);l=e.options.lineWidth>0&&b>e.options.lineWidth}if(l){let b=f;for(let m of u)b+=m?`
|
|
66
66
|
${i}${s}${m}`:`
|
|
67
|
-
`;return`${
|
|
68
|
-
${s}${p}`}else return`${
|
|
69
|
-
`:" ")}return
|
|
67
|
+
`;return`${b}
|
|
68
|
+
${s}${p}`}else return`${f}${o}${u.join(" ")}${o}${p}`}function Ls({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=$s.indentComment(e(n),r);t.push(i.trimStart())}}Hf.stringifyCollection=Dw});var lt=T(Pa=>{"use strict";var Fw=Aa(),qw=xa(),Uw=ks(),ct=F(),Ms=at(),Jw=X();function sn(r,e){let t=ct.isScalar(e)?e.value:e;for(let n of r)if(ct.isPair(n)&&(n.key===e||n.key===t||ct.isScalar(n.key)&&n.key.value===t))return n}var Ta=class extends Uw.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(ct.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(Ms.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;ct.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Ms.Pair(e,e?.value):n=new Ms.Pair(e.key,e.value);let s=sn(this.items,n.key),i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);ct.isScalar(s.value)&&Jw.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=sn(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let s=sn(this.items,e)?.value;return(!t&&ct.isScalar(s)?s.value:s)??void 0}has(e){return!!sn(this.items,e)}set(e,t){this.add(new Ms.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)qw.addPairToJSMap(t,s,i);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(let s of this.items)if(!ct.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})),Fw.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};Pa.YAMLMap=Ta;Pa.findPair=sn});var cr=T(Yf=>{"use strict";var Kw=F(),Wf=lt(),Hw={collection:"map",default:!0,nodeClass:Wf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(r,e){return Kw.isMap(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Wf.YAMLMap.from(r,e,t)};Yf.map=Hw});var ut=T(Vf=>{"use strict";var Ww=zr(),Yw=Aa(),Vw=ks(),Bs=F(),Gw=X(),zw=nt(),Oa=class extends Vw.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Bs.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Ds(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=Ds(e);if(typeof n!="number")return;let s=this.items[n];return!t&&Bs.isScalar(s)?s.value:s}has(e){let t=Ds(e);return typeof t=="number"&&t<this.items.length}set(e,t){let n=Ds(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let s=this.items[n];Bs.isScalar(s)&&Gw.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(zw.toJS(i,String(s++),t));return n}toString(e,t,n){return e?Yw.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:s}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof s=="function"){let c=t instanceof Set?a:String(o++);a=s.call(t,c,a)}i.items.push(Ww.createNode(a,void 0,n))}}return i}};function Ds(r){let e=Bs.isScalar(r)?r.value:r;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Vf.YAMLSeq=Oa});var lr=T(zf=>{"use strict";var Xw=F(),Gf=ut(),Qw={collection:"seq",default:!0,nodeClass:Gf.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Xw.isSeq(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Gf.YAMLSeq.from(r,e,t)};zf.seq=Qw});var on=T(Xf=>{"use strict";var Zw=en(),ev={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),Zw.stringifyString(r,e,t,n)}};Xf.string=ev});var js=T(ed=>{"use strict";var Qf=X(),Zf={identify:r=>r==null,createNode:()=>new Qf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Qf.Scalar(null),stringify:({source:r},e)=>typeof r=="string"&&Zf.test.test(r)?r:e.options.nullStr};ed.nullTag=Zf});var Ca=T(rd=>{"use strict";var tv=X(),td={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new tv.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&td.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};rd.boolTag=td});var ur=T(nd=>{"use strict";function rv({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}nd.stringifyNumber=rv});var Ra=T(Fs=>{"use strict";var nv=X(),_a=ur(),sv={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:_a.stringifyNumber},iv={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():_a.stringifyNumber(r)}},ov={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 nv.Scalar(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:_a.stringifyNumber};Fs.float=ov;Fs.floatExp=iv;Fs.floatNaN=sv});var Ia=T(Us=>{"use strict";var sd=ur(),qs=r=>typeof r=="bigint"||Number.isInteger(r),Na=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function id(r,e,t){let{value:n}=r;return qs(n)&&n>=0?t+n.toString(e):sd.stringifyNumber(r)}var av={identify:r=>qs(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>Na(r,2,8,t),stringify:r=>id(r,8,"0o")},cv={identify:qs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>Na(r,0,10,t),stringify:sd.stringifyNumber},lv={identify:r=>qs(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>Na(r,2,16,t),stringify:r=>id(r,16,"0x")};Us.int=cv;Us.intHex=lv;Us.intOct=av});var ad=T(od=>{"use strict";var uv=cr(),fv=js(),dv=lr(),pv=on(),mv=Ca(),$a=Ra(),La=Ia(),hv=[uv.map,dv.seq,pv.string,fv.nullTag,mv.boolTag,La.intOct,La.int,La.intHex,$a.floatNaN,$a.floatExp,$a.float];od.schema=hv});var ud=T(ld=>{"use strict";var gv=X(),yv=cr(),bv=lr();function cd(r){return typeof r=="bigint"||Number.isInteger(r)}var Js=({value:r})=>JSON.stringify(r),wv=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Js},{identify:r=>r==null,createNode:()=>new gv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Js},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Js},{identify:cd,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})=>cd(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:Js}],vv={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},Sv=[yv.map,bv.seq].concat(wv,vv);ld.schema=Sv});var Da=T(fd=>{"use strict";var an=cs("buffer"),Ma=X(),kv=en(),xv={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof an.Buffer=="function")return an.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 an.Buffer=="function")a=o instanceof an.Buffer?o.toString("base64"):an.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=Ma.Scalar.BLOCK_LITERAL),e!==Ma.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===Ma.Scalar.BLOCK_LITERAL?`
|
|
69
|
+
`:" ")}return kv.stringifyString({comment:r,type:e,value:a},n,s,i)}};fd.binary=xv});var Ws=T(Hs=>{"use strict";var Ks=F(),Ba=at(),Ev=X(),Av=ut();function dd(r,e){if(Ks.isSeq(r))for(let t=0;t<r.items.length;++t){let n=r.items[t];if(!Ks.isPair(n)){if(Ks.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let s=n.items[0]||new Ba.Pair(new Ev.Scalar(null));if(n.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${n.commentBefore}
|
|
70
70
|
${s.key.commentBefore}`:n.commentBefore),n.comment){let i=s.value??s.key;i.comment=i.comment?`${n.comment}
|
|
71
|
-
${i.comment}`:n.comment}n=s}r.items[t]=Cs.isPair(n)?n:new Ea.Pair(n)}}else e("Expected a sequence for this tag");return r}function Jd(r,e,t){let{replacer:n}=t,s=new Gw.YAMLSeq(r);s.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(i++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;s.items.push(Ea.createPair(a,c,t))}return s}var zw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ud,createNode:Jd};Rs.createPairs=Jd;Rs.pairs=zw;Rs.resolvePairs=Ud});var Pa=E(Ta=>{"use strict";var Kd=j(),Aa=Ze(),en=it(),Xw=ot(),Hd=Ns(),At=class r extends Xw.YAMLSeq{constructor(){super(),this.add=en.YAMLMap.prototype.add.bind(this),this.delete=en.YAMLMap.prototype.delete.bind(this),this.get=en.YAMLMap.prototype.get.bind(this),this.has=en.YAMLMap.prototype.has.bind(this),this.set=en.YAMLMap.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let s of this.items){let i,o;if(Kd.isPair(s)?(i=Aa.toJS(s.key,"",t),o=Aa.toJS(s.value,i,t)):i=Aa.toJS(s,"",t),n.has(i))throw new Error("Ordered maps must not include duplicate keys");n.set(i,o)}return n}static from(e,t,n){let s=Hd.createPairs(e,t,n),i=new this;return i.items=s.items,i}};At.tag="tag:yaml.org,2002:omap";var Qw={collection:"seq",identify:r=>r instanceof Map,nodeClass:At,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Hd.resolvePairs(r,e),n=[];for(let{key:s}of t.items)Kd.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new At,t)},createNode:(r,e,t)=>At.from(r,e,t)};Ta.YAMLOMap=At;Ta.omap=Qw});var zd=E(Oa=>{"use strict";var Wd=G();function Yd({value:r,source:e},t){return e&&(r?Vd:Gd).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Vd={identify:r=>r===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Wd.Scalar(!0),stringify:Yd},Gd={identify:r=>r===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Wd.Scalar(!1),stringify:Yd};Oa.falseTag=Gd;Oa.trueTag=Vd});var Xd=E(Is=>{"use strict";var Zw=G(),_a=nr(),ev={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:_a.stringifyNumber},tv={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():_a.stringifyNumber(r)}},rv={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new Zw.Scalar(parseFloat(r.replace(/_/g,""))),t=r.indexOf(".");if(t!==-1){let n=r.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:_a.stringifyNumber};Is.float=rv;Is.floatExp=tv;Is.floatNaN=ev});var Zd=E(rn=>{"use strict";var Qd=nr(),tn=r=>typeof r=="bigint"||Number.isInteger(r);function $s(r,e,t,{intAsBigInt:n}){let s=r[0];if((s==="-"||s==="+")&&(e+=1),r=r.substring(e).replace(/_/g,""),n){switch(t){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}let o=BigInt(r);return s==="-"?BigInt(-1)*o:o}let i=parseInt(r,t);return s==="-"?-1*i:i}function Ca(r,e,t){let{value:n}=r;if(tn(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return Qd.stringifyNumber(r)}var nv={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>$s(r,2,2,t),stringify:r=>Ca(r,2,"0b")},sv={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>$s(r,1,8,t),stringify:r=>Ca(r,8,"0")},iv={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>$s(r,0,10,t),stringify:Qd.stringifyNumber},ov={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>$s(r,2,16,t),stringify:r=>Ca(r,16,"0x")};rn.int=iv;rn.intBin=nv;rn.intHex=ov;rn.intOct=sv});var Na=E(Ra=>{"use strict";var Ds=j(),Ls=nt(),Ms=it(),Tt=class r extends Ms.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;Ds.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Ls.Pair(e.key,null):t=new Ls.Pair(e,null),Ms.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=Ms.findPair(this.items,e);return!t&&Ds.isPair(n)?Ds.isScalar(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=Ms.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Ls.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){let{replacer:s}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof s=="function"&&(o=s.call(t,o,o)),i.items.push(Ls.createPair(o,null,n));return i}};Tt.tag="tag:yaml.org,2002:set";var av={collection:"map",identify:r=>r instanceof Set,nodeClass:Tt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>Tt.from(r,e,t),resolve(r,e){if(Ds.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new Tt,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Ra.YAMLSet=Tt;Ra.set=av});var $a=E(Bs=>{"use strict";var cv=nr();function Ia(r,e){let t=r[0],n=t==="-"||t==="+"?r.substring(1):r,s=o=>e?BigInt(o):Number(o),i=n.replace(/_/g,"").split(":").reduce((o,a)=>o*s(60)+s(a),s(0));return t==="-"?s(-1)*i:i}function ef(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return cv.stringifyNumber(r);let n="";e<0&&(n="-",e*=t(-1));let s=t(60),i=[e%s];return e<60?i.unshift(0):(e=(e-i[0])/s,i.unshift(e%s),e>=60&&(e=(e-i[0])/s,i.unshift(e))),n+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var lv={identify:r=>typeof r=="bigint"||Number.isInteger(r),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(r,e,{intAsBigInt:t})=>Ia(r,t),stringify:ef},uv={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:r=>Ia(r,!1),stringify:ef},tf={identify:r=>r instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(r){let e=r.match(tf.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,s,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,s,i||0,o||0,a||0,c),f=e[8];if(f&&f!=="Z"){let u=Ia(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Bs.floatTime=uv;Bs.intTime=lv;Bs.timestamp=tf});var sf=E(nf=>{"use strict";var dv=tr(),fv=As(),pv=rr(),mv=Qr(),hv=ka(),rf=zd(),La=Xd(),js=Zd(),gv=ys(),yv=Pa(),bv=Ns(),wv=Na(),Ma=$a(),vv=[dv.map,pv.seq,mv.string,fv.nullTag,rf.trueTag,rf.falseTag,js.intBin,js.intOct,js.int,js.intHex,La.floatNaN,La.floatExp,La.float,hv.binary,gv.merge,yv.omap,bv.pairs,wv.set,Ma.intTime,Ma.floatTime,Ma.timestamp];nf.schema=vv});var hf=E(ja=>{"use strict";var lf=tr(),Sv=As(),uf=rr(),xv=Qr(),kv=ha(),Da=ya(),Ba=wa(),Ev=Dd(),Av=Fd(),df=ka(),nn=ys(),ff=Pa(),pf=Ns(),of=sf(),mf=Na(),Fs=$a(),af=new Map([["core",Ev.schema],["failsafe",[lf.map,uf.seq,xv.string]],["json",Av.schema],["yaml11",of.schema],["yaml-1.1",of.schema]]),cf={binary:df.binary,bool:kv.boolTag,float:Da.float,floatExp:Da.floatExp,floatNaN:Da.floatNaN,floatTime:Fs.floatTime,int:Ba.int,intHex:Ba.intHex,intOct:Ba.intOct,intTime:Fs.intTime,map:lf.map,merge:nn.merge,null:Sv.nullTag,omap:ff.omap,pairs:pf.pairs,seq:uf.seq,set:mf.set,timestamp:Fs.timestamp},Tv={"tag:yaml.org,2002:binary":df.binary,"tag:yaml.org,2002:merge":nn.merge,"tag:yaml.org,2002:omap":ff.omap,"tag:yaml.org,2002:pairs":pf.pairs,"tag:yaml.org,2002:set":mf.set,"tag:yaml.org,2002:timestamp":Fs.timestamp};function Pv(r,e,t){let n=af.get(e);if(n&&!r)return t&&!n.includes(nn.merge)?n.concat(nn.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(af.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(r))for(let i of r)s=s.concat(i);else typeof r=="function"&&(s=r(s.slice()));return t&&(s=s.concat(nn.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?cf[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(cf).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}ja.coreKnownTags=Tv;ja.getTags=Pv});var Ua=E(gf=>{"use strict";var Fa=j(),Ov=tr(),_v=rr(),Cv=Qr(),qs=hf(),Rv=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,qa=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?qs.getTags(e,"compat"):e?qs.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?qs.coreKnownTags:{},this.tags=qs.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Fa.MAP,{value:Ov.map}),Object.defineProperty(this,Fa.SCALAR,{value:Cv.string}),Object.defineProperty(this,Fa.SEQ,{value:_v.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Rv:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};gf.Schema=qa});var bf=E(yf=>{"use strict";var Nv=j(),Ja=Vr(),sn=Kr();function Iv(r,e){let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let c=r.directives.toString(r);c?(t.push(c),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let s=Ja.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(sn.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(Nv.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let f=i(r.contents.commentBefore);t.push(sn.indentComment(f,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Ja.stringify(r.contents,s,()=>a=null,c);a&&(l+=sn.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Ja.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
72
|
-
`)?(t.push("..."),t.push(
|
|
71
|
+
${i.comment}`:n.comment}n=s}r.items[t]=Ks.isPair(n)?n:new Ba.Pair(n)}}else e("Expected a sequence for this tag");return r}function pd(r,e,t){let{replacer:n}=t,s=new Av.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(Ba.createPair(a,c,t))}return s}var Tv={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:dd,createNode:pd};Hs.createPairs=pd;Hs.pairs=Tv;Hs.resolvePairs=dd});var qa=T(Fa=>{"use strict";var md=F(),ja=nt(),cn=lt(),Pv=ut(),hd=Ws(),It=class r extends Pv.YAMLSeq{constructor(){super(),this.add=cn.YAMLMap.prototype.add.bind(this),this.delete=cn.YAMLMap.prototype.delete.bind(this),this.get=cn.YAMLMap.prototype.get.bind(this),this.has=cn.YAMLMap.prototype.has.bind(this),this.set=cn.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(md.isPair(s)?(i=ja.toJS(s.key,"",t),o=ja.toJS(s.value,i,t)):i=ja.toJS(s,"",t),n.has(i))throw new Error("Ordered maps must not include duplicate keys");n.set(i,o)}return n}static from(e,t,n){let s=hd.createPairs(e,t,n),i=new this;return i.items=s.items,i}};It.tag="tag:yaml.org,2002:omap";var Ov={collection:"seq",identify:r=>r instanceof Map,nodeClass:It,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=hd.resolvePairs(r,e),n=[];for(let{key:s}of t.items)md.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new It,t)},createNode:(r,e,t)=>It.from(r,e,t)};Fa.YAMLOMap=It;Fa.omap=Ov});var vd=T(Ua=>{"use strict";var gd=X();function yd({value:r,source:e},t){return e&&(r?bd:wd).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var bd={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 gd.Scalar(!0),stringify:yd},wd={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 gd.Scalar(!1),stringify:yd};Ua.falseTag=wd;Ua.trueTag=bd});var Sd=T(Ys=>{"use strict";var Cv=X(),Ja=ur(),_v={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:Ja.stringifyNumber},Rv={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():Ja.stringifyNumber(r)}},Nv={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 Cv.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:Ja.stringifyNumber};Ys.float=Nv;Ys.floatExp=Rv;Ys.floatNaN=_v});var xd=T(un=>{"use strict";var kd=ur(),ln=r=>typeof r=="bigint"||Number.isInteger(r);function Vs(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 Ka(r,e,t){let{value:n}=r;if(ln(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return kd.stringifyNumber(r)}var Iv={identify:ln,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Vs(r,2,2,t),stringify:r=>Ka(r,2,"0b")},$v={identify:ln,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Vs(r,1,8,t),stringify:r=>Ka(r,8,"0")},Lv={identify:ln,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Vs(r,0,10,t),stringify:kd.stringifyNumber},Mv={identify:ln,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Vs(r,2,16,t),stringify:r=>Ka(r,16,"0x")};un.int=Lv;un.intBin=Iv;un.intHex=Mv;un.intOct=$v});var Wa=T(Ha=>{"use strict";var Xs=F(),Gs=at(),zs=lt(),$t=class r extends zs.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;Xs.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Gs.Pair(e.key,null):t=new Gs.Pair(e,null),zs.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=zs.findPair(this.items,e);return!t&&Xs.isPair(n)?Xs.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=zs.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Gs.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(Gs.createPair(o,null,n));return i}};$t.tag="tag:yaml.org,2002:set";var Dv={collection:"map",identify:r=>r instanceof Set,nodeClass:$t,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>$t.from(r,e,t),resolve(r,e){if(Xs.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new $t,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Ha.YAMLSet=$t;Ha.set=Dv});var Va=T(Qs=>{"use strict";var Bv=ur();function Ya(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 Ed(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Bv.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 jv={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})=>Ya(r,t),stringify:Ed},Fv={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=>Ya(r,!1),stringify:Ed},Ad={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(Ad.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=Ya(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$/,"")??""};Qs.floatTime=Fv;Qs.intTime=jv;Qs.timestamp=Ad});var Od=T(Pd=>{"use strict";var qv=cr(),Uv=js(),Jv=lr(),Kv=on(),Hv=Da(),Td=vd(),Ga=Sd(),Zs=xd(),Wv=Rs(),Yv=qa(),Vv=Ws(),Gv=Wa(),za=Va(),zv=[qv.map,Jv.seq,Kv.string,Uv.nullTag,Td.trueTag,Td.falseTag,Zs.intBin,Zs.intOct,Zs.int,Zs.intHex,Ga.floatNaN,Ga.floatExp,Ga.float,Hv.binary,Wv.merge,Yv.omap,Vv.pairs,Gv.set,za.intTime,za.floatTime,za.timestamp];Pd.schema=zv});var Bd=T(Za=>{"use strict";var Nd=cr(),Xv=js(),Id=lr(),Qv=on(),Zv=Ca(),Xa=Ra(),Qa=Ia(),eS=ad(),tS=ud(),$d=Da(),fn=Rs(),Ld=qa(),Md=Ws(),Cd=Od(),Dd=Wa(),ei=Va(),_d=new Map([["core",eS.schema],["failsafe",[Nd.map,Id.seq,Qv.string]],["json",tS.schema],["yaml11",Cd.schema],["yaml-1.1",Cd.schema]]),Rd={binary:$d.binary,bool:Zv.boolTag,float:Xa.float,floatExp:Xa.floatExp,floatNaN:Xa.floatNaN,floatTime:ei.floatTime,int:Qa.int,intHex:Qa.intHex,intOct:Qa.intOct,intTime:ei.intTime,map:Nd.map,merge:fn.merge,null:Xv.nullTag,omap:Ld.omap,pairs:Md.pairs,seq:Id.seq,set:Dd.set,timestamp:ei.timestamp},rS={"tag:yaml.org,2002:binary":$d.binary,"tag:yaml.org,2002:merge":fn.merge,"tag:yaml.org,2002:omap":Ld.omap,"tag:yaml.org,2002:pairs":Md.pairs,"tag:yaml.org,2002:set":Dd.set,"tag:yaml.org,2002:timestamp":ei.timestamp};function nS(r,e,t){let n=_d.get(e);if(n&&!r)return t&&!n.includes(fn.merge)?n.concat(fn.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(_d.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(fn.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?Rd[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Rd).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},[])}Za.coreKnownTags=rS;Za.getTags=nS});var rc=T(jd=>{"use strict";var ec=F(),sS=cr(),iS=lr(),oS=on(),ti=Bd(),aS=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,tc=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ti.getTags(e,"compat"):e?ti.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?ti.coreKnownTags:{},this.tags=ti.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,ec.MAP,{value:sS.map}),Object.defineProperty(this,ec.SCALAR,{value:oS.string}),Object.defineProperty(this,ec.SEQ,{value:iS.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?aS:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};jd.Schema=tc});var qd=T(Fd=>{"use strict";var cS=F(),nc=tn(),dn=Xr();function lS(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=nc.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(dn.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(cS.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let d=i(r.contents.commentBefore);t.push(dn.indentComment(d,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=nc.stringify(r.contents,s,()=>a=null,c);a&&(l+=dn.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(nc.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
72
|
+
`)?(t.push("..."),t.push(dn.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(dn.indentComment(i(c),"")))}return t.join(`
|
|
73
73
|
`)+`
|
|
74
|
-
`}
|
|
74
|
+
`}Fd.stringifyDocument=lS});var pn=T(Ud=>{"use strict";var uS=Gr(),fr=ks(),me=F(),fS=at(),dS=nt(),pS=rc(),mS=qd(),sc=bs(),hS=ca(),gS=zr(),ic=aa(),oc=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,me.NODE_TYPE,{value:me.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 ic.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,{[me.NODE_TYPE]:{value:me.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=me.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){dr(this.contents)&&this.contents.add(e)}addIn(e,t){dr(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=sc.anchorNames(this);e.anchor=!t||n.has(t)?sc.findNewAnchor(t||"a",n):t}return new uS.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 g=A=>typeof A=="number"||A instanceof String||A instanceof Number,x=t.filter(g).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}=sc.createNodeAnchors(this,o||"a"),b={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:p},m=gS.createNode(e,d,b);return a&&me.isCollection(m)&&(m.flow=!0),f(),m}createPair(e,t,n={}){let s=this.createNode(e,null,n),i=this.createNode(t,null,n);return new fS.Pair(s,i)}delete(e){return dr(this.contents)?this.contents.delete(e):!1}deleteIn(e){return fr.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):dr(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return me.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return fr.isEmptyPath(e)?!t&&me.isScalar(this.contents)?this.contents.value:this.contents:me.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return me.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return fr.isEmptyPath(e)?this.contents!==void 0:me.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=fr.collectionFromPath(this.schema,[e],t):dr(this.contents)&&this.contents.set(e,t)}setIn(e,t){fr.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=fr.collectionFromPath(this.schema,Array.from(e),t):dr(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 ic.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 ic.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 pS.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=dS.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"?hS.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 mS.stringifyDocument(this,e)}};function dr(r){if(me.isCollection(r))return!0;throw new Error("Expected a YAML collection as document contents")}Ud.Document=oc});var gn=T(hn=>{"use strict";var mn=class extends Error{constructor(e,t,n,s){super(),this.name=e,this.code=n,this.message=s,this.pos=t}},ac=class extends mn{constructor(e,t,n){super("YAMLParseError",e,t,n)}},cc=class extends mn{constructor(e,t,n){super("YAMLWarning",e,t,n)}},yS=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:s}=t.linePos[0];t.message+=` at line ${n}, column ${s}`;let i=s-1,o=r.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){let a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,i))){let a=r.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
|
|
75
75
|
`),o=a+o}if(/[^ ]/.test(o)){let a=1,c=t.linePos[1];c?.line===n&&c.col>s&&(a=Math.max(1,Math.min(c.col-s,80-i)));let l=" ".repeat(i)+"^".repeat(a);t.message+=`:
|
|
76
76
|
|
|
77
77
|
${o}
|
|
78
78
|
${l}
|
|
79
|
-
`}};
|
|
80
|
-
`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(
|
|
81
|
-
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||
|
|
82
|
-
`+
|
|
83
|
-
`+
|
|
84
|
-
|
|
85
|
-
`+
|
|
86
|
-
`+
|
|
87
|
-
`.repeat(Math.max(1,o.length-1)):"",
|
|
88
|
-
`;for(let m=
|
|
89
|
-
`):
|
|
90
|
-
`:!p&&
|
|
91
|
-
`&&(
|
|
92
|
-
|
|
93
|
-
`),u+=
|
|
94
|
-
`,p=!0):x===""?
|
|
79
|
+
`}};hn.YAMLError=mn;hn.YAMLParseError=ac;hn.YAMLWarning=cc;hn.prettifyError=yS});var yn=T(Jd=>{"use strict";function bS(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,m=null,g=null,x=null,A=null,P=null,R=null,N=null;for(let E of r)switch(b&&(E.type!=="space"&&E.type!=="newline"&&E.type!=="comma"&&i(E.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),b=!1),m&&(l&&E.type!=="comment"&&E.type!=="newline"&&i(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),E.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&E.source.includes(" ")&&(m=E),d=!0;break;case"comment":{d||i(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let y=E.source.substring(1)||" ";u?u+=f+y:u=y,f="",l=!1;break}case"newline":l?u?u+=E.source:(!R||t!=="seq-item-ind")&&(c=!0):f+=E.source,l=!0,p=!0,(g||x)&&(A=E),d=!0;break;case"anchor":g&&i(E,"MULTIPLE_ANCHORS","A node can have at most one anchor"),E.source.endsWith(":")&&i(E.offset+E.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=E,N??(N=E.offset),l=!1,d=!1,b=!0;break;case"tag":{x&&i(E,"MULTIPLE_TAGS","A node can have at most one tag"),x=E,N??(N=E.offset),l=!1,d=!1,b=!0;break}case t:(g||x)&&i(E,"BAD_PROP_ORDER",`Anchors and tags must be after the ${E.source} indicator`),R&&i(E,"UNEXPECTED_TOKEN",`Unexpected ${E.source} in ${e??"collection"}`),R=E,l=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){P&&i(E,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),P=E,l=!1,d=!1;break}default:i(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),l=!1,d=!1}let O=r[r.length-1],$=O?O.offset+O.source.length:s;return b&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&i(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&i(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:P,found:R,spaceBefore:c,comment:u,hasNewline:p,anchor:g,tag:x,newlineAfterProp:A,end:$,start:N??$}}Jd.resolveProps=bS});var ri=T(Kd=>{"use strict";function lc(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(lc(e.key)||lc(e.value))return!0}return!1;default:return!0}}Kd.containsNewline=lc});var uc=T(Hd=>{"use strict";var wS=ri();function vS(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&wS.containsNewline(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Hd.flowIndentCheck=vS});var fc=T(Yd=>{"use strict";var Wd=F();function SS(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let s=typeof n=="function"?n:(i,o)=>i===o||Wd.isScalar(i)&&Wd.isScalar(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}Yd.mapIncludes=SS});var Zd=T(Qd=>{"use strict";var Vd=at(),kS=lt(),Gd=yn(),xS=ri(),zd=uc(),ES=fc(),Xd="All mapping items must start at the same column";function AS({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??kS.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,m=Gd.resolveProps(u,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0}),g=!m.found;if(g){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",Xd)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(a.comment?a.comment+=`
|
|
81
|
+
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||xS.containsNewline(f))&&s(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==n.indent&&s(c,"BAD_INDENT",Xd);t.atKey=!0;let x=m.end,A=f?r(t,f,m,s):e(t,x,u,null,m,s);t.schema.compat&&zd.flowIndentCheck(n.indent,f,s),t.atKey=!1,ES.mapIncludes(t,a.items,A)&&s(x,"DUPLICATE_KEY","Map keys must be unique");let P=Gd.resolveProps(p??[],{indicator:"map-value-ind",next:b,offset:A.range[2],onError:s,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=P.end,P.found){g&&(b?.type==="block-map"&&!P.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&m.start<P.found.offset-1024&&s(A.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let R=b?r(t,b,P,s):e(t,c,p,null,P,s);t.schema.compat&&zd.flowIndentCheck(n.indent,b,s),c=R.range[2];let N=new Vd.Pair(A,R);t.options.keepSourceTokens&&(N.srcToken=d),a.items.push(N)}else{g&&s(A.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),P.comment&&(A.comment?A.comment+=`
|
|
82
|
+
`+P.comment:A.comment=P.comment);let R=new Vd.Pair(A);t.options.keepSourceTokens&&(R.srcToken=d),a.items.push(R)}}return l&&l<c&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,l??c],a}Qd.resolveBlockMap=AS});var tp=T(ep=>{"use strict";var TS=ut(),PS=yn(),OS=uc();function CS({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??TS.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=PS.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&&OS.flowIndentCheck(n.indent,u,s),c=p.range[2],a.items.push(p)}return a.range=[n.offset,c,l??c],a}ep.resolveBlockSeq=CS});var pr=T(rp=>{"use strict";function _S(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}}rp.resolveEnd=_S});var op=T(ip=>{"use strict";var RS=F(),NS=at(),np=lt(),IS=ut(),$S=pr(),sp=yn(),LS=ri(),MS=fc(),dc="Block collections are not allowed within flow collections",pc=r=>r&&(r.type==="block-map"||r.type==="block-seq");function DS({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?np.YAMLMap:IS.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 g=0;g<n.items.length;++g){let x=n.items[g],{start:A,key:P,sep:R,value:N}=x,O=sp.resolveProps(A,{flow:a,indicator:"explicit-key-ind",next:P??R?.[0],offset:u,onError:s,parentIndent:n.indent,startOnNewline:!1});if(!O.found){if(!O.anchor&&!O.tag&&!R&&!N){g===0&&O.comma?s(O.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):g<n.items.length-1&&s(O.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),O.comment&&(l.comment?l.comment+=`
|
|
83
|
+
`+O.comment:l.comment=O.comment),u=O.end;continue}!o&&t.options.strict&&LS.containsNewline(P)&&s(P,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)O.comma&&s(O.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(O.comma||s(O.start,"MISSING_CHAR",`Missing , between ${a} items`),O.comment){let $="";e:for(let E of A)switch(E.type){case"comma":case"space":break;case"comment":$=E.source.substring(1);break e;default:break e}if($){let E=l.items[l.items.length-1];RS.isPair(E)&&(E=E.value??E.key),E.comment?E.comment+=`
|
|
84
|
+
`+$:E.comment=$,O.comment=O.comment.substring($.length+1)}}if(!o&&!R&&!O.found){let $=N?r(t,N,O,s):e(t,O.end,R,null,O,s);l.items.push($),u=$.range[2],pc(N)&&s($.range,"BLOCK_IN_FLOW",dc)}else{t.atKey=!0;let $=O.end,E=P?r(t,P,O,s):e(t,$,A,null,O,s);pc(P)&&s(E.range,"BLOCK_IN_FLOW",dc),t.atKey=!1;let y=sp.resolveProps(R??[],{flow:a,indicator:"map-value-ind",next:N,offset:E.range[2],onError:s,parentIndent:n.indent,startOnNewline:!1});if(y.found){if(!o&&!O.found&&t.options.strict){if(R)for(let _ of R){if(_===y.found)break;if(_.type==="newline"){s(_,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}O.start<y.found.offset-1024&&s(y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else N&&("source"in N&&N.source?.[0]===":"?s(N,"MISSING_CHAR",`Missing space after : in ${a}`):s(y.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let k=N?r(t,N,y,s):y.found?e(t,y.end,R,null,y,s):null;k?pc(N)&&s(k.range,"BLOCK_IN_FLOW",dc):y.comment&&(E.comment?E.comment+=`
|
|
85
|
+
`+y.comment:E.comment=y.comment);let I=new NS.Pair(E,k);if(t.options.keepSourceTokens&&(I.srcToken=x),o){let _=l;MS.mapIncludes(t,_.items,E)&&s($,"DUPLICATE_KEY","Map keys must be unique"),_.items.push(I)}else{let _=new np.YAMLMap(t.schema);_.flow=!0,_.items.push(I);let M=(k??E).range;_.range=[E.range[0],M[1],M[2]],l.items.push(_)}u=k?k.range[2]:y.end}}let f=o?"}":"]",[p,...b]=n.end,m=u;if(p?.source===f)m=p.offset+p.source.length;else{let g=a[0].toUpperCase()+a.substring(1),x=d?`${g} must end with a ${f}`:`${g} 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 g=$S.resolveEnd(b,m,t.options.strict,s);g.comment&&(l.comment?l.comment+=`
|
|
86
|
+
`+g.comment:l.comment=g.comment),l.range=[n.offset,m,g.offset]}else l.range=[n.offset,m,m];return l}ip.resolveFlowCollection=DS});var cp=T(ap=>{"use strict";var BS=F(),jS=X(),FS=lt(),qS=ut(),US=Zd(),JS=tp(),KS=op();function mc(r,e,t,n,s,i){let o=t.type==="block-map"?US.resolveBlockMap(r,e,t,n,i):t.type==="block-seq"?JS.resolveBlockSeq(r,e,t,n,i):KS.resolveFlowCollection(r,e,t,n,i),a=o.constructor;return s==="!"||s===a.tagName?(o.tag=a.tagName,o):(s&&(o.tag=s),o)}function HS(r,e,t,n,s){let i=n.tag,o=i?e.directives.tagName(i.source,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===FS.YAMLMap.tagName&&a==="map"||o===qS.YAMLSeq.tagName&&a==="seq")return mc(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),mc(r,e,t,s,o)}let l=mc(r,e,t,s,o,c),d=c.resolve?.(l,f=>s(i,"TAG_RESOLVE_FAILED",f),e.options)??l,u=BS.isNode(d)?d:new jS.Scalar(d);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}ap.composeCollection=HS});var gc=T(lp=>{"use strict";var hc=X();function WS(r,e,t){let n=e.offset,s=YS(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let i=s.mode===">"?hc.Scalar.BLOCK_FOLDED:hc.Scalar.BLOCK_LITERAL,o=e.source?VS(e.source):[],a=o.length;for(let m=o.length-1;m>=0;--m){let g=o[m][1];if(g===""||g==="\r")a=m;else break}if(a===0){let m=s.chomp==="+"&&o.length>0?`
|
|
87
|
+
`.repeat(Math.max(1,o.length-1)):"",g=n+s.length;return e.source&&(g+=e.source.length),{value:m,type:i,comment:s.comment,range:[n,g,g]}}let c=e.indent+s.indent,l=e.offset+s.length,d=0;for(let m=0;m<a;++m){let[g,x]=o[m];if(x===""||x==="\r")s.indent===0&&g.length>c&&(c=g.length);else{g.length<c&&t(l+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(c=g.length),d=m,c===0&&!r.atRoot&&t(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=g.length+x.length+1}for(let m=o.length-1;m>=a;--m)o[m][0].length>c&&(a=m+1);let u="",f="",p=!1;for(let m=0;m<d;++m)u+=o[m][0].slice(c)+`
|
|
88
|
+
`;for(let m=d;m<a;++m){let[g,x]=o[m];l+=g.length+x.length+1;let A=x[x.length-1]==="\r";if(A&&(x=x.slice(0,-1)),x&&g.length<c){let R=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;t(l-x.length-(A?2:1),"BAD_INDENT",R),g=""}i===hc.Scalar.BLOCK_LITERAL?(u+=f+g.slice(c)+x,f=`
|
|
89
|
+
`):g.length>c||x[0]===" "?(f===" "?f=`
|
|
90
|
+
`:!p&&f===`
|
|
91
|
+
`&&(f=`
|
|
92
|
+
|
|
93
|
+
`),u+=f+g.slice(c)+x,f=`
|
|
94
|
+
`,p=!0):x===""?f===`
|
|
95
95
|
`?u+=`
|
|
96
|
-
`:
|
|
97
|
-
`:(u+=
|
|
96
|
+
`:f=`
|
|
97
|
+
`:(u+=f+x,f=" ",p=!1)}switch(s.chomp){case"-":break;case"+":for(let m=a;m<o.length;++m)u+=`
|
|
98
98
|
`+o[m][0].slice(c);u[u.length-1]!==`
|
|
99
99
|
`&&(u+=`
|
|
100
100
|
`);break;default:u+=`
|
|
101
|
-
`}let
|
|
101
|
+
`}let b=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,b,b]}}function YS({offset:r,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:s}=e[0],i=s[0],o=0,a="",c=-1;for(let 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 m=p.source;m&&typeof m=="string"&&(u+=m.length)}}}return{mode:i,indent:o,chomp:a,comment:d,length:u}}function VS(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}lp.resolveBlockScalar=WS});var bc=T(fp=>{"use strict";var yc=X(),GS=pr();function zS(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=yc.Scalar.PLAIN,c=XS(i,l);break;case"single-quoted-scalar":a=yc.Scalar.QUOTE_SINGLE,c=QS(i,l);break;case"double-quoted-scalar":a=yc.Scalar.QUOTE_DOUBLE,c=ZS(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=GS.resolveEnd(o,d,e,t);return{value:c,type:a,comment:u.comment,range:[n,d,u.offset]}}function XS(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}`),up(r)}function QS(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),up(r.slice(1,-1)).replace(/''/g,"'")}function up(r){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
102
102
|
`,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
103
103
|
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=e.exec(r);if(!n)return r;let s=n[1],i=" ",o=e.lastIndex;for(t.lastIndex=o;n=t.exec(r);)n[1]===""?i===`
|
|
104
104
|
`?s+=i:i=`
|
|
105
|
-
`:(s+=i+n[1],i=" "),o=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(r),s+i+(n?.[1]??"")}function
|
|
105
|
+
`:(s+=i+n[1],i=" "),o=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(r),s+i+(n?.[1]??"")}function ZS(r,e){let t="";for(let n=1;n<r.length-1;++n){let s=r[n];if(!(s==="\r"&&r[n+1]===`
|
|
106
106
|
`))if(s===`
|
|
107
|
-
`){let{fold:i,offset:o}=
|
|
107
|
+
`){let{fold:i,offset:o}=ek(r,n);t+=i,n=o}else if(s==="\\"){let i=r[++n],o=tk[i];if(o)t+=o;else if(i===`
|
|
108
108
|
`)for(i=r[n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="\r"&&r[n+1]===`
|
|
109
|
-
`)for(i=r[++n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];t+=
|
|
109
|
+
`)for(i=r[++n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];t+=rk(r,n+1,a,e),n+=a}else{let a=r.substr(n-1,2);e(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(s===" "||s===" "){let i=n,o=r[n+1];for(;o===" "||o===" ";)o=r[++n+1];o!==`
|
|
110
110
|
`&&!(o==="\r"&&r[n+2]===`
|
|
111
|
-
`)&&(t+=n>i?r.slice(i,n+1):s)}else t+=s}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function
|
|
111
|
+
`)&&(t+=n>i?r.slice(i,n+1):s)}else t+=s}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function ek(r,e){let t="",n=r[e+1];for(;(n===" "||n===" "||n===`
|
|
112
112
|
`||n==="\r")&&!(n==="\r"&&r[e+2]!==`
|
|
113
113
|
`);)n===`
|
|
114
114
|
`&&(t+=`
|
|
115
|
-
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var
|
|
116
|
-
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
115
|
+
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var tk={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 rk(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)}fp.resolveFlowScalar=zS});var mp=T(pp=>{"use strict";var Lt=F(),dp=X(),nk=gc(),sk=bc();function ik(r,e,t,n){let{value:s,type:i,comment:o,range:a}=e.type==="block-scalar"?nk.resolveBlockScalar(r,e,n):sk.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[Lt.SCALAR]:c?l=ok(r.schema,s,c,t,n):e.type==="scalar"?l=ak(r,s,e,n):l=r.schema[Lt.SCALAR];let d;try{let u=l.resolve(s,f=>n(t??e,"TAG_RESOLVE_FAILED",f),r.options);d=Lt.isScalar(u)?u:new dp.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);n(t??e,"TAG_RESOLVE_FAILED",f),d=new dp.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 ok(r,e,t,n,s){if(t==="!")return r[Lt.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[Lt.SCALAR])}function ak({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[Lt.SCALAR];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[Lt.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}pp.composeScalar=ik});var gp=T(hp=>{"use strict";function ck(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}hp.emptyScalarPosition=ck});var wp=T(vc=>{"use strict";var lk=Gr(),uk=F(),fk=cp(),yp=mp(),dk=pr(),pk=gp(),mk={composeNode:bp,composeEmptyNode:wc};function bp(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=hk(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=yp.composeScalar(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=fk.composeCollection(mk,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=wc(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&&(!uk.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 wc(r,e,t,n,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let d={type:"scalar",offset:pk.emptyScalarPosition(e,t,n),indent:-1,source:""},u=yp.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 hk({options:r},{offset:e,source:t,end:n},s){let i=new lk.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=dk.resolveEnd(n,o,r.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}vc.composeEmptyNode=wc;vc.composeNode=bp});var kp=T(Sp=>{"use strict";var gk=pn(),vp=wp(),yk=pr(),bk=yn();function wk(r,e,{offset:t,start:n,value:s,end:i},o){let a=Object.assign({_directives:e},r),c=new gk.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=bk.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?vp.composeNode(l,s,d,o):vp.composeEmptyNode(l,d.end,n,null,d,o);let u=c.contents.range[2],f=yk.resolveEnd(i,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,u,f.offset],c}Sp.composeDoc=wk});var kc=T(Ap=>{"use strict";var vk=cs("process"),Sk=aa(),kk=pn(),bn=gn(),xp=F(),xk=kp(),Ek=pr();function wn(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 Ep(r){let e="",t=!1,n=!1;for(let s=0;s<r.length;++s){let i=r[s];switch(i[0]){case"#":e+=(e===""?"":n?`
|
|
117
117
|
|
|
118
118
|
`:`
|
|
119
|
-
`)+(i.substring(1)||" "),t=!0,n=!1;break;case"%":r[s+1]?.[0]!=="#"&&(s+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var
|
|
120
|
-
${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(
|
|
119
|
+
`)+(i.substring(1)||" "),t=!0,n=!1;break;case"%":r[s+1]?.[0]!=="#"&&(s+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var Sc=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,s,i)=>{let o=wn(t);i?this.warnings.push(new bn.YAMLWarning(o,n,s)):this.errors.push(new bn.YAMLParseError(o,n,s))},this.directives=new Sk.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:s}=Ep(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(xp.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];xp.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n}
|
|
121
121
|
${a}`:n}else{let o=i.commentBefore;i.commentBefore=o?`${n}
|
|
122
|
-
${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
123
|
-
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new
|
|
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:Ep(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(vk.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,n,s)=>{let i=wn(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,s)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=xk.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 bn.YAMLParseError(wn(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 bn.YAMLParseError(wn(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=Ek.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 bn.YAMLParseError(wn(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 kk.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}}};Ap.Composer=Sc});var Op=T(ni=>{"use strict";var Ak=gc(),Tk=bc(),Pk=gn(),Tp=en();function Ok(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 Pk.YAMLParseError([a,a+1],i,o)};switch(r.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Tk.resolveFlowScalar(r,e,n);case"block-scalar":return Ak.resolveBlockScalar({options:{strict:e}},r,n)}}return null}function Ck(r,e){let{implicitKey:t=!1,indent:n,inFlow:s=!1,offset:i=-1,type:o="PLAIN"}=e,a=Tp.stringifyString({type:o,value:r},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:`
|
|
124
124
|
`}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
|
|
125
|
-
`),
|
|
126
|
-
`,
|
|
127
|
-
`}),{type:"block-scalar",offset:i,indent:n,props:
|
|
125
|
+
`),d=a.substring(0,l),u=a.substring(l+1)+`
|
|
126
|
+
`,f=[{type:"block-scalar-header",offset:i,indent:n,source:d}];return Pp(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 _k(r,e,t={}){let{afterKey:n=!1,implicitKey:s=!1,inFlow:i=!1,type:o}=t,a="indent"in r?r.indent:null;if(n&&typeof a=="number"&&(a+=2),!o)switch(r.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=r.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Tp.stringifyString({type:o,value:e},{implicitKey:s||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Rk(r,c);break;case'"':xc(r,c,"double-quoted-scalar");break;case"'":xc(r,c,"single-quoted-scalar");break;default:xc(r,c,"scalar")}}function Rk(r,e){let t=e.indexOf(`
|
|
128
128
|
`),n=e.substring(0,t),s=e.substring(t+1)+`
|
|
129
|
-
`;if(r.type==="block-scalar"){let i=r.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=n,r.source=s}else{let{offset:i}=r,o="indent"in r?r.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:n}];
|
|
130
|
-
`});for(let c of Object.keys(r))c!=="type"&&c!=="offset"&&delete r[c];Object.assign(r,{type:"block-scalar",indent:o,props:a,source:s})}}function
|
|
131
|
-
`};delete r.items,Object.assign(r,{type:t,source:e,end:[s]});break}default:{let n="indent"in r?r.indent:-1,s="end"in r&&Array.isArray(r.end)?r.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(r))i!=="type"&&i!=="offset"&&delete r[i];Object.assign(r,{type:t,indent:n,source:e,end:s})}}}
|
|
129
|
+
`;if(r.type==="block-scalar"){let i=r.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=n,r.source=s}else{let{offset:i}=r,o="indent"in r?r.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:n}];Pp(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 Pp(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 xc(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})}}}ni.createScalarToken=Ck;ni.resolveAsScalar=Ok;ni.setScalarValue=_k});var _p=T(Cp=>{"use strict";var Nk=r=>"type"in r?ii(r):si(r);function ii(r){switch(r.type){case"block-scalar":{let e="";for(let t of r.props)e+=ii(t);return e+r.source}case"block-map":case"block-seq":{let e="";for(let t of r.items)e+=si(t);return e}case"flow-collection":{let e=r.start.source;for(let t of r.items)e+=si(t);for(let t of r.end)e+=t.source;return e}case"document":{let e=si(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 si({start:r,key:e,sep:t,value:n}){let s="";for(let i of r)s+=i.source;if(e&&(s+=ii(e)),t)for(let i of t)s+=i.source;return n&&(s+=ii(n)),s}Cp.stringify=Nk});var $p=T(Ip=>{"use strict";var Ec=Symbol("break visit"),Ik=Symbol("skip children"),Rp=Symbol("remove item");function Mt(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),Np(Object.freeze([]),r,e)}Mt.BREAK=Ec;Mt.SKIP=Ik;Mt.REMOVE=Rp;Mt.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};Mt.parentCollection=(r,e)=>{let t=Mt.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 Np(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=Np(Object.freeze(r.concat([[s,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===Ec)return Ec;a===Rp&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&s==="key"&&(n=n(e,r))}}return typeof n=="function"?n(e,r):n}Ip.visit=Mt});var oi=T(ue=>{"use strict";var Ac=Op(),$k=_p(),Lk=$p(),Tc="\uFEFF",Pc="",Oc="",Cc="",Mk=r=>!!r&&"items"in r,Dk=r=>!!r&&(r.type==="scalar"||r.type==="single-quoted-scalar"||r.type==="double-quoted-scalar"||r.type==="block-scalar");function Bk(r){switch(r){case Tc:return"<BOM>";case Pc:return"<DOC>";case Oc:return"<FLOW_END>";case Cc:return"<SCALAR>";default:return JSON.stringify(r)}}function jk(r){switch(r){case Tc:return"byte-order-mark";case Pc:return"doc-mode";case Oc:return"flow-error-end";case Cc:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
132
132
|
`:case`\r
|
|
133
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(r[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}
|
|
134
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
135
|
-
\r `),
|
|
133
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(r[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}ue.createScalarToken=Ac.createScalarToken;ue.resolveAsScalar=Ac.resolveAsScalar;ue.setScalarValue=Ac.setScalarValue;ue.stringify=$k.stringify;ue.visit=Lk.visit;ue.BOM=Tc;ue.DOCUMENT=Pc;ue.FLOW_END=Oc;ue.SCALAR=Cc;ue.isCollection=Mk;ue.isScalar=Dk;ue.prettyToken=Bk;ue.tokenType=jk});var Nc=T(Mp=>{"use strict";var vn=oi();function Se(r){switch(r){case void 0:case" ":case`
|
|
134
|
+
`:case"\r":case" ":return!0;default:return!1}}var Lp=new Set("0123456789ABCDEFabcdef"),Fk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ai=new Set(",[]{}"),qk=new Set(` ,[]{}
|
|
135
|
+
\r `),_c=r=>!r||qk.has(r),Rc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
|
|
136
136
|
`?!0:t==="\r"?this.buffer[e+1]===`
|
|
137
137
|
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){let s=this.buffer[n+e+1];if(s===`
|
|
138
138
|
`||!s&&!this.atEnd)return e+n+1}return t===`
|
|
139
|
-
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&
|
|
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]===
|
|
139
|
+
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&Se(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]===vn.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 vn.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==="...")&&Se(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&&!Se(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===":")&&Se(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(_c),"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("..."))&&Se(s[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield vn.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(_c),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Se(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let i=0;for(;this.buffer[t-1-i]==="\\";)i+=1;if(i%2===0)break;t=this.buffer.indexOf('"',t+1)}let n=this.buffer.substring(0,t),s=n.indexOf(`
|
|
141
141
|
`,this.pos);if(s!==-1){for(;s!==-1;){let i=this.continueScalar(s+1);if(i===-1)break;s=n.indexOf(`
|
|
142
|
-
`,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=>Se(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let i=this.pos;n=this.buffer[i];++i)switch(n){case" ":t+=1;break;case`
|
|
143
143
|
`:e=i,t=0;break;case"\r":{let o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
144
144
|
`)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let i=this.continueScalar(e+1);if(i===-1)break;e=this.buffer.indexOf(`
|
|
145
145
|
`,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let s=e+1;for(n=this.buffer[s];n===" ";)n=this.buffer[++s];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
|
|
146
146
|
`;)n=this.buffer[++s];e=s-1}else if(!this.blockScalarKeep)do{let i=e-1,o=this.buffer[i];o==="\r"&&(o=this.buffer[--i]);let a=i;for(;o===" ";)o=this.buffer[--i];if(o===`
|
|
147
|
-
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield
|
|
147
|
+
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield vn.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(Se(i)||e&&ai.has(i))break;t=n}else if(Se(s)){let i=this.buffer[n+1];if(s==="\r"&&(i===`
|
|
148
148
|
`?(n+=1,s=`
|
|
149
|
-
`,i=this.buffer[n+1]):t=n),i==="#"||e&&
|
|
150
|
-
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&
|
|
149
|
+
`,i=this.buffer[n+1]):t=n),i==="#"||e&&ai.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&&ai.has(s))break;t=n}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield vn.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(_c))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(Se(t)||e&&ai.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(;!Se(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(Fk.has(t))t=this.buffer[++e];else if(t==="%"&&Lp.has(this.buffer[e+1])&&Lp.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
151
151
|
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
152
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");let s=t-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=t),s}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};
|
|
152
|
+
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");let s=t-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=t),s}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};Mp.Lexer=Rc});var $c=T(Dp=>{"use strict";var Ic=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let i=t+n>>1;this.lineStarts[i]<e?t=i+1:n=i}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let s=this.lineStarts[t-1];return{line:t,col:e-s+1}}}};Dp.LineCounter=Ic});var Mc=T(Up=>{"use strict";var Uk=cs("process"),Bp=oi(),Jk=Nc();function ft(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function jp(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 qp(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 ci(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 mr(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 Fp(r){if(r.start.type==="flow-seq-start")for(let e of r.items)e.sep&&!e.value&&!ft(e.start,"explicit-key-ind")&&!ft(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,qp(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 Lc=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 Jk.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,Uk.env.LOG_TOKENS&&console.log("|",Bp.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Bp.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"&&Fp(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&&jp(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":{jp(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=ci(this.peek(2)),n=mr(t),s;e.end?(s=e.end,s.push(this.sourceToken),delete e.end):s=[this.sourceToken];let i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
|
|
153
153
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
154
|
-
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,s=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&t.sep&&!t.value){let o=[];for(let a=0;a<t.sep.length;++a){let c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(
|
|
154
|
+
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,s=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&t.sep&&!t.value){let o=[];for(let a=0;a<t.sep.length;++a){let c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ft(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(qp(t.key)&&!ft(t.sep,"newline")){let o=mr(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(ft(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=mr(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]}):ft(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&&!ft(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||ft(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=ci(n),i=mr(s);Fp(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
|
155
155
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
156
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=
|
|
157
|
-
`),t=e.trim();if(
|
|
156
|
+
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=ci(e),n=mr(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=ci(e),n=mr(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())}}};Up.Parser=Lc});var Yp=T(kn=>{"use strict";var Jp=kc(),Kk=pn(),Sn=gn(),Hk=va(),Wk=F(),Yk=$c(),Kp=Mc();function Hp(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new Yk.LineCounter||null,prettyErrors:e}}function Vk(r,e={}){let{lineCounter:t,prettyErrors:n}=Hp(e),s=new Kp.Parser(t?.addNewLine),i=new Jp.Composer(e),o=Array.from(i.compose(s.parse(r)));if(n&&t)for(let a of o)a.errors.forEach(Sn.prettifyError(r,t)),a.warnings.forEach(Sn.prettifyError(r,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Wp(r,e={}){let{lineCounter:t,prettyErrors:n}=Hp(e),s=new Kp.Parser(t?.addNewLine),i=new Jp.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 Sn.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Sn.prettifyError(r,t)),o.warnings.forEach(Sn.prettifyError(r,t))),o}function Gk(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=Wp(r,t);if(!s)return null;if(s.warnings.forEach(i=>Hk.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 zk(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 Wk.isDocument(r)&&!n?r.toString(t):new Kk.Document(r,n,t).toString(t)}kn.parse=Gk;kn.parseAllDocuments=Vk;kn.parseDocument=Wp;kn.stringify=zk});var Gp=T(q=>{"use strict";var Xk=kc(),Qk=pn(),Zk=rc(),Dc=gn(),ex=Gr(),dt=F(),tx=at(),rx=X(),nx=lt(),sx=ut(),ix=oi(),ox=Nc(),ax=$c(),cx=Mc(),li=Yp(),Vp=Hr();q.Composer=Xk.Composer;q.Document=Qk.Document;q.Schema=Zk.Schema;q.YAMLError=Dc.YAMLError;q.YAMLParseError=Dc.YAMLParseError;q.YAMLWarning=Dc.YAMLWarning;q.Alias=ex.Alias;q.isAlias=dt.isAlias;q.isCollection=dt.isCollection;q.isDocument=dt.isDocument;q.isMap=dt.isMap;q.isNode=dt.isNode;q.isPair=dt.isPair;q.isScalar=dt.isScalar;q.isSeq=dt.isSeq;q.Pair=tx.Pair;q.Scalar=rx.Scalar;q.YAMLMap=nx.YAMLMap;q.YAMLSeq=sx.YAMLSeq;q.CST=ix;q.Lexer=ox.Lexer;q.LineCounter=ax.LineCounter;q.Parser=cx.Parser;q.parse=li.parse;q.parseAllDocuments=li.parseAllDocuments;q.parseDocument=li.parseDocument;q.stringify=li.stringify;q.visit=Vp.visit;q.visitAsync=Vp.visitAsync});function ux(r){try{return JSON.parse(r.trim()),!0}catch{return!1}}function fx(r){let e=r.trim();if(!e.startsWith("<"))return!1;let t=e.match(lx);return t?Kr(e,t[1])!==null:!1}function dx(r){let e=r.trim();if(!e.match(/^(---|#|\w+:|-)/)||"[{<".includes(e[0]))return!1;try{let t=zp.parse(e);return t!==null&&typeof t=="object"}catch{return!1}}function Xp(r){return ux(r)||fx(r)||dx(r)}var zp,lx,Bc=S(()=>{af();zp=vb(Gp(),1),lx=/<([a-zA-Z_][\w.-]*)/});function px(r){if(!r?.trim())return[];let e=r.replace(/\r\n/g,`
|
|
157
|
+
`),t=e.trim();if(Xp(t))return[{text:t,startLine:1,endLine:e.split(`
|
|
158
158
|
`).length}];let n=e.split(`
|
|
159
159
|
`),s=[],i=0,o=-1,a=0,c=()=>{if(o>=i){let l=n.slice(i,o+1).join(`
|
|
160
|
-
`).trim();l&&s.push({text:l,startLine:i+1,endLine:o+1})}};for(let l=0;l<n.length;l++)n[l].trim()?(a>=2&&o>=i&&(c(),i=l),a=0,o=l):a++;return c(),s}function
|
|
160
|
+
`).trim();l&&s.push({text:l,startLine:i+1,endLine:o+1})}};for(let l=0;l<n.length;l++)n[l].trim()?(a>=2&&o>=i&&(c(),i=l),a=0,o=l):a++;return c(),s}function ui(r){return px(r).map(e=>e.text)}var Qp,Zp=S(()=>{Bc();Qp=`
|
|
161
161
|
|
|
162
162
|
|
|
163
|
-
`});var
|
|
164
|
-
`).length-1}));return n}function
|
|
165
|
-
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;for(let l of
|
|
166
|
-
`)).filter(({root:n})=>!t.has(n)).map(({root:n,lineIndex:s})=>({type:"UNDECLARED_IMPORT",severity:"error",message:
|
|
163
|
+
`});var Re=S(()=>{us();Xo();Qu();Zu();Bc();Zp();fs()});function hr(r){return{...Vu(r),server:r.files.get("server.ts")??""}}function fi(r){return!!r.server&&!r.code}var xn=S(()=>{Re();Re()});import{transform as mx}from"sucrase";function jc(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=mx(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}var em=S(()=>{});function yx(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 tm(r){let e=[];for(let s of gx)for(let i of r.matchAll(s)){let o=yx(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 rm(r){return tm(r).map(e=>e.root)}function En(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 hx)l.targets.includes(t)&&l.pattern.test(a)&&s.push({type:l.type,severity:"error",message:vx(l.type,c),lineNumber:c,lineContent:a})}return t==="client"&&n&&s.push(...bx(i,n)),s}function bx(r,e){let t=new Set(Object.keys(e));return tm(r.join(`
|
|
166
|
+
`)).filter(({root:n})=>!t.has(n)).map(({root:n,lineIndex:s})=>({type:"UNDECLARED_IMPORT",severity:"error",message:wx(n,s+1),lineNumber:s+1,lineContent:r[s]}))}function wx(r,e){return`Import "${r}" is not declared in config.json dependencies! Found on line ${e}.
|
|
167
167
|
|
|
168
168
|
**CRITICAL**: Every bare import in code.tsx must be declared in the **config.json** "dependencies" block. A bulb that imports a package it doesn't declare is incomplete \u2014 it won't type-check, its versions aren't pinned, and it can't be reliably re-run or ported to typebulb.com.
|
|
169
169
|
|
|
@@ -177,7 +177,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
177
177
|
}
|
|
178
178
|
\`\`\`
|
|
179
179
|
|
|
180
|
-
**Fix:** Add a **config.json** block (or extend the existing one) with a "dependencies" entry for "${r}" \u2014 and for every other bare import in code.tsx. Pin a real version where you can (e.g. "react": "^19.2.7").`}function
|
|
180
|
+
**Fix:** Add a **config.json** block (or extend the existing one) with a "dependencies" entry for "${r}" \u2014 and for every other bare import in code.tsx. Pin a real version where you can (e.g. "react": "^19.2.7").`}function vx(r,e){return r==="URL_IMPORT"?`Direct URL imports are not supported! Found on line ${e}.
|
|
181
181
|
|
|
182
182
|
**CRITICAL**: Import packages by name only. Do NOT use CDN URLs:
|
|
183
183
|
|
|
@@ -331,907 +331,507 @@ import { something } from 'module-name'
|
|
|
331
331
|
const something = require('module-name') // NOT SUPPORTED!
|
|
332
332
|
\`\`\`
|
|
333
333
|
|
|
334
|
-
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var
|
|
335
|
-
|
|
336
|
-
`)
|
|
337
|
-
`)),!t&&s.type==="message"&&s.content&&(t=s.content.filter(i=>i.type==="output_text").map(i=>i.text).join(""));return{text:t,reasoning:n}}parseProviderStreamChunk(e){if(!this.isResponsesApiEvent(e))return null;switch(e.type){case"response.failed":{let n=e.response?.error,s=n?.message||"Response failed",i=n?.code==="insufficient_quota"||n?.code==="rate_limit_exceeded";throw new de(s,i?"rate_limit":"unknown",i)}case"response.output_text.delta":return{text:e.delta};case"response.reasoning_summary_text.delta":return{reasoning:e.delta};default:return null}}convertMessagesToInput(e){return e.map(t=>t.role==="system"?`System: ${t.content}`:t.role==="user"?`User: ${t.content}`:t.role==="assistant"?`Assistant: ${t.content}`:t.content).join(`
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
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(`
|
|
334
|
+
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var Dt,Bt,hx,gx,di=S(()=>{Dt=["client"],Bt=["client","server"],hx=[{type:"DYNAMIC_IMPORT",pattern:/\bimport\s*\(\s*['"`]/,targets:Dt},{type:"COMMONJS_REQUIRE",pattern:/\brequire\s*\(\s*['"`]/,targets:Bt},{type:"JS_EXTENSION_IMPORT",pattern:/from\s+['"][^'"]*\/[^'"]*\.js['"]/,targets:Dt},{type:"URL_IMPORT",pattern:/from\s+['"]https?:\/\//,targets:Dt},{type:"VERSION_SPECIFIER_IMPORT",pattern:/from\s+['"][^'"]*@[\d^~]/,targets:Dt},{type:"REDUNDANT_TB_DECLARATION",pattern:/declare\s+(const|var|let)\s+tb\b/,targets:Bt},{type:"CONST_ENUM",pattern:/\bconst\s+enum\b/,targets:Bt},{type:"NAMESPACE_DECLARATION",pattern:/\bnamespace\s+\w+/,targets:Bt},{type:"COMMONJS_EXPORT_EQUALS",pattern:/\bexport\s*=/,targets:Bt},{type:"COMMONJS_IMPORT_EQUALS",pattern:/\bimport\s+\w+\s*=/,targets:Bt},{type:"MODULE_DECLARATION",pattern:/\bmodule\s+\w+\s*\{/,targets:Bt},{type:"CSS_FILE_IMPORT",pattern:/(?:from|import)\s+['"][^'"]*\.css['"]/,targets:Dt},{type:"NAVIGATION",pattern:/window\.(location\.(reload|assign|replace)\s*\(|open\s*\()/,targets:Dt},{type:"NAVIGATION",pattern:/window\.location(\.href)?\s*=[^=]/,targets:Dt}],gx=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});function Sx(r){return r.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
|
|
335
|
+
`)[0]}`).join(`
|
|
336
|
+
`)}function nm(r,e){let t=En(r,{target:"client",dependencies:e}).filter(n=>n.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
337
|
+
${Sx(t)}`)}var sm=S(()=>{di()});var pt,An,Fc,Tn=S(()=>{pt="https://esm.sh",An="https://cdn.jsdelivr.net/npm/",Fc="https://data.jsdelivr.com/v1/package/npm/"});function im(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var B,gr,om,Pn=S(()=>{Tn();B=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=gr(t??s.version),this.subpath=gr(n??s.subpath)}static parse(e){let t=im(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=om(t[1]??""),a=gr(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=om(t[0]),o=gr(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(pt).host,s=new URL(An).host;if(t.host===n){let i=im(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:gr(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://")}},gr=r=>r&&r.length?r:void 0,om=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),gr(r.slice(e+1))]}});async function fe(r){try{return await r()}catch{return}}var pi=S(()=>{});function jt(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function qc(r){return r.startsWith("./")?r:`./${r}`}var On,Uc=S(()=>{Pn();pi();Tn();On=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 B(e):e;return`${An}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(jt(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(",")),`${pt}/${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),`${pt}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await fe(()=>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 fe(()=>this.http.getJson(`${Fc}${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=B.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 B(`${e}@${t}`)),i=await fe(()=>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 am,Cn,Jc,kx,_n,mi=S(()=>{am=r=>r.startsWith("@types/"),Cn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!am(e)),Jc=r=>Object.keys(r?.dependencies||{}).filter(e=>!am(e)),kx=r=>Cn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),_n=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 kx(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=>Cn(i.meta))),n=new Map;for(let i of e)for(let o of Jc(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:Cn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}}});var Rn,Kc=S(()=>{Pn();pi();Rn=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await fe(()=>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 fe(()=>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 fe(()=>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 B(e),s=n.root(),i=t[s],o=i?await fe(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}}});import{init as xx,parse as Ex}from"es-module-lexer";var yr,Hc=S(()=>{Pn();Tn();mi();yr=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))B.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{B.isBare(s)&&t.add(s)};try{await xx;let[s]=Ex(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(B.rootOf(u))),i=[...new Set(s.map(B.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(B.rootOf(p));return new B(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!==B.rootOf(p)).map(B.rootOf)),c=[],l=new Set,d=new Set(e.filter(p=>p===B.rootOf(p))),u=new Set;for(let p of e){let b=B.rootOf(p),m=s.get(b),{isPeerRoot:g,hasPeers:x,isSharedDep:A}=n.get(b),P=a.has(b),R=p!==b,O=!(g||A)&&(P||!x),$=this.singletonDepsOf(m,o),E=R&&d.has(b);E&&u.add(b);let y=E?[...$,b]:$.length?$:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:O,external:y})]),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}/`,`${pt}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...Cn(e.meta),...Jc(e.meta)])].filter(n=>t.has(n))}};yr.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});import{gt as cm,satisfies as Ax,maxSatisfying as lm,major as Tx,valid as Px}from"semver";var hi,Ft,Wc=S(()=>{hi=class{cmp(e,t){return e===t?0:cm(e,t)?1:cm(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Ax(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=lm(e,n,{includePrerelease:!1});if(a)return a}return lm(e,n,{includePrerelease:!0})??void 0}majorOf(e){return Tx(e)}isExactVersion(e){return Px(e)!==null}},Ft=new hi});function Ox(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}var qt,um=S(()=>{pi();qt=class{constructor(e){this.store=e}async isNegative(e){let t=await fe(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await fe(()=>this.store.get(e)))?.attempts||0)+1;await fe(()=>this.store.set(e,{until:Date.now()+Ox(n),attempts:n}))}async clearNegative(e){await fe(()=>this.store.delete(e))}}});function fm(r,e){let t=new On(r,e),n=new _n(t),s=new Rn(r,t,Ft);return{packageService:new yr(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}var Ke=S(()=>{Uc();mi();Kc();Hc();Wc();Pn();Wc();Tn();Uc();mi();Kc();Hc();um()});import*as Yc from"fs/promises";import*as dm from"crypto";function ke(r){return dm.createHash("sha1").update(r).digest("hex")}async function He(r){try{return JSON.parse(await Yc.readFile(r,"utf8"))}catch{return}}async function gi(r){try{return await Yc.readFile(r,"utf8")}catch{return}}var br=S(()=>{});import*as ht from"fs/promises";import*as We from"path";import*as mm from"os";function G(){return Vc||(Vc=_x()),Vc}function bi(r,e){return We.join(Cx,ke(r),e)}async function _x(){await ht.mkdir(mt,{recursive:!0});let r=We.join(mt,"version.json");if((await He(r))?.version===pm)return;let t=await ht.readdir(mt).catch(()=>[]);await Promise.all(t.map(n=>ht.rm(We.join(mt,n),{recursive:!0,force:!0}))),await ht.writeFile(r,JSON.stringify({version:pm})+`
|
|
338
|
+
`,"utf8")}var pm,mt,Nn,In,yi,Cx,Vc,wr=S(()=>{br();pm=1,mt=We.join(mm.homedir(),".typebulb","cache"),Nn=We.join(mt,"packages"),In=We.join(mt,"proxy"),yi=We.join(mt,"dts"),Cx=We.join(mt,"emit")});import*as gt from"fs/promises";import*as hm from"path";async function he(r,e){await gt.mkdir(hm.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await gt.writeFile(t,e,"utf8"),await gt.rename(t,r).catch(async n=>{throw await gt.rm(t,{force:!0}).catch(()=>{}),n})}var $n=S(()=>{});var vr,Gc=S(()=>{$n();br();vr=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=He(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 he(this.filePath,JSON.stringify(Object.fromEntries(e)))}}});import*as bm from"fs/promises";import*as xe from"path";function ym(r,e){return xe.join(Rx,wi(r),encodeURIComponent(e)+".json")}function wi(r){return r.replace(/\//g,"__")}var zc,gm,Rx,Nx,vi,wm=S(()=>{Ke();wr();$n();Gc();br();zc=xe.join(Nn,"indexes"),gm=xe.join(Nn,"pinned"),Rx=xe.join(Nn,"meta"),Nx=xe.join(Nn,"negative.json"),vi=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new qt(new vr(Nx));async getPinnedExact(e,t){let n=`${e}@${t}`;if(this.pinnedMem.has(n))return this.pinnedMem.get(n);await G();let s=await gi(xe.join(gm,ke(n)+".txt"));return this.pinnedMem.set(n,s),s}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await G(),await he(xe.join(gm,ke(s)+".txt"),n)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await G();let t=await He(xe.join(zc,wi(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 G(),await he(xe.join(zc,wi(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await bm.rm(xe.join(zc,wi(e)+".json"),{force:!0})}async isNegative(e){return await G(),this.negativeCache.isNegative(e)}async recordNegative(e){await G(),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 G();let s=await He(ym(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 G(),await he(ym(e,t),JSON.stringify(o))}}});var vm,Sm=S(()=>{vm={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 Ix,Si,km,xm,OR,Xc=S(()=>{Ke();wm();Sm();Ix=new vi,{packageService:Si,versionResolver:km,cdnClient:xm,peerResolver:OR}=fm(Ix,vm)});var Em,Am=S(()=>{Em=`
|
|
339
|
+
(() => {
|
|
340
|
+
// Embedded (bulb-in-a-bulb): runs inside a sandboxed iframe with no parent
|
|
341
|
+
// bridge, so privileged tb.* (AI, fs, server RPC) can't reach a host and would
|
|
342
|
+
// otherwise fail with cryptic CORS/CSP errors. Detect it and fail clearly.
|
|
343
|
+
//
|
|
344
|
+
// The host injects window.__TB_EMBED_ERR__ to override the text; absent it, the
|
|
345
|
+
// nested-bulb wording applies. (The CLI's untrusted launch is NOT this path \u2014 it's
|
|
346
|
+
// a top-level page, and its \`--trust\` message comes from the server 403.)
|
|
347
|
+
const isEmbedded = window.parent !== window;
|
|
348
|
+
const embedErr = (name) => new Error(
|
|
349
|
+
typeof window.__TB_EMBED_ERR__ === 'function'
|
|
350
|
+
? window.__TB_EMBED_ERR__(name)
|
|
351
|
+
: name + ' is not available in an embedded bulb (no host bridge).'
|
|
352
|
+
);
|
|
365
353
|
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
`),n=[];if(t.forEach((o,a)=>{let c=w0(o);c!==void 0&&n.push({id:c,idx:a})}),!n.length)return e==="latest"?r:"";let s=e==="latest"?n[n.length-1]:n.find(o=>o.id===e);if(!s)return"";let i=n.find(o=>o.idx>s.idx);return t.slice(s.idx,i?i.idx:t.length).join(`
|
|
376
|
-
`)}function ul(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function Tm(r){await h0(Ve(),{recursive:!0}),await Sm(ol(r.pid),JSON.stringify(r))}async function Pm(r,e){let t=ol(r);try{let n=JSON.parse(await vm(t,"utf8"));if(n.denied===e)return;n.denied=e,await Sm(t,JSON.stringify(n))}catch{}}async function In(r){await sl(ol(r)).catch(()=>{}),await sl($n(r)).catch(()=>{}),await sl(al(r)).catch(()=>{})}async function z(r){let e;try{e=await m0(Ve())}catch{return[]}let t=[];return await Promise.all(e.map(async s=>{if(!/^\d+\.json$/.test(s))return;let i=parseInt(s,10),o;try{o=JSON.parse(await vm(he.join(Ve(),s),"utf8"))}catch{await In(i);return}o&&typeof o.pid=="number"&&ul(o.pid)?t.push(o):await In(i)})),(r?t.filter(s=>s.agent==null&&fm(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function dl(r,e){let t=re(r);return(await z()).find(n=>n.cwd!=null&&re(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function Ft(r){try{process.kill(r,"SIGTERM")}catch{}await In(r)}function xr(r,e){let t=re(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&re(n.file)===t)}async function fl(r){let e=xr(await z(),r);for(let t of e)await Ft(t.pid);return e}function S0(r,e,t){(process.platform==="win32"?bm("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):bm(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function Om(){return he.join(he.dirname(y0(import.meta.url)),"index.js")}function x0(r,e={}){return{command:process.execPath,args:[Om(),...e.trust?["--trust"]:[],...e.dir?["--dir",e.dir]:[],...e.mode?["--mode",e.mode]:[],r,...e.open===!1?["--no-open"]:[]]}}function k0(r){return{command:process.execPath,args:[Om(),`agent:${r}`,"--no-open"]}}async function _m(r,e,t,n){let s=await r();if(s)return s;S0(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await v0(150);let o=await r();if(o)return o}throw new Error(`Launched ${n} but it did not register within 20s.`)}async function Li(r,e={}){let t=e.cwd??process.cwd(),n=he.resolve(t,r),[s]=await fl(n),i={...e,dir:e.dir??s?.dir,mode:e.mode??s?.mode};return _m(async()=>xr(await z(),n)[0],x0(r,i),t,he.basename(r))}async function Cm(r,e=process.cwd()){return _m(()=>dl(e,r),k0(r),e,`the ${r} mirror`)}var wm,b0,v0,Ne=A(()=>{Ti();wm=1e6;b0=/^── run (\d+) ── /;v0=r=>new Promise(e=>setTimeout(e,r))});function Mi(r){let e=/^---[^\n]*\n([\s\S]*?)\n---/.exec(r),t=e?/^\s*name:\s*(.+?)\s*$/m.exec(e[1]):null;return t?t[1].replace(/^["']|["']$/g,""):void 0}function pl(r){return(Mi(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var ml=A(()=>{});import{readdirSync as E0,readFileSync as A0,statSync as T0}from"fs";import{join as Rm,basename as P0}from"path";function Nm(r,e,t){if(e>8)return t;let n;try{n=E0(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;Nm(Rm(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(Rm(r,s.name));return t}function Di(r){return Nm(r,0,[]).map(e=>{let t=0;try{t=T0(e).mtimeMs}catch{}let n,s=!1;try{let i=A0(e,"utf8");n=Mi(i.slice(0,1024));let o=fe(i);s=!!o&&Xs(cr(o))}catch{}return{path:e,name:n??P0(e).replace(/\.bulb\.md$/,""),mtime:t,serverOnly:s}})}var Im=A(()=>{Ue();gn();ml()});function kr(r){if(r.server.trim())return"server-side code (server.ts)";let e=r.code;if(/\btb\s*\.\s*fs\b/.test(e)||e.includes("/__fs"))return"the filesystem";if(/\btb\s*\.\s*ai\b/.test(e)||e.includes("/__ai")||r.infer.trim()||/\btb\s*\.\s*infer\b/.test(e))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s*(?!log\b)\w/.test(e)||e.includes("/__api"))return"server-side code (server.ts)"}var Bi=A(()=>{});import{readFile as O0}from"fs/promises";async function hl(r){try{let e=fe(await O0(r,"utf-8"));return e?kr(cr(e)):void 0}catch{return}}var $m=A(()=>{gn();Bi()});function gl(r){let e=fe(r);if(!e)return r;let t=e.files.get("code.tsx");if(!t)return r;let n=Np(t);if(!n.length)return r;let s=e.files.get("config.json"),i={};if(s)try{let l=JSON.parse(s);l&&typeof l=="object"&&(i=l)}catch{}let o=i.dependencies&&typeof i.dependencies=="object"?{...i.dependencies}:{},a=n.filter(l=>!(l in o));if(!a.length)return r;for(let l of a)o[l]="latest";i.dependencies=o;let c={name:e.frontmatter.name};for(let[l,f]of e.files){let u=vu(l);u&&(c[u]=f)}return c.config=JSON.stringify(i,null,2),Ou(c)}var Lm=A(()=>{Ue();Qs()});import{spawn as Mm}from"child_process";import{basename as _0}from"path";function C0(){return process.env.TYPEBULB_EDITOR||"code"}function N0(r,e,t){return t==null?[e]:R0.test(_0(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function I0(r,e){let t=C0();return{command:t,args:N0(t,r,e)}}function yl(r,e){let{command:t,args:n}=I0(r,e),s=process.platform==="win32"?Mm("cmd.exe",["/d","/s","/c",t,...n],{detached:!0,stdio:"ignore",windowsHide:!0}):Mm(t,n,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var R0,Dm=A(()=>{R0=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as $0,existsSync as L0}from"fs";import*as qt from"path";import{fileURLToPath as M0}from"url";function Bm(){let r=qt.dirname(M0(import.meta.url));for(;!L0(qt.join(r,"package.json"));){let e=qt.dirname(r);if(e===r)break;r=e}return r}function Ut(){return qt.join(Bm(),"README.md")}function Er(){return qt.join(Bm(),"description.md")}function D0(r){let e=$0(Er(),"utf8").trim().replace(/\s+/g," ");return`---
|
|
377
|
-
name: typebulb
|
|
378
|
-
description: ${JSON.stringify(e)}
|
|
379
|
-
version: ${r}
|
|
380
|
-
---`}function B0(r){return`> Generated from typebulb v${r}. If \`npx typebulb --version\` reports a newer version, re-run \`npx typebulb skill\` to refresh this file.`}function jm(r,e){return`${D0(e)}
|
|
354
|
+
// JSON parser (handles jsonish - unquoted keys)
|
|
355
|
+
const parseJson = (str) => {
|
|
356
|
+
try {
|
|
357
|
+
return JSON.parse(str);
|
|
358
|
+
} catch {
|
|
359
|
+
const fixed = str.replace(/(?<!")(\\b[a-zA-Z_][a-zA-Z0-9_]*\\b)\\s*:/g, '"$1":');
|
|
360
|
+
return JSON.parse(fixed);
|
|
361
|
+
}
|
|
362
|
+
};
|
|
381
363
|
|
|
382
|
-
|
|
364
|
+
// Read from window each time so updates are visible
|
|
365
|
+
const getData = () => window.__TB_DATA__ || [];
|
|
383
366
|
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
367
|
+
// #tb= fragment restore (TB-Inference.md "Sharing a local run"): a refreshed or pasted share
|
|
368
|
+
// URL re-injects its run before the bulb code reads tb.insight()/tb.data() \u2014 the template's
|
|
369
|
+
// module script awaits __tbBoot, so the async decode still lands ahead of synchronous startup
|
|
370
|
+
// reads. Decode failure falls through to the file's own blocks with a console note.
|
|
371
|
+
if (!isEmbedded && location.protocol.indexOf('http') === 0 && location.hash.indexOf('#tb=') === 0) {
|
|
372
|
+
globalThis.__tbBoot = fetch('/__infer-decode', {
|
|
373
|
+
method: 'POST',
|
|
374
|
+
headers: { 'Content-Type': 'application/json' },
|
|
375
|
+
body: JSON.stringify({ hash: location.hash })
|
|
376
|
+
})
|
|
377
|
+
.then((r) => r.json())
|
|
378
|
+
.then((res) => {
|
|
379
|
+
if (res && Array.isArray(res.data)) {
|
|
380
|
+
window.__TB_INSIGHT__ = res.insightJson;
|
|
381
|
+
window.__TB_DATA__ = res.data;
|
|
382
|
+
} else {
|
|
383
|
+
console.warn('[typebulb] The #tb= fragment could not be decoded (incomplete or corrupted link) \u2014 using the bulb file state.');
|
|
384
|
+
}
|
|
385
|
+
})
|
|
386
|
+
.catch(() => {});
|
|
387
|
+
}
|
|
397
388
|
|
|
398
|
-
|
|
389
|
+
// tb.onMessage subscribers, fed by the events-SSE 'message' channel (typebulb send). A message is
|
|
390
|
+
// JSON-or-string: parse as JSON, else hand back the raw string; '' (a bare \`send\`) \u21D2 undefined.
|
|
391
|
+
const messageHandlers = new Set();
|
|
392
|
+
const parseMsg = (s) => { if (s === '' || s == null) return undefined; try { return JSON.parse(s); } catch { return s; } };
|
|
399
393
|
|
|
400
|
-
//
|
|
401
|
-
|
|
394
|
+
// The trust gate denies privileged routes with a plain-text 403 naming --trust;
|
|
395
|
+
// surface that as-is rather than a JSON-parse miss on a non-JSON body.
|
|
396
|
+
const deny403 = async (resp, what) => {
|
|
397
|
+
if (resp.status === 403) throw new Error((await resp.text().catch(() => '')) || (what + ' is blocked \u2014 re-run with --trust'));
|
|
398
|
+
};
|
|
402
399
|
|
|
403
|
-
//
|
|
404
|
-
//
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
400
|
+
// Filesystem API - calls back to the local server.
|
|
401
|
+
// The server returns raw bytes (no JSON envelope); read() decodes as UTF-8.
|
|
402
|
+
const failIfNotOk = async (resp, action, path) => {
|
|
403
|
+
if (resp.ok) return;
|
|
404
|
+
await deny403(resp, 'tb.fs');
|
|
405
|
+
const err = await resp.json().catch(() => ({}));
|
|
406
|
+
throw new Error(err.error || 'Failed to ' + action + ' file: ' + path);
|
|
407
|
+
};
|
|
408
|
+
const fetchFileBytes = async (path) => {
|
|
409
|
+
if (isEmbedded) throw embedErr('tb.fs');
|
|
410
|
+
const resp = await fetch('/__fs/read', {
|
|
411
|
+
method: 'POST',
|
|
412
|
+
headers: { 'Content-Type': 'application/json' },
|
|
413
|
+
body: JSON.stringify({ path })
|
|
414
|
+
});
|
|
415
|
+
await failIfNotOk(resp, 'read', path);
|
|
416
|
+
return resp.arrayBuffer();
|
|
417
|
+
};
|
|
418
|
+
const fs = {
|
|
419
|
+
read: async (path) => {
|
|
420
|
+
const buf = await fetchFileBytes(path);
|
|
421
|
+
try {
|
|
422
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(buf);
|
|
423
|
+
} catch {
|
|
424
|
+
throw new Error('File is not valid UTF-8 text: ' + path + ' \u2014 use tb.fs.readBytes() for binary files.');
|
|
425
|
+
}
|
|
426
|
+
},
|
|
427
|
+
readBytes: async (path) => new Uint8Array(await fetchFileBytes(path)),
|
|
428
|
+
write: async (path, content) => {
|
|
429
|
+
if (isEmbedded) throw embedErr('tb.fs');
|
|
430
|
+
const resp = await fetch('/__fs/write?path=' + encodeURIComponent(path), {
|
|
431
|
+
method: 'POST',
|
|
432
|
+
body: content
|
|
433
|
+
});
|
|
434
|
+
await failIfNotOk(resp, 'write', path);
|
|
435
|
+
return true;
|
|
414
436
|
}
|
|
415
|
-
|
|
416
|
-
} catch (e) { return null; }
|
|
417
|
-
}
|
|
437
|
+
};
|
|
418
438
|
|
|
419
|
-
//
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
439
|
+
// Clipboard helper
|
|
440
|
+
const copy = async (text) => {
|
|
441
|
+
try {
|
|
442
|
+
await navigator.clipboard.writeText(String(text));
|
|
443
|
+
return true;
|
|
444
|
+
} catch {
|
|
445
|
+
return false;
|
|
446
|
+
}
|
|
447
|
+
};
|
|
423
448
|
|
|
424
|
-
//
|
|
425
|
-
//
|
|
426
|
-
//
|
|
427
|
-
//
|
|
428
|
-
//
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
" • or, open its parts:",
|
|
441
|
-
" " + TB_DESCRIPTION_PATH,
|
|
442
|
-
" " + TB_README_PATH,
|
|
443
|
-
].join("\n");
|
|
449
|
+
// Diagnostic logging (tb.server.log). Routes to the UNGATED /__log endpoint, which only ever
|
|
450
|
+
// runs the server's built-in console.log \u2014 never a user server.ts export \u2014 so it crosses no
|
|
451
|
+
// capability boundary and works even on a Restricted (untrusted) bulb (the FAQ's recommended
|
|
452
|
+
// debugging path). Embedded bulbs have no host, and any transport failure degrades to the page's
|
|
453
|
+
// own console: a diagnostic log must never throw or block.
|
|
454
|
+
const serverLog = async (...args) => {
|
|
455
|
+
if (isEmbedded) { console.log(...args); return; }
|
|
456
|
+
try {
|
|
457
|
+
const resp = await fetch('/__log', {
|
|
458
|
+
method: 'POST',
|
|
459
|
+
headers: { 'Content-Type': 'application/json' },
|
|
460
|
+
body: JSON.stringify({ args })
|
|
461
|
+
});
|
|
462
|
+
if (!resp.ok) console.log(...args);
|
|
463
|
+
} catch { console.log(...args); }
|
|
464
|
+
};
|
|
444
465
|
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
466
|
+
// Streaming. The server tunnels an async iterable as enveloped NDJSON over
|
|
467
|
+
// the bridge POST; isStreamResp flags it via a response header so a normal single-return call is
|
|
468
|
+
// untouched. readStream yields each {type:'chunk'} value; a {type:'error'} line rejects the
|
|
469
|
+
// iterator (so try/catch around for-await fires); breaking the loop cancels the body (finally),
|
|
470
|
+
// which disconnects the server and tears down the source generator \u2014 that's how Stop/unmount
|
|
471
|
+
// actually aborts the upstream rather than just hiding it.
|
|
472
|
+
const isStreamResp = (resp) => resp.headers.get('X-TB-Stream') === '1';
|
|
473
|
+
async function* readStream(resp) {
|
|
474
|
+
const reader = resp.body.getReader();
|
|
475
|
+
const dec = new TextDecoder();
|
|
476
|
+
let buf = '';
|
|
477
|
+
const decodeLine = (line) => {
|
|
478
|
+
if (!line.trim()) return undefined;
|
|
479
|
+
const env = JSON.parse(line);
|
|
480
|
+
if (env.type === 'error') {
|
|
481
|
+
const e = new Error((env.error && env.error.message) || 'stream error');
|
|
482
|
+
e.code = env.error && env.error.code;
|
|
483
|
+
e.retryable = !!(env.error && env.error.retryable);
|
|
484
|
+
throw e;
|
|
485
|
+
}
|
|
486
|
+
return env.type === 'chunk' ? { value: env.value } : undefined;
|
|
487
|
+
};
|
|
488
|
+
try {
|
|
489
|
+
while (true) {
|
|
490
|
+
const { done, value } = await reader.read();
|
|
491
|
+
if (done) break;
|
|
492
|
+
buf += dec.decode(value, { stream: true });
|
|
493
|
+
let nl;
|
|
494
|
+
while ((nl = buf.indexOf('\\n')) !== -1) {
|
|
495
|
+
const r = decodeLine(buf.slice(0, nl));
|
|
496
|
+
buf = buf.slice(nl + 1);
|
|
497
|
+
if (r) yield r.value;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
const r = decodeLine(buf);
|
|
501
|
+
if (r) yield r.value;
|
|
502
|
+
} finally {
|
|
503
|
+
try { await reader.cancel(); } catch {}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
448
506
|
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
507
|
+
// Shared /__ai transport: embed guard, POST (stream:true flags the NDJSON path \u2014 JSON.stringify
|
|
508
|
+
// drops the key when undefined, so the non-streaming body is unchanged), 403 \u2192 trust hint.
|
|
509
|
+
const aiFetch = async (what, { messages, system, effort, provider, model, webSearch, signal } = {}, stream) => {
|
|
510
|
+
if (isEmbedded) throw embedErr(what);
|
|
511
|
+
const resp = await fetch('/__ai', {
|
|
512
|
+
method: 'POST',
|
|
513
|
+
headers: { 'Content-Type': 'application/json' },
|
|
514
|
+
body: JSON.stringify({ messages, system, effort, provider, model, webSearch, stream }),
|
|
515
|
+
signal
|
|
454
516
|
});
|
|
517
|
+
await deny403(resp, what);
|
|
518
|
+
return resp;
|
|
519
|
+
};
|
|
520
|
+
const aiError = (data) => {
|
|
521
|
+
const err = new Error(data.message || 'tb.ai() call failed');
|
|
522
|
+
err.code = data.code || 'unknown';
|
|
523
|
+
err.retryable = !!data.retryable;
|
|
524
|
+
return err;
|
|
525
|
+
};
|
|
526
|
+
// tb.ai(): non-streaming, resolves with the full { text } (unchanged 90% path).
|
|
527
|
+
const aiCall = async (opts) => {
|
|
528
|
+
const resp = await aiFetch('tb.ai()', opts, undefined);
|
|
529
|
+
const data = await resp.json();
|
|
530
|
+
if (!resp.ok) throw aiError(data);
|
|
531
|
+
return data;
|
|
532
|
+
};
|
|
533
|
+
// tb.ai.stream(): async iterable of AiChunk ({ kind:'text'|'reasoning', text }). Same idiom as a
|
|
534
|
+
// streaming tb.server.<gen>(). Break the loop (or abort the signal) to cancel.
|
|
535
|
+
const aiStream = (opts = {}) => (async function* () {
|
|
536
|
+
const resp = await aiFetch('tb.ai.stream()', opts, true);
|
|
537
|
+
if (!resp.ok && !isStreamResp(resp)) throw aiError(await resp.json().catch(() => ({})));
|
|
538
|
+
yield* readStream(resp);
|
|
539
|
+
})();
|
|
540
|
+
const ai = Object.assign(aiCall, { stream: aiStream });
|
|
455
541
|
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
// mirror): the agent parked on a wake that can never come, so that failure must wake too —
|
|
500
|
-
// missed wakes are fatal, spurious wakes cheap (TB-Wait.md). null (reap-killed) stays silent.
|
|
501
|
-
// EXCEPT an embed's clean ok verdict ("[embed <name> vN] ok" — core/client/bulbEmbed.ts):
|
|
502
|
-
// the user already sees the bulb and the skill orders silence on ok, so a wake would spend
|
|
503
|
-
// a whole turn saying nothing and render a noise message. Silence IS the ok. Anything else
|
|
504
|
-
// (an embed error, a turn-based loop event) still wakes; an unrecognized shape wakes too.
|
|
505
|
-
// Checked PER LINE, not over the whole blob: wait lingers 10s and bursts every matching line
|
|
506
|
-
// into one payload, and a version-agnostic --match ("[embed <name>") replays v1+v2+... from
|
|
507
|
-
// log start, so an all-ok payload is routinely multi-line. Suppress iff EVERY line is an ok;
|
|
508
|
-
// one error line among oks still wakes.
|
|
509
|
-
var waitLines = text.split("\n").map(function (l) { return l.trim(); }).filter(Boolean);
|
|
510
|
-
const embedOk = code === 0 && waitLines.length > 0 && waitLines.every(function (l) { return /^\[embed .*\] ok$/.test(l); });
|
|
511
|
-
if (code === 0 && text && !embedOk) {
|
|
512
|
-
pi.sendUserMessage("typebulb wait result:\n" + text, { deliverAs: "followUp" });
|
|
513
|
-
} else if (code === 0 && !text) {
|
|
514
|
-
// A successful wait always prints its matched line(s), so exit 0 with nothing captured
|
|
515
|
-
// means the agent redirected stdout (e.g. '> /tmp/x.log 2>&1') — the verdict landed in a
|
|
516
|
-
// file nobody reads. The line is still in the mirror's log; point the agent there.
|
|
517
|
-
pi.sendUserMessage("typebulb wait ended (exit 0) but its output was redirected away — read the verdict with: typebulb logs agent\nNext time run the wait plainly: no output redirect, no trailing &.", { deliverAs: "followUp" });
|
|
518
|
-
} else if (code !== null && code !== 0 && code !== 2 && code !== 3) {
|
|
519
|
-
var diag = (text + "\n" + errOut.trim()).trim();
|
|
520
|
-
pi.sendUserMessage("typebulb wait FAILED (exit " + code + ")" + (diag ? ":\n" + diag : " with no output.") + "\nThe wait never armed — nothing is watching. Fix the command and re-arm it.", { deliverAs: "followUp" });
|
|
521
|
-
} else if (ctx.ui && typeof ctx.ui.notify === "function") {
|
|
522
|
-
// INVARIANT: this notify must never quote the "[embed <name>" tag verbatim. In a
|
|
523
|
-
// composer-driven session the mirror's driver echoes extension notifies into the
|
|
524
|
-
// mirror's own log (driver.ts) — the very log wait watches by substring — so a
|
|
525
|
-
// verbatim tag re-fires the next same-match wait with a non-ok line: a self-
|
|
526
|
-
// sustaining wake loop that defeats this suppression (TB-Wait.md). Stripping the
|
|
527
|
-
// brackets kills the matchable substring while keeping the verdict readable.
|
|
528
|
-
ctx.ui.notify("typebulb wait: " + (embedOk ? text.replace(/[\[\]]/g, "") : code === 2 ? "timed out, nothing to report" : "ended (code " + code + ")"), "info");
|
|
529
|
-
}
|
|
530
|
-
} catch (e) { logErr("exit", e && e.message); }
|
|
531
|
-
});
|
|
532
|
-
|
|
533
|
-
return {
|
|
534
|
-
block: true,
|
|
535
|
-
reason: "Armed in the background. You will be re-invoked automatically with the result when it is ready - do not run this command again; end your turn now and wait for the result.",
|
|
536
|
-
};
|
|
537
|
-
} catch (e) { logErr("tool_call", e && e.message); return undefined; }
|
|
542
|
+
// tb.infer() \u2014 the local inference layer (TB-Inference.md). The UI and network live in the
|
|
543
|
+
// lazy-imported modal module (/__infer-ui.js \u2014 zero bytes here until the first call); the shim
|
|
544
|
+
// stays the state machine and globals writer. The promise settles once: a modal retry after a
|
|
545
|
+
// rejected promise still updates runtime state on success, for tb.insight() readers.
|
|
546
|
+
let inferState = 'idle';
|
|
547
|
+
let dataOverrides = null;
|
|
548
|
+
const infer = (opts = {}) => {
|
|
549
|
+
if (isEmbedded) return Promise.reject(embedErr('tb.infer()'));
|
|
550
|
+
if (inferState === 'running') return Promise.reject(new Error('Inference already in progress'));
|
|
551
|
+
inferState = 'running';
|
|
552
|
+
// Data priority (matching the .com sandbox): explicit arg > setData overrides > undefined \u2014
|
|
553
|
+
// the modal then seeds from the SOURCE chunks (/__infer-info), the local Data tab, exactly as
|
|
554
|
+
// .com's IDE modal reseeds from the Data tab rather than post-run runtime state.
|
|
555
|
+
let data = opts.data;
|
|
556
|
+
if (data === undefined && dataOverrides) data = Object.values(dataOverrides);
|
|
557
|
+
if (data !== undefined && !Array.isArray(data)) data = [data];
|
|
558
|
+
return new Promise((resolve, reject) => {
|
|
559
|
+
let settled = false;
|
|
560
|
+
const settle = (fn, v) => { if (!settled) { settled = true; fn(v); } };
|
|
561
|
+
import('/__infer-ui.js').then((ui) => {
|
|
562
|
+
ui.runInference({
|
|
563
|
+
data,
|
|
564
|
+
// The transport reader is the shim's \u2014 one NDJSON decoder per page, never two
|
|
565
|
+
// drifting copies (TB-Streaming.md envelope: payload-side, so drift is not tolerable).
|
|
566
|
+
readStream,
|
|
567
|
+
onComplete: (final) => {
|
|
568
|
+
// Runtime state only, never the file (TB-Inference.md Invariant 2).
|
|
569
|
+
window.__TB_INSIGHT__ = final.insightJson;
|
|
570
|
+
if (final.data && final.data.length) window.__TB_DATA__ = final.data;
|
|
571
|
+
if (final.hash) history.replaceState(null, '', location.pathname + location.search + final.hash);
|
|
572
|
+
inferState = 'complete';
|
|
573
|
+
settle(resolve, final.insight);
|
|
574
|
+
},
|
|
575
|
+
onError: (err) => {
|
|
576
|
+
inferState = 'error';
|
|
577
|
+
const e = new Error(err.message); e.code = err.code; e.retryable = !!err.retryable;
|
|
578
|
+
settle(reject, e);
|
|
579
|
+
},
|
|
580
|
+
onCancel: () => {
|
|
581
|
+
if (!settled) { inferState = 'idle'; settle(resolve, undefined); }
|
|
582
|
+
}
|
|
583
|
+
});
|
|
584
|
+
}).catch((e) => { inferState = 'error'; settle(reject, e); });
|
|
538
585
|
});
|
|
586
|
+
};
|
|
539
587
|
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
588
|
+
// tb.server.<fn>(...) \u2014 one call object that is both awaitable (single result) and async-iterable
|
|
589
|
+
// (a streamed async-generator export). The server picks by export kind; this stays graceful if
|
|
590
|
+
// they're mismatched (await a stream \u2192 array of chunks; for-await a normal result \u2192 one value).
|
|
591
|
+
const serverCall = (name, args) => {
|
|
592
|
+
const what = 'tb.server.' + name + '()';
|
|
593
|
+
let respP = null;
|
|
594
|
+
const start = () => respP || (respP = fetch('/__api/' + name, {
|
|
595
|
+
method: 'POST',
|
|
596
|
+
headers: { 'Content-Type': 'application/json' },
|
|
597
|
+
body: JSON.stringify({ args })
|
|
598
|
+
}));
|
|
599
|
+
const single = async () => {
|
|
600
|
+
if (isEmbedded) throw embedErr(what);
|
|
601
|
+
const resp = await start();
|
|
602
|
+
await deny403(resp, what);
|
|
603
|
+
if (isStreamResp(resp)) { const out = []; for await (const v of readStream(resp)) out.push(v); return out; }
|
|
604
|
+
const data = await resp.json();
|
|
605
|
+
if (!resp.ok) throw new Error(data.error || 'API call failed');
|
|
606
|
+
return data.result;
|
|
607
|
+
};
|
|
608
|
+
const iterate = async function* () {
|
|
609
|
+
if (isEmbedded) throw embedErr(what);
|
|
610
|
+
const resp = await start();
|
|
611
|
+
await deny403(resp, what);
|
|
612
|
+
if (isStreamResp(resp)) { yield* readStream(resp); return; }
|
|
613
|
+
const data = await resp.json();
|
|
614
|
+
if (!resp.ok) throw new Error(data.error || 'API call failed');
|
|
615
|
+
yield data.result;
|
|
616
|
+
};
|
|
617
|
+
return {
|
|
618
|
+
then: (f, r) => single().then(f, r),
|
|
619
|
+
catch: (r) => single().catch(r),
|
|
620
|
+
finally: (f) => single().finally(f),
|
|
621
|
+
[Symbol.asyncIterator]: iterate
|
|
622
|
+
};
|
|
623
|
+
};
|
|
570
624
|
|
|
571
|
-
|
|
572
|
-
|
|
625
|
+
// tb namespace
|
|
626
|
+
globalThis.tb = Object.freeze({
|
|
627
|
+
data: (index) => getData()[index],
|
|
628
|
+
json: (index) => parseJson(getData()[index]),
|
|
629
|
+
insight: () => window.__TB_INSIGHT__ ? parseJson(window.__TB_INSIGHT__) : undefined,
|
|
573
630
|
|
|
574
|
-
|
|
631
|
+
// Inference (TB-Inference.md) \u2014 modal-hosted one-shot LLM call over the bulb's own blocks
|
|
632
|
+
infer,
|
|
633
|
+
inferenceState: () => inferState,
|
|
634
|
+
setData: (index, content) => { if (!dataOverrides) dataOverrides = {}; dataOverrides[index] = content; },
|
|
635
|
+
resetInferenceState: () => { inferState = 'idle'; dataOverrides = null; },
|
|
575
636
|
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
`:"";Yh(n,i+`OPENROUTER_API_KEY=${e}
|
|
579
|
-
`)}}catch(i){return{ok:!1,error:U(i)}}return process.env.OPENROUTER_API_KEY=e,Gh(t,[".env"],"# secrets"),{ok:!0}}function NA(){if(!(!Cr&&!De)){try{Zh(H)}catch{}kA()}}function IA(r,e){return tg.test(e)?"blocked by your OpenRouter data policy":r===401||r===403||/unauthor|invalid api key|no auth|forbidden/i.test(e)?"auth rejected \u2014 check your OpenRouter key":r===404||/not a valid model|no such model|unknown model|model not found/i.test(e)?"model not found on this route":r===429||/rate limit/i.test(e)?"rate limited":r===402||/insufficient|credit|quota|balance/i.test(e)?"out of credits / quota":e.slice(0,160)}function $A(r){if(tg.test(r))return"This model's only provider(s) require prompt logging/training, which your OpenRouter account disallows by default. Allow it (or that provider) at openrouter.ai/settings/privacy, then probe again."}function LA(r,e,t){if(!r)return{works:null,read:0,note:t?`couldn't re-test on ${t} \u2014 caching unconfirmed`:"caching unconfirmed"};let n=$l(e?.cache_read_input_tokens)||$l(e?.prompt_tokens_details?.cached_tokens),s=e?.cache_read_input_tokens!==void 0||e?.cache_creation_input_tokens!==void 0||e?.prompt_tokens_details!==void 0;return n>0?{works:!0,read:n,note:`${n} tokens read from cache on the 2nd call`}:s?{works:!1,read:n,note:"no cache reads after a warm call \u2014 every turn re-bills the full context"}:{works:null,read:n,note:"route doesn't report cache usage \u2014 caching almost certainly not honored"}}async function MA({model:r}){let e=process.env.OPENROUTER_API_KEY;if(!e)return{ok:!1,error:"OPENROUTER_API_KEY not set \u2014 add a key first"};if(!r)return{ok:!1,error:"no model given"};if(Dl(r))return{ok:!1,error:"Anthropic model \u2014 not offered or probed via OpenRouter"};let t=Date.now(),n=Array(350).fill("Caching probe filler sentence; its only purpose is to exceed the prompt-cache minimum token threshold.").join(" "),s={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":"2023-06-01"},i={model:r,max_tokens:64,system:[{type:"text",text:n,cache_control:{type:"ephemeral"}}],messages:[{role:"user",content:"Reply with exactly: ok"}]},o=async a=>{let c=new AbortController,l=setTimeout(()=>c.abort(),2e4);try{let f=JSON.stringify(a?{...i,provider:zh(a)}:i),u=await fetch(Ml,{method:"POST",signal:c.signal,headers:s,body:f}),d=await u.json().catch(()=>({}));return{r:u,j:d}}finally{clearTimeout(l)}};try{let{r:a,j:c}=await o();if(!a.ok){let x=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:IA(a.status,x),restriction:$A(x)}}let l=typeof c?.provider=="string"?c.provider:void 0,f=c?.content?.find?.(x=>x.type==="text")?.text??c?.content?.[0]?.text??"ok",u=$l(c?.usage?.cache_creation_input_tokens),{r:d,j:p}=await o(l),{works:y,read:m,note:b}=LA(d.ok,p?.usage,l);return y===!0&&l&&(Bl[r]=l,De===r&&(Yt=l)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-t,provider:l,sample:String(f).trim().slice(0,60),cache:{works:y,created:u,read:m,note:b}}}catch(a){let c=U(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(c)?"timed out (20s)":c}}}var dA,Ml,fA,pA,Vh,mA,Il,lo,uo,oo,Dl,Cr,Wt,De,Yt,Dn,Bn,jn,Bl,$l,zh,tg,rg=A(()=>{Tr();bt();dA="https://openrouter.ai/api",Ml=`${dA}/v1/messages`,fA="typebulb-proxy-managed",pA="The typebulb model override was reverted to Anthropic, but this Claude Code session still points at the now-idle proxy. Reload the window (VS Code/Cursor: \u201CDeveloper: Reload Window\u201D) or relaunch `claude` in a terminal to return to your Anthropic subscription.",Vh=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],mA=5e3,Il=["low","medium","high"],lo=r=>co(r,".claude","settings.local.json"),uo=r=>co(r,".claude",".cc-switcher.json"),oo=r=>`http://127.0.0.1:${r}`;Dl=r=>/^anthropic\//i.test(r)||/claude/i.test(r),Cr=null,Wt=null,De=null,Yt=null,Dn=null,Bn="unknown",jn=1,Bl={},$l=r=>typeof r=="number"?r:0,zh=r=>({order:[r],allow_fallbacks:!1});tg=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=vt(uo(H)),t=e?.active?.model;if(!t)return;let s=(vt(lo(H))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await eg(t,e.active.provider??Bl[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${oo(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",U(e))}})()});var sg={};cu(sg,{attach:()=>KA,blockToMarkdown:()=>Ci,breakout:()=>Ph,capText:()=>Ce,cleanUserText:()=>ht,clearSwitchModel:()=>CA,composerPasteRead:()=>HA,displayName:()=>DA,downloadSample:()=>Fh,firstLineDigest:()=>Ge,git:()=>Me,gitChangedFiles:()=>ph,gitDiff:()=>mh,info:()=>BA,isHiddenTurn:()=>Rn,launchBulb:()=>Nh,listBreakouts:()=>Oh,listBulbFiles:()=>Ch,listMyBulbs:()=>qh,listSamples:()=>jh,listSessions:()=>qA,listSwitchModels:()=>TA,logEmbedStatus:()=>FA,openFile:()=>Th,poll:()=>jA,predictTrustOf:()=>Ih,probeModel:()=>MA,pullRemoteBulb:()=>Uh,pushLocalBulb:()=>Kh,readBulbLog:()=>Lh,repoRoot:()=>Or,saveOpenRouterKey:()=>RA,searchBulbs:()=>Rh,searchSessions:()=>UA,sessionPeek:()=>JA,setBulbTrust:()=>$h,setReasoning:()=>_A,setSwitchModel:()=>OA,shutdownSwitcher:()=>NA,stopBreakout:()=>_h,switchState:()=>PA,toolResultDigest:()=>nl});var ng,DA,BA,jA,FA,qA,UA,JA,KA,HA,ig=A(()=>{Al();Ri();Nl();Qi();rg();Ri();Oi();ng=new Sr,DA=ng.displayName,{info:BA,poll:jA,logEmbedStatus:FA,listSessions:qA,searchSessions:UA,sessionPeek:JA,attach:KA,composerPasteRead:HA}=so(ng)});import{readFileSync as WA,writeFileSync as YA,mkdirSync as VA}from"fs";import{homedir as GA}from"os";import*as fo from"path";async function cg(){try{let r=await fetch(new URL("/api/tags",ag()).toString(),{signal:AbortSignal.timeout(zA)});return r.ok?((await r.json()).models??[]).map(t=>t.name).filter(t=>!!t):[]}catch{return[]}}function lg(r){let e;try{e=WA(r,"utf-8")}catch{return{json:void 0,unreadable:!1}}try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t;return{json:n,unreadable:"providers"in n&&!jl(n)}}}catch{}return{json:void 0,unreadable:!0}}function jl(r){let e=r?.providers;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function XA(r){let e=jl(r);if(!e||!("ollama"in e))return null;let t=e.ollama?.models;return Array.isArray(t)?t.map(n=>n?.id).filter(n=>typeof n=="string"):[]}async function ug(){let{json:r,unreadable:e}=lg(og());return e?{installed:[],configured:null}:{installed:await cg(),configured:XA(r)}}async function dg(){let r=await cg();return r.length?QA(og(),r,ag()):{ok:!1,error:"Ollama is not running (or has no models installed)"}}function QA(r,e,t){let{json:n,unreadable:s}=lg(r);if(s)return{ok:!1,error:`could not parse ${r} \u2014 edit the ollama provider there yourself`};let i={...n??{},providers:{...jl(n)??{},ollama:{baseUrl:`${t}/v1`,api:"openai-completions",apiKey:"ollama",models:e.map(o=>({id:o}))}}};try{VA(fo.dirname(r),{recursive:!0}),YA(r,JSON.stringify(i,null,2)+`
|
|
580
|
-
`)}catch(o){return{ok:!1,error:`could not write ${r}: ${U(o)}`}}return{ok:!0,count:e.length}}var zA,og,ag,fg=A(()=>{bt();Tr();zA=1500,og=()=>fo.join(GA(),".pi","agent","models.json"),ag=()=>yr(process.env.OLLAMA_HOST??"http://localhost:11434")});var mg={};cu(mg,{attach:()=>oT,breakout:()=>Ph,composerFiles:()=>uT,composerNew:()=>lT,composerPaste:()=>pT,composerPasteRead:()=>mT,composerRpc:()=>fT,composerSend:()=>aT,composerStop:()=>cT,composerUiRespond:()=>dT,displayName:()=>ZA,downloadSample:()=>Fh,git:()=>Me,gitChangedFiles:()=>ph,gitDiff:()=>mh,info:()=>eT,launchBulb:()=>Nh,listBreakouts:()=>Oh,listBulbFiles:()=>Ch,listMyBulbs:()=>qh,listSamples:()=>jh,listSessions:()=>nT,logEmbedStatus:()=>rT,ollamaOffer:()=>ug,ollamaSync:()=>dg,openFile:()=>Th,poll:()=>tT,predictTrustOf:()=>Ih,pullRemoteBulb:()=>Uh,pushLocalBulb:()=>Kh,readBulbLog:()=>Lh,repoRoot:()=>Or,searchBulbs:()=>Rh,searchSessions:()=>sT,sessionPeek:()=>iT,setBulbTrust:()=>$h,shutdownComposer:()=>hT,stopBreakout:()=>_h});var pg,ZA,eT,tT,rT,nT,sT,iT,oT,aT,cT,lT,uT,dT,fT,pT,mT,hT,hg=A(()=>{Al();xl();Nl();Qi();fg();pg=new Pr,ZA=pg.displayName,{info:eT,poll:tT,logEmbedStatus:rT,listSessions:nT,searchSessions:sT,sessionPeek:iT,attach:oT,composerSend:aT,composerStop:cT,composerNew:lT,composerFiles:uT,composerUiRespond:dT,composerRpc:fT,composerPaste:pT,composerPasteRead:mT,shutdownComposer:hT}=so(pg)});import*as xy from"fs/promises";import*as Gt from"path";import*as yu from"path";import*as uu from"fs/promises";import{existsSync as zt,readFileSync as Hy}from"fs";import*as X from"path";import{pathToFileURL as Wy}from"url";import{resolve as Ro}from"resolve.exports";import{init as du,parse as fu}from"es-module-lexer";function pu(r,e){let t=X.join(r,"package.json");try{return JSON.parse(Hy(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var Co=["browser","import","default"],lu=["node","import","default"];function mu(r){let e=r.indexOf("=");if(e===-1)throw new Error(`--replace must be <name>=<path> (got '${r}')`);let t=r.slice(0,e).trim(),n=r.slice(e+1).trim();if(!t)throw new Error(`--replace missing package name (got '${r}')`);if(!n)throw new Error(`--replace missing path for '${t}'`);if(t.startsWith("@"))throw new Error(`--replace does not support scoped names yet; '${t}' is scoped`);return{name:t,dir:X.resolve(n)}}async function hu(r){let{name:e,dir:t}=r;if(!zt(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=pu(t,e),s=Yy(n,e),i=X.resolve(t,s);if(!zt(i))throw new Error(`--replace package '${e}' entry not found on disk: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);let o=X.dirname(i),a=`/local/${e}/${X.basename(i)}`,c=Vy(n,t);return await Gy(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function Yy(r,e){if(r.exports!==void 0){let n;try{n=Ro(r,".",{browser:!0,conditions:Co})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${Co.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=No(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${Co.join(", ")}); too complex to override.`);return s}let t=r.module??r.main;if(!t)throw new Error(`--replace package '${e}' has no "exports", "module", or "main" entry to resolve.`);return t}function Vy(r,e){if(r.exports!==void 0)try{let n=Ro(r,".",{conditions:["types"]}),s=No(n);if(s){let i=X.resolve(e,s);if(zt(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=X.resolve(e,t);if(zt(n))return n}}function No(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function Gy(r,e,t){await du;let n=X.normalize(t),s=new Set,i=[e];for(;i.length;){let o=i.shift();if(s.has(o))continue;s.add(o);let a;try{a=await uu.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=fu(a,o)}catch{continue}if(o===e&&!l)throw new Error(`override package '${r}' entry is not an ES module (no import/export syntax); CommonJS or non-module entries aren't supported (esm.sh would have to transform it).`);for(let f of c){if(f.d===-2)continue;let u=f.n;if(u&&!u.startsWith("node:")){if(u.startsWith("./")||u.startsWith("../")||u.startsWith("/")){let d=zy(o,u,n);d&&!s.has(d)&&i.push(d);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${r} externalizes '${u}'`)}}}}function zy(r,e,t){let n=e.replace(/[?#].*$/,""),s=X.resolve(X.dirname(r),n),i=[s,s+".js",s+".mjs",X.join(s,"index.js"),X.join(s,"index.mjs")];for(let o of i)if(X.normalize(o).startsWith(t)&&zt(o))return o}function Xy(r,e,t){let n=pu(r,e),s;if(n.exports!==void 0)try{s=No(Ro(n,t,{conditions:lu}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${lu.join(", ")}): ${o instanceof Error?o.message:o}`)}else t==="."&&(s=n.main??n.module);if(!s)throw new Error(`--replace package '${e}' has no node export for '${t}'.`);let i=X.resolve(r,s);if(!zt(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return Wy(i).href}async function gu(r,e){await du;let t;try{[t]=fu(r)}catch{return r}let n="",s=0;for(let i of t){if(i.d!==-1)continue;let o=i.n;if(!o||o!==e.name&&!o.startsWith(e.name+"/"))continue;let a=o===e.name?".":"."+o.slice(e.name.length),c=Xy(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var Io=5e3;function bu(r){let t={subcommand:"run",file:"",port:3e3,watch:!0,open:!(process.env.TERM_PROGRAM==="vscode"),server:!1,trust:!1,noTrust:!1,force:!1,follow:!1,clear:!1,help:!1,version:!1,callArgs:[],hasArgsFlag:!1},n=["call","check","predict","logs","wait","stop","trust","untrust","skill","models","send","pull","push"],s=r[0];if(s==="agent"||s?.startsWith("agent:")){t.subcommand="agent";let o=s.indexOf(":");if(o!==-1){let a=s.slice(o+1);a&&(t.agentTarget=a)}r=r.slice(1)}else s&&n.includes(s)&&(t.subcommand=s,r=r.slice(1));let i=[];for(let o=0;o<r.length;o++){let a=r[o];if(a==="--help"||a==="-h")t.help=!0;else if(a==="--version"||a==="-V")t.version=!0;else if(a==="--no-watch")t.watch=!1;else if(a==="--open")t.open=!0;else if(a==="--no-open")t.open=!1;else if(a==="--server")t.server=!0;else if(a==="--trust")t.trust=!0;else if(a==="--no-trust")t.noTrust=!0;else if(a==="--force")t.force=!0;else if(a==="--mode"){let c=r[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),t.mode=c}else if(a==="--dir"){let c=r[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --dir (a subfolder of the bulb's folder, e.g. --dir batch2)"),process.exit(1));let l=c.replace(/[\\/]+$/,"");(!l||yu.isAbsolute(l)||l.split(/[\\/]/).some(f=>f===""||f===".."))&&(console.error(`Invalid --dir value: ${c} (a relative subfolder of the bulb's folder \u2014 no absolute paths or '..')`),process.exit(1)),t.dir=l}else if(a==="--follow"||a==="-f")t.follow=!0;else if(a==="--clear")t.clear=!0;else if(a==="--run"){let c=r[++o];if(c==="latest")t.run="latest";else{let l=parseInt(c,10);(isNaN(l)||l<1)&&(console.error(`Invalid --run value: ${c} (a run number, or 'latest')`),process.exit(1)),t.run=l}}else if(a==="--bulbs")t.stopScope="bulbs";else if(a==="--agent")t.stopScope="agent";else if(a==="--global")t.stopScope="global";else if(a==="--match"){let c=r[++o];c===void 0&&(console.error("Missing value for --match (a literal substring new log lines must contain)"),process.exit(1)),t.match=c}else if(a==="--timeout"){let c=parseInt(r[++o],10);(isNaN(c)||c<=0)&&(console.error(`Invalid --timeout value: ${r[o]} (seconds)`),process.exit(1)),t.timeoutSec=c}else if(a==="--wait"||a.startsWith("--wait="))if(a.startsWith("--wait=")){let c=parseInt(a.slice(7),10);(isNaN(c)||c<=0)&&(console.error(`Invalid --wait value: ${a.slice(7)} (milliseconds)`),process.exit(1)),t.sendWaitMs=c}else t.sendWaitMs=Io;else if(a==="--lines"||a==="-n"){let c=parseInt(r[++o],10);(isNaN(c)||c<0)&&(console.error(`Invalid --lines value: ${r[o]}`),process.exit(1)),t.lines=c}else if(a==="--port"||a==="-p"){let c=r[++o],l=parseInt(c,10);isNaN(l)&&(console.error(`Invalid port: ${c}`),process.exit(1)),t.port=l}else if(a==="--replace"||a.startsWith("--replace=")){let c=a.startsWith("--replace=")?a.slice(10):r[++o]??"";try{let l=mu(c);if(t.local)throw new Error(`--replace can only be used once (got '${t.local.name}' and '${l.name}')`);t.local=l}catch(l){console.error(l instanceof Error?l.message:String(l)),process.exit(1)}}else if(a==="--args"||a.startsWith("--args=")){t.hasArgsFlag=!0;let c=a.startsWith("--args=")?a.slice(7):r[++o];c===void 0&&(console.error("Missing value for --args (a JSON array, or - to read it from stdin)"),process.exit(1)),t.argsJson=c}else if(!a.startsWith("-"))t.subcommand==="call"||t.subcommand==="send"?i.push(a):t.file=a;else{let c=t.subcommand==="call"?" (for a negative or dash-leading argument, use --args '<json-array>')":"";console.error(`Unknown option: ${a}${c}`),process.exit(1)}}return t.subcommand==="call"&&(i.length<2&&(console.error("Usage: typebulb call <file> <fn> [arg\u2026]"),process.exit(1)),t.file=i[0],t.fn=i[1],t.callArgs=i.slice(2)),t.subcommand==="send"&&(i.length<1&&(console.error("Usage: typebulb send <file> [message]"),process.exit(1)),t.file=i[0],t.sendMessage=i[1]),t}function wu(){console.log(`
|
|
581
|
-
typebulb - Local bulb runner for Typebulb
|
|
637
|
+
// AI - tb.ai() proxies to the provider via the local server; tb.ai.stream() streams AiChunks.
|
|
638
|
+
ai,
|
|
582
639
|
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
view of your coding agent's sessions) \u2014 explicit / override.
|
|
591
|
-
typebulb skill Print this README as an Agent Skill (stdout), for the
|
|
592
|
-
agent to read and copy into its own skills folder.
|
|
593
|
-
typebulb call <file> <fn> [\u2026] Invoke one server.ts export headlessly: prints
|
|
594
|
-
its return as JSON to stdout, logs/errors to
|
|
595
|
-
stderr. Gated by trust like --server. Args after
|
|
596
|
-
<fn> are JSON-or-string; --args '<json-array>'
|
|
597
|
-
(or --args - for stdin) is the escape hatch.
|
|
598
|
-
typebulb check [file.bulb.md] Type-check a bulb without running it
|
|
599
|
-
typebulb predict [file] Report the capability a bulb probably needs
|
|
600
|
-
(fs / AI / server.ts) without running it.
|
|
601
|
-
typebulb models List AI models for tb.ai, filtered by the API
|
|
602
|
-
keys in your .env (the exact ids to pass).
|
|
603
|
-
typebulb logs [file|agent] Print a running bulb server's (or the 'agent' mirror's) console
|
|
604
|
-
(no arg: list this project's running servers;
|
|
605
|
-
--run latest|N shows just one hot-reload run;
|
|
606
|
-
--clear empties it). For agents: fetch
|
|
607
|
-
tb.server.log / errors of a bulb you launched
|
|
608
|
-
without watching its terminal.
|
|
609
|
-
typebulb send <file> [msg] Push a message into a running bulb's page \u2014
|
|
610
|
-
its tb.onMessage(cb) handlers receive it. The
|
|
611
|
-
client-side twin of 'call'; msg is JSON-or-
|
|
612
|
-
string, omit it for a bare trigger. No --trust.
|
|
613
|
-
With --wait, a handler's non-undefined return
|
|
614
|
-
prints on stdout (JSON; a bare string raw).
|
|
615
|
-
msg 'tb:snapshot' instead prints the page's
|
|
616
|
-
rendered outline (roles, names, visible text).
|
|
617
|
-
typebulb pull <url|file> Fetch a bulb from typebulb.com into
|
|
618
|
-
typebulbs/u/<user>/<slug>.bulb.md (a local file
|
|
619
|
-
at that path re-pulls in place). Unlisted and
|
|
620
|
-
public bulbs need no login; a differing local
|
|
621
|
-
file is refused unless --force.
|
|
622
|
-
typebulb push <file> Upload a typebulbs/u/<user>/<slug>.bulb.md to
|
|
623
|
-
typebulb.com as you (needs TYPEBULB_TOKEN in
|
|
624
|
-
.env, minted on the settings page). Refused if
|
|
625
|
-
the remote changed since your last pull/push,
|
|
626
|
-
unless --force. A new slug is created unlisted.
|
|
627
|
-
typebulb wait [file|agent] Block until the target server logs a new line,
|
|
628
|
-
print it, exit (2: timeout; 3: server died).
|
|
629
|
-
For agents: run it in the background \u2014 the exit
|
|
630
|
-
is your wake-up ('wait agent': embed outcomes;
|
|
631
|
-
'wait <file>': the bulb's own console.log).
|
|
632
|
-
Resumes where your last wait/call left off, so
|
|
633
|
-
an event that beats the wait still fires it.
|
|
634
|
-
typebulb stop [file|pid|agent] Stop a running bulb or mirror (no arg: list this
|
|
635
|
-
project's running servers; a pid/path/agent stops any).
|
|
636
|
-
Batch flags: --bulbs (this project's bulbs, the
|
|
637
|
-
mirror survives), --agent (this project's mirror),
|
|
638
|
-
--global (every bulb + mirror, all projects).
|
|
639
|
-
typebulb trust [file] Remember a bulb as Trusted, so a later run grants
|
|
640
|
-
fs/AI/server.ts without --trust (no arg: list the
|
|
641
|
-
remembered-trusted bulbs).
|
|
642
|
-
typebulb untrust <file> Forget a bulb's trust (back to Restricted).
|
|
643
|
-
|
|
644
|
-
Options:
|
|
645
|
-
-f, --follow Stream new log output until interrupted (logs)
|
|
646
|
-
--run <latest|N> Show only one hot-reload run's output: 'latest'
|
|
647
|
-
(the current run) or run number N (logs)
|
|
648
|
-
--clear Empty the target server's log instead of
|
|
649
|
-
printing it, for a clean run (logs)
|
|
650
|
-
-n, --lines <n> Print only the last n lines (logs)
|
|
651
|
-
--match <substring> Only lines containing this literal substring end
|
|
652
|
-
the wait \u2014 not a regex (wait)
|
|
653
|
-
--force Overwrite the side the command writes to: a
|
|
654
|
-
differing local file (pull), or a remote that
|
|
655
|
-
changed since your last sync (push)
|
|
656
|
-
--timeout <sec> Give up after this long; exit 2 \u2014 bounds only a
|
|
657
|
-
manual (foreground) bulb wait, default 1800 (wait)
|
|
658
|
-
--wait[=ms] For 'send': bound the whole exchange \u2014 retry while
|
|
659
|
-
no page is connected (a hot reload's gap), then
|
|
660
|
-
hold for the handlers' replies (default 5000).
|
|
661
|
-
Use it right after an edit, and for any send
|
|
662
|
-
whose reply you read.
|
|
663
|
-
--no-watch Disable hot reload (watch is on by default)
|
|
664
|
-
-p, --port <port> Use a specific port (default: 3000)
|
|
665
|
-
--open Force-open the external browser (default off
|
|
666
|
-
inside VS Code's integrated terminal)
|
|
667
|
-
--no-open Don't auto-open browser
|
|
668
|
-
--trust Grant privileged capabilities (filesystem, AI,
|
|
669
|
-
and server.ts) for this run. Without it a bulb runs
|
|
670
|
-
Restricted: tb.fs / tb.ai / tb.server are blocked and
|
|
671
|
-
the page shows the exact --trust command to unlock
|
|
672
|
-
them. A bulb remembered via 'typebulb trust' runs
|
|
673
|
-
trusted without this flag.
|
|
674
|
-
--no-trust Force a Restricted run even if the bulb is
|
|
675
|
-
remembered-trusted (overrides the trust store).
|
|
676
|
-
--mode <name> Also load .env.<name> (+ .env.<name>.local) on top
|
|
677
|
-
of .env / .env.local. Free-form name; loads no mode
|
|
678
|
-
file by default.
|
|
679
|
-
--dir <sub> Scope the bulb's dir to a subfolder for this run:
|
|
680
|
-
tb.dir and relative tb.fs paths land in
|
|
681
|
-
<bulb-folder>/<sub>. Batch runs without touching
|
|
682
|
-
the bulb's code (e.g. --dir batch2). Relative
|
|
683
|
-
subpaths only \u2014 no absolute paths or '..'.
|
|
684
|
-
--server Run server.ts only, no web server (needs --trust)
|
|
685
|
-
--args <json-array> For 'call': the whole argument list as one JSON
|
|
686
|
-
array (strict). '--args -' reads it from stdin,
|
|
687
|
-
sidestepping shell quoting.
|
|
688
|
-
--replace <name>=<path> Replace a declared dependency with a local built
|
|
689
|
-
package folder instead of a CDN (dev only).
|
|
690
|
-
Applies to both run and check. Watched for
|
|
691
|
-
rebuilds under --watch; --no-watch freezes it.
|
|
692
|
-
e.g. --replace tensorgrad=../tensorgrad
|
|
693
|
-
-V, --version Show version number
|
|
694
|
-
-h, --help Show this help message
|
|
695
|
-
|
|
696
|
-
Filesystem API:
|
|
697
|
-
Bulbs can read and write local files via tb.fs:
|
|
698
|
-
await tb.fs.read('file.txt') // UTF-8 text (throws on non-UTF-8)
|
|
699
|
-
await tb.fs.readBytes('image.png') // raw bytes (Uint8Array)
|
|
700
|
-
await tb.fs.write('output.html', content) // text or bytes
|
|
640
|
+
// Model discovery - fetches catalog from typebulb.com, filtered by local API keys
|
|
641
|
+
models: async () => {
|
|
642
|
+
if (isEmbedded) return [];
|
|
643
|
+
const resp = await fetch('/__models');
|
|
644
|
+
if (!resp.ok) return [];
|
|
645
|
+
return resp.json();
|
|
646
|
+
},
|
|
701
647
|
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
648
|
+
// Own-keys check - true when the user's own AI backs tb.ai (env keys, compat endpoint, or Ollama)
|
|
649
|
+
hasOwnKeys: async () => {
|
|
650
|
+
if (isEmbedded) return false;
|
|
651
|
+
const resp = await fetch('/__has-own-keys');
|
|
652
|
+
if (!resp.ok) return false;
|
|
653
|
+
return (await resp.json()) === true;
|
|
654
|
+
},
|
|
708
655
|
|
|
709
|
-
|
|
710
|
-
|
|
656
|
+
// Dump just logs to console in local mode
|
|
657
|
+
dump: async (...args) => console.log('[tb.dump]', ...args),
|
|
711
658
|
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
ANTHROPIC_API_KEY=sk-ant-...
|
|
715
|
-
OPENAI_API_KEY=sk-...
|
|
716
|
-
GOOGLE_API_KEY=AIza...
|
|
717
|
-
OPENROUTER_API_KEY=sk-or-...
|
|
718
|
-
Set provider and model (required):
|
|
719
|
-
TB_AI_PROVIDER=anthropic
|
|
720
|
-
TB_AI_MODEL=claude-haiku-4-5-20251001
|
|
721
|
-
Both can be overridden per-call: tb.ai({ provider: "openai", model: "gpt-5.4-mini", ... })
|
|
722
|
-
Don't guess a model id \u2014 run 'typebulb models' to list the exact ids your keys cover.
|
|
723
|
-
Optional effort level (1=low, 2=med, 3=high; omit for the model's native default):
|
|
724
|
-
tb.ai({ ..., effort: 2 })
|
|
659
|
+
// Clipboard
|
|
660
|
+
copy,
|
|
725
661
|
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
typebulb --no-watch --port 8080 my-editor.bulb.md
|
|
729
|
-
typebulb .
|
|
730
|
-
`)}gn();import*as mt from"fs/promises";import*as ie from"path";import{pathToFileURL as Bk}from"url";import{transform as Bx}from"sucrase";function Ac(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=Bx(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}Qs();function Hx(r){return r.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
|
|
731
|
-
`)[0]}`).join(`
|
|
732
|
-
`)}function Ip(r,e){let t=yn(r,{target:"client",dependencies:e}).filter(n=>n.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
733
|
-
${Hx(t)}`)}var lt="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Tc="https://data.jsdelivr.com/v1/package/npm/";function $p(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var D=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=lr(t??s.version),this.subpath=lr(n??s.subpath)}static parse(e){let t=$p(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=Lp(t[1]??""),a=lr(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=Lp(t[0]),o=lr(t.slice(1).join("/"));return new r({name:s,version:i,subpath:o})}}static fromUrl(e){try{let t=new URL(e),n=new URL(lt).host,s=new URL(bn).host;if(t.host===n){let i=$p(t.pathname.replace(/^\/v\d+\//,"/"));if(!i.length)return;let o=i[0].startsWith("@")?`${i[0]}/${i[1]??""}`:i[0];return r.parse(o)}if(t.host===s){let i=t.pathname.split("/npm/")[1];if(!i)return;let o=i.split("/")[0]||"";return r.parse(o)}return}catch{return}}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return r.parse(e).name}withVersion(e){return new r({name:this.name,version:lr(e),subpath:this.subpath})}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},lr=r=>r&&r.length?r:void 0,Lp=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),lr(r.slice(e+1))]};async function le(r){try{return await r()}catch{return}}function Rt(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function Pc(r){return r.startsWith("./")?r:`./${r}`}var wn=class{constructor(e,t){this.cache=e,this.http=t,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}baseDir(e){let t=typeof e=="string"?new D(e):e;return`${bn}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(Rt(t),this.baseDir(e)).toString()}packageJson(e){return this.file(e,"package.json")}buildEsmUrl(e,t={}){let{target:n="es2022",bundle:s=!1,external:i}=t,o=new URLSearchParams({target:n});return s&&o.append("bundle",""),i?.length&&o.append("external",i.join(",")),`${lt}/${e}?${o.toString()}`}async resolveExactVersion(e){let t=Date.now(),n=this.pinCache.get(e);if(n&&t-n.ts<this.pinMs)return n.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${lt}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await le(()=>this.http.head(t)),s=this.parseVersionFromUrl(n?.url||t);if(s)return s}}async fetchVersionsIndex(e){if(await this.cache.isNegative(e))return;let t=await this.cache.getIndex(e);if(t&&Date.now()-t.updatedAt<this.versionsIndexMs)return{versions:t.versions,distTags:t.distTags};let n=await le(()=>this.http.getJson(`${Tc}${encodeURIComponent(e)}`));if(!n?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=n.tags&&Object.keys(n.tags).length?n.tags:void 0;return await this.cache.setIndex(e,n.versions,s),{versions:n.versions,distTags:s}}parseVersionFromUrl(e){let t=D.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let n=await this.cache.getMeta(e,t);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:f,peerDependencies:u,peerDependenciesMeta:d}=n;return{name:e,version:t,dependencies:f,peerDependencies:u,peerDependenciesMeta:d}}let s=this.packageJson(new D(`${e}@${t}`)),i=await le(()=>this.http.getJson(s));if(!i)return;let o=f=>f&&Object.keys(f).length?f:void 0,a=o(i.dependencies),c=o(i.peerDependencies),l=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}};var Mp=r=>r.startsWith("@types/"),vn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!Mp(e)),Oc=r=>Object.keys(r?.dependencies||{}).filter(e=>!Mp(e)),Wx=r=>vn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),Sn=class{constructor(e){this.cdn=e}async resolve(e,t){let n=await this.fetchMeta(e),{allRoots:s,autoAddedPeers:i}=await this.expandWithPeers(n,t),o=this.computeFlags(s);return{allRoots:s,flags:o,autoAddedPeers:i}}async fetchMeta(e){return Promise.all(e.map(async({name:t,version:n})=>({name:t,version:n,meta:await this.cdn.fetchPackageMeta(t,n)})))}async expandWithPeers(e,t){let n=new Map(e.map(i=>[i.name,i])),s=[];for(let i of e)for(let o of Wx(i.meta))!n.has(o)&&!s.some(a=>a.name===o)&&s.push({name:o,requiredBy:i.name});for(let{name:i,requiredBy:o}of s)try{let a=await t(i),c=await this.cdn.fetchPackageMeta(i,a);n.set(i,{name:i,version:a,meta:c})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${i}" for "${o}":`,a)}return{allRoots:[...n.values()],autoAddedPeers:s.filter(i=>n.has(i.name))}}computeFlags(e){let t=new Set(e.flatMap(i=>vn(i.meta))),n=new Map;for(let i of e)for(let o of Oc(i.meta))n.set(o,(n.get(o)||0)+1);let s=new Set([...n.entries()].filter(([,i])=>i>=2).map(([i])=>i));return new Map(e.map(i=>[i.name,{isPeerRoot:t.has(i.name),hasPeers:vn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var xn=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await le(()=>this.cdn.fetchVersionsIndex(e));if(t?.versions?.length){let n=this.semver.selectBestVersion(t.versions,{distTags:t.distTags});if(n)return n}return this.cdn.resolveExactVersion(e)}async resolveExactForRoot(e,t){if(!t)return this.learnExactVersion(e);let n=await this.cache.getPinnedExact(e,t);if(n){if(this.semver.isExactVersion(n))return n;console.debug("[typebulb] cached version for",e,"is not exact (",n,"); re-resolving from registry")}let s=async o=>{if(o&&this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o},i=await le(()=>this.cdn.fetchVersionsIndex(e));if(i?.versions?.length){let o=this.semver.selectBestVersion(i.versions,{range:t,distTags:i.distTags});if(o){let a=await s(o);if(a)return a}else{console.debug("[typebulb] refreshing version cache for",e,"(",t,"not in cached set \u2014 likely a new release)"),await this.cache.invalidateVersionsCache(e);let a=await le(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=await s(this.semver.selectBestVersion(a.versions,{range:t,distTags:a.distTags}));if(c)return c}}}return s(await this.cdn.resolveExactVersion(`${e}@${t}`))}async effectivePackage(e,t){let n=new D(e),s=n.root(),i=t[s],o=i?await le(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as Yx,parse as Vx}from"es-module-lexer";var ur=class r{constructor(e,t,n){this.version=e,this.cdn=t,this.peer=n}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))D.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{D.isBare(s)&&t.add(s)};try{await Yx;let[s]=Vx(e);s.forEach(i=>n(e.slice(i.s,i.e).trim()))}catch{return this.extractImportsSync(e)}return Array.from(t)}async buildImportMap(e,t,n){let s=(await this.extractImports(e)).filter(u=>!n?.has(D.rootOf(u))),i=[...new Set(s.map(D.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),f=this.buildEntries([...s,...l.map(u=>u.name)],a,c);return{importMap:{imports:Object.fromEntries(f)},prefetchUrls:f.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=await this.version.resolveExactForRoot(e,n);if(!s)throw new Error(`Cannot resolve ${n?`${e}@${n}`:e}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);return s}buildEntries(e,t,n){let s=new Map(t.map(p=>[p.name,p])),i=p=>{let y=s.get(D.rootOf(p));return new D(p).withVersion(y.version).format()},o=new Set([...n.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==D.rootOf(p)).map(D.rootOf)),c=[],l=new Set,f=new Set(e.filter(p=>p===D.rootOf(p))),u=new Set;for(let p of e){let y=D.rootOf(p),m=s.get(y),{isPeerRoot:b,hasPeers:x,isSharedDep:k}=n.get(y),T=a.has(y),P=p!==y,_=!(b||k)&&(T||!x),N=this.singletonDepsOf(m,o),h=P&&f.has(y);h&&u.add(y);let v=h?[...N,y]:N.length?N:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:_,external:v})]),l.add(p)}let d=new Set([...o,...u]);for(let p of d)s.has(p)&&(l.has(p)||c.push([p,this.cdn.buildEsmUrl(i(p),{})]),c.push([`${p}/`,`${lt}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...vn(e.meta),...Oc(e.meta)])].filter(n=>t.has(n))}};ur.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as Dp,satisfies as Gx,maxSatisfying as Bp,major as zx,valid as Xx}from"semver";var Zs=class{cmp(e,t){return e===t?0:Dp(e,t)?1:Dp(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Gx(t,e,{includePrerelease:!0})}selectBestVersion(e,t){if(!e?.length)return;let n=t?.range?.trim()||"*",s=t?.preferStable??!0,i=t?.distTags?.latest;if(i&&e.includes(i)&&this.satisfies(n,i))return i;if(s){let a=Bp(e,n,{includePrerelease:!1});if(a)return a}return Bp(e,n,{includePrerelease:!0})??void 0}majorOf(e){return zx(e)}isExactVersion(e){return Xx(e)!==null}},Nt=new Zs;var It=class{constructor(e){this.store=e}async isNegative(e){let t=await le(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await le(()=>this.store.get(e)))?.attempts||0)+1;await le(()=>this.store.set(e,{until:Date.now()+Qx(n),attempts:n}))}async clearNegative(e){await le(()=>this.store.delete(e))}};function Qx(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}function jp(r,e){let t=new wn(r,e),n=new Sn(t),s=new xn(r,t,Nt);return{packageService:new ur(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as Wp from"fs/promises";import*as Se from"path";import*as dt from"fs/promises";import*as Ke from"path";import*as Up from"os";import*as _c from"fs/promises";import*as Fp from"crypto";function ve(r){return Fp.createHash("sha1").update(r).digest("hex")}async function Je(r){try{return JSON.parse(await _c.readFile(r,"utf8"))}catch{return}}async function ei(r){try{return await _c.readFile(r,"utf8")}catch{return}}var qp=1,ut=Ke.join(Up.homedir(),".typebulb","cache"),kn=Ke.join(ut,"packages"),En=Ke.join(ut,"proxy"),ti=Ke.join(ut,"dts"),Zx=Ke.join(ut,"emit"),Cc;function V(){return Cc||(Cc=ek()),Cc}function ri(r,e){return Ke.join(Zx,ve(r),e)}async function ek(){await dt.mkdir(ut,{recursive:!0});let r=Ke.join(ut,"version.json");if((await Je(r))?.version===qp)return;let t=await dt.readdir(ut).catch(()=>[]);await Promise.all(t.map(n=>dt.rm(Ke.join(ut,n),{recursive:!0,force:!0}))),await dt.writeFile(r,JSON.stringify({version:qp})+`
|
|
734
|
-
`,"utf8")}import*as ft from"fs/promises";import*as Jp from"path";async function me(r,e){await ft.mkdir(Jp.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await ft.writeFile(t,e,"utf8"),await ft.rename(t,r).catch(async n=>{throw await ft.rm(t,{force:!0}).catch(()=>{}),n})}var dr=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=Je(this.filePath).then(e=>(this.mem=new Map(Object.entries(e??{})),this.mem))),this.loadPromise)}async get(e){return(await this.load()).get(e)}async set(e,t){let n=await this.load();n.set(e,t),await this.persist(n)}async delete(e){let t=await this.load();t.delete(e)&&await this.persist(t)}async persist(e){await me(this.filePath,JSON.stringify(Object.fromEntries(e)))}};var Rc=Se.join(kn,"indexes"),Kp=Se.join(kn,"pinned"),tk=Se.join(kn,"meta"),rk=Se.join(kn,"negative.json"),si=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new It(new dr(rk));async getPinnedExact(e,t){let n=`${e}@${t}`;if(this.pinnedMem.has(n))return this.pinnedMem.get(n);await V();let s=await ei(Se.join(Kp,ve(n)+".txt"));return this.pinnedMem.set(n,s),s}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await V(),await me(Se.join(Kp,ve(s)+".txt"),n)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await V();let t=await Je(Se.join(Rc,ni(e)+".json"));return this.indexMem.set(e,t),t}async setIndex(e,t,n){let s={versions:t,distTags:n,updatedAt:Date.now()};this.indexMem.set(e,s),await V(),await me(Se.join(Rc,ni(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await Wp.rm(Se.join(Rc,ni(e)+".json"),{force:!0})}async isNegative(e){return await V(),this.negativeCache.isNegative(e)}async recordNegative(e){await V(),await this.negativeCache.recordNegative(e)}async clearNegative(e){await this.negativeCache.clearNegative(e)}async getMeta(e,t){let n=`${e}@${t}`;if(this.metaMem.has(n))return this.metaMem.get(n);await V();let s=await Je(Hp(e,t));return this.metaMem.set(n,s),s}async setMeta(e,t,n,s,i){let o={dependencies:n,peerDependencies:s,peerDependenciesMeta:i,updatedAt:Date.now()};this.metaMem.set(`${e}@${t}`,o),await V(),await me(Hp(e,t),JSON.stringify(o))}};function Hp(r,e){return Se.join(tk,ni(r),encodeURIComponent(e)+".json")}function ni(r){return r.replace(/\//g,"__")}var Yp={async getJson(r){try{let e=await fetch(r,{redirect:"follow"});return e.ok?await e.json():void 0}catch{return}},async head(r){try{let e=await fetch(r,{method:"HEAD",redirect:"follow"});return{ok:e.ok,url:e.url}}catch{return}}};var nk=new si,{packageService:ii,versionResolver:Vp,cdnClient:Gp,peerResolver:XC}=jp(nk,Yp);var zp=`
|
|
735
|
-
(() => {
|
|
736
|
-
// Embedded (bulb-in-a-bulb): runs inside a sandboxed iframe with no parent
|
|
737
|
-
// bridge, so privileged tb.* (AI, fs, server RPC) can't reach a host and would
|
|
738
|
-
// otherwise fail with cryptic CORS/CSP errors. Detect it and fail clearly.
|
|
739
|
-
//
|
|
740
|
-
// The host injects window.__TB_EMBED_ERR__ to override the text; absent it, the
|
|
741
|
-
// nested-bulb wording applies. (The CLI's untrusted launch is NOT this path \u2014 it's
|
|
742
|
-
// a top-level page, and its \`--trust\` message comes from the server 403.)
|
|
743
|
-
const isEmbedded = window.parent !== window;
|
|
744
|
-
const embedErr = (name) => new Error(
|
|
745
|
-
typeof window.__TB_EMBED_ERR__ === 'function'
|
|
746
|
-
? window.__TB_EMBED_ERR__(name)
|
|
747
|
-
: name + ' is not available in an embedded bulb (no host bridge).'
|
|
748
|
-
);
|
|
662
|
+
// URL
|
|
663
|
+
url: () => Promise.resolve(location.href),
|
|
749
664
|
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
665
|
+
// Proxy: rewrite CDN URLs to the local server's /proxy/. Absolute when we have a
|
|
666
|
+
// real origin (the CLI page, or a broken-out bulb) so the URL also works from a
|
|
667
|
+
// worker's importScripts, which rejects a root-relative path. Relative in a
|
|
668
|
+
// null-origin srcdoc embed, where prefixing the "null" origin would yield the
|
|
669
|
+
// broken string null/proxy/... ; there the relative path resolves against the
|
|
670
|
+
// host page. Absolute and root-relative are equivalent for every other consumer
|
|
671
|
+
// (fetch, new Worker, script src) when there is one real origin, so this only
|
|
672
|
+
// adds the importScripts case and changes nothing else.
|
|
673
|
+
proxy: (url) => {
|
|
674
|
+
if (!url) return url;
|
|
675
|
+
const i = url.lastIndexOf('https://');
|
|
676
|
+
const clean = i !== -1 ? url.slice(i) : url;
|
|
677
|
+
if (!clean.startsWith('https://')) return url;
|
|
678
|
+
const rel = '/proxy/' + clean;
|
|
679
|
+
return location.origin && location.origin !== 'null' ? location.origin + rel : rel;
|
|
680
|
+
},
|
|
759
681
|
|
|
760
|
-
|
|
761
|
-
|
|
682
|
+
// Server API - call functions from **server.ts**. Returns the hybrid call object: await it for
|
|
683
|
+
// a normal export's result, or for-await it for an async-generator export's stream.
|
|
684
|
+
api: (name, ...args) => serverCall(name, args),
|
|
762
685
|
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
body: JSON.stringify({ hash: location.hash })
|
|
772
|
-
})
|
|
773
|
-
.then((r) => r.json())
|
|
774
|
-
.then((res) => {
|
|
775
|
-
if (res && Array.isArray(res.data)) {
|
|
776
|
-
window.__TB_INSIGHT__ = res.insightJson;
|
|
777
|
-
window.__TB_DATA__ = res.data;
|
|
778
|
-
} else {
|
|
779
|
-
console.warn('[typebulb] The #tb= fragment could not be decoded (incomplete or corrupted link) \u2014 using the bulb file state.');
|
|
780
|
-
}
|
|
781
|
-
})
|
|
782
|
-
.catch(() => {});
|
|
783
|
-
}
|
|
686
|
+
// Server proxy - tb.server.fn(...) delegates to serverCall. 'log' is special: it's the ungated
|
|
687
|
+
// diagnostic (serverLog -> /__log, built-in only), so it prints untrusted; everything else is a
|
|
688
|
+
// gated /__api call into the bulb's own server.ts.
|
|
689
|
+
server: new Proxy({}, {
|
|
690
|
+
get: (_, name) => name === 'log'
|
|
691
|
+
? (...args) => serverLog(...args)
|
|
692
|
+
: (...args) => serverCall(name, args)
|
|
693
|
+
}),
|
|
784
694
|
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
const messageHandlers = new Set();
|
|
788
|
-
const parseMsg = (s) => { if (s === '' || s == null) return undefined; try { return JSON.parse(s); } catch { return s; } };
|
|
695
|
+
// Filesystem - local CLI extension
|
|
696
|
+
fs,
|
|
789
697
|
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
698
|
+
// The bulb's folder, absolute (TB-FS.md) \u2014 for interop (paths handed to server.ts or
|
|
699
|
+
// spawned tools); tb.fs itself already resolves relative paths against it. Absent in an
|
|
700
|
+
// embed (no filesystem to name), where access throws like tb.fs.
|
|
701
|
+
get dir() {
|
|
702
|
+
if (isEmbedded || !window.__TB_DIR__) throw embedErr('tb.dir');
|
|
703
|
+
return window.__TB_DIR__;
|
|
704
|
+
},
|
|
795
705
|
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
};
|
|
804
|
-
const fetchFileBytes = async (path) => {
|
|
805
|
-
if (isEmbedded) throw embedErr('tb.fs');
|
|
806
|
-
const resp = await fetch('/__fs/read', {
|
|
807
|
-
method: 'POST',
|
|
808
|
-
headers: { 'Content-Type': 'application/json' },
|
|
809
|
-
body: JSON.stringify({ path })
|
|
810
|
-
});
|
|
811
|
-
await failIfNotOk(resp, 'read', path);
|
|
812
|
-
return resp.arrayBuffer();
|
|
813
|
-
};
|
|
814
|
-
const fs = {
|
|
815
|
-
read: async (path) => {
|
|
816
|
-
const buf = await fetchFileBytes(path);
|
|
817
|
-
try {
|
|
818
|
-
return new TextDecoder('utf-8', { fatal: true }).decode(buf);
|
|
819
|
-
} catch {
|
|
820
|
-
throw new Error('File is not valid UTF-8 text: ' + path + ' \u2014 use tb.fs.readBytes() for binary files.');
|
|
821
|
-
}
|
|
706
|
+
// Receive a value pushed from the terminal via \`typebulb send\` (data-in, the dual of the
|
|
707
|
+
// ungated tb.server.log). Returns an unsubscribe fn. Inert when embedded \u2014 no server, so no
|
|
708
|
+
// sender; the handler is registered but never fires (cf. tb.models returning []). A handler's
|
|
709
|
+
// non-undefined return (awaited) becomes the reply \`send --wait\` prints (TB-Interrogation.md).
|
|
710
|
+
onMessage: (handler) => {
|
|
711
|
+
if (typeof handler === 'function') messageHandlers.add(handler);
|
|
712
|
+
return () => messageHandlers.delete(handler);
|
|
822
713
|
},
|
|
823
|
-
readBytes: async (path) => new Uint8Array(await fetchFileBytes(path)),
|
|
824
|
-
write: async (path, content) => {
|
|
825
|
-
if (isEmbedded) throw embedErr('tb.fs');
|
|
826
|
-
const resp = await fetch('/__fs/write?path=' + encodeURIComponent(path), {
|
|
827
|
-
method: 'POST',
|
|
828
|
-
body: content
|
|
829
|
-
});
|
|
830
|
-
await failIfNotOk(resp, 'write', path);
|
|
831
|
-
return true;
|
|
832
|
-
}
|
|
833
|
-
};
|
|
834
714
|
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
try {
|
|
838
|
-
await navigator.clipboard.writeText(String(text));
|
|
839
|
-
return true;
|
|
840
|
-
} catch {
|
|
841
|
-
return false;
|
|
842
|
-
}
|
|
843
|
-
};
|
|
715
|
+
// Environment ('embedded' when running as a bulb-in-a-bulb)
|
|
716
|
+
mode: isEmbedded ? 'embedded' : 'local',
|
|
844
717
|
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
if (isEmbedded) { console.log(...args); return; }
|
|
852
|
-
try {
|
|
853
|
-
const resp = await fetch('/__log', {
|
|
854
|
-
method: 'POST',
|
|
855
|
-
headers: { 'Content-Type': 'application/json' },
|
|
856
|
-
body: JSON.stringify({ args })
|
|
857
|
-
});
|
|
858
|
-
if (!resp.ok) console.log(...args);
|
|
859
|
-
} catch { console.log(...args); }
|
|
860
|
-
};
|
|
718
|
+
// Theme accessor - delegates to the head-script engine (window.__tbTheme).
|
|
719
|
+
// Get: override slot ('dark'|'light'|undefined). Set applies + persists
|
|
720
|
+
// per-bulb; undefined clears the override.
|
|
721
|
+
get theme() { return window.__tbTheme ? window.__tbTheme.get() : undefined; },
|
|
722
|
+
set theme(v) { if (window.__tbTheme) window.__tbTheme.set(v); }
|
|
723
|
+
});
|
|
861
724
|
|
|
862
|
-
//
|
|
863
|
-
// the
|
|
864
|
-
//
|
|
865
|
-
//
|
|
866
|
-
//
|
|
867
|
-
|
|
868
|
-
const
|
|
869
|
-
|
|
870
|
-
const
|
|
871
|
-
const
|
|
872
|
-
|
|
873
|
-
const
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
}
|
|
882
|
-
return env.type === 'chunk' ? { value: env.value } : undefined;
|
|
725
|
+
// tb:snapshot \u2014 the page serializes its own accessibility outline (roles, names, visible text;
|
|
726
|
+
// the YAML-not-pixels shape) as the reply to \`typebulb send <file> tb:snapshot\`
|
|
727
|
+
// (TB-Interrogation.md). Heuristic by design: explicit role attr, a small
|
|
728
|
+
// implicit-role map, aria-label/alt/value then visible text for names \u2014 enough to catch
|
|
729
|
+
// text/structure divergence, which is what an agent can judge without pixels.
|
|
730
|
+
const IMPLICIT_ROLES = { BUTTON: 'button', SELECT: 'combobox', TEXTAREA: 'textbox', OPTION: 'option', IMG: 'img', NAV: 'navigation', MAIN: 'main', HEADER: 'banner', FOOTER: 'contentinfo', ASIDE: 'complementary', FORM: 'form', DIALOG: 'dialog', TABLE: 'table', TR: 'row', TH: 'columnheader', TD: 'cell', UL: 'list', OL: 'list', LI: 'listitem', LABEL: 'label', P: 'paragraph', PROGRESS: 'progressbar', SUMMARY: 'button', FIGURE: 'figure', BLOCKQUOTE: 'blockquote', HR: 'separator' };
|
|
731
|
+
const INPUT_ROLES = { checkbox: 'checkbox', radio: 'radio', range: 'slider', number: 'spinbutton', search: 'searchbox', button: 'button', submit: 'button', reset: 'button', hidden: '' };
|
|
732
|
+
const snapshot = () => {
|
|
733
|
+
const MAX_LINES = 400;
|
|
734
|
+
const squash = (s) => (s || '').replace(/\\s+/g, ' ').trim();
|
|
735
|
+
const clip = (s) => (s.length > 200 ? s.slice(0, 200) + '\u2026' : s);
|
|
736
|
+
const roleOf = (el) => {
|
|
737
|
+
const explicit = el.getAttribute('role');
|
|
738
|
+
if (explicit) return explicit;
|
|
739
|
+
const t = el.tagName;
|
|
740
|
+
if (t === 'A') return el.hasAttribute('href') ? 'link' : '';
|
|
741
|
+
if (t === 'INPUT') { const r = INPUT_ROLES[(el.getAttribute('type') || 'text').toLowerCase()]; return r === undefined ? 'textbox' : r; }
|
|
742
|
+
if (/^H[1-6]$/.test(t)) return 'heading';
|
|
743
|
+
return IMPLICIT_ROLES[t] || '';
|
|
883
744
|
};
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
745
|
+
const hiddenEl = (el) => {
|
|
746
|
+
if (el.hidden || el.getAttribute('aria-hidden') === 'true') return true;
|
|
747
|
+
const cs = getComputedStyle(el);
|
|
748
|
+
return cs.display === 'none' || cs.visibility === 'hidden';
|
|
749
|
+
};
|
|
750
|
+
const lines = [];
|
|
751
|
+
const walk = (node, depth) => {
|
|
752
|
+
for (let ch = node.firstChild; ch && lines.length <= MAX_LINES; ch = ch.nextSibling) {
|
|
753
|
+
if (ch.nodeType === 3) {
|
|
754
|
+
const t = squash(ch.nodeValue);
|
|
755
|
+
if (t) lines.push(' '.repeat(depth) + '- text: ' + clip(t));
|
|
756
|
+
continue;
|
|
894
757
|
}
|
|
758
|
+
if (ch.nodeType !== 1) continue;
|
|
759
|
+
const tag = ch.tagName;
|
|
760
|
+
if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'TEMPLATE' || tag === 'NOSCRIPT' || tag === 'LINK' || tag === 'META') continue;
|
|
761
|
+
if (hiddenEl(ch)) continue;
|
|
762
|
+
const role = roleOf(ch);
|
|
763
|
+
if (!role) { walk(ch, depth); continue; } // structural (div/span/\u2026): descend transparently
|
|
764
|
+
const attr = (n) => squash(ch.getAttribute(n) || '');
|
|
765
|
+
const text = squash(ch.textContent);
|
|
766
|
+
const name = attr('aria-label') || (tag === 'IMG' ? attr('alt') : '') || (typeof ch.value === 'string' ? squash(ch.value) || attr('placeholder') : '') || text;
|
|
767
|
+
let line = role + (name ? ' "' + clip(name) + '"' : '');
|
|
768
|
+
const lv = role === 'heading' ? (attr('aria-level') || (/^H[1-6]$/.test(tag) ? tag.charAt(1) : '')) : '';
|
|
769
|
+
if (lv) line += ' [level=' + lv + ']';
|
|
770
|
+
lines.push(' '.repeat(depth) + '- ' + line);
|
|
771
|
+
if (!(name && name === text)) walk(ch, depth + 1); // subtree \u2261 name \u21D2 the one line says it all
|
|
895
772
|
}
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
}
|
|
901
|
-
}
|
|
902
|
-
|
|
903
|
-
// Shared /__ai transport: embed guard, POST (stream:true flags the NDJSON path \u2014 JSON.stringify
|
|
904
|
-
// drops the key when undefined, so the non-streaming body is unchanged), 403 \u2192 trust hint.
|
|
905
|
-
const aiFetch = async (what, { messages, system, effort, provider, model, webSearch, signal } = {}, stream) => {
|
|
906
|
-
if (isEmbedded) throw embedErr(what);
|
|
907
|
-
const resp = await fetch('/__ai', {
|
|
908
|
-
method: 'POST',
|
|
909
|
-
headers: { 'Content-Type': 'application/json' },
|
|
910
|
-
body: JSON.stringify({ messages, system, effort, provider, model, webSearch, stream }),
|
|
911
|
-
signal
|
|
912
|
-
});
|
|
913
|
-
await deny403(resp, what);
|
|
914
|
-
return resp;
|
|
915
|
-
};
|
|
916
|
-
const aiError = (data) => {
|
|
917
|
-
const err = new Error(data.message || 'tb.ai() call failed');
|
|
918
|
-
err.code = data.code || 'unknown';
|
|
919
|
-
err.retryable = !!data.retryable;
|
|
920
|
-
return err;
|
|
921
|
-
};
|
|
922
|
-
// tb.ai(): non-streaming, resolves with the full { text } (unchanged 90% path).
|
|
923
|
-
const aiCall = async (opts) => {
|
|
924
|
-
const resp = await aiFetch('tb.ai()', opts, undefined);
|
|
925
|
-
const data = await resp.json();
|
|
926
|
-
if (!resp.ok) throw aiError(data);
|
|
927
|
-
return data;
|
|
773
|
+
};
|
|
774
|
+
walk(document.body, 0);
|
|
775
|
+
if (lines.length > MAX_LINES) { lines.length = MAX_LINES; lines.push('- \u2026 (truncated)'); }
|
|
776
|
+
return lines.length ? lines.join('\\n') : '(empty page)';
|
|
928
777
|
};
|
|
929
|
-
// tb.ai.stream(): async iterable of AiChunk ({ kind:'text'|'reasoning', text }). Same idiom as a
|
|
930
|
-
// streaming tb.server.<gen>(). Break the loop (or abort the signal) to cancel.
|
|
931
|
-
const aiStream = (opts = {}) => (async function* () {
|
|
932
|
-
const resp = await aiFetch('tb.ai.stream()', opts, true);
|
|
933
|
-
if (!resp.ok && !isStreamResp(resp)) throw aiError(await resp.json().catch(() => ({})));
|
|
934
|
-
yield* readStream(resp);
|
|
935
|
-
})();
|
|
936
|
-
const ai = Object.assign(aiCall, { stream: aiStream });
|
|
937
778
|
|
|
938
|
-
//
|
|
939
|
-
//
|
|
940
|
-
//
|
|
941
|
-
//
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
inferState = 'running';
|
|
948
|
-
// Data priority (matching the .com sandbox): explicit arg > setData overrides > undefined \u2014
|
|
949
|
-
// the modal then seeds from the SOURCE chunks (/__infer-info), the local Data tab, exactly as
|
|
950
|
-
// .com's IDE modal reseeds from the Data tab rather than post-run runtime state.
|
|
951
|
-
let data = opts.data;
|
|
952
|
-
if (data === undefined && dataOverrides) data = Object.values(dataOverrides);
|
|
953
|
-
if (data !== undefined && !Array.isArray(data)) data = [data];
|
|
954
|
-
return new Promise((resolve, reject) => {
|
|
955
|
-
let settled = false;
|
|
956
|
-
const settle = (fn, v) => { if (!settled) { settled = true; fn(v); } };
|
|
957
|
-
import('/__infer-ui.js').then((ui) => {
|
|
958
|
-
ui.runInference({
|
|
959
|
-
data,
|
|
960
|
-
// The transport reader is the shim's \u2014 one NDJSON decoder per page, never two
|
|
961
|
-
// drifting copies (TB-Streaming.md envelope: payload-side, so drift is not tolerable).
|
|
962
|
-
readStream,
|
|
963
|
-
onComplete: (final) => {
|
|
964
|
-
// Runtime state only, never the file (TB-Inference.md Invariant 2).
|
|
965
|
-
window.__TB_INSIGHT__ = final.insightJson;
|
|
966
|
-
if (final.data && final.data.length) window.__TB_DATA__ = final.data;
|
|
967
|
-
if (final.hash) history.replaceState(null, '', location.pathname + location.search + final.hash);
|
|
968
|
-
inferState = 'complete';
|
|
969
|
-
settle(resolve, final.insight);
|
|
970
|
-
},
|
|
971
|
-
onError: (err) => {
|
|
972
|
-
inferState = 'error';
|
|
973
|
-
const e = new Error(err.message); e.code = err.code; e.retryable = !!err.retryable;
|
|
974
|
-
settle(reject, e);
|
|
975
|
-
},
|
|
976
|
-
onCancel: () => {
|
|
977
|
-
if (!settled) { inferState = 'idle'; settle(resolve, undefined); }
|
|
978
|
-
}
|
|
979
|
-
});
|
|
980
|
-
}).catch((e) => { inferState = 'error'; settle(reject, e); });
|
|
779
|
+
// Events channel (dev server only): 'reload' drives hot reload (only emitted when watching),
|
|
780
|
+
// 'message' delivers \`typebulb send\` pushes to tb.onMessage. Connect for a CLI-served page (http
|
|
781
|
+
// origin, not an embed); a srcdoc embed or a file:// static export has no server, so onMessage just
|
|
782
|
+
// stays inert there. Opening it independent of watch is what lets send reach a --no-watch page.
|
|
783
|
+
if (!isEmbedded && location.protocol.indexOf('http') === 0) {
|
|
784
|
+
const es = new EventSource('/__reload');
|
|
785
|
+
es.addEventListener('reload', () => {
|
|
786
|
+
console.log('[typebulb] Reloading...');
|
|
787
|
+
window.location.reload();
|
|
981
788
|
});
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
const
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
if (
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
[Symbol.asyncIterator]: iterate
|
|
1018
|
-
};
|
|
1019
|
-
};
|
|
1020
|
-
|
|
1021
|
-
// tb namespace
|
|
1022
|
-
globalThis.tb = Object.freeze({
|
|
1023
|
-
data: (index) => getData()[index],
|
|
1024
|
-
json: (index) => parseJson(getData()[index]),
|
|
1025
|
-
insight: () => window.__TB_INSIGHT__ ? parseJson(window.__TB_INSIGHT__) : undefined,
|
|
1026
|
-
|
|
1027
|
-
// Inference (TB-Inference.md) \u2014 modal-hosted one-shot LLM call over the bulb's own blocks
|
|
1028
|
-
infer,
|
|
1029
|
-
inferenceState: () => inferState,
|
|
1030
|
-
setData: (index, content) => { if (!dataOverrides) dataOverrides = {}; dataOverrides[index] = content; },
|
|
1031
|
-
resetInferenceState: () => { inferState = 'idle'; dataOverrides = null; },
|
|
1032
|
-
|
|
1033
|
-
// AI - tb.ai() proxies to the provider via the local server; tb.ai.stream() streams AiChunks.
|
|
1034
|
-
ai,
|
|
1035
|
-
|
|
1036
|
-
// Model discovery - fetches catalog from typebulb.com, filtered by local API keys
|
|
1037
|
-
models: async () => {
|
|
1038
|
-
if (isEmbedded) return [];
|
|
1039
|
-
const resp = await fetch('/__models');
|
|
1040
|
-
if (!resp.ok) return [];
|
|
1041
|
-
return resp.json();
|
|
1042
|
-
},
|
|
1043
|
-
|
|
1044
|
-
// Own-keys check - true when the user's own AI backs tb.ai (env keys, compat endpoint, or Ollama)
|
|
1045
|
-
hasOwnKeys: async () => {
|
|
1046
|
-
if (isEmbedded) return false;
|
|
1047
|
-
const resp = await fetch('/__has-own-keys');
|
|
1048
|
-
if (!resp.ok) return false;
|
|
1049
|
-
return (await resp.json()) === true;
|
|
1050
|
-
},
|
|
1051
|
-
|
|
1052
|
-
// Dump just logs to console in local mode
|
|
1053
|
-
dump: async (...args) => console.log('[tb.dump]', ...args),
|
|
1054
|
-
|
|
1055
|
-
// Clipboard
|
|
1056
|
-
copy,
|
|
1057
|
-
|
|
1058
|
-
// URL
|
|
1059
|
-
url: () => Promise.resolve(location.href),
|
|
1060
|
-
|
|
1061
|
-
// Proxy: rewrite CDN URLs to the local server's /proxy/. Absolute when we have a
|
|
1062
|
-
// real origin (the CLI page, or a broken-out bulb) so the URL also works from a
|
|
1063
|
-
// worker's importScripts, which rejects a root-relative path. Relative in a
|
|
1064
|
-
// null-origin srcdoc embed, where prefixing the "null" origin would yield the
|
|
1065
|
-
// broken string null/proxy/... ; there the relative path resolves against the
|
|
1066
|
-
// host page. Absolute and root-relative are equivalent for every other consumer
|
|
1067
|
-
// (fetch, new Worker, script src) when there is one real origin, so this only
|
|
1068
|
-
// adds the importScripts case and changes nothing else.
|
|
1069
|
-
proxy: (url) => {
|
|
1070
|
-
if (!url) return url;
|
|
1071
|
-
const i = url.lastIndexOf('https://');
|
|
1072
|
-
const clean = i !== -1 ? url.slice(i) : url;
|
|
1073
|
-
if (!clean.startsWith('https://')) return url;
|
|
1074
|
-
const rel = '/proxy/' + clean;
|
|
1075
|
-
return location.origin && location.origin !== 'null' ? location.origin + rel : rel;
|
|
1076
|
-
},
|
|
1077
|
-
|
|
1078
|
-
// Server API - call functions from **server.ts**. Returns the hybrid call object: await it for
|
|
1079
|
-
// a normal export's result, or for-await it for an async-generator export's stream.
|
|
1080
|
-
api: (name, ...args) => serverCall(name, args),
|
|
1081
|
-
|
|
1082
|
-
// Server proxy - tb.server.fn(...) delegates to serverCall. 'log' is special: it's the ungated
|
|
1083
|
-
// diagnostic (serverLog -> /__log, built-in only), so it prints untrusted; everything else is a
|
|
1084
|
-
// gated /__api call into the bulb's own server.ts.
|
|
1085
|
-
server: new Proxy({}, {
|
|
1086
|
-
get: (_, name) => name === 'log'
|
|
1087
|
-
? (...args) => serverLog(...args)
|
|
1088
|
-
: (...args) => serverCall(name, args)
|
|
1089
|
-
}),
|
|
1090
|
-
|
|
1091
|
-
// Filesystem - local CLI extension
|
|
1092
|
-
fs,
|
|
1093
|
-
|
|
1094
|
-
// The bulb's folder, absolute (TB-FS.md) \u2014 for interop (paths handed to server.ts or
|
|
1095
|
-
// spawned tools); tb.fs itself already resolves relative paths against it. Absent in an
|
|
1096
|
-
// embed (no filesystem to name), where access throws like tb.fs.
|
|
1097
|
-
get dir() {
|
|
1098
|
-
if (isEmbedded || !window.__TB_DIR__) throw embedErr('tb.dir');
|
|
1099
|
-
return window.__TB_DIR__;
|
|
1100
|
-
},
|
|
1101
|
-
|
|
1102
|
-
// Receive a value pushed from the terminal via \`typebulb send\` (data-in, the dual of the
|
|
1103
|
-
// ungated tb.server.log). Returns an unsubscribe fn. Inert when embedded \u2014 no server, so no
|
|
1104
|
-
// sender; the handler is registered but never fires (cf. tb.models returning []). A handler's
|
|
1105
|
-
// non-undefined return (awaited) becomes the reply \`send --wait\` prints (TB-Interrogation.md).
|
|
1106
|
-
onMessage: (handler) => {
|
|
1107
|
-
if (typeof handler === 'function') messageHandlers.add(handler);
|
|
1108
|
-
return () => messageHandlers.delete(handler);
|
|
1109
|
-
},
|
|
1110
|
-
|
|
1111
|
-
// Environment ('embedded' when running as a bulb-in-a-bulb)
|
|
1112
|
-
mode: isEmbedded ? 'embedded' : 'local',
|
|
1113
|
-
|
|
1114
|
-
// Theme accessor - delegates to the head-script engine (window.__tbTheme).
|
|
1115
|
-
// Get: override slot ('dark'|'light'|undefined). Set applies + persists
|
|
1116
|
-
// per-bulb; undefined clears the override.
|
|
1117
|
-
get theme() { return window.__tbTheme ? window.__tbTheme.get() : undefined; },
|
|
1118
|
-
set theme(v) { if (window.__tbTheme) window.__tbTheme.set(v); }
|
|
1119
|
-
});
|
|
1120
|
-
|
|
1121
|
-
// tb:snapshot \u2014 the page serializes its own accessibility outline (roles, names, visible text;
|
|
1122
|
-
// the YAML-not-pixels shape) as the reply to \`typebulb send <file> tb:snapshot\`
|
|
1123
|
-
// (TB-Interrogation.md). Heuristic by design: explicit role attr, a small
|
|
1124
|
-
// implicit-role map, aria-label/alt/value then visible text for names \u2014 enough to catch
|
|
1125
|
-
// text/structure divergence, which is what an agent can judge without pixels.
|
|
1126
|
-
const IMPLICIT_ROLES = { BUTTON: 'button', SELECT: 'combobox', TEXTAREA: 'textbox', OPTION: 'option', IMG: 'img', NAV: 'navigation', MAIN: 'main', HEADER: 'banner', FOOTER: 'contentinfo', ASIDE: 'complementary', FORM: 'form', DIALOG: 'dialog', TABLE: 'table', TR: 'row', TH: 'columnheader', TD: 'cell', UL: 'list', OL: 'list', LI: 'listitem', LABEL: 'label', P: 'paragraph', PROGRESS: 'progressbar', SUMMARY: 'button', FIGURE: 'figure', BLOCKQUOTE: 'blockquote', HR: 'separator' };
|
|
1127
|
-
const INPUT_ROLES = { checkbox: 'checkbox', radio: 'radio', range: 'slider', number: 'spinbutton', search: 'searchbox', button: 'button', submit: 'button', reset: 'button', hidden: '' };
|
|
1128
|
-
const snapshot = () => {
|
|
1129
|
-
const MAX_LINES = 400;
|
|
1130
|
-
const squash = (s) => (s || '').replace(/\\s+/g, ' ').trim();
|
|
1131
|
-
const clip = (s) => (s.length > 200 ? s.slice(0, 200) + '\u2026' : s);
|
|
1132
|
-
const roleOf = (el) => {
|
|
1133
|
-
const explicit = el.getAttribute('role');
|
|
1134
|
-
if (explicit) return explicit;
|
|
1135
|
-
const t = el.tagName;
|
|
1136
|
-
if (t === 'A') return el.hasAttribute('href') ? 'link' : '';
|
|
1137
|
-
if (t === 'INPUT') { const r = INPUT_ROLES[(el.getAttribute('type') || 'text').toLowerCase()]; return r === undefined ? 'textbox' : r; }
|
|
1138
|
-
if (/^H[1-6]$/.test(t)) return 'heading';
|
|
1139
|
-
return IMPLICIT_ROLES[t] || '';
|
|
1140
|
-
};
|
|
1141
|
-
const hiddenEl = (el) => {
|
|
1142
|
-
if (el.hidden || el.getAttribute('aria-hidden') === 'true') return true;
|
|
1143
|
-
const cs = getComputedStyle(el);
|
|
1144
|
-
return cs.display === 'none' || cs.visibility === 'hidden';
|
|
1145
|
-
};
|
|
1146
|
-
const lines = [];
|
|
1147
|
-
const walk = (node, depth) => {
|
|
1148
|
-
for (let ch = node.firstChild; ch && lines.length <= MAX_LINES; ch = ch.nextSibling) {
|
|
1149
|
-
if (ch.nodeType === 3) {
|
|
1150
|
-
const t = squash(ch.nodeValue);
|
|
1151
|
-
if (t) lines.push(' '.repeat(depth) + '- text: ' + clip(t));
|
|
1152
|
-
continue;
|
|
1153
|
-
}
|
|
1154
|
-
if (ch.nodeType !== 1) continue;
|
|
1155
|
-
const tag = ch.tagName;
|
|
1156
|
-
if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'TEMPLATE' || tag === 'NOSCRIPT' || tag === 'LINK' || tag === 'META') continue;
|
|
1157
|
-
if (hiddenEl(ch)) continue;
|
|
1158
|
-
const role = roleOf(ch);
|
|
1159
|
-
if (!role) { walk(ch, depth); continue; } // structural (div/span/\u2026): descend transparently
|
|
1160
|
-
const attr = (n) => squash(ch.getAttribute(n) || '');
|
|
1161
|
-
const text = squash(ch.textContent);
|
|
1162
|
-
const name = attr('aria-label') || (tag === 'IMG' ? attr('alt') : '') || (typeof ch.value === 'string' ? squash(ch.value) || attr('placeholder') : '') || text;
|
|
1163
|
-
let line = role + (name ? ' "' + clip(name) + '"' : '');
|
|
1164
|
-
const lv = role === 'heading' ? (attr('aria-level') || (/^H[1-6]$/.test(tag) ? tag.charAt(1) : '')) : '';
|
|
1165
|
-
if (lv) line += ' [level=' + lv + ']';
|
|
1166
|
-
lines.push(' '.repeat(depth) + '- ' + line);
|
|
1167
|
-
if (!(name && name === text)) walk(ch, depth + 1); // subtree \u2261 name \u21D2 the one line says it all
|
|
1168
|
-
}
|
|
1169
|
-
};
|
|
1170
|
-
walk(document.body, 0);
|
|
1171
|
-
if (lines.length > MAX_LINES) { lines.length = MAX_LINES; lines.push('- \u2026 (truncated)'); }
|
|
1172
|
-
return lines.length ? lines.join('\\n') : '(empty page)';
|
|
1173
|
-
};
|
|
1174
|
-
|
|
1175
|
-
// Events channel (dev server only): 'reload' drives hot reload (only emitted when watching),
|
|
1176
|
-
// 'message' delivers \`typebulb send\` pushes to tb.onMessage. Connect for a CLI-served page (http
|
|
1177
|
-
// origin, not an embed); a srcdoc embed or a file:// static export has no server, so onMessage just
|
|
1178
|
-
// stays inert there. Opening it independent of watch is what lets send reach a --no-watch page.
|
|
1179
|
-
if (!isEmbedded && location.protocol.indexOf('http') === 0) {
|
|
1180
|
-
const es = new EventSource('/__reload');
|
|
1181
|
-
es.addEventListener('reload', () => {
|
|
1182
|
-
console.log('[typebulb] Reloading...');
|
|
1183
|
-
window.location.reload();
|
|
1184
|
-
});
|
|
1185
|
-
es.addEventListener('message', async (e) => {
|
|
1186
|
-
// Wire envelope { id?, payload } (JSON \u2014 SSE-line-safe). tb:* payloads are the shim's reserved
|
|
1187
|
-
// namespace (TB-Interrogation.md): answered by a built-in handler, never delivered to
|
|
1188
|
-
// tb.onMessage. Each settled non-undefined return is a reply candidate \u2014 the CLI enforces the
|
|
1189
|
-
// one-reply rule, the shim just reports what it collected.
|
|
1190
|
-
let env;
|
|
1191
|
-
try { env = JSON.parse(e.data) || {}; } catch { return; }
|
|
1192
|
-
const errText = (err) => String((err && err.message) || err);
|
|
1193
|
-
const results = []; const errors = [];
|
|
1194
|
-
const keep = (v) => {
|
|
1195
|
-
try {
|
|
1196
|
-
const enc = JSON.stringify(v);
|
|
1197
|
-
if (enc === undefined) throw new Error('unsupported value');
|
|
1198
|
-
results.push(enc);
|
|
1199
|
-
} catch (err) { errors.push('reply is not JSON-serializable: ' + errText(err)); }
|
|
1200
|
-
};
|
|
1201
|
-
const reservedCall = async () => {
|
|
1202
|
-
if (env.payload === 'tb:snapshot') return snapshot();
|
|
1203
|
-
throw new Error('unknown reserved message: ' + env.payload);
|
|
1204
|
-
};
|
|
1205
|
-
const value = parseMsg(env.payload);
|
|
1206
|
-
const calls = typeof env.payload === 'string' && env.payload.indexOf('tb:') === 0
|
|
1207
|
-
? [reservedCall]
|
|
1208
|
-
: Array.from(messageHandlers, (h) => async () => h(value));
|
|
1209
|
-
for (const s of await Promise.allSettled(calls.map((f) => f()))) {
|
|
1210
|
-
if (s.status === 'rejected') { console.error(s.reason); errors.push(errText(s.reason)); }
|
|
1211
|
-
else if (s.value !== undefined) keep(s.value);
|
|
1212
|
-
}
|
|
1213
|
-
if (env.id !== undefined) {
|
|
1214
|
-
try { fetch('/__send-reply', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: env.id, results, errors }) }); } catch {}
|
|
1215
|
-
}
|
|
1216
|
-
});
|
|
1217
|
-
es.onerror = () => {
|
|
1218
|
-
// Server closed, stop trying
|
|
1219
|
-
es.close();
|
|
789
|
+
es.addEventListener('message', async (e) => {
|
|
790
|
+
// Wire envelope { id?, payload } (JSON \u2014 SSE-line-safe). tb:* payloads are the shim's reserved
|
|
791
|
+
// namespace (TB-Interrogation.md): answered by a built-in handler, never delivered to
|
|
792
|
+
// tb.onMessage. Each settled non-undefined return is a reply candidate \u2014 the CLI enforces the
|
|
793
|
+
// one-reply rule, the shim just reports what it collected.
|
|
794
|
+
let env;
|
|
795
|
+
try { env = JSON.parse(e.data) || {}; } catch { return; }
|
|
796
|
+
const errText = (err) => String((err && err.message) || err);
|
|
797
|
+
const results = []; const errors = [];
|
|
798
|
+
const keep = (v) => {
|
|
799
|
+
try {
|
|
800
|
+
const enc = JSON.stringify(v);
|
|
801
|
+
if (enc === undefined) throw new Error('unsupported value');
|
|
802
|
+
results.push(enc);
|
|
803
|
+
} catch (err) { errors.push('reply is not JSON-serializable: ' + errText(err)); }
|
|
804
|
+
};
|
|
805
|
+
const reservedCall = async () => {
|
|
806
|
+
if (env.payload === 'tb:snapshot') return snapshot();
|
|
807
|
+
throw new Error('unknown reserved message: ' + env.payload);
|
|
808
|
+
};
|
|
809
|
+
const value = parseMsg(env.payload);
|
|
810
|
+
const calls = typeof env.payload === 'string' && env.payload.indexOf('tb:') === 0
|
|
811
|
+
? [reservedCall]
|
|
812
|
+
: Array.from(messageHandlers, (h) => async () => h(value));
|
|
813
|
+
for (const s of await Promise.allSettled(calls.map((f) => f()))) {
|
|
814
|
+
if (s.status === 'rejected') { console.error(s.reason); errors.push(errText(s.reason)); }
|
|
815
|
+
else if (s.value !== undefined) keep(s.value);
|
|
816
|
+
}
|
|
817
|
+
if (env.id !== undefined) {
|
|
818
|
+
try { fetch('/__send-reply', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: env.id, results, errors }) }); } catch {}
|
|
819
|
+
}
|
|
820
|
+
});
|
|
821
|
+
es.onerror = () => {
|
|
822
|
+
// Server closed, stop trying
|
|
823
|
+
es.close();
|
|
1220
824
|
};
|
|
1221
825
|
}
|
|
1222
826
|
})();
|
|
1223
|
-
|
|
1224
|
-
canvas { max-width: 100%; }
|
|
1225
|
-
body { margin: 0; display: flow-root; font-family: system-ui, -apple-system, sans-serif; }
|
|
1226
|
-
html[data-theme="dark"] { color-scheme: dark; }
|
|
1227
|
-
html[data-theme="light"] { color-scheme: light; }`;function ci(r,e){return` <script>
|
|
827
|
+
`});function ki(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Ei(r,e){return` <script>
|
|
1228
828
|
(function() {
|
|
1229
829
|
try {
|
|
1230
|
-
var KEY = ${
|
|
830
|
+
var KEY = ${Ut(JSON.stringify("tb-theme:"+r))};
|
|
1231
831
|
var doc = document.documentElement;
|
|
1232
832
|
var mq = window.matchMedia('(prefers-color-scheme: dark)');
|
|
1233
833
|
var os = function() { return mq.matches ? 'dark' : 'light'; };
|
|
1234
|
-
var FORCED = ${
|
|
834
|
+
var FORCED = ${Ut(JSON.stringify(e??null))};
|
|
1235
835
|
var stored = function() {
|
|
1236
836
|
try { var v = localStorage.getItem(KEY); return (v === 'dark' || v === 'light') ? v : undefined; }
|
|
1237
837
|
catch (e) { return undefined; }
|
|
@@ -1259,19 +859,23 @@ ${Hx(t)}`)}var lt="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Tc="https:
|
|
|
1259
859
|
});
|
|
1260
860
|
} catch (e) {}
|
|
1261
861
|
})();
|
|
1262
|
-
</script>`}
|
|
1263
|
-
|
|
862
|
+
</script>`}var Ut,xi,Qc=S(()=>{Ut=r=>r.replace(/<\/script/gi,"<\\/script");xi=` *, *::before, *::after { box-sizing: border-box; }
|
|
863
|
+
canvas { max-width: 100%; }
|
|
864
|
+
body { margin: 0; display: flow-root; font-family: system-ui, -apple-system, sans-serif; }
|
|
865
|
+
html[data-theme="dark"] { color-scheme: dark; }
|
|
866
|
+
html[data-theme="light"] { color-scheme: light; }`});function Tm(r){let{name:e,code:t,css:n,html:s,data:i,insight:o,importMap:a,theme:c,embedded:l,dir:d}=r,u=s.trim()||'<div id="app"></div>',f=l?"":`
|
|
867
|
+
html, body { height: 100%; }`,p={imports:Lx(a.imports)};return`<!DOCTYPE html>
|
|
1264
868
|
<html>
|
|
1265
869
|
<head>
|
|
1266
870
|
<meta charset="utf-8">
|
|
1267
871
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1268
|
-
<title>${
|
|
1269
|
-
${
|
|
872
|
+
<title>${ki(e)} - typebulb</title>
|
|
873
|
+
${Ei(e,c)}
|
|
1270
874
|
<script type="importmap">
|
|
1271
875
|
${JSON.stringify(p,null,2)}
|
|
1272
876
|
</script>
|
|
1273
877
|
<style>
|
|
1274
|
-
${
|
|
878
|
+
${xi}${f}
|
|
1275
879
|
</style>
|
|
1276
880
|
<style>
|
|
1277
881
|
${n}
|
|
@@ -1280,23 +884,23 @@ ${n}
|
|
|
1280
884
|
<body>
|
|
1281
885
|
${u}
|
|
1282
886
|
|
|
1283
|
-
${i.length>0?`<script>window.__TB_DATA__ = ${
|
|
1284
|
-
${o?`<script>window.__TB_INSIGHT__ = ${
|
|
1285
|
-
${
|
|
887
|
+
${i.length>0?`<script>window.__TB_DATA__ = ${Ut(JSON.stringify(i))};</script>`:""}
|
|
888
|
+
${o?`<script>window.__TB_INSIGHT__ = ${Ut(JSON.stringify(o))};</script>`:""}
|
|
889
|
+
${d?`<script>window.__TB_DIR__ = ${Ut(JSON.stringify(d))};</script>`:""}
|
|
1286
890
|
|
|
1287
891
|
<script>
|
|
1288
|
-
${
|
|
892
|
+
${Em}
|
|
1289
893
|
</script>
|
|
1290
894
|
|
|
1291
|
-
${
|
|
895
|
+
${$x}
|
|
1292
896
|
|
|
1293
897
|
<script type="module">
|
|
1294
898
|
globalThis.__tbEntryRan = true; /* import graph resolved \u2014 the load-failure backstop's signal (imports hoist above this line) */
|
|
1295
899
|
await globalThis.__tbBoot; /* #tb= fragment restore, set by the shim when present (TB-Inference.md) */
|
|
1296
|
-
${
|
|
900
|
+
${Ut(t)}
|
|
1297
901
|
</script>
|
|
1298
902
|
</body>
|
|
1299
|
-
</html>`}var
|
|
903
|
+
</html>`}function Lx(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}var $x,Pm=S(()=>{Am();Qc();$x=`<script>
|
|
1300
904
|
(function () {
|
|
1301
905
|
var framed = window.parent !== window;
|
|
1302
906
|
var post = function (m) { try { parent.postMessage(m, '*'); } catch (e) {} }; /* framed only */
|
|
@@ -1392,8 +996,404 @@ ${$t(t)}
|
|
|
1392
996
|
}
|
|
1393
997
|
});
|
|
1394
998
|
})();
|
|
1395
|
-
</script
|
|
1396
|
-
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await
|
|
999
|
+
</script>`});import*as Ti from"fs/promises";import*as Ai from"path";import{existsSync as Om,readFileSync as Mx}from"fs";import{execFile as Dx}from"child_process";import{promisify as Bx}from"util";import{satisfies as jx}from"semver";async function Pi(r,e,t,n){let i=r.map(l=>Ux(l,t)).filter(l=>!Jx(l,e));if(i.length===0)return;let o=i.filter(l=>!qx.test(l));if(o.length)throw new Error(`Refusing to install npm spec(s) with unsupported characters: ${o.join(", ")}
|
|
1000
|
+
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await Ti.mkdir(e,{recursive:!0});let a=Ai.join(e,"package.json");Om(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 Fx("npm",["install",...c,...i],{cwd:e,shell:!0})}function Ux(r,e){if(!e||B.parse(r).version)return r;let t=e[r];return t?`${r}@${t}`:r}function Jx(r,e){let{name:t,version:n}=B.parse(r),s=Ai.join(e,"node_modules",t);if(!Om(s))return!1;if(!n)return!0;try{let i=JSON.parse(Mx(Ai.join(s,"package.json"),"utf-8")).version;return jx(i,n)}catch{return!1}}function Oi(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(B.rootOf(s))}return[...e]}var Fx,qx,Zc=S(()=>{Ke();Fx=Bx(Dx),qx=/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+(@[a-zA-Z0-9.^~*x-]+)?$/i});var Cm=S(()=>{});var pe,Ee,Sr=S(()=>{pe=class extends Error{constructor(e,t="unknown",n=!1){super(e),this.code=t,this.retryable=n}},Ee=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=`
|
|
1001
|
+
|
|
1002
|
+
`){let n=e.filter(s=>s.role==="system").map(s=>s.content);return{system:n.length?n.join(t):void 0,conversationMessages:e.filter(s=>s.role!=="system")}}parseJsonError(e,t){if(!e)return{message:`HTTP ${t}`};try{let n=JSON.parse(e);return n.error&&typeof n.error=="object"?{message:n.error.message||`HTTP ${t}`,type:n.error.type}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}checkAndThrowError(e){if(typeof e!="object"||e===null)return;let t=e;if(t.type==="error"&&"message"in t){let n=t.code||"unknown";throw new pe(t.message,n,!!t.retryable)}if(t.error){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 pe(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 Ci,el=S(()=>{Sr();Ci=class extends Ee{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(`
|
|
1003
|
+
`)),!t&&s.type==="message"&&s.content&&(t=s.content.filter(i=>i.type==="output_text").map(i=>i.text).join(""));return{text:t,reasoning:n}}parseProviderStreamChunk(e){if(!this.isResponsesApiEvent(e))return null;switch(e.type){case"response.failed":{let n=e.response?.error,s=n?.message||"Response failed",i=n?.code==="insufficient_quota"||n?.code==="rate_limit_exceeded";throw new pe(s,i?"rate_limit":"unknown",i)}case"response.output_text.delta":return{text:e.delta};case"response.reasoning_summary_text.delta":return{reasoning:e.delta};default:return null}}convertMessagesToInput(e){return e.map(t=>t.role==="system"?`System: ${t.content}`:t.role==="user"?`User: ${t.content}`:t.role==="assistant"?`Assistant: ${t.content}`:t.content).join(`
|
|
1004
|
+
|
|
1005
|
+
`)}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 kr,_i=S(()=>{Sr();kr=class extends Ee{parseNonStreamingResponse(e){if(!this.hasChoices(e))return{text:""};let t=e,n=t.choices[0],s=n?.message,i=s?.content??n?.text??"",o=s?.reasoning??s?.reasoning_content??t.reasoning;return{text:i,reasoning:o}}parseProviderStreamChunk(e){if(!this.hasChoices(e))return null;let t=e.choices[0];if(!t)return null;let n=t.delta||t.message;if(!n)return null;let s=n.content||void 0,i=n.reasoning||n.reasoning_content||void 0;return!s&&!i?null:{text:s,reasoning:i}}hasChoices(e){return typeof e=="object"&&e!==null&&"choices"in e&&Array.isArray(e.choices)}}});var Ri,tl=S(()=>{_i();Ri=class extends kr{constructor(){super(...arguments),this.providerName="OpenRouter",this.defaultBaseUrl="https://openrouter.ai",this.path="/api/v1/chat/completions",this.effortMap={0:"none",1:"low",2:"medium",3:"high"}}buildHeaders(e,t){let n={Authorization:`Bearer ${e}`,"x-api-key":e,"Content-Type":"application/json",Accept:"application/json","X-Title":"Typebulb"};return t&&(n["HTTP-Referer"]=t,n.Referer=t,n.Origin=t),n}buildPayload(e,t,n,s){let i={model:t,messages:e,stream:s};n?.webSearch===!0&&(i.plugins=[{id:"web"}]);let o=n?.effort;return o!==void 0&&(i.reasoning={effort:this.effortMap[o]}),i}}});var Ni,rl=S(()=>{Sr();Ni=class extends Ee{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(`
|
|
1006
|
+
|
|
1007
|
+
`);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 Ii,nl=S(()=>{Sr();Ii=class extends Ee{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,`
|
|
1008
|
+
`),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(`
|
|
1009
|
+
`)[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 pe(`Prompt blocked: ${t}`)}}}});var $i,sl=S(()=>{_i();$i=class extends kr{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 Jt(r){let e=Kx.get(r);if(!e)throw new Error(`Unsupported protocol: ${r}`);return e}function Hx(r,e){return r.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function il(r,e){let t=Jt(r.protocol),n=t.getPath(r.model,e.stream),s=Hx(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 Wx(r){return/prompt is too long|context[_ ](length|window)|maximum context|token count exceeds|too many tokens/i.test(r)}async function xr(r,e){let t=Jt(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||Wx(s))&&(o="context_exceeded"),{code:o,message:s,retryable:i===429||i>=500}}var _m,Kx,ol=S(()=>{el();tl();rl();nl();sl();_m=new $i,Kx=new Map([["openai",new Ci],["openrouter",new Ri],["anthropic",new Ni],["gemini",new Ii],["ollama",_m],["openai-compat",_m]])});function Rm(r){let e=r.indexOf(`\r
|
|
1010
|
+
\r
|
|
1011
|
+
`),t=r.indexOf(`
|
|
1012
|
+
|
|
1013
|
+
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function al(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(`
|
|
1014
|
+
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*Nm(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=al(s);u!==null&&u!=="done"&&(yield u)}return}t?.(),s+=n.decode(c,{stream:!0});let{pos:l,len:d}=Rm(s);for(;l!==-1;){let u=s.slice(0,l);s=s.slice(l+d);let f=al(u);if(f==="done")return;f!==null&&(yield f),{pos:l,len:d}=Rm(s)}}}finally{i&&e?.removeEventListener("abort",i);try{await r.cancel()}catch{}}}async function Kt(r,e){if(!r.body)throw new Error("Response body is missing");let t="";for await(let n of Ht(r,e))n.kind==="text"&&(t+=n.text);return t}async function*Ht(r,e){let t=e??(r.headers.get("X-Provider-Protocol")||"openai"),n=Jt(t);if(!r.body)return;let s=r.body.getReader();for await(let i of Nm(s)){let o=n.parseStreamChunk(i);o?.reasoning&&(yield{kind:"reasoning",text:o.reasoning}),o?.text&&(yield{kind:"text",text:o.text})}}var Im=S(()=>{ol()});import{strToU8 as Yx,strFromU8 as Vx,deflateSync as Gx,inflateSync as zx}from"fflate";function ll(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.
|
|
1015
|
+
|
|
1016
|
+
---
|
|
1017
|
+
Instructions:
|
|
1018
|
+
${r.infer||"Process the data and return a JSON object."}`),r.insight&&t.push(`---
|
|
1019
|
+
Example output:
|
|
1020
|
+
${r.insight}`),r.code&&t.push(`---
|
|
1021
|
+
Code that will consume your output:
|
|
1022
|
+
${r.code}`),e.length>0){let n=e.length===1?e[0]:e.map((s,i)=>`[Chunk ${i+1}]
|
|
1023
|
+
${s}`).join(`
|
|
1024
|
+
|
|
1025
|
+
`);t.push(`---
|
|
1026
|
+
Data to process:
|
|
1027
|
+
<data>
|
|
1028
|
+
${n}
|
|
1029
|
+
</data>`)}return t.push(`
|
|
1030
|
+
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(`
|
|
1031
|
+
|
|
1032
|
+
`)}function Ln(r){try{return JSON.parse(r)}catch{return null}}function Qx(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 Zx(r){let e=Qx(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 e0(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 t0(r){let e=null,t=0;for(;t<r.length;){let n=r[t];if(n==="{"||n==="["){let s=e0(r,t);if(s!==-1){let i=r.slice(t,s+1),o=Ln(i);o!==null&&(e={parsed:o,json:i}),t=s+1;continue}}t++}return e}function ul(r){let e=[],t=r.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*\n?/,"").replace(/\n?```\s*$/,""),e.push("markdown fences"));let n=Ln(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=Ln(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=Ln(t),n!==null))return{parsed:n,json:t,fixesApplied:e}}for(let[o,a]of Xx){let c=a(t);if(c!==null){let l=Ln(c);if(l!==null)return{parsed:l,json:c,fixesApplied:[...e,o]}}}let i=t0(r);return i!==null?{...i,fixesApplied:[...e,"extracted last JSON value"]}:{parsed:null,json:t,fixesApplied:e}}function fl(r){try{let e={i:r.insight,d:r.data},t=JSON.stringify(e),n=Gx(Yx(t),{level:9}),s=n0(n),i=`${$m}:${s}`;return i.length>r0?"":"#"+cl+i}catch{return""}}function dl(r){try{let e=r.startsWith("#")?r.slice(1):r;if(!e.startsWith(cl))return null;let t=e.slice(cl.length),n=t.indexOf(":");if(n===-1||t.slice(0,n)!==$m)return null;let s=s0(t.slice(n+1)),i=JSON.parse(Vx(zx(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 n0(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 s0(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 Xx,cl,$m,r0,Lm=S(()=>{Xx=[["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",Zx]];cl="tb=",$m="1",r0=6e4});var Er=S(()=>{Cm();Sr();ol();Im();Lm();_i();rl();nl();el();tl();sl()});function Tr(r){return(r.includes("://")?r:`http://${r}`).replace(/\/+$/,"")}function pl(){return Dn}async function Ye(){let[r,e]=await Promise.all([Dm(),u0()]);return l0([...f0(e),...r],process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL)}function l0(r,e,t){return!e||!t?r:r.map(n=>n.provider===e&&n.name===t?{...n,default:!0}:n)}async function Mm(){let r;try{r=await fetch(i0,{signal:AbortSignal.timeout(a0)})}catch(e){return Dn=`catalog fetch failed: ${e?.message??e}`,null}if(!r.ok)return Dn=`catalog fetch failed: HTTP ${r.status}`,null;try{return await r.json()}catch(e){return Dn=`catalog returned an unreadable body: ${e?.message??e}`,null}}async function u0(){if(Mn&&Date.now()-Mn.fetchedAt<=o0)return Mn.models;let r=await Mm()??await Mm();return r?(Mn={models:r,fetchedAt:Date.now()},Dn=null,r):Mn?.models??[]}async function Dm(){if(Li&&Date.now()-Li.fetchedAt<=c0)return Li.models;let r=Tr(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 Li={models:e,fetchedAt:Date.now()},e}function f0(r){let e=new Set(Object.entries(Ar).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function ml(){return Object.values(Ar).some(r=>!!process.env[r])}async function Mi(){return ml()||process.env.TB_AI_BASE_URL?!0:(await Dm()).length>0}function Bm(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(`
|
|
1033
|
+
`)}var Ar,i0,o0,a0,c0,Mn,Li,Dn,Wt=S(()=>{Ar={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};i0="https://api.typebulb.com/api/models",o0=1440*60*1e3,a0=5e3,c0=60*1e3,Mn=null,Li=null,Dn=null});function Ve(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=Jt(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${Tr(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=Ar[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 yt(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 il(r,{messages:t,stream:!0,effort:n!=null&&n>=0&&n<=3?n:void 0,webSearch:e.webSearch??!0,signal:e.signal})}var Di=S(()=>{Er();Wt()});import*as Pr from"fs/promises";import*as Ge from"path";function Bn(r,e,t=e){let n=Ge.resolve(e,r),s=Ge.normalize(t),i=Ge.normalize(n);if(i!==s&&!i.startsWith(s+Ge.sep))throw new Error("Path traversal detected - access denied");return n}async function jn(r,e,t){return Pr.readFile(Bn(r,e,t))}async function Bi(r,e,t,n){let s=Bn(r,t,n);await Pr.mkdir(Ge.dirname(s),{recursive:!0}),await Pr.writeFile(s,typeof e=="string"?e:Buffer.from(e))}var hl=S(()=>{});async function jm(r){let e=Ve(r.provider,r.model);if(typeof e=="string")throw new Error(e);let t=await yt(e,r);if(!t.ok){let n=await xr(t,e.protocol);throw new Error(n.message)}return{response:t,protocol:e.protocol}}async function d0(r){let{response:e,protocol:t}=await jm(r);return{text:await Kt(e,t)}}async function*p0(r){let{response:e,protocol:t}=await jm(r);yield*Ht(e,t)}function Fm(r,e=process.cwd()){let t=Object.assign(d0,{stream:p0}),n={read:async s=>{let i=await jn(s,r,e);try{return new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{throw new Error(`File is not valid UTF-8 text: ${s} \u2014 use tb.fs.readBytes() for binary files.`)}},readBytes:async s=>new Uint8Array(await jn(s,r,e)),write:async(s,i)=>(await Bi(s,i,r,e),!0)};globalThis.tb=Object.freeze({ai:t,fs:n,dir:r,models:()=>Ye(),hasOwnKeys:Mi,mode:"local"})}var qm=S(()=>{Er();Di();Wt();hl()});import*as bt from"fs/promises";import*as oe from"path";import{pathToFileURL as m0}from"url";async function Um(r){let t=(await bt.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?oe.join(r,t):null}function wt(r,e){let t=oe.resolve(r),n=oe.join(oe.dirname(t),oe.basename(t).replace(/\.bulb\.md$/,""));return e?oe.join(n,e):n}async function Ae(r){let e=await bt.readFile(r,"utf-8"),t=ce(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=hr(t);return{bulb:n,config:rt(n.config),warnings:Yu(e)}}function gl(r){let e=oe.basename(r).replace(/\.bulb\.md$/i,"");return oe.join(oe.dirname(r),".typebulb",`${e}.server.mjs`)}async function Fn(r,e,t,n,s){let i=jc(r,{serverOnly:!0});if(i.error)throw new Error(`Server compilation error: ${i.error}`);let o=i.code;t&&(o=await ju(o,t));let a=oe.join(oe.dirname(e),".typebulb");await bt.mkdir(a,{recursive:!0});let c=Oi(o);c.length>0&&await Pi(c,a,n);let l=gl(e);return await bt.writeFile(l,o,"utf-8"),Fm(wt(e,s)),await import(`${m0(l).href}?t=${Date.now()}`)}async function yl(r,e,t,n,s){let{bulb:i,config:o}=await Ae(r),a=ui(i.data);nm(i.code,o.dependencies??{});let c=jc(i.code,{jsxImportSource:o.ts?.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:l}=await Si.buildImportMap(c.code,o.dependencies??{},n?new Set([n.name]):void 0);n&&(l.imports[n.name]=n.entryUrl);let d=Tm({name:i.name,code:c.code,css:i.css,html:i.html,data:a,insight:i.insight,importMap:l,dir:wt(r,s),watch:e}),u=null;return i.server&&t&&(u=await Fn(i.server,r,n,o.dependencies,s)),{html:d,bulb:i,serverExports:u}}var vt=S(()=>{xn();em();sm();Xc();Pm();Zc();ls();qm()});import{realpathSync as h0}from"fs";import{join as bl,resolve as g0}from"path";import{homedir as y0}from"os";function ji(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?bl(r,".."):bl(y0(),".typebulb")}function ze(){return process.env.TYPEBULB_SERVERS_DIR||bl(ji(),"servers")}function ne(r){let e=g0(r),t=e;try{t=h0.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function Jm(r,e){let t=ne(r),n=ne(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var Fi=S(()=>{});import{readFileSync as b0,writeFileSync as w0,mkdirSync as v0}from"fs";import{join as S0}from"path";function Km(){return S0(ji(),"trust.json")}function wl(){try{let r=JSON.parse(b0(Km(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function k0(r){v0(ji(),{recursive:!0}),w0(Km(),JSON.stringify([...r]))}function Yt(r){return wl().has(ne(r))}function Or(r,e){let t=wl(),n=ne(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),k0(t))}function vl(){return[...wl()]}var qn=S(()=>{Fi()});function Ne(r){return r.length>5e4?r.slice(0,5e4)+`
|
|
1034
|
+
\u2026[${r.length-5e4} more characters truncated]`:r}function Xe(r){let e=r.replace(x0,"").split(`
|
|
1035
|
+
`).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 x0,qi,Ui=S(()=>{x0=/\u001b\[[0-9;]*m/g;qi=(r,e)=>``});import{existsSync as E0,readdirSync as A0,statSync as T0}from"fs";import{join as P0}from"path";function Ji(r){if(!E0(r))return[];let e;try{e=A0(r)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(".jsonl"))continue;let s=P0(r,n);try{let i=T0(s);i.isFile()&&t.push({sessionId:n.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var Sl=S(()=>{});var Cr,kl=S(()=>{Cr=class{ensureHarnessSupport(){}}});import{openSync as O0,readSync as C0,closeSync as _0,statSync as R0,readdirSync as N0,readFileSync as I0,existsSync as $0}from"fs";import{join as Jn}from"path";import{homedir as Al}from"os";function L0(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function Ki(r){let e=r?.type==="image"?r.source:void 0;return e?.type==="base64"&&e.data?qi(e.data,e.media_type):""}function xl(r){return typeof r=="string"?Ne(r):Array.isArray(r)?r.map(e=>{if(typeof e=="string")return Ne(e);let t=e;return typeof t?.text=="string"?Ne(t.text):t?.content!=null?xl(t.content):Ki(t)}).join(`
|
|
1036
|
+
`):r==null?"":Ne(JSON.stringify(r))}function D0(r){let e=r.trim();return!!e&&Vm.some(t=>t.test(e))}function B0(r){let e=r.trim();return e?Vm.some(t=>{let n=t.exec(e);return!!n&&n.index===0}):!0}function F0(r){return r.replace(j0,"")}function q0(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 St(r){let e=F0(r).trim();return e?q0(e)??(D0(e)?"":e):""}function El(r){return r?.type==="text"&&typeof r.text=="string"?St(r.text):""}function Tl(r,e){if(typeof r=="string")return Xe(r);if(!r||typeof r!="object")return Xe(e);let t=r;if(t.type==="text"&&typeof t.file?.numLines=="number")return Te(t.file.numLines,"line");if(t.type==="image"){let n=Wm(t.file?.originalSize);return n?`image (${n})`:"image"}if(t.type==="pdf"){let n=Wm(t.file?.originalSize);return n?`PDF (${n})`:"PDF"}if(t.type==="parts"&&typeof t.file?.count=="number")return Te(t.file.count,"page");if(t.type==="file_unchanged")return"unchanged since last read";if(t.type==="create"&&typeof t.content=="string")return`created, ${Te(t.content.split(`
|
|
1037
|
+
`).length,"line")}`;if(t.mode==="content")return Te(t.numLines??0,"line");if(t.mode==="count")return`${Te(t.numMatches??0,"match","matches")} (${Te(t.numFiles??0,"file")})`;if(t.mode==="files_with_matches")return Te(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":Xe(t.stdout||t.stderr||"")||"no output":typeof t.code=="number"&&typeof t.codeText=="string"?`${t.code} ${t.codeText}`:typeof t.searchCount=="number"?Te(t.searchCount,"search","searches"):Array.isArray(t.matches)&&typeof t.total_deferred_tools=="number"?Te(t.matches.length,"tool"):Array.isArray(t.newTodos)?Te(t.newTodos.length,"todo"):typeof t.numFiles=="number"?Te(t.numFiles,"file"):Xe(e)}function Un(r){return!!r.isSidechain||!!r.isMeta}function U0(r){let e;try{e=O0(r,"r")}catch{return""}try{let n=65536;try{n=R0(r).size}catch{}let s=(l,d)=>{if(d<=0)return"";let u=Buffer.alloc(d),f=C0(e,u,0,d,l);return u.subarray(0,f).toString("utf8")},i=(l,d,u)=>{let f="";for(let p of l.split(`
|
|
1038
|
+
`)){if(!p.includes(`"${d}"`))continue;let b;try{b=JSON.parse(p)}catch{continue}let m=b?.[u];b?.type===d&&typeof m=="string"&&m&&(f=m)}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(`
|
|
1039
|
+
`)){if(!l.trim())continue;let d;try{d=JSON.parse(l)}catch{continue}if(!d||Un(d)||d.type!=="user")continue;let u=d.message?.content,f="";typeof u=="string"?f=St(u):Array.isArray(u)&&(f=u.map(El).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{_0(e)}}function J0(r){let e;try{e=N0(Ym)}catch{return!1}for(let t of e)if(t.endsWith(".json"))try{let n=JSON.parse(I0(Jn(Ym,t),"utf8"));if(n?.sessionId!==r)continue;return process.kill(n.pid,0),!0}catch{}return!1}var M0,Hm,Vm,j0,Te,Wm,Ym,_r,Hi=S(()=>{Ui();Sl();kl();M0=Jn(Al(),".claude","projects"),Hm=r=>Jn(M0,L0(r));Vm=[/\[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];j0=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;Te=(r,e,t=e+"s")=>`${r} ${r===1?e:t}`,Wm=r=>typeof r!="number"?"":r<1024?`${r}B`:r<1048576?`${Math.round(r/1024)}KB`:`${(r/1048576).toFixed(1)}MB`;Ym=Jn(Al(),".claude","sessions");_r=class extends Cr{displayName="Claude Mirror";detectsSelf(){return process.env.CLAUDECODE==="1"}detectsInstalled(){return $0(Jn(Al(),".claude"))}sessionsDir(e){return Hm(e)}listSessionFiles(e){return Ji(Hm(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(Un(e))return{events:[]};let n=[];if(e.type==="user"){let s=e.message?.content;if(typeof s=="string"){let i=St(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=xl(i.content);n.push({type:"tool_result",id:i.tool_use_id??"",content:o,isError:!!i.is_error,digest:Tl(e.toolUseResult,o)})}else{let o=El(i)||Ki(i);o&&n.push({type:"user",text:o})}return{events:n}}if(e.type==="attachment"&&e.attachment?.type==="queued_command"){let s=St(xl(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=>!B0(u)).join(""),a=i.filter(u=>u.type==="thinking").map(u=>u.thinking??"").join(`
|
|
1040
|
+
`),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()&&St(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 J0(e)}readPreview(e){return U0(e)}searchText(e){if(!e||Un(e)||e.type!=="user"&&e.type!=="assistant")return"";let t=e.message?.content,n="";if(typeof t=="string")n=St(t);else if(Array.isArray(t)){let s=t;n=e.type==="user"?s.map(El).filter(Boolean).join(" "):s.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(" ")}return n.replace(/\s+/g," ").trim()}}});import{spawn as Gm}from"child_process";import{readdir as K0,readFile as Xm,writeFile as Qm,unlink as Pl,mkdir as H0}from"fs/promises";import{mkdirSync as Zm,writeFileSync as Wi,appendFileSync as W0,readFileSync as Ol}from"fs";import*as ge from"path";import{fileURLToPath as Y0}from"url";function Cl(r){return ge.join(ze(),`${r}.json`)}function Hn(r){return ge.join(ze(),`${r}.log`)}function _l(r){return ge.join(ze(),`${r}.wait.json`)}function eh(r){try{let e=JSON.parse(Ol(_l(r),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function Rl(r,e=""){let t=eh(r)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Yi(r,e,t=""){try{Zm(ze(),{recursive:!0});let n=eh(r);n[t]=e,Wi(_l(r),JSON.stringify({cursors:n}))}catch{}}function Vi(r){let e=Hn(r);try{Zm(ze(),{recursive:!0}),Wi(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(W0(e,c),s+=c.length,s>2*zm){let l=Ol(e),d=l.subarray(Math.max(0,l.length-zm));Wi(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 th(r){try{Wi(Hn(r),"")}catch{}}function Ie(r,e=0){try{let t=Ol(Hn(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 Nl(r){return`\u2500\u2500 run ${r} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function G0(r){let e=V0.exec(r);return e?Number(e[1]):void 0}function rh(r,e){let t=r.split(`
|
|
1041
|
+
`),n=[];if(t.forEach((o,a)=>{let c=G0(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(`
|
|
1042
|
+
`)}function Il(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function nh(r){await H0(ze(),{recursive:!0}),await Qm(Cl(r.pid),JSON.stringify(r))}async function sh(r,e){let t=Cl(r);try{let n=JSON.parse(await Xm(t,"utf8"));if(n.denied===e)return;n.denied=e,await Qm(t,JSON.stringify(n))}catch{}}async function Kn(r){await Pl(Cl(r)).catch(()=>{}),await Pl(Hn(r)).catch(()=>{}),await Pl(_l(r)).catch(()=>{})}async function Q(r){let e;try{e=await K0(ze())}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 Xm(ge.join(ze(),s),"utf8"))}catch{await Kn(i);return}o&&typeof o.pid=="number"&&Il(o.pid)?t.push(o):await Kn(i)})),(r?t.filter(s=>s.agent==null&&Jm(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function $l(r,e){let t=ne(r);return(await Q()).find(n=>n.cwd!=null&&ne(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function Vt(r){try{process.kill(r,"SIGTERM")}catch{}await Kn(r)}function Rr(r,e){let t=ne(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&ne(n.file)===t)}async function Ll(r){let e=Rr(await Q(),r);for(let t of e)await Vt(t.pid);return e}function X0(r,e,t){(process.platform==="win32"?Gm("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):Gm(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function ih(){return ge.join(ge.dirname(Y0(import.meta.url)),"index.js")}function Q0(r,e={}){return{command:process.execPath,args:[ih(),...e.trust?["--trust"]:[],...e.dir?["--dir",e.dir]:[],...e.mode?["--mode",e.mode]:[],r,...e.open===!1?["--no-open"]:[]]}}function Z0(r){return{command:process.execPath,args:[ih(),`agent:${r}`,"--no-open"]}}async function oh(r,e,t,n){let s=await r();if(s)return s;X0(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await z0(150);let o=await r();if(o)return o}throw new Error(`Launched ${n} but it did not register within 20s.`)}async function Gi(r,e={}){let t=e.cwd??process.cwd(),n=ge.resolve(t,r),[s]=await Ll(n),i={...e,dir:e.dir??s?.dir,mode:e.mode??s?.mode};return oh(async()=>Rr(await Q(),n)[0],Q0(r,i),t,ge.basename(r))}async function ah(r,e=process.cwd()){return oh(()=>$l(e,r),Z0(r),e,`the ${r} mirror`)}var zm,V0,z0,$e=S(()=>{Fi();zm=1e6;V0=/^── run (\d+) ── /;z0=r=>new Promise(e=>setTimeout(e,r))});function zi(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 Ml(r){return(zi(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var Dl=S(()=>{});import{readdirSync as eE,readFileSync as tE,statSync as rE}from"fs";import{join as ch,basename as nE}from"path";function lh(r,e,t){if(e>8)return t;let n;try{n=eE(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;lh(ch(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(ch(r,s.name));return t}function Xi(r){return lh(r,0,[]).map(e=>{let t=0;try{t=rE(e).mtimeMs}catch{}let n,s=!1;try{let i=tE(e,"utf8");n=zi(i.slice(0,1024));let o=ce(i);s=!!o&&fi(hr(o))}catch{}return{path:e,name:n??nE(e).replace(/\.bulb\.md$/,""),mtime:t,serverOnly:s}})}var uh=S(()=>{Re();xn();Dl()});function Nr(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 Qi=S(()=>{});import{readFile as sE}from"fs/promises";async function Bl(r){try{let e=ce(await sE(r,"utf-8"));return e?Nr(hr(e)):void 0}catch{return}}var fh=S(()=>{xn();Qi()});function jl(r){let e=ce(r);if(!e)return r;let t=e.files.get("code.tsx");if(!t)return r;let n=rm(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=Ju(l);u&&(c[u]=d)}return c.config=JSON.stringify(i,null,2),Xu(c)}var dh=S(()=>{Re();di()});import{spawn as ph}from"child_process";import{basename as iE}from"path";function oE(){return process.env.TYPEBULB_EDITOR||"code"}function cE(r,e,t){return t==null?[e]:aE.test(iE(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function lE(r,e){let t=oE();return{command:t,args:cE(t,r,e)}}function Fl(r,e){let{command:t,args:n}=lE(r,e),s=process.platform==="win32"?ph("cmd.exe",["/d","/s","/c",t,...n],{detached:!0,stdio:"ignore",windowsHide:!0}):ph(t,n,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var aE,mh=S(()=>{aE=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as uE,existsSync as fE}from"fs";import*as Gt from"path";import{fileURLToPath as dE}from"url";function hh(){let r=Gt.dirname(dE(import.meta.url));for(;!fE(Gt.join(r,"package.json"));){let e=Gt.dirname(r);if(e===r)break;r=e}return r}function zt(){return Gt.join(hh(),"README.md")}function Ir(){return Gt.join(hh(),"description.md")}function pE(r){let e=uE(Ir(),"utf8").trim().replace(/\s+/g," ");return`---
|
|
1043
|
+
name: typebulb
|
|
1044
|
+
description: ${JSON.stringify(e)}
|
|
1045
|
+
version: ${r}
|
|
1046
|
+
---`}function mE(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 gh(r,e){return`${pE(e)}
|
|
1047
|
+
|
|
1048
|
+
${mE(e)}
|
|
1049
|
+
|
|
1050
|
+
${r.trim()}
|
|
1051
|
+
`}var Zi=S(()=>{});import{readFileSync as yh,existsSync as hE}from"fs";import*as Le from"path";function bh(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function ye(r,e=process.cwd()){let t={},n=[];for(let s of bh(r)){let i;try{i=yh(Le.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[o,a]of wh(i))process.env[o]===void 0&&(process.env[o]=a,t[o]=s)}return{mode:r,sources:t,loaded:n}}function*wh(r){for(let e of r.split(`
|
|
1052
|
+
`)){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 eo(r,e=process.cwd()){for(let t of bh()){let n;try{n=yh(Le.resolve(e,t),"utf-8")}catch{continue}for(let[s,i]of wh(n))if(s===r)return i}return process.env[r]}function gE(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 kt(r,e,t){let{sources:n,mode:s,loaded:i}=r,o=process.cwd(),a=Le.dirname(e),c=`(mode: ${s??"none"})`,l=t?gE(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=Le.resolve(a)!==Le.resolve(o);if(u)for(let p of[".env.local",".env"])hE(Le.join(a,p))&&console.log(`env: ${Le.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}`)}}var xt=S(()=>{});import*as Me from"fs/promises";import*as Pe from"path";function Ul(r,e){ye(e);let t=process.env.TYPEBULB_ORIGIN||yE;try{return ro(r,process.cwd(),t)}catch(n){console.error(n instanceof Error?n.message:String(n)),process.exit(1)}}function ro(r,e,t){if(/^https?:\/\//i.test(r)){let c=new URL(r),l=c.pathname.split("/").filter(Boolean).map(decodeURIComponent),d=l[0]==="api"&&l[1]==="scripts"?l.slice(2):l;if(d[0]!=="u"||!d[1]||!d[2])throw new Error(`Not a bulb URL: ${r}
|
|
1053
|
+
Expected <origin>/u/<user>/<slug>`);let u=d[1],f=d[2].replace(/(\.bulb)?\.md$/,"");return{origin:c.origin,userSlug:u,slug:f,dest:Pe.join(e,to(u,f))}}let n=Pe.resolve(e,r),[s,i,o,a]=n.split(Pe.sep).slice(-4);if(s!=="typebulbs"||i!=="u"||!o||!a?.endsWith(".bulb.md"))throw new Error(`Not a conventional bulb path: ${r}
|
|
1054
|
+
A pull target must be a bulb URL, or a local file at typebulbs/u/<user>/<slug>.bulb.md \u2014 the path is its remote identity.`);return{origin:t,userSlug:o,slug:a.slice(0,-8),dest:n}}async function no(r,e={}){let t=await fetch(ql(r),{headers:e.token?{Authorization:`Bearer ${e.token}`}:{},signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0});if(!t.ok)return{kind:"http-error",status:t.status};let n=t.headers.get("content-type");if(!n?.includes("text/markdown"))return{kind:"not-markdown",contentType:n};let s=await t.text(),i;try{i=await Me.readFile(r.dest,"utf-8")}catch{}if(i!==void 0){if(bE(i,s))return{kind:"up-to-date",dest:r.dest};if(!e.force){let{mtime:a}=await Me.stat(r.dest);return{kind:"conflict",dest:r.dest,localMtime:a,remoteLastModified:t.headers.get("last-modified")}}}await Me.mkdir(Pe.dirname(r.dest),{recursive:!0}),await Me.writeFile(r.dest,s);let o=new Date(t.headers.get("last-modified")??"");return isNaN(o.getTime())||await Me.utimes(r.dest,new Date,o),{kind:"written",dest:r.dest,created:i===void 0}}function bE(r,e){let t=i=>i.replace(/\r\n/g,`
|
|
1055
|
+
`),n=ce(t(r)),s=ce(t(e));return!n||!s?t(r)===t(e):n.frontmatter.name===s.frontmatter.name&&tt.every(i=>(n.files.get(Oe[i].path)||"")===(s.files.get(Oe[i].path)||""))}async function vh(r,e){r||(console.error("Usage: typebulb pull <bulb url | typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1));let t=Ul(r,e.mode),n=`${t.origin}/u/${t.userSlug}/${t.slug}`,s;try{s=await no(t,{force:e.force,token:process.env.TYPEBULB_TOKEN})}catch(o){console.error(`Could not reach ${t.origin}: ${o instanceof Error?o.message:String(o)}`),process.exitCode=1;return}let i=Pe.relative(process.cwd(),t.dest)||t.dest;switch(s.kind){case"written":console.log(`pulled ${n} \u2192 ${i}${s.created?"":" (overwritten)"}`);return;case"up-to-date":console.log(`up to date: ${i}`);return;case"conflict":console.error(`Refusing to overwrite ${i} \u2014 it differs from ${n}
|
|
1056
|
+
local file modified ${s.localMtime.toISOString()}
|
|
1057
|
+
remote last saved ${s.remoteLastModified??"unknown"}
|
|
1058
|
+
Re-run with --force to overwrite the local file.`),process.exitCode=1;return;case"http-error":s.status===404?console.error(`Bulb not found: ${n}`):s.status===401||s.status===403?console.error(`This bulb is private (${s.status}) \u2014 pulling it needs a TYPEBULB_TOKEN for its owner.`):console.error(`Pull failed: ${t.origin} responded ${s.status}`),process.exitCode=1;return;case"not-markdown":console.error(`${n}.md did not return bulb markdown (got ${s.contentType??"no content-type"}) \u2014 is ${t.origin} a typebulb host?`),process.exitCode=1}}var yE,to,ql,so=S(()=>{xt();Re();yE="https://typebulb.com",to=(r,e)=>Pe.join("typebulbs","u",r,`${e}.bulb.md`),ql=r=>`${r.origin}/u/${encodeURIComponent(r.userSlug)}/${encodeURIComponent(r.slug)}.md`});import*as Qe from"fs/promises";import*as Wn from"path";async function wE(r,e){let t=Wn.join(wt(r),"assets"),n=await kh(t);if(!n.length)return{kind:"none"};let s=await Qe.readFile(r,"utf-8"),i=Ur(ce(s)?.files.get("config.json"));if(!i)return{kind:"no-key",count:n.length};let o=(await Promise.all(n.map(async a=>{let c=i+a.split("/").map(encodeURIComponent).join("/");return await vE(c,e?.timeoutMs??1e4)?void 0:{rel:a,url:c}}))).filter(a=>a!==void 0);return o.length?{kind:"missing",missing:o,count:n.length,base:i}:{kind:"verified",count:n.length,base:i}}async function kh(r,e=""){let t=await Qe.readdir(r,{withFileTypes:!0}).catch(()=>[]),n=[];for(let s of t)s.isDirectory()?n.push(...await kh(Wn.join(r,s.name),`${e}${s.name}/`)):s.isFile()&&n.push(e+s.name);return n}async function vE(r,e){try{let t=await fetch(r,{method:"HEAD",signal:AbortSignal.timeout(e)});return t.ok?!0:t.status!==405&&t.status!==501?!1:(await fetch(r,{headers:{Range:"bytes=0-0"},signal:AbortSignal.timeout(e)})).ok}catch{return!1}}async function io(r,e){let t=await Qe.readFile(r.dest,"utf-8"),{mtime:n}=await Qe.stat(r.dest),s={Authorization:`Bearer ${e.token}`,"Content-Type":"text/markdown; charset=utf-8"};e.force||(s["If-Unmodified-Since"]=n.toUTCString());let i=await fetch(ql(r),{method:"PUT",body:t,headers:s,signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0}),o=await i.text();if(i.status===409)return{kind:"conflict",message:Sh(o)};if(!i.ok)return{kind:"http-error",status:i.status,message:Sh(o)};let a=JSON.parse(o);return await Qe.utimes(r.dest,new Date,new Date(a.updatedAt)),{kind:"pushed",created:a.created,serverStripped:a.serverStripped,updatedAt:a.updatedAt}}function Sh(r){try{return JSON.parse(r).error||r}catch{return r}}async function xh(r,e){r||(console.error("Usage: typebulb push <typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1)),/^https?:\/\//i.test(r)&&(console.error("push takes a local .bulb.md file, not a URL (the path is its remote identity)"),process.exit(1));let t=Ul(r,e.mode),n=process.env.TYPEBULB_TOKEN;n||(console.error("push needs TYPEBULB_TOKEN in your .env \u2014 create one on your typebulb.com settings page."),process.exit(1));let s=`${t.origin}/u/${t.userSlug}/${t.slug}`,i=Wn.relative(process.cwd(),t.dest)||t.dest,o;try{let a=await wE(t.dest);if(a.kind==="missing"){console.error(`assets check against ${a.base}`);for(let c of a.missing)console.error(` MISSING ${c.rel} \u2192 expected at ${c.url}`);if(!e.force){console.error(`push refused: ${a.missing.length} of ${a.count} asset(s) not hosted yet (typebulb.com stores the bulb text only). Upload them, or push --force to publish anyway.`),process.exitCode=1;return}console.error(" continuing (--force): the published bulb will 404 on these until they are uploaded.")}a.kind==="no-key"&&console.log(`note: this bulb has an assets/ folder (${a.count} file(s)) but no "assets" base URL in config.json \u2014 local assets don't travel with a push; host them and set the key, or inline them.`),a.kind==="verified"&&console.log(`assets: verified ${a.count} file(s) against ${a.base}`),o=await io(t,{token:n,force:e.force})}catch(a){let c=a instanceof Error?a.message:String(a);console.error(a?.code==="ENOENT"?`File not found: ${i}`:`Could not push to ${t.origin}: ${c}`),process.exitCode=1;return}switch(o.kind){case"pushed":console.log(`pushed ${i} \u2192 ${s}${o.created?" (created, unlisted)":""}`),o.serverStripped&&console.log("note: the server.ts block was stripped on the server copy (CLI-only); your local file is untouched.");return;case"conflict":console.error(`${o.message}
|
|
1059
|
+
pull to see the remote: typebulb pull ${i}
|
|
1060
|
+
or overwrite it: typebulb push ${i} --force`),process.exitCode=1;return;case"http-error":o.status===401?console.error("The server rejected TYPEBULB_TOKEN (401) \u2014 it may be revoked; mint a new one on the settings page."):console.error(`Push failed: ${t.origin} responded ${o.status}${o.message?` \u2014 ${o.message}`:""}`),process.exitCode=1}}var Jl=S(()=>{Re();so();vt()});var $r=S(()=>{$e();uh();fh();Dl();dh();mh();qn();Wt();Wt();Di();Zi();so();Jl();xt()});import{copyFileSync as SE,existsSync as Eh,mkdirSync as Ah,rmSync as kE,writeFileSync as xE}from"fs";import{homedir as EE}from"os";import*as De from"path";import{fileURLToPath as AE}from"url";function RE(){return _E.replace('"__TB_DESCRIPTION_PATH__"',JSON.stringify(Ir())).replace('"__TB_README_PATH__"',JSON.stringify(zt()))}function Th(){try{if(!Eh(oo()))return}catch{return}try{let r=TE();Ah(De.dirname(r),{recursive:!0}),xE(r,RE()),kE(PE(),{force:!0})}catch{}try{let r=OE();if(!Eh(r))return;let e=CE();Ah(De.dirname(e),{recursive:!0}),SE(r,e)}catch{}}var oo,TE,PE,OE,CE,_E,Ph=S(()=>{$r();oo=()=>De.join(EE(),".pi","agent"),TE=()=>De.join(oo(),"extensions","typebulb.ts"),PE=()=>De.join(oo(),"extensions","typebulb-wait.ts"),OE=()=>De.join(De.dirname(AE(import.meta.url)),"agents","pi","matchu-patchu.ts"),CE=()=>De.join(oo(),"extensions","matchu-patchu.ts"),_E=String.raw`// Generated by typebulb — do not edit; overwritten on each run.
|
|
1061
|
+
import { spawn } from "node:child_process";
|
|
1062
|
+
import { existsSync } from "node:fs";
|
|
1063
|
+
|
|
1064
|
+
function logErr(...a) { try { console.error("[typebulb]", ...a); } catch (e) {} }
|
|
1065
|
+
|
|
1066
|
+
// Matches "typebulb wait", "npx typebulb wait", "/path/to/typebulb wait", "pnpm exec typebulb wait", etc.
|
|
1067
|
+
function isWaitCommand(command) { return /\btypebulb\s+wait\b/.test(String(command || "")); }
|
|
1068
|
+
|
|
1069
|
+
// pi's bash tool runs every command under Git Bash on Windows (its getShellConfig), so the
|
|
1070
|
+
// intercepted string is POSIX. Re-running it under node's shell:true (cmd.exe on Windows) breaks
|
|
1071
|
+
// that syntax — cmd doesn't split on ";", so a trailing "; echo ..." rides along as extra ARGS to
|
|
1072
|
+
// typebulb wait, which resolves a garbage target and dies code 1 before the event (field: a wait
|
|
1073
|
+
// that resolved the target 'exit: $?'). Resolve bash the way pi does; null → shell:true (POSIX sh).
|
|
1074
|
+
function resolveBash() {
|
|
1075
|
+
try {
|
|
1076
|
+
if (process.platform !== "win32") return existsSync("/bin/bash") ? "/bin/bash" : null;
|
|
1077
|
+
var dirs = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]];
|
|
1078
|
+
for (var i = 0; i < dirs.length; i++) {
|
|
1079
|
+
if (dirs[i] && existsSync(dirs[i] + "\\Git\\bin\\bash.exe")) return dirs[i] + "\\Git\\bin\\bash.exe";
|
|
1080
|
+
}
|
|
1081
|
+
return "bash.exe"; // PATH fallback (Cygwin/MSYS2); a spawn miss lands in the "error" handler
|
|
1082
|
+
} catch (e) { return null; }
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
// Resolved at shim-write time to this install's absolute skill-part paths (same files
|
|
1086
|
+
// commands/agent.ts prints — readable without a permission prompt, unlike the npx command).
|
|
1087
|
+
var TB_DESCRIPTION_PATH = "__TB_DESCRIPTION_PATH__";
|
|
1088
|
+
var TB_README_PATH = "__TB_README_PATH__";
|
|
1089
|
+
|
|
1090
|
+
// Orientation for a MIRROR-DRIVEN session (TYPEBULB_MIRROR=1 — set only by the mirror's composer
|
|
1091
|
+
// driver). A composer-driven agent never runs "typebulb agent", so the guaranteed-delivery block
|
|
1092
|
+
// that command prints (commands/agent.ts) never reaches it; this re-delivers it via the system
|
|
1093
|
+
// prompt. The wording below is copied from agent.ts, hard-won across many failed interactions —
|
|
1094
|
+
// only the mirror-link lines differ (the user is already IN the mirror). Change it there first.
|
|
1095
|
+
var TB_MIRROR_BLOCK = [
|
|
1096
|
+
"Typebulb: the user is prompting you from the typebulb agent mirror (already open in front of them).",
|
|
1097
|
+
" Embedded bulbs render live in this conversation.",
|
|
1098
|
+
" • do not run npx typebulb agent — the mirror is already running",
|
|
1099
|
+
" • no need to end your reply with a mirror link",
|
|
1100
|
+
" Reusable app/tool → write a .bulb.md",
|
|
1101
|
+
" Show something inline → embed a bulb",
|
|
1102
|
+
" arm a wait for its render verdict — run it plainly:",
|
|
1103
|
+
' • typebulb wait agent --match "[embed <name>"',
|
|
1104
|
+
" Read the authoring skill before writing a bulb:",
|
|
1105
|
+
" • npx typebulb skill — assembles one SKILL.md",
|
|
1106
|
+
" • or, open its parts:",
|
|
1107
|
+
" " + TB_DESCRIPTION_PATH,
|
|
1108
|
+
" " + TB_README_PATH,
|
|
1109
|
+
].join("\n");
|
|
1110
|
+
|
|
1111
|
+
export default function (pi) {
|
|
1112
|
+
try {
|
|
1113
|
+
const pending = new Set();
|
|
1114
|
+
|
|
1115
|
+
pi.on("before_agent_start", (event) => {
|
|
1116
|
+
try {
|
|
1117
|
+
if (process.env.TYPEBULB_MIRROR !== "1") return undefined;
|
|
1118
|
+
return { systemPrompt: event.systemPrompt + "\n\n" + TB_MIRROR_BLOCK };
|
|
1119
|
+
} catch (e) { logErr("before_agent_start", e && e.message); return undefined; }
|
|
1120
|
+
});
|
|
1121
|
+
|
|
1122
|
+
pi.on("tool_call", (event, ctx) => {
|
|
1123
|
+
try {
|
|
1124
|
+
if (!event || event.toolName !== "bash") return undefined;
|
|
1125
|
+
const command = event.input && event.input.command;
|
|
1126
|
+
if (!isWaitCommand(command)) return undefined;
|
|
1127
|
+
|
|
1128
|
+
// Run the REAL typebulb wait in the background instead of foreground (which would deadlock the
|
|
1129
|
+
// turn). It does the mirror/registry lookup, --match and offsets itself. The marker tells it this
|
|
1130
|
+
// is a shim-backgrounded (non-blocking) wait, so it runs as a pure subscription: no give-up clock,
|
|
1131
|
+
// it waits for the event however long (bounded by the session-shutdown reap below) — an embed's
|
|
1132
|
+
// first paint OR a running bulb's next event line alike.
|
|
1133
|
+
// The agent may self-background ("… &") — the generic-shell reading of "arm it in the
|
|
1134
|
+
// background", but here the SHIM is the backgrounder: bash would exit 0 instantly with empty
|
|
1135
|
+
// output, firing the wake before the event while the detached wait delivers to nobody
|
|
1136
|
+
// (field: Toroidal Life, '> /tmp/x.log 2>&1 &'). Strip a trailing "&" so the wait runs
|
|
1137
|
+
// foreground inside the shim's already-backgrounded child.
|
|
1138
|
+
const cmd = String(command).replace(/(?<!&)\s*&\s*$/, "");
|
|
1139
|
+
const bash = resolveBash();
|
|
1140
|
+
const opts = {
|
|
1141
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1142
|
+
env: { ...process.env, TYPEBULB_WAIT_SHIM: "1" },
|
|
1143
|
+
};
|
|
1144
|
+
const child = bash ? spawn(bash, ["-c", cmd], opts) : spawn(cmd, { ...opts, shell: true });
|
|
1145
|
+
pending.add(child);
|
|
1146
|
+
let out = "";
|
|
1147
|
+
let errOut = "";
|
|
1148
|
+
if (child.stdout) child.stdout.on("data", (b) => { out += b.toString(); });
|
|
1149
|
+
if (child.stderr) child.stderr.on("data", (b) => { errOut += b.toString(); });
|
|
1150
|
+
child.on("error", (e) => {
|
|
1151
|
+
pending.delete(child);
|
|
1152
|
+
logErr("spawn", e && e.message);
|
|
1153
|
+
// Same class as a failure exit: the subscription never armed, so silence is a deadlock.
|
|
1154
|
+
try { pi.sendUserMessage("typebulb wait FAILED to spawn: " + (e && e.message) + "\nNothing is watching — fix and re-arm the wait.", { deliverAs: "followUp" }); } catch (e2) {}
|
|
1155
|
+
});
|
|
1156
|
+
child.on("exit", (code) => {
|
|
1157
|
+
pending.delete(child);
|
|
1158
|
+
try {
|
|
1159
|
+
const text = out.trim();
|
|
1160
|
+
// Exit 0 with output is a real outcome (embed ok/error, a turn-based move) -> wake the
|
|
1161
|
+
// agent (followUp delivers immediately when idle and queues when streaming — the same call
|
|
1162
|
+
// git-merge-and-resolve.ts makes from agent_end). A late wake is fine; it just reports
|
|
1163
|
+
// something true. Exit 2/3 (no render yet / server gone) surface passively, no turn.
|
|
1164
|
+
// Any OTHER non-zero exit means the subscription itself broke (bad args, no resolvable
|
|
1165
|
+
// mirror): the agent parked on a wake that can never come, so that failure must wake too —
|
|
1166
|
+
// missed wakes are fatal, spurious wakes cheap (TB-Wait.md). null (reap-killed) stays silent.
|
|
1167
|
+
// EXCEPT an embed's clean ok verdict ("[embed <name> vN] ok" — core/client/bulbEmbed.ts):
|
|
1168
|
+
// the user already sees the bulb and the skill orders silence on ok, so a wake would spend
|
|
1169
|
+
// a whole turn saying nothing and render a noise message. Silence IS the ok. Anything else
|
|
1170
|
+
// (an embed error, a turn-based loop event) still wakes; an unrecognized shape wakes too.
|
|
1171
|
+
// Checked PER LINE, not over the whole blob: wait lingers 10s and bursts every matching line
|
|
1172
|
+
// into one payload, and a version-agnostic --match ("[embed <name>") replays v1+v2+... from
|
|
1173
|
+
// log start, so an all-ok payload is routinely multi-line. Suppress iff EVERY line is an ok;
|
|
1174
|
+
// one error line among oks still wakes.
|
|
1175
|
+
var waitLines = text.split("\n").map(function (l) { return l.trim(); }).filter(Boolean);
|
|
1176
|
+
const embedOk = code === 0 && waitLines.length > 0 && waitLines.every(function (l) { return /^\[embed .*\] ok$/.test(l); });
|
|
1177
|
+
if (code === 0 && text && !embedOk) {
|
|
1178
|
+
pi.sendUserMessage("typebulb wait result:\n" + text, { deliverAs: "followUp" });
|
|
1179
|
+
} else if (code === 0 && !text) {
|
|
1180
|
+
// A successful wait always prints its matched line(s), so exit 0 with nothing captured
|
|
1181
|
+
// means the agent redirected stdout (e.g. '> /tmp/x.log 2>&1') — the verdict landed in a
|
|
1182
|
+
// file nobody reads. The line is still in the mirror's log; point the agent there.
|
|
1183
|
+
pi.sendUserMessage("typebulb wait ended (exit 0) but its output was redirected away — read the verdict with: typebulb logs agent\nNext time run the wait plainly: no output redirect, no trailing &.", { deliverAs: "followUp" });
|
|
1184
|
+
} else if (code !== null && code !== 0 && code !== 2 && code !== 3) {
|
|
1185
|
+
var diag = (text + "\n" + errOut.trim()).trim();
|
|
1186
|
+
pi.sendUserMessage("typebulb wait FAILED (exit " + code + ")" + (diag ? ":\n" + diag : " with no output.") + "\nThe wait never armed — nothing is watching. Fix the command and re-arm it.", { deliverAs: "followUp" });
|
|
1187
|
+
} else if (ctx.ui && typeof ctx.ui.notify === "function") {
|
|
1188
|
+
// INVARIANT: this notify must never quote the "[embed <name>" tag verbatim. In a
|
|
1189
|
+
// composer-driven session the mirror's driver echoes extension notifies into the
|
|
1190
|
+
// mirror's own log (driver.ts) — the very log wait watches by substring — so a
|
|
1191
|
+
// verbatim tag re-fires the next same-match wait with a non-ok line: a self-
|
|
1192
|
+
// sustaining wake loop that defeats this suppression (TB-Wait.md). Stripping the
|
|
1193
|
+
// brackets kills the matchable substring while keeping the verdict readable.
|
|
1194
|
+
ctx.ui.notify("typebulb wait: " + (embedOk ? text.replace(/[\[\]]/g, "") : code === 2 ? "timed out, nothing to report" : "ended (code " + code + ")"), "info");
|
|
1195
|
+
}
|
|
1196
|
+
} catch (e) { logErr("exit", e && e.message); }
|
|
1197
|
+
});
|
|
1198
|
+
|
|
1199
|
+
return {
|
|
1200
|
+
block: true,
|
|
1201
|
+
reason: "Armed in the background. You will be re-invoked automatically with the result when it is ready - do not run this command again; end your turn now and wait for the result.",
|
|
1202
|
+
};
|
|
1203
|
+
} catch (e) { logErr("tool_call", e && e.message); return undefined; }
|
|
1204
|
+
});
|
|
1205
|
+
|
|
1206
|
+
try { pi.on("session_shutdown", () => { for (const c of pending) { try { c.kill(); } catch (e) {} } pending.clear(); }); } catch (e) {}
|
|
1207
|
+
} catch (e) { logErr("load", e && e.message); }
|
|
1208
|
+
}
|
|
1209
|
+
`});function J(r){return r?.message??String(r)}var Y,Et=S(()=>{Y=process.cwd()});import{spawn as Oh}from"child_process";import{StringDecoder as NE}from"string_decoder";function FE(r,e){let t=new NE("utf8"),n="";r.on("data",s=>{n+=typeof s=="string"?s:t.write(s);let i;for(;(i=n.indexOf(`
|
|
1210
|
+
`))>=0;){let o=n.slice(0,i);n=n.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var IE,$E,Ch,LE,ME,DE,BE,jE,ao,co,_h,Rh=S(()=>{Et();IE=3e4,$E=5e3,Ch=2e3,LE=2e3,ME=12e4,DE=8e3,BE=15e3,jE=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"]),ao=new Set;process.on("exit",()=>{for(let r of ao)try{r.kill()}catch{}});co=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)=>Oh(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: ${J(o)}`,this.#b();return}this.#e=i,this.#f=t,ao.add(i),i.stdout&&FE(i.stdout,o=>this.#T(o)),i.stderr&&i.stderr.on("data",o=>{this.#y=(this.#y+o.toString()).slice(-LE)}),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"),ao.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(!jE.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:J(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:J(o)}}return i.success&&!n&&(this.#c=Date.now()+$E),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"})+`
|
|
1211
|
+
`)}catch{}await Promise.race([this.#v,_h(Ch)])}try{e.stdin?.end()}catch{}if(await Promise.race([this.#v,_h(Ch)]),e.exitCode===null&&!e.killed)if(process.platform==="win32"&&e.pid)try{Oh("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}else try{e.kill("SIGKILL")}catch{}ao.delete(e),this.#r=[],this.#E("pi was shut down")}}#k(e){try{this.#e?.stdin?.write(JSON.stringify(e)+`
|
|
1212
|
+
`)}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"?DE:BE)})}#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)"))},IE);o.unref?.(),this.#s.set(n,{resolve:s,timer:o});try{t.stdin.write(JSON.stringify({id:n,...e})+`
|
|
1213
|
+
`)}catch(a){clearTimeout(o),this.#s.delete(n),i(new Error(J(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:[],i=s[s.length-1];this.#l={text:s.filter(o=>o?.type==="text").map(o=>o.text??"").join(""),thinking:s.filter(o=>o?.type==="thinking").map(o=>o.thinking??"").join(`
|
|
1214
|
+
`),tool:i?.type==="toolCall"?i.name:void 0};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??ME),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()}},_h=r=>new Promise(e=>{setTimeout(e,r).unref?.()})});import{existsSync as Nh,readFileSync as qE,realpathSync as UE}from"fs";import{join as Xt,dirname as Mh,resolve as JE}from"path";import{homedir as Ih}from"os";function HE(r,e){let t=Xt(r,".pi");if(KE.some(s=>Nh(Xt(t,s))))return!0;let n=Xt(e,".agents","skills");for(let s=r;;){let i=Xt(s,".agents","skills");if(i!==n&&Nh(i))return!0;let o=Mh(s);if(o===s)return!1;s=o}}function WE(r,e){for(let t=e;;){if(r[t]===!0||r[t]===!1)return!0;let n=Mh(t);if(n===t)return!1;t=n}}function Dh(r,e){try{let t=e?.agentDir??Xt(Ih(),".pi","agent"),n=$h(e?.home??process.env.HOME??Ih()),s=$h(JE(r));if(!HE(s,n))return null;let i=Lh(Xt(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||WE(Lh(Xt(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 KE,$h,Lh,Bh=S(()=>{KE=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],$h=r=>{try{return UE(r)}catch{return r}},Lh=r=>{try{return JSON.parse(qE(r,"utf8"))}catch{return{}}}});import{statSync as YE,openSync as VE,readSync as GE,closeSync as zE,existsSync as Fh}from"fs";import{join as lo}from"path";import{homedir as Kl}from"os";import{execFile as XE}from"child_process";async function ZE(r){let e=lo(Kl(),".pi","agent","bin",process.platform==="win32"?"fd.exe":"fd");for(let t of["fd","fdfind",...Fh(e)?[e]:[]]){let n=await new Promise(s=>{XE(t,["--base-directory",r,"--type","f","--follow","--hidden","--exclude",".git"],{maxBuffer:67108864},(i,o)=>s(i?null:o))});if(n!==null)return n.split(`
|
|
1215
|
+
`).filter(Boolean).map(s=>s.replace(/\\/g,"/"))}return null}function eA(r){return`--${r.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function jh(r){return r.type==="message"?tA(r.message?.role):r.type==="custom_message"?r.display!==!1:!1}var QE,tA,Lr,Hl=S(()=>{Ui();Sl();kl();Ph();Rh();Bh();QE=lo(Kl(),".pi","agent","sessions");tA=r=>r==="user"||r==="assistant"||r==="toolResult"||r==="bashExecution";Lr=class extends Cr{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}detectsInstalled(){return Fh(lo(Kl(),".pi","agent"))}ensureHarnessSupport(){Th()}createDriver(e,t){let n=new co(e,t),s=Dh(e);return s&&n.notice(s,"warning"),n}walkFiles(e){return ZE(e)}sessionsDir(e){return lo(QE,eA(e))}listSessionFiles(e){return Ji(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 jh(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:Xe(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(`
|
|
1216
|
+
`),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)jh(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=VE(e,"r")}catch{return""}try{let s=65536;try{s=YE(e).size}catch{}let i=(u,f)=>{let p=Buffer.alloc(f),b=GE(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(`
|
|
1217
|
+
`))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(`
|
|
1218
|
+
`))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{zE(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"?Ne(e):Array.isArray(e)?e.map(t=>typeof t?.text=="string"?Ne(t.text):t?.type==="image"&&t.data?qi(t.data,t.mimeType):"").filter(Boolean).join(`
|
|
1219
|
+
`):""}}});var uo,qh=S(()=>{uo=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});import{execFile as rA}from"child_process";import{promisify as nA}from"util";import{readFile as sA}from"fs/promises";import{resolve as Uh,sep as iA}from"path";async function Be(r,e){let{stdout:t}=await oA("git",r,{cwd:e,maxBuffer:67108864});return t}async function Mr(){if(fo)return fo;try{fo=(await Be(["rev-parse","--show-toplevel"],Y)).trim()}catch{}return fo}function aA(r,e){let t=e===" "?r:e;return t==="?"?"U":t}async function Kh(){let r=await Mr();if(!r)return{repo:!1,root:"",files:[]};try{let e=await Be(["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:aA(i[0],i[1])}))}try{let s=await Be(["diff","--numstat","HEAD"],r),i=new Map;for(let o of s.split(`
|
|
1220
|
+
`)){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:J(e)}}}async function Hh(r){let e=await Mr();if(!e)return{ok:!1,error:"not a git repository"};try{if((await Be(["status","--porcelain","-z","--",r],e)).startsWith("??")){let s=Uh(e,r);if(!s.startsWith(Uh(e)+iA))return{ok:!1,error:"outside repository"};let i=await sA(s);return i.includes(0)?Wl("Binary file (not shown)",!1):Wl(i.toString("utf8"),!0)}let n;try{n=await Be(["diff","--no-color","--unified=999999","HEAD","--",r],e)}catch{n=await Be(["diff","--no-color","--unified=999999","--",r],e)}return Wl(n,!1)}catch(t){return{ok:!1,error:J(t)}}}var oA,Jh,fo,Wl,po=S(()=>{Et();oA=nA(rA),Jh=2e6;Wl=(r,e)=>({ok:!0,text:r.slice(0,Jh),untracked:e,truncated:r.length>Jh})});function mo(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 Yl=S(()=>{});var ho,go,Wh=S(()=>{ho=".typebulb/paste",go={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 cA,mkdirSync as lA,writeFileSync as uA,readFileSync as fA}from"fs";import{join as yo}from"path";function Yh(){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 hA(r){return r.trim().toLowerCase().replace(/\.[a-z0-9]{1,4}$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function gA(r){let e=AbortSignal.timeout(dA);for(let[t,n]of mA){let s=Ve(t,n);if(typeof s!="string"){try{let i=await yt(s,{messages:[{role:"user",content:`Reply with ONLY a short kebab-case filename (2-5 words, lowercase, no extension) describing this text:
|
|
1221
|
+
|
|
1222
|
+
${r.slice(0,pA)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=hA(await Kt(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function Vh(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=yo(r,ho);try{lA(t,{recursive:!0})}catch(a){return{ok:!1,error:J(a)}}let n,s,i;if(e.kind==="image"){if(n=`img-${Yh()}`,s=Object.keys(go).find(a=>go[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else n=await gA(e.data)??`paste-${Yh()}`,s="md",i=e.data;let o=`${n}.${s}`;for(let a=2;cA(yo(t,o));a++)o=`${n}-${a}.${s}`;try{uA(yo(t,o),i)}catch(a){return{ok:!1,error:J(a)}}return{ok:!0,path:`${ho}/${o}`}}function Gh(r,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),n=go[t];if(!n)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:n,base64:fA(yo(r,ho,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var dA,pA,mA,zh=S(()=>{Er();$r();Et();Wh();dA=4e3,pA=4e3,mA=[["openrouter","google/gemini-3.1-flash-lite-preview"],["gemini","gemini-3.1-flash-lite"]]});import{existsSync as Xh,openSync as yA,readSync as bA,closeSync as wA,statSync as Dr,readdirSync as Qh,watchFile as vA,unwatchFile as Zh,mkdirSync as SA,writeFileSync as kA,readFileSync as bo,unlinkSync as xA,rmSync as EA}from"fs";import{stat as AA}from"fs/promises";import{dirname as TA,join as Qt,resolve as eg}from"path";function _A(r){if(!Number.isInteger(r))return!0;try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}function wo(r){let e={cwd:Y,sessionId:"",sessionStartMs:Date.now(),buffer:[],partial:"",offset:0,latest:{in:0,out:0,cached:0,cacheCreate:0},latestModel:null,everAttached:!1,entries:new Map},t=new Set,n;function s(){if(e.file){for(let h of t)if(h.file===e.file)return h;return}return n}function i(h){let w={d:r.createDriver(e.cwd,h),file:h};return t.add(w),e.file||(n=w),w}async function o(h){t.delete(h),n===h&&(n=void 0);try{await h.d.dispose()}catch(w){console.error("[composer] dispose:",J(w))}}function a(){let h=s();for(let w of[...t])w!==h&&(w.d.streaming||w.d.queue||w.d.error||o(w))}function c(){for(let h of t)h.d.sessionFile&&h.file!==h.d.sessionFile&&(h.file=h.d.sessionFile);if(n&&!e.file&&n.file){let h=r.listSessionFiles(e.cwd).find(w=>w.file===n.file);h&&N(h)}}let l=h=>Qt(h,OA),d=(h,w)=>Qt(l(h),`${w}.lock`);function u(h,w){try{let v=d(h,w);if(Date.now()-Dr(v).mtimeMs>=tg)return!1;try{let C=parseInt(bo(v,"utf8").trim(),10);if(C===process.pid||!_A(C))return!1}catch{}return!0}catch{return!1}}function f(h,w){if(w)try{SA(l(h),{recursive:!0}),kA(d(h,w),String(process.pid))}catch(v){console.error("[lock] claim failed:",J(v))}}function p(h){try{EA(Qt(h,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function b(h){let w=l(h);if(!Xh(w))return;let v;try{v=Qh(w)}catch{return}let C=Date.now();for(let D of v){if(!D.endsWith(".lock"))continue;let j=Qt(w,D);try{let L=Dr(j);C-L.mtimeMs>CA&&xA(j)}catch{}}}function m(h){try{return Dr(h),!1}catch(w){return w.code==="ENOENT"}}function g(){let h=e;if(h.file&&!m(h.file)){f(h.cwd,h.sessionId);return}let w=x(h);w&&N(w)}function x(h){if(!h.everAttached)return A(h.cwd)??P(h.cwd,()=>!0)}function A(h){let w=l(h);if(!Xh(w))return;let v;try{v=Qh(w)}catch{return}let C;for(let j of v)if(j.endsWith(".lock"))try{let L=Dr(Qt(w,j));if(Date.now()-L.mtimeMs>=tg||parseInt(bo(Qt(w,j),"utf8").trim(),10)!==process.pid)continue;(!C||L.mtimeMs>C.mtime)&&(C={sessionId:j.slice(0,-5),mtime:L.mtimeMs})}catch{}if(!C)return;let D=r.listSessionFiles(h).find(j=>j.sessionId===C.sessionId);if(!(!D||m(D.file)))return D}function P(h,w){return r.listSessionFiles(h).sort((v,C)=>C.mtime-v.mtime).find(v=>!u(h,v.sessionId)&&w(v))}function R(h,w){let v=e;if(v.file)try{Zh(v.file)}catch{}v.file=h,v.sessionId=w,v.partial="",v.offset=0,v.latest={in:0,out:0,cached:0,cacheCreate:0},v.latestModel=null,v.entries=new Map,v.chainLastId=void 0,v.buffer.push({type:"cleared"}),v.buffer.push({type:"session",sessionId:w})}function N(h){let w=e;n=void 0,R(h.file,h.sessionId),w.everAttached=!0,f(w.cwd,h.sessionId),$();try{Zh(h.file)}catch{}vA(h.file,{interval:200},()=>$())}function O(){R(void 0,"")}function $(){let h=e;if(!h.file)return;let w;try{w=Dr(h.file).size}catch{return}if(w<=h.offset)return;let v;try{v=yA(h.file,"r")}catch{return}try{let U=w-h.offset,de=Buffer.alloc(U),te=0;for(;te<U;){let _u=bA(v,de,te,U-te,h.offset+te);if(!_u)break;te+=_u}h.offset+=te,h.partial+=de.subarray(0,te).toString("utf8")}finally{wA(v)}let C,D;for(;(D=h.partial.indexOf(`
|
|
1223
|
+
`))>=0;){let U=h.partial.slice(0,D);if(h.partial=h.partial.slice(D+1),!U.trim())continue;let de=r.parseEntry(U);if(!de)continue;let te=r.idOf(de);te&&(h.entries.set(te,de),!r.isSidechain(de)&&r.isLeafType(de)&&(C=te))}if(!C)return;let j=[],L=h.entries.get(C),H=!1;for(;L;){if(j.push(L),r.idOf(L)===h.chainLastId){H=!0;break}let U=r.parentOf(L);L=U?h.entries.get(U):void 0}if(H)for(let U=j.length-2;U>=0;U--)I(j[U]);else{h.chainLastId!==void 0&&(h.buffer.push({type:"cleared"}),h.buffer.push({type:"session",sessionId:h.sessionId}),h.latest={in:0,out:0,cached:0,cacheCreate:0});let U=new Set(j.map(te=>r.idOf(te))),de=E(h.entries);for(let te=j.length-1;te>=0;te--)I(j[te]),y(r.idOf(j[te]),de,U)}h.chainLastId=C}function E(h){let w=new Map;for(let v of h.values()){let C=r.parentOf(v);if(!C)continue;let D=w.get(C);D?D.push(v):w.set(C,[v])}return w}function y(h,w,v){if(!h)return;let C=w.get(h);if(!C)return;let D=C.filter(U=>!r.isSidechain(U));if(D.length<2)return;let j=D.filter(U=>!v.has(r.idOf(U)));if(!j.length)return;let L=[],H=0;for(let U of j){let de=k(U,w);L.push(...de.events),H+=de.count}H>0&&e.buffer.push({type:"fork",atId:h,count:H,events:L})}function k(h,w){let v=[],C=[h];for(;C.length;){let L=C.pop();if(r.isSidechain(L))continue;v.push(L);let H=w.get(r.idOf(L)??"");if(H)for(let U of H)C.push(U)}v.sort((L,H)=>(Date.parse(r.timestampOf(L)??"")||0)-(Date.parse(r.timestampOf(H)??"")||0));let D=[];for(let L of v)r.isRecoveryNoise(L)||D.push(...r.apply(L,e.sessionStartMs).events);return{count:D.reduce((L,H)=>L+(H.type==="user"||H.type==="assistant"?1:0),0),events:D}}function I(h){try{let{events:w,usage:v,model:C,cost:D}=r.apply(h,e.sessionStartMs);for(let j of w)e.buffer.push(j);w.some(j=>j.type==="assistant")&&s()?.d.clearCompletedDraft(),w.some(j=>j.type==="user")&&s()?.d.clearEcho(),C&&(e.latestModel=C),v&&(e.latest=v),(v||D)&&e.buffer.push({type:"usage",...e.latest,cost:D})}catch(w){console.error("[mirror] skipped malformed entry:",J(w))}}async function _(){return{cwd:e.cwd,pid:process.pid,composer:!!r.createDriver,elsewhere:await M()}}async function M(){if(r.listSessionFiles(e.cwd).length)return;let h=await Mr();if(!h)return;let w=eg(h).toLowerCase();for(let v=eg(e.cwd);v.toLowerCase()!==w;){let C=TA(v);if(C===v)return;v=C;let D=r.listSessionFiles(v).length;if(D)return{dir:v,count:D}}}M().then(h=>{h&&console.log(`No sessions for ${e.cwd} \u2014 ${h.count} exist for ${h.dir}. Launched from a subfolder? Relaunch from the project root.`)}).catch(()=>{});let W=new uo;async function K(h,w){W.accept(h,w)&&console.log(w)}function Fe(){let h=r.sessionAlive(e.sessionId,e.cwd);if(h!==void 0)return h;if(!e.file)return!1;try{return Date.now()-Dr(e.file).mtimeMs<1e4}catch{return!1}}function z(){return r.chainWorking([...e.entries.values()])&&Fe()}function V(){!r.createDriver||s()||e.latestModel||z()||i(e.file)}async function qe(h){let w=e;g(),c(),V(),a();let v=s();for(let L of t)L!==v&&L.d.dialog;let C=new Set([...t].filter(L=>L.d.streaming&&L.file).map(L=>L.file)),D=C.size?r.listSessionFiles(w.cwd).filter(L=>C.has(L.file)).map(L=>L.sessionId):[],j=r.createDriver?{streaming:!!v?.d.streaming,draft:v?.d.draft??null,echo:v?.d.echo??null,status:v?.d.status??null,dialog:v?.d.dialog??null,queue:v?.d.queue??null,stats:v?.d.stats??null,model:v?.d.model??null,error:v?.d.error}:void 0;return{events:w.buffer.slice(h),cursor:w.buffer.length,working:!!v?.d.streaming||z(),latestModel:w.latestModel,composer:j,busy:D}}async function we(){g(),c();let h=s();if(h?.d.error&&!h.d.streaming&&(await o(h),h=void 0),!h){if(z())return{ok:!1,error:"the agent is mid-turn in a terminal \u2014 watch only"};h=i(e.file)}return{ok:!0,d:h.d}}async function Zy(h,w){if(!r.createDriver)return{ok:!1,error:"not supported"};let v=String(h??"").trim();if(!v)return{ok:!1,error:"empty message"};let C=await we();return C.ok?C.d.send(v,w):C}async function eb(h,w){let v=s();return v?v.d.respondUi(String(h??""),w??{}):{ok:!1,error:"no dialog pending"}}async function tb(h,w){if(!r.createDriver)return{ok:!1,error:"not supported"};if(!h||typeof h.type!="string")return{ok:!1,error:"bad command"};if(w?.spawn){let C=await we();return C.ok?C.d.rpc(h):C}let v=s();return!v||v.d.error?{ok:!1,error:"not running"}:v.d.rpc(h)}async function rb(){let h=s();if(h)try{await h.d.stop()}catch(w){console.error("[composer] stop:",J(w))}return{ok:!0}}async function nb(){return r.createDriver?(c(),!e.file&&n&&!n.d.streaming&&!n.d.error?{ok:!0}:(n?.d.error&&await o(n),n=void 0,e.file&&O(),i(void 0),a(),{ok:!0})):{ok:!1,error:"not supported"}}async function sb(){if(!r.createDriver)return[];let h=await Be(["ls-files","--cached","--others","--exclude-standard"],e.cwd).catch(()=>null),w=h!==null?h.split(`
|
|
1224
|
+
`).filter(Boolean):await r.walkFiles?.(e.cwd)??[];return(await Promise.all(w.map(async C=>{try{return{f:C,m:(await AA(Qt(e.cwd,C))).mtimeMs}}catch{return{f:C,m:0}}}))).sort((C,D)=>D.m-C.m).map(C=>C.f)}function ib(){for(let h of[...t])o(h)}async function ob(h){return r.createDriver?Vh(e.cwd,h):{ok:!1,error:"not supported"}}async function ab(h){return Gh(e.cwd,String(h??""))}async function cb(){return r.listSessionFiles(e.cwd).sort((h,w)=>w.mtime-h.mtime).map(({sessionId:h,file:w,mtime:v})=>({sessionId:h,mtime:v,preview:r.readPreview(w)}))}let Pu=new Map;function lb(h,w){let v=Pu.get(h);if(v&&v.mtime===w)return v.turns;let C=[],D="";try{D=bo(h,"utf8")}catch{return[]}for(let j of D.split(`
|
|
1225
|
+
`)){if(!j.trim())continue;let L=r.parseEntry(j);if(!L)continue;let H=r.searchText(L);H&&C.push({text:H,lower:H.toLowerCase()})}return Pu.set(h,{mtime:w,turns:C}),C}async function ub(h){let w=h.toLowerCase(),v=[];for(let{sessionId:C,file:D,mtime:j}of r.listSessionFiles(e.cwd).sort((L,H)=>H.mtime-L.mtime)){let{hitCount:L,snippet:H}=mo(lb(D,j),w);if(L&&(v.push({sessionId:C,mtime:j,preview:r.readPreview(D),hitCount:L,snippet:H}),v.length>=RA))break}return v}let Ou=800,Cu=new Map;function fb(h,w){let v=Cu.get(h);if(v&&v.mtime===w)return v.text;let C="";try{C=bo(h,"utf8")}catch{return""}let D="";for(let L of C.split(`
|
|
1226
|
+
`)){if(!L.trim())continue;let H=r.parseEntry(L);if(H)for(let U of r.apply(H,e.sessionStartMs).events)U.type==="assistant"&&U.text.trim()&&(D=U.text.trim())}let j=D.length>Ou?D.slice(0,Ou).trimEnd()+"\u2026":D;return Cu.set(h,{mtime:w,text:j}),j}async function db(h){let w=r.listSessionFiles(e.cwd).find(v=>v.sessionId===h);return{text:w?fb(w.file,w.mtime):""}}async function pb(h){let w=e,v=r.listSessionFiles(w.cwd).find(C=>C.sessionId===h);return v?v.file===w.file?{ok:!0}:(N(v),c(),a(),{ok:!0}):{ok:!1,error:"session not found"}}return p(e.cwd),b(e.cwd),g(),{info:_,poll:qe,logEmbedStatus:K,listSessions:cb,searchSessions:ub,sessionPeek:db,attach:pb,composerSend:Zy,composerStop:rb,composerNew:nb,composerFiles:sb,composerUiRespond:eb,composerRpc:tb,composerPaste:ob,composerPasteRead:ab,shutdownComposer:ib}}var PA,OA,tg,CA,RA,Vl=S(()=>{Et();qh();po();Yl();zh();PA=".typebulb",OA=`${PA}/locks`,tg=5e3,CA=6e4;RA=50});import{existsSync as Ql,mkdirSync as NA,readFileSync as rg,writeFileSync as IA}from"fs";import{join as Zt,isAbsolute as $A}from"path";async function ng(r,e){let t=$A(r)?r:Zt(Y,r);return Ql(t)?(Fl(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function sg(r){let e=Y,t=jl(r),n=Zt(e,"typebulbs");NA(n,{recursive:!0});let s=Ml(t),i=`${s}.bulb.md`;for(let l=2;Ql(Zt(n,i))&&rg(Zt(n,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=Zt(n,i);Ql(o)||IA(o,t);let a=Zt("typebulbs",i),c=await Gi(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function ig(){return Q(Y)}async function og(r){return await Vt(r),{ok:!0}}async function ag(){return Xi(Y).filter(r=>!r.serverOnly).map(r=>({...r,trusted:Yt(r.path)}))}async function cg(r){let e=r.toLowerCase(),t=[];for(let n of Xi(Y).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=rg(n.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
|
|
1227
|
+
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=mo(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function lg(r,e){let t=Y;e!=null&&Or(r,e);let n=await Gi(r,{cwd:t,open:!1,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function ug(r){return{cap:await Bl(r)}}async function fg(r,e){return Or(r,e),{ok:!0}}async function dg(r,e){return Ie(r,e)}async function gg(){return Yn&&Date.now()-Yn.fetchedAt<=MA?Yn.samples:(Gl??=DA().finally(()=>{Gl=null}),Gl)}async function DA(){try{let r=await fetch(`${LA}/api/scripts/u/samples?stubs`,{signal:AbortSignal.timeout(mg)});if(!r.ok)throw new Error(`HTTP ${r.status}`);let e=await r.json(),t=i=>i.order??Number.MAX_SAFE_INTEGER,n=i=>Date.parse(i.createdAt??"")||0,s=e.filter(i=>i.slug!=="welcome").sort((i,o)=>t(i)-t(o)||n(o)-n(i)).map(i=>({slug:i.slug,name:i.name,description:Zo(i.config)}));return Yn={samples:s,fetchedAt:Date.now()},s}catch{return Yn?.samples??[]}}async function yg(r){return Zl.test(r)?vg(pg,"samples",r,!0):{ok:!1,error:"bad slug"}}async function bg(){let r=eu();if(!r)return{bulbs:[]};let e=`${vo()}
|
|
1228
|
+
${r}`;return At?.key===e&&Date.now()-At.fetchedAt<=BA?{user:At.user,bulbs:At.bulbs}:(zl??=jA(e,r).finally(()=>{zl=null}),zl)}async function Xl(r,e,t){let n=await fetch(`${r}${e}`,{headers:t,signal:AbortSignal.timeout(mg)});if(!n.ok)throw new Error(`HTTP ${n.status}`);if(!n.headers.get("content-type")?.includes("json"))throw new Error("not json");return n.json()}async function jA(r,e){let t={Authorization:`Bearer ${e}`};try{let n=vo(),s;try{s=await Xl(n,"/api/me",t)}catch{let a=new URL(n);n=`${a.protocol}//api.${a.host}`,s=await Xl(n,"/api/me",t)}let o=(await Xl(n,"/api/scripts/list",t)).filter(a=>a.userSlug===s.slug&&!a.isTemplate).map(a=>({slug:a.slug,name:a.name,description:Zo(a.config)}));return At={key:r,user:s.slug,bulbs:o,fetchedAt:Date.now()},{user:s.slug,bulbs:o}}catch{return At?.key===r?{user:At.user,bulbs:At.bulbs}:{bulbs:[]}}}async function wg(r,e,t=!1){return!Zl.test(e)||!Zl.test(r)?{ok:!1,error:"bad slug"}:vg(vo(),r,e,t)}async function vg(r,e,t,n){let s=to(e,t);try{let i=await no({origin:r,userSlug:e,slug:t,dest:Zt(Y,s)},{force:n,token:eu(),timeoutMs:hg});return i.kind==="conflict"?{ok:!1,conflict:!0,error:"local file differs from the site copy"}:i.kind==="http-error"?{ok:!1,error:`HTTP ${i.status}`}:i.kind==="not-markdown"?{ok:!1,error:`not a bulb (${i.contentType??"no content-type"})`}:{ok:!0,file:s,upToDate:i.kind==="up-to-date"}}catch(i){return{ok:!1,error:i?.message??String(i)}}}async function Sg(r,e=!1){let t=eu();if(!t)return{ok:!1,error:"no TYPEBULB_TOKEN in .env"};try{let n=ro(r,Y,vo()),s=await io(n,{token:t,force:e,timeoutMs:hg});return s.kind==="conflict"?{ok:!1,conflict:!0,error:s.message}:s.kind==="http-error"?{ok:!1,error:`HTTP ${s.status}: ${s.message}`}:{ok:!0,created:s.created,serverStripped:s.serverStripped}}catch(n){return{ok:!1,error:n?.message??String(n)}}}var LA,pg,MA,mg,hg,Yn,Gl,Zl,BA,At,zl,vo,eu,tu=S(()=>{$r();Et();Yl();Re();LA="https://api.typebulb.com",pg="https://typebulb.com",MA=3600*1e3,mg=5e3,hg=15e3,Yn=null,Gl=null;Zl=/^[a-z0-9][a-z0-9-]*$/,BA=300*1e3,At=null,zl=null,vo=()=>eo("TYPEBULB_ORIGIN",Y)||pg,eu=()=>eo("TYPEBULB_TOKEN",Y)});import{readFileSync as su,writeFileSync as xg,mkdirSync as FA,appendFileSync as Eg,rmSync as kg}from"fs";import{join as xo,dirname as qA}from"path";import{createServer as UA}from"http";function Tt(r){try{return JSON.parse(su(r,"utf8"))}catch{return null}}function ko(r,e){FA(qA(r),{recursive:!0}),xg(r,JSON.stringify(e,null,2)+`
|
|
1229
|
+
`)}function Tg(r,e,t){let n=xo(r,".gitignore"),s="";try{s=su(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(`
|
|
1230
|
+
`)?`
|
|
1231
|
+
`:"";try{Eg(n,a+t+`
|
|
1232
|
+
`+o.join(`
|
|
1233
|
+
`)+`
|
|
1234
|
+
`)}catch(c){console.error("[switcher] .gitignore update failed",J(c))}}function YA(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?zn="live":s>WA&&(zn="uncached")}function Og(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 VA(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 Cg(r){let e;try{e=JSON.parse(r)}catch{return r}Gn=typeof e?.model=="string"?e.model:null,je&&(e.model=je),tr&&(e.provider=Pg(tr));let t=/haiku/i.test(Gn||"");return Xn!=null&&!t&&(e.reasoning={effort:ru[Xn]}),delete e.thinking,e.output_config&&delete e.output_config.effort,VA(e),JSON.stringify(e)}function GA(){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}
|
|
1235
|
+
data: ${JSON.stringify(a)}
|
|
1236
|
+
|
|
1237
|
+
`}case"content_block_delta":case"content_block_stop":{let c=t.get(a.index);return c==null?null:(a.index=c,`event: ${a.type}
|
|
1238
|
+
data: ${JSON.stringify(a)}
|
|
1239
|
+
|
|
1240
|
+
`)}default:return i}};return i=>{r+=i;let o="",a;for(;(a=r.indexOf(`
|
|
1241
|
+
|
|
1242
|
+
`))!==-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 zA(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 Vn(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 XA(r,e,t){if(!je){Vn(e,400,"invalid_request_error",HA);return}let n=process.env.OPENROUTER_API_KEY;if(!n){Vn(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(iu,{method:"POST",headers:Og(r,n),body:Cg(t),signal:s.signal})}catch(u){Vn(e,502,"api_error",`proxy upstream failed: ${J(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?GA():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});YA(p);let b=d(p);b&&e.write(b)}else e.write(Buffer.from(f))}}catch{}finally{e.writableEnded||e.end()}}async function QA(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(!je||!n)return s();try{let i=await fetch(`${iu}/count_tokens`,{method:"POST",headers:Og(r,n),body:Cg(t)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function ZA(r,e){let t=r.url||"/";if(r.method==="HEAD"){e.writeHead(200),e.end();return}if(r.method!=="POST"){Vn(e,404,"not_found_error",t);return}zA(r).then(n=>{if(t.includes("count_tokens"))return QA(r,e,n);if(t.includes("/v1/messages"))return XA(r,e,n);Vn(e,404,"not_found_error",t)})}function eT(){return Br&&er?Promise.resolve(er):new Promise((r,e)=>{let t=UA(ZA);t.on("error",e),t.listen(0,"127.0.0.1",()=>{Br=t,er=t.address().port,console.log(`[switcher] wire proxy listening on ${So(er)}`),r(er)})})}function tT(){try{Br?.close()}catch{}Br=null,er=null}function rT(r,e){let t=Eo(r),n=Tt(t),s=n||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===So(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=Ao(r);if(!Tt(i)){let a={};for(let c of Ag)a[c]=c in s.env?s.env[c]:null;ko(i,{managedBy:"agent-switcher",fileExisted:n!==null,snapshot:a,active:null})}s.env.ANTHROPIC_BASE_URL=So(e),s.env.ANTHROPIC_AUTH_TOKEN=KA,ko(t,s),Tg(r,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function nT(r,e,t){let n=Ao(r),s=Tt(n)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:t},ko(n,s)}function _g(r){let e=Eo(r),t=Ao(r),n=Tt(t),s=Tt(e);if(s?.env){let i=n?.snapshot||{};for(let o of Ag){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{kg(e,{force:!0})}catch{}else ko(e,s)}try{kg(t,{force:!0})}catch{}}async function sT(){let r=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await Ye()).filter(n=>n.provider==="openrouter"&&!ou(n.name)).map(n=>({id:n.name,label:n.friendlyName||n.name}))}catch(n){console.error("[switcher] model list failed",J(n))}let t=e.length?void 0:pl()??void 0;return{hasKey:r,models:e,error:t}}async function iT(){if(Br&&je)return{active:!0,managed:!0,model:je,port:er,provider:tr,routedModel:Gn,caching:zn,reasoning:Xn,externalBaseUrl:null};let r=Tt(Eo(Y))?.env||{};return{active:!1,managed:!1,model:null,port:null,provider:null,routedModel:null,caching:"unknown",reasoning:Xn,externalBaseUrl:r.ANTHROPIC_BASE_URL||null}}async function Rg(r,e){let t=await eT();return je=r,tr=e,rT(Y,t),t}async function oT({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(ou(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 Rg(r,au[r]??null),Gn=null,zn="unknown",nT(Y,r,tr)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${J(e)}`}}return{ok:!0}}async function aT({level:r}){return r!=null&&(!Number.isInteger(r)||r<0||r>=ru.length)?{ok:!1,error:`reasoning level must be 0\u2013${ru.length-1} or null`}:(Xn=r,{ok:!0,level:r})}async function cT(){return _g(Y),je=null,tr=null,Gn=null,zn="unknown",{ok:!0}}async function lT({key:r}){let e=(r||"").trim();if(!e)return{ok:!1,error:"empty key"};let t=Y,n=xo(t,".env"),s="";try{s=su(n,"utf8")}catch{}try{if(/^\s*OPENROUTER_API_KEY\s*=/m.test(s))xg(n,s.replace(/^\s*OPENROUTER_API_KEY\s*=.*$/m,`OPENROUTER_API_KEY=${e}`));else{let i=s&&!s.endsWith(`
|
|
1243
|
+
`)?`
|
|
1244
|
+
`:"";Eg(n,i+`OPENROUTER_API_KEY=${e}
|
|
1245
|
+
`)}}catch(i){return{ok:!1,error:J(i)}}return process.env.OPENROUTER_API_KEY=e,Tg(t,[".env"],"# secrets"),{ok:!0}}function uT(){if(!(!Br&&!je)){try{_g(Y)}catch{}tT()}}function fT(r,e){return Ng.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 dT(r){if(Ng.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 pT(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=nu(e?.cache_read_input_tokens)||nu(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 mT({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(ou(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:Pg(a)}:i),u=await fetch(iu,{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:fT(a.status,x),restriction:dT(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=nu(c?.usage?.cache_creation_input_tokens),{r:f,j:p}=await o(l),{works:b,read:m,note:g}=pT(f.ok,p?.usage,l);return b===!0&&l&&(au[r]=l,je===r&&(tr=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:m,note:g}}}catch(a){let c=J(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(c)?"timed out (20s)":c}}}var JA,iu,KA,HA,Ag,WA,ru,Eo,Ao,So,ou,Br,er,je,tr,Gn,zn,Xn,au,nu,Pg,Ng,Ig=S(()=>{$r();Et();JA="https://openrouter.ai/api",iu=`${JA}/v1/messages`,KA="typebulb-proxy-managed",HA="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.",Ag=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],WA=5e3,ru=["low","medium","high"],Eo=r=>xo(r,".claude","settings.local.json"),Ao=r=>xo(r,".claude",".cc-switcher.json"),So=r=>`http://127.0.0.1:${r}`;ou=r=>/^anthropic\//i.test(r)||/claude/i.test(r),Br=null,er=null,je=null,tr=null,Gn=null,zn="unknown",Xn=1,au={},nu=r=>typeof r=="number"?r:0,Pg=r=>({order:[r],allow_fallbacks:!1});Ng=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=Tt(Ao(Y)),t=e?.active?.model;if(!t)return;let s=(Tt(Eo(Y))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await Rg(t,e.active.provider??au[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${So(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",J(e))}})()});var Lg={};Ru(Lg,{attach:()=>kT,blockToMarkdown:()=>Ki,breakout:()=>sg,capText:()=>Ne,cleanUserText:()=>St,clearSwitchModel:()=>cT,composerPasteRead:()=>xT,displayName:()=>hT,downloadSample:()=>yg,firstLineDigest:()=>Xe,git:()=>Be,gitChangedFiles:()=>Kh,gitDiff:()=>Hh,info:()=>gT,isHiddenTurn:()=>Un,launchBulb:()=>lg,listBreakouts:()=>ig,listBulbFiles:()=>ag,listMyBulbs:()=>bg,listSamples:()=>gg,listSessions:()=>wT,listSwitchModels:()=>sT,logEmbedStatus:()=>bT,openFile:()=>ng,poll:()=>yT,predictTrustOf:()=>ug,probeModel:()=>mT,pullRemoteBulb:()=>wg,pushLocalBulb:()=>Sg,readBulbLog:()=>dg,repoRoot:()=>Mr,saveOpenRouterKey:()=>lT,searchBulbs:()=>cg,searchSessions:()=>vT,sessionPeek:()=>ST,setBulbTrust:()=>fg,setReasoning:()=>aT,setSwitchModel:()=>oT,shutdownSwitcher:()=>uT,stopBreakout:()=>og,switchState:()=>iT,toolResultDigest:()=>Tl});var $g,hT,gT,yT,bT,wT,vT,ST,kT,xT,Mg=S(()=>{Vl();Hi();tu();po();Ig();Hi();Ui();$g=new _r,hT=$g.displayName,{info:gT,poll:yT,logEmbedStatus:bT,listSessions:wT,searchSessions:vT,sessionPeek:ST,attach:kT,composerPasteRead:xT}=wo($g)});import{readFileSync as ET,writeFileSync as AT,mkdirSync as TT}from"fs";import{homedir as PT}from"os";import*as To from"path";async function jg(){try{let r=await fetch(new URL("/api/tags",Bg()).toString(),{signal:AbortSignal.timeout(OT)});return r.ok?((await r.json()).models??[]).map(t=>t.name).filter(t=>!!t):[]}catch{return[]}}function Fg(r){let e;try{e=ET(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&&!cu(n)}}}catch{}return{json:void 0,unreadable:!0}}function cu(r){let e=r?.providers;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function CT(r){let e=cu(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 qg(){let{json:r,unreadable:e}=Fg(Dg());return e?{installed:[],configured:null}:{installed:await jg(),configured:CT(r)}}async function Ug(){let r=await jg();return r.length?_T(Dg(),r,Bg()):{ok:!1,error:"Ollama is not running (or has no models installed)"}}function _T(r,e,t){let{json:n,unreadable:s}=Fg(r);if(s)return{ok:!1,error:`could not parse ${r} \u2014 edit the ollama provider there yourself`};let i={...n??{},providers:{...cu(n)??{},ollama:{baseUrl:`${t}/v1`,api:"openai-completions",apiKey:"ollama",models:e.map(o=>({id:o}))}}};try{TT(To.dirname(r),{recursive:!0}),AT(r,JSON.stringify(i,null,2)+`
|
|
1246
|
+
`)}catch(o){return{ok:!1,error:`could not write ${r}: ${J(o)}`}}return{ok:!0,count:e.length}}var OT,Dg,Bg,Jg=S(()=>{Et();$r();OT=1500,Dg=()=>To.join(PT(),".pi","agent","models.json"),Bg=()=>Tr(process.env.OLLAMA_HOST??"http://localhost:11434")});var Hg={};Ru(Hg,{attach:()=>BT,breakout:()=>sg,composerFiles:()=>UT,composerNew:()=>qT,composerPaste:()=>HT,composerPasteRead:()=>WT,composerRpc:()=>KT,composerSend:()=>jT,composerStop:()=>FT,composerUiRespond:()=>JT,displayName:()=>RT,downloadSample:()=>yg,git:()=>Be,gitChangedFiles:()=>Kh,gitDiff:()=>Hh,info:()=>NT,launchBulb:()=>lg,listBreakouts:()=>ig,listBulbFiles:()=>ag,listMyBulbs:()=>bg,listSamples:()=>gg,listSessions:()=>LT,logEmbedStatus:()=>$T,ollamaOffer:()=>qg,ollamaSync:()=>Ug,openFile:()=>ng,poll:()=>IT,predictTrustOf:()=>ug,pullRemoteBulb:()=>wg,pushLocalBulb:()=>Sg,readBulbLog:()=>dg,repoRoot:()=>Mr,searchBulbs:()=>cg,searchSessions:()=>MT,sessionPeek:()=>DT,setBulbTrust:()=>fg,shutdownComposer:()=>YT,stopBreakout:()=>og});var Kg,RT,NT,IT,$T,LT,MT,DT,BT,jT,FT,qT,UT,JT,KT,HT,WT,YT,Wg=S(()=>{Vl();Hl();tu();po();Jg();Kg=new Lr,RT=Kg.displayName,{info:NT,poll:IT,logEmbedStatus:$T,listSessions:LT,searchSessions:MT,sessionPeek:DT,attach:BT,composerSend:jT,composerStop:FT,composerNew:qT,composerFiles:UT,composerUiRespond:JT,composerRpc:KT,composerPaste:HT,composerPasteRead:WT,shutdownComposer:YT}=wo(Kg)});import*as Qy from"fs/promises";import*as rr from"path";ls();import*as Fu from"path";var Yo=5e3;function qu(r){let t={subcommand:"run",file:"",port:3e3,watch:!0,open:!(process.env.TERM_PROGRAM==="vscode"),server:!1,trust:!1,noTrust:!1,force:!1,follow:!1,clear:!1,help:!1,version:!1,callArgs:[],hasArgsFlag:!1},n=["call","check","predict","logs","wait","stop","trust","untrust","skill","models","send","pull","push"],s=r[0];if(s==="agent"||s?.startsWith("agent:")){t.subcommand="agent";let o=s.indexOf(":");if(o!==-1){let a=s.slice(o+1);a&&(t.agentTarget=a)}r=r.slice(1)}else s&&n.includes(s)&&(t.subcommand=s,r=r.slice(1));let i=[];for(let o=0;o<r.length;o++){let a=r[o];if(a==="--help"||a==="-h")t.help=!0;else if(a==="--version"||a==="-V")t.version=!0;else if(a==="--no-watch")t.watch=!1;else if(a==="--open")t.open=!0;else if(a==="--no-open")t.open=!1;else if(a==="--server")t.server=!0;else if(a==="--trust")t.trust=!0;else if(a==="--no-trust")t.noTrust=!0;else if(a==="--force")t.force=!0;else if(a==="--mode"){let c=r[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),t.mode=c}else if(a==="--dir"){let c=r[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --dir (a subfolder of the bulb's folder, e.g. --dir batch2)"),process.exit(1));let l=c.replace(/[\\/]+$/,"");(!l||Fu.isAbsolute(l)||l.split(/[\\/]/).some(d=>d===""||d===".."))&&(console.error(`Invalid --dir value: ${c} (a relative subfolder of the bulb's folder \u2014 no absolute paths or '..')`),process.exit(1)),t.dir=l}else if(a==="--follow"||a==="-f")t.follow=!0;else if(a==="--clear")t.clear=!0;else if(a==="--run"){let c=r[++o];if(c==="latest")t.run="latest";else{let l=parseInt(c,10);(isNaN(l)||l<1)&&(console.error(`Invalid --run value: ${c} (a run number, or 'latest')`),process.exit(1)),t.run=l}}else if(a==="--bulbs")t.stopScope="bulbs";else if(a==="--agent")t.stopScope="agent";else if(a==="--global")t.stopScope="global";else if(a==="--match"){let c=r[++o];c===void 0&&(console.error("Missing value for --match (a literal substring new log lines must contain)"),process.exit(1)),t.match=c}else if(a==="--timeout"){let c=parseInt(r[++o],10);(isNaN(c)||c<=0)&&(console.error(`Invalid --timeout value: ${r[o]} (seconds)`),process.exit(1)),t.timeoutSec=c}else if(a==="--wait"||a.startsWith("--wait="))if(a.startsWith("--wait=")){let c=parseInt(a.slice(7),10);(isNaN(c)||c<=0)&&(console.error(`Invalid --wait value: ${a.slice(7)} (milliseconds)`),process.exit(1)),t.sendWaitMs=c}else t.sendWaitMs=Yo;else if(a==="--lines"||a==="-n"){let c=parseInt(r[++o],10);(isNaN(c)||c<0)&&(console.error(`Invalid --lines value: ${r[o]}`),process.exit(1)),t.lines=c}else if(a==="--port"||a==="-p"){let c=r[++o],l=parseInt(c,10);isNaN(l)&&(console.error(`Invalid port: ${c}`),process.exit(1)),t.port=l}else if(a==="--replace"||a.startsWith("--replace=")){let c=a.startsWith("--replace=")?a.slice(10):r[++o]??"";try{let l=Du(c);if(t.local)throw new Error(`--replace can only be used once (got '${t.local.name}' and '${l.name}')`);t.local=l}catch(l){console.error(l instanceof Error?l.message:String(l)),process.exit(1)}}else if(a==="--args"||a.startsWith("--args=")){t.hasArgsFlag=!0;let c=a.startsWith("--args=")?a.slice(7):r[++o];c===void 0&&(console.error("Missing value for --args (a JSON array, or - to read it from stdin)"),process.exit(1)),t.argsJson=c}else if(!a.startsWith("-"))t.subcommand==="call"||t.subcommand==="send"?i.push(a):t.file=a;else{let c=t.subcommand==="call"?" (for a negative or dash-leading argument, use --args '<json-array>')":"";console.error(`Unknown option: ${a}${c}`),process.exit(1)}}return t.subcommand==="call"&&(i.length<2&&(console.error("Usage: typebulb call <file> <fn> [arg\u2026]"),process.exit(1)),t.file=i[0],t.fn=i[1],t.callArgs=i.slice(2)),t.subcommand==="send"&&(i.length<1&&(console.error("Usage: typebulb send <file> [message]"),process.exit(1)),t.file=i[0],t.sendMessage=i[1]),t}function Uu(){console.log(`
|
|
1247
|
+
typebulb - Local bulb runner for Typebulb
|
|
1248
|
+
|
|
1249
|
+
Usage:
|
|
1250
|
+
typebulb [file.bulb.md] Run a bulb (defaults to .bulb.md in cwd)
|
|
1251
|
+
typebulb agent An agent's first command \u2014 auto-detects the calling
|
|
1252
|
+
harness, brings up the agent mirror without opening a
|
|
1253
|
+
browser, prints its URL and the authoring-skill paths.
|
|
1254
|
+
Always exits 0 (a status report).
|
|
1255
|
+
typebulb agent:{claude|pi} Open a named harness's mirror in the foreground (a browser
|
|
1256
|
+
view of your coding agent's sessions) \u2014 explicit / override.
|
|
1257
|
+
typebulb skill Print this README as an Agent Skill (stdout), for the
|
|
1258
|
+
agent to read and copy into its own skills folder.
|
|
1259
|
+
typebulb call <file> <fn> [\u2026] Invoke one server.ts export headlessly: prints
|
|
1260
|
+
its return as JSON to stdout, logs/errors to
|
|
1261
|
+
stderr. Gated by trust like --server. Args after
|
|
1262
|
+
<fn> are JSON-or-string; --args '<json-array>'
|
|
1263
|
+
(or --args - for stdin) is the escape hatch.
|
|
1264
|
+
typebulb check [file.bulb.md] Type-check a bulb without running it
|
|
1265
|
+
typebulb predict [file] Report the capability a bulb probably needs
|
|
1266
|
+
(fs / AI / server.ts) without running it.
|
|
1267
|
+
typebulb models List AI models for tb.ai, filtered by the API
|
|
1268
|
+
keys in your .env (the exact ids to pass).
|
|
1269
|
+
typebulb logs [file|agent] Print a running bulb server's (or the 'agent' mirror's) console
|
|
1270
|
+
(no arg: list this project's running servers;
|
|
1271
|
+
--run latest|N shows just one hot-reload run;
|
|
1272
|
+
--clear empties it). For agents: fetch
|
|
1273
|
+
tb.server.log / errors of a bulb you launched
|
|
1274
|
+
without watching its terminal.
|
|
1275
|
+
typebulb send <file> [msg] Push a message into a running bulb's page \u2014
|
|
1276
|
+
its tb.onMessage(cb) handlers receive it. The
|
|
1277
|
+
client-side twin of 'call'; msg is JSON-or-
|
|
1278
|
+
string, omit it for a bare trigger. No --trust.
|
|
1279
|
+
With --wait, a handler's non-undefined return
|
|
1280
|
+
prints on stdout (JSON; a bare string raw).
|
|
1281
|
+
msg 'tb:snapshot' instead prints the page's
|
|
1282
|
+
rendered outline (roles, names, visible text).
|
|
1283
|
+
typebulb pull <url|file> Fetch a bulb from typebulb.com into
|
|
1284
|
+
typebulbs/u/<user>/<slug>.bulb.md (a local file
|
|
1285
|
+
at that path re-pulls in place). Unlisted and
|
|
1286
|
+
public bulbs need no login; a differing local
|
|
1287
|
+
file is refused unless --force.
|
|
1288
|
+
typebulb push <file> Upload a typebulbs/u/<user>/<slug>.bulb.md to
|
|
1289
|
+
typebulb.com as you (needs TYPEBULB_TOKEN in
|
|
1290
|
+
.env, minted on the settings page). Refused if
|
|
1291
|
+
the remote changed since your last pull/push,
|
|
1292
|
+
unless --force. A new slug is created unlisted.
|
|
1293
|
+
typebulb wait [file|agent] Block until the target server logs a new line,
|
|
1294
|
+
print it, exit (2: timeout; 3: server died).
|
|
1295
|
+
For agents: run it in the background \u2014 the exit
|
|
1296
|
+
is your wake-up ('wait agent': embed outcomes;
|
|
1297
|
+
'wait <file>': the bulb's own console.log).
|
|
1298
|
+
Resumes where your last wait/call left off, so
|
|
1299
|
+
an event that beats the wait still fires it.
|
|
1300
|
+
typebulb stop [file|pid|agent] Stop a running bulb or mirror (no arg: list this
|
|
1301
|
+
project's running servers; a pid/path/agent stops any).
|
|
1302
|
+
Batch flags: --bulbs (this project's bulbs, the
|
|
1303
|
+
mirror survives), --agent (this project's mirror),
|
|
1304
|
+
--global (every bulb + mirror, all projects).
|
|
1305
|
+
typebulb trust [file] Remember a bulb as Trusted, so a later run grants
|
|
1306
|
+
fs/AI/server.ts without --trust (no arg: list the
|
|
1307
|
+
remembered-trusted bulbs).
|
|
1308
|
+
typebulb untrust <file> Forget a bulb's trust (back to Restricted).
|
|
1309
|
+
|
|
1310
|
+
Options:
|
|
1311
|
+
-f, --follow Stream new log output until interrupted (logs)
|
|
1312
|
+
--run <latest|N> Show only one hot-reload run's output: 'latest'
|
|
1313
|
+
(the current run) or run number N (logs)
|
|
1314
|
+
--clear Empty the target server's log instead of
|
|
1315
|
+
printing it, for a clean run (logs)
|
|
1316
|
+
-n, --lines <n> Print only the last n lines (logs)
|
|
1317
|
+
--match <substring> Only lines containing this literal substring end
|
|
1318
|
+
the wait \u2014 not a regex (wait)
|
|
1319
|
+
--force Overwrite the side the command writes to: a
|
|
1320
|
+
differing local file (pull), or a remote that
|
|
1321
|
+
changed since your last sync (push)
|
|
1322
|
+
--timeout <sec> Give up after this long; exit 2 \u2014 bounds only a
|
|
1323
|
+
manual (foreground) bulb wait, default 1800 (wait)
|
|
1324
|
+
--wait[=ms] For 'send': bound the whole exchange \u2014 retry while
|
|
1325
|
+
no page is connected (a hot reload's gap), then
|
|
1326
|
+
hold for the handlers' replies (default 5000).
|
|
1327
|
+
Use it right after an edit, and for any send
|
|
1328
|
+
whose reply you read.
|
|
1329
|
+
--no-watch Disable hot reload (watch is on by default)
|
|
1330
|
+
-p, --port <port> Use a specific port (default: 3000)
|
|
1331
|
+
--open Force-open the external browser (default off
|
|
1332
|
+
inside VS Code's integrated terminal)
|
|
1333
|
+
--no-open Don't auto-open browser
|
|
1334
|
+
--trust Grant privileged capabilities (filesystem, AI,
|
|
1335
|
+
and server.ts) for this run. Without it a bulb runs
|
|
1336
|
+
Restricted: tb.fs / tb.ai / tb.server are blocked and
|
|
1337
|
+
the page shows the exact --trust command to unlock
|
|
1338
|
+
them. A bulb remembered via 'typebulb trust' runs
|
|
1339
|
+
trusted without this flag.
|
|
1340
|
+
--no-trust Force a Restricted run even if the bulb is
|
|
1341
|
+
remembered-trusted (overrides the trust store).
|
|
1342
|
+
--mode <name> Also load .env.<name> (+ .env.<name>.local) on top
|
|
1343
|
+
of .env / .env.local. Free-form name; loads no mode
|
|
1344
|
+
file by default.
|
|
1345
|
+
--dir <sub> Scope the bulb's dir to a subfolder for this run:
|
|
1346
|
+
tb.dir and relative tb.fs paths land in
|
|
1347
|
+
<bulb-folder>/<sub>. Batch runs without touching
|
|
1348
|
+
the bulb's code (e.g. --dir batch2). Relative
|
|
1349
|
+
subpaths only \u2014 no absolute paths or '..'.
|
|
1350
|
+
--server Run server.ts only, no web server (needs --trust)
|
|
1351
|
+
--args <json-array> For 'call': the whole argument list as one JSON
|
|
1352
|
+
array (strict). '--args -' reads it from stdin,
|
|
1353
|
+
sidestepping shell quoting.
|
|
1354
|
+
--replace <name>=<path> Replace a declared dependency with a local built
|
|
1355
|
+
package folder instead of a CDN (dev only).
|
|
1356
|
+
Applies to both run and check. Watched for
|
|
1357
|
+
rebuilds under --watch; --no-watch freezes it.
|
|
1358
|
+
e.g. --replace tensorgrad=../tensorgrad
|
|
1359
|
+
-V, --version Show version number
|
|
1360
|
+
-h, --help Show this help message
|
|
1361
|
+
|
|
1362
|
+
Filesystem API:
|
|
1363
|
+
Bulbs can read and write local files via tb.fs:
|
|
1364
|
+
await tb.fs.read('file.txt') // UTF-8 text (throws on non-UTF-8)
|
|
1365
|
+
await tb.fs.readBytes('image.png') // raw bytes (Uint8Array)
|
|
1366
|
+
await tb.fs.write('output.html', content) // text or bytes
|
|
1367
|
+
|
|
1368
|
+
Server API:
|
|
1369
|
+
Add a **server.ts** section to run Node.js code server-side.
|
|
1370
|
+
Exported functions become callable from the browser:
|
|
1371
|
+
// in **server.ts**: export async function query(sql) { ... }
|
|
1372
|
+
// in **code.tsx**: const rows = await tb.server.query(sql)
|
|
1373
|
+
.env / .env.local load from the working directory; --mode <name> adds .env.<name>.
|
|
1374
|
+
|
|
1375
|
+
Built-in server functions (available without a **server.ts** section):
|
|
1376
|
+
tb.server.log(...) Print to the CLI's stdout
|
|
1377
|
+
|
|
1378
|
+
AI API:
|
|
1379
|
+
Bulbs can call AI providers via tb.ai(). Set API keys in .env:
|
|
1380
|
+
ANTHROPIC_API_KEY=sk-ant-...
|
|
1381
|
+
OPENAI_API_KEY=sk-...
|
|
1382
|
+
GOOGLE_API_KEY=AIza...
|
|
1383
|
+
OPENROUTER_API_KEY=sk-or-...
|
|
1384
|
+
Set provider and model (required):
|
|
1385
|
+
TB_AI_PROVIDER=anthropic
|
|
1386
|
+
TB_AI_MODEL=claude-haiku-4-5-20251001
|
|
1387
|
+
Both can be overridden per-call: tb.ai({ provider: "openai", model: "gpt-5.4-mini", ... })
|
|
1388
|
+
Don't guess a model id \u2014 run 'typebulb models' to list the exact ids your keys cover.
|
|
1389
|
+
Optional effort level (1=low, 2=med, 3=high; omit for the model's native default):
|
|
1390
|
+
tb.ai({ ..., effort: 2 })
|
|
1391
|
+
|
|
1392
|
+
Examples:
|
|
1393
|
+
typebulb my-editor.bulb.md
|
|
1394
|
+
typebulb --no-watch --port 8080 my-editor.bulb.md
|
|
1395
|
+
typebulb .
|
|
1396
|
+
`)}vt();xn();ls();qn();Hi();Hl();var Po={claude:{adapter:()=>new _r,server:()=>Promise.resolve().then(()=>(Mg(),Lg))},pi:{adapter:()=>new Lr,server:()=>Promise.resolve().then(()=>(Wg(),Hg))}};function Yg(r){return r in Po}function jr(){return Object.keys(Po)}function Vg(){return Object.fromEntries(Object.entries(Po).map(([r,e])=>[r,e.adapter]))}function Gg(r){return Po[r].server()}vt();import*as Ot from"path";import{spawn as bP,execSync as wP}from"child_process";import{createRequire as vP}from"module";import{existsSync as SP}from"fs";import*as ae from"fs/promises";import*as se from"path";var lu=[{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"}],uu=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function fu(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 VT=`
|
|
1397
1397
|
/**
|
|
1398
1398
|
* Get raw data chunk from the Data tab.
|
|
1399
1399
|
* @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
|
|
@@ -1404,7 +1404,7 @@ ${$t(t)}
|
|
|
1404
1404
|
* @param index - Chunk index (0-based)
|
|
1405
1405
|
* @throws If chunk is not valid JSON/JSON-ish
|
|
1406
1406
|
*/
|
|
1407
|
-
json<T = unknown>(index: number): T;`,
|
|
1407
|
+
json<T = unknown>(index: number): T;`,GT=`
|
|
1408
1408
|
/**
|
|
1409
1409
|
* Get the insight data produced by the inference layer.
|
|
1410
1410
|
*
|
|
@@ -1413,7 +1413,7 @@ ${$t(t)}
|
|
|
1413
1413
|
*
|
|
1414
1414
|
* @returns The parsed insight JSON, or undefined if no insight is available
|
|
1415
1415
|
*/
|
|
1416
|
-
insight<T = unknown>(): T | undefined;`,
|
|
1416
|
+
insight<T = unknown>(): T | undefined;`,zg=`options: {
|
|
1417
1417
|
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
1418
1418
|
system?: string;
|
|
1419
1419
|
/** Reasoning effort hint: 0=minimal, 1=low, 2=med, 3=high. Mapped to each provider's native mechanism (OpenAI/OpenRouter reasoning effort, Gemini thinking budget, Anthropic adaptive thinking). 0 minimizes reasoning \u2014 a floor, not a guaranteed "off": some models still think a little at 0, and adaptive models already self-skip at 1 (low). Level 1 (low) is the sensible default for most work; reach for 0 only when you truly want minimal deliberation. Omit for the model's own default. */
|
|
@@ -1424,12 +1424,12 @@ ${$t(t)}
|
|
|
1424
1424
|
webSearch?: boolean;
|
|
1425
1425
|
/** Abort the request. On abort the promise rejects / the stream ends. */
|
|
1426
1426
|
signal?: AbortSignal;
|
|
1427
|
-
}`,
|
|
1427
|
+
}`,Xg=`
|
|
1428
1428
|
/** A single streamed delta from \`tb.ai.stream()\`. Discriminated by \`kind\`. */
|
|
1429
1429
|
type AiChunk =
|
|
1430
1430
|
| { kind: "text"; text: string }
|
|
1431
1431
|
| { kind: "reasoning"; text: string };
|
|
1432
|
-
`,
|
|
1432
|
+
`,Qg=`
|
|
1433
1433
|
/**
|
|
1434
1434
|
* General-purpose AI call. \`tb.ai(opts)\` resolves with the full text; \`tb.ai.stream(opts)\`
|
|
1435
1435
|
* returns an async iterable of {@link AiChunk} deltas you consume with \`for await\`.
|
|
@@ -1438,7 +1438,7 @@ type AiChunk =
|
|
|
1438
1438
|
* @throws On rate limit, network error, or provider error
|
|
1439
1439
|
*/
|
|
1440
1440
|
ai: {
|
|
1441
|
-
(${
|
|
1441
|
+
(${zg}): Promise<{ text: string }>;
|
|
1442
1442
|
/**
|
|
1443
1443
|
* Streaming counterpart of \`tb.ai()\`. Yields \`{ kind: "text" | "reasoning", text }\` deltas
|
|
1444
1444
|
* as they arrive; break the loop (or abort \`signal\`) to cancel and stop the upstream.
|
|
@@ -1452,8 +1452,8 @@ type AiChunk =
|
|
|
1452
1452
|
* if (c.kind === "text") answer += c.text;
|
|
1453
1453
|
* }
|
|
1454
1454
|
*/
|
|
1455
|
-
stream(${
|
|
1456
|
-
};`,
|
|
1455
|
+
stream(${zg}): AsyncIterable<AiChunk>;
|
|
1456
|
+
};`,Zg=`
|
|
1457
1457
|
/**
|
|
1458
1458
|
* Returns AI models available to the current user.
|
|
1459
1459
|
* Models are filtered by the user's configured API keys.
|
|
@@ -1477,7 +1477,7 @@ type AiChunk =
|
|
|
1477
1477
|
* making many AI calls should check this and show a "use your own keys"
|
|
1478
1478
|
* notice instead of running.
|
|
1479
1479
|
*/
|
|
1480
|
-
hasOwnKeys(): Promise<boolean>;`,
|
|
1480
|
+
hasOwnKeys(): Promise<boolean>;`,zT="\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;",ey=`
|
|
1481
1481
|
/**
|
|
1482
1482
|
* The mode this bulb is running in.
|
|
1483
1483
|
*
|
|
@@ -1487,7 +1487,7 @@ type AiChunk =
|
|
|
1487
1487
|
* - \`'embedded'\` \u2014 Running as a bulb embedded inside another bulb (sandboxed,
|
|
1488
1488
|
* client-only: AI, filesystem, and server RPC are unavailable)
|
|
1489
1489
|
*/
|
|
1490
|
-
mode: 'local' | 'editor' | 'published' | 'embedded';`,
|
|
1490
|
+
mode: 'local' | 'editor' | 'published' | 'embedded';`,ty=`
|
|
1491
1491
|
/**
|
|
1492
1492
|
* Local filesystem access (CLI only).
|
|
1493
1493
|
*
|
|
@@ -1504,7 +1504,7 @@ type AiChunk =
|
|
|
1504
1504
|
readBytes(path: string): Promise<Uint8Array>;
|
|
1505
1505
|
/** Write text or raw bytes to a file. Creates parent directories if needed. */
|
|
1506
1506
|
write(path: string, content: string | Uint8Array): Promise<boolean>;
|
|
1507
|
-
};`,
|
|
1507
|
+
};`,ry=`
|
|
1508
1508
|
/**
|
|
1509
1509
|
* The bulb's folder \u2014 absolute path to \`<bulb-dir>/<filename-stem>/\`
|
|
1510
1510
|
* (or its subfolder when the run is scoped with \`--dir\`).
|
|
@@ -1513,7 +1513,7 @@ type AiChunk =
|
|
|
1513
1513
|
* \`tb.fs\` already resolves relative paths against it, so bulb code writing
|
|
1514
1514
|
* its own files never needs it. CLI only \u2014 throws in editor/published/embedded mode.
|
|
1515
1515
|
*/
|
|
1516
|
-
readonly dir: string;`,
|
|
1516
|
+
readonly dir: string;`,XT=`
|
|
1517
1517
|
/**
|
|
1518
1518
|
* Async value inspector for tensor-like objects.
|
|
1519
1519
|
*
|
|
@@ -1580,39 +1580,39 @@ type AiChunk =
|
|
|
1580
1580
|
*
|
|
1581
1581
|
* @returns The full canonical URL
|
|
1582
1582
|
*/
|
|
1583
|
-
url(): Promise<string>;`,
|
|
1583
|
+
url(): Promise<string>;`,QT="\n /**\n * Subscribe to a value pushed from the terminal via `typebulb send <file> [message]`.\n *\n * The dual of `tb.server.log` (data out): a value sent *in* from the CLI, no `--trust` required.\n * Use it to start expensive work on demand instead of on load \u2014 e.g. `tb.onMessage(() => start())`\n * \u2014 so hot reloads don't re-trigger it while you edit, and an agent kicks off one run when ready.\n *\n * The message is the JSON-parsed value of what `send` was given (or the raw string if it isn't\n * JSON; `undefined` for a bare `typebulb send <file>`). A non-`undefined` return value (awaited)\n * becomes the reply `send --wait` prints on stdout \u2014 JSON-serializable, at most one handler\n * replying \u2014 the structured read-back for self-tests. Returns an unsubscribe function. Inert in\n * an embedded bulb (no sender) \u2014 the handler is registered but never fires.\n *\n * @param handler - Called with each pushed message; may return a JSON-serializable reply.\n * @returns An unsubscribe function.\n */\n onMessage(handler: (message: any) => unknown): () => void;",ZT="\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>>;",du=`${Xg}
|
|
1584
1584
|
/**
|
|
1585
1585
|
* Typebulb utilities namespace.
|
|
1586
1586
|
* Type \`tb.\` to discover available helpers.
|
|
1587
1587
|
*/
|
|
1588
|
-
declare const tb: {${
|
|
1588
|
+
declare const tb: {${VT}${XT}${GT}${ZT}${QT}${Qg}${ty}${ry}${Zg}${zT}${ey}
|
|
1589
1589
|
};
|
|
1590
|
-
`,
|
|
1590
|
+
`,pu=`${Xg}
|
|
1591
1591
|
/**
|
|
1592
1592
|
* Typebulb utilities namespace (server-side).
|
|
1593
1593
|
* Type \`tb.\` to discover available helpers.
|
|
1594
1594
|
*/
|
|
1595
|
-
declare const tb: {${
|
|
1595
|
+
declare const tb: {${Qg}${ty}${ry}${Zg}${ey}
|
|
1596
1596
|
};
|
|
1597
|
-
`;import
|
|
1597
|
+
`;Ke();import nP from"p-limit";Ke();import{resolve as sy}from"resolve.exports";var Ze={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},Qn=["index.d.ts","index.d.mts"],mu=/\.d\.(ts|mts|cts)$/i;function Oo(r){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(r)||/[?&]dts(?:[&#]|$)/i.test(r)}function ny(r){return[`${r}.d.ts`,`${r}.d.mts`]}function Pt(r){if(!r||r==="./"||r==="/")return[...Qn];let e=r.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=ny(e),n=e.endsWith("/")?e:`${e}/`;return t.push(...ny(`${n}index`)),t}async function Fr(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(eP(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function eP(r){return r===408||r===429||r>=500&&r<600}var Co=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)||Oo(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 B({name:e,version:t})),s=await Fr(n);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new B({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=jt(e.path);if(!o||o==="/"||o===".")return this.tryUntilSuccess([...Qn],t);if(!mu.test(o)){let a=await this.tryUntilSuccess(Pt(o),t);if(a)return a}return t(o)}let s=Pt(e.path),i=n?.subpath?[...s,...Qn]:[...Qn,...s];return this.tryUntilSuccess(i,t)}toResolutionResult(e){return{kind:mu.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(sy(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(sy(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=B.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 B(i).format(),a=new B({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=qc(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(Pt(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=jt(n),i=new URL(s,e).toString(),o=await this.tryUrls([i]);return o?{dts:o.dts,url:o.url,resolvedPkg:t}:void 0}};Ke();import{gunzipSync as tP}from"fflate";var _o=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Fr(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=tP(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 Ro=class{constructor(e,t,n=new _o){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=Ft.majorOf(n),o=e.filter(a=>Ft.majorOf(a)===i);if(o.length)return o.sort((a,c)=>Ft.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=Pt(e);return t!==e&&n.push(`${e}.d.ts`,`${e}/index.d.ts`),n}async fetchFromVersionedRoot(e,t){let n=new B(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 B(t).format():t.name}}}async resolve(e){let t=B.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 No=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(`
|
|
1598
1598
|
`).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
|
|
1599
|
-
`),n=new Set;for(let s of t.matchAll(/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/g))n.add(s[2]);for(let s of t.matchAll(/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/g))n.add(s[1]);return Array.from(n)}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};var
|
|
1600
|
-
`);await this.prefetchBareDeps(
|
|
1601
|
-
`,"utf8"),await
|
|
1602
|
-
`,"utf8"),{dir:e}}function
|
|
1603
|
-
`))console.log(`${e} ${n}`);return r.length>0}function
|
|
1599
|
+
`),n=new Set;for(let s of t.matchAll(/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/g))n.add(s[2]);for(let s of t.matchAll(/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/g))n.add(s[1]);return Array.from(n)}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};Ke();var iy="file:///node_modules",Io=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${iy}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=jt(t);return`${iy}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as rP}from"lru-cache";function oy(r){let e=new rP({ttl:Ze.negativeTtlMs,max:500}),t=new Map;return async function(s){try{if(await r.isNegative(s)||e.has(s))return;let i=await r.getCachedFile(s);if(i)return{dts:i,url:s};let o=t.get(s);if(o)return o;let a=(async()=>{let c=await Fr(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 Zn=class{constructor(e){this.inFlight=new Map,this.scanner=new No,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=oy(e.cache),this.typescriptProvider=new Co(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Ro(e.cdnClient,e.cache),this.virtualFs=new Io}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 B(n).subpath===new B(a.resolvedPkg||n).subpath){try{await this.cache.setCachedDts(n,a.dts,a.url)}catch{}return a}}extractPackageRootUrl(e){let t=e.pathname.match(/^(.+@[^/]+\/)/);return t?new URL(t[1],e.origin):new URL("./",e)}toVirtualPath(e,t,n){let s=t.pathname.startsWith(e.pathname)?t.pathname.slice(e.pathname.length):`__deps__/${encodeURIComponent(t.toString()).replace(/%/g,"_")}.d.ts`;return this.virtualFs.pathFor(n,s)}computeEntryPath(e,t){if(!e)return{mainPath:this.virtualFs.pathForMain(t),packageRootUrl:void 0};let n=new URL(e),s=this.extractPackageRootUrl(n);return{mainPath:this.toVirtualPath(s,n,t),packageRootUrl:s}}async expandRelativeRefs(e,t,n,s,i=new Set,o){if(!i.has(t)&&(i.add(t),!(i.size>Ze.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.scanner.collectRelativeTypeRefs(e).slice(0,Ze.maxRelativeTypeRefs);for(let 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=Oo(c)?[c]:Pt(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 B(e).name!==new B(t).name}ambientlyDeclares(e,t){if(/^(?:import|export)\b/m.test(e))return!1;for(let n of e.matchAll(/declare\s+module\s+['"]([^'"]+)['"]/g)){let s=n[1];if(s===t||s.endsWith("/*")&&t.startsWith(s.slice(0,-1)))return!0}return!1}markFileAmbient(e,t){let n=e.find(s=>s.path===t);n&&(n.ambient=!0)}async prefetchBareDeps(e,t,n,s,i){try{let o=this.scanner.collectBareModuleRefs(e).slice(0,Ze.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=nP(Ze.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,Ze.maxBareDepth,a,i).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,i,o){if(s<=0||i.has(e))return;i.add(e);let a=await this.fetchRootDts(e,o);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):n.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let d=this.scanner.collectBareModuleRefs(a.dts).slice(0,Ze.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 B(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 B(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(A=>A.content).join(`
|
|
1600
|
+
`);await this.prefetchBareDeps(b,l,f,p,s);let m=c.format(),g=e===m?[e]:[e,m],x=g.some(A=>this.ambientlyDeclares(i,A));return x?this.markFileAmbient(f,d):p.push(...g.map(A=>({module:A,path:d}))),{pkg:e,mainPath:d,files:f,shims:p,ambient:x}}};Xc();Ke();wr();$n();Gc();br();import*as qr from"path";var sP=qr.join(yi,"pkg"),iP=qr.join(yi,"files"),oP=qr.join(yi,"negative.json"),Lo=class{pkgMem=new Map;fileMem=new Map;negativeCache=new qt(new vr(oP));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await G();let t=await He(ay(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 $o(async()=>{await G(),await he(ay(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await G();let t=await gi(cy(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await $o(async()=>{await G(),await he(cy(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await $o(async()=>{await G(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return $o(()=>this.negativeCache.clearNegative(e))}};async function $o(r){try{await r()}catch{}}function ay(r){return qr.join(sP,ke(r)+".json")}function cy(r){return qr.join(iP,ke(r)+".txt")}wr();var hu;function aP(){return hu||(hu=new Zn({cache:new Lo,cdnClient:xm,packageService:Si,versionResolver:km})),hu}var ly="file:///node_modules/";async function uy(r){let e=bi(r.emitKey,"typecheck");await G(),await ae.rm(e,{recursive:!0,force:!0}),await ae.mkdir(e,{recursive:!0});let t=fP(r.jsxImportSource,r.dependencies),n=await aP().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=Mo(u.path);if(!f||o.has(f))continue;o.add(f);let p=se.join(e,"node_modules",f);await ae.mkdir(se.dirname(p),{recursive:!0}),await ae.writeFile(p,u.content,"utf8")}let a={};for(let d of i)for(let u of d.shims){let f=Mo(u.path);f&&(a[u.module]=[`./node_modules/${f}`])}for(let d of i){if(d.ambient)continue;let u=Mo(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=Mo(u.path);f&&c.add(`node_modules/${f}`)}if(r.local){delete a[r.local.name];let d=await dP(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=cP(r.jsxImportSource,a,[...c]);return await ae.writeFile(se.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
|
|
1601
|
+
`,"utf8"),await ae.writeFile(se.join(e,"code.tsx"),r.code,"utf8"),await ae.writeFile(se.join(e,"tb.d.ts"),du,"utf8"),{dir:e}}var gu={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function cP(r,e,t=[]){return{compilerOptions:{...gu,lib:lP([...lu,...uu]),jsx:"react-jsx",jsxImportSource:r??"react",paths:e},include:["code.tsx","tb.d.ts",...t]}}function lP(r){return fu(r).map(e=>uP(e.name))}function uP(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 fP(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function Mo(r){if(!r.startsWith(ly))return;let e=r.slice(ly.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function dP(r,e){if(!r.typesAbs)return;let t=se.dirname(r.typesAbs),n=se.join(e,"node_modules",r.name);for(let s of await pP(t)){let i=se.join(n,se.relative(t,s));await ae.mkdir(se.dirname(i),{recursive:!0}),await ae.copyFile(s,i)}return se.basename(r.typesAbs)}async function pP(r){let e=[];async function t(n){let s=await ae.readdir(n,{withFileTypes:!0});for(let i of s){let o=se.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 be from"fs/promises";import*as et from"path";import{existsSync as mP}from"fs";wr();Zc();var hP="^22";async function fy(r){let e=bi(r.emitKey,"typecheck-server");await G(),await be.rm(e,{recursive:!0,force:!0}),await be.mkdir(e,{recursive:!0});let t=et.join(r.bulbDir,".typebulb"),n=Oi(r.server).filter(o=>o!==r.local?.name);await Pi([`@types/node@${hP}`,...n],t,r.dependencies,{ignoreScripts:!0});let s=et.join(t,"node_modules"),i=et.join(e,"node_modules");return await yP(s,i),await be.writeFile(et.join(e,"server.ts"),r.server,"utf8"),await be.writeFile(et.join(e,"tb.d.ts"),pu,"utf8"),await be.writeFile(et.join(e,"tsconfig.json"),JSON.stringify(gP(r.local),null,2)+`
|
|
1602
|
+
`,"utf8"),{dir:e}}function gP(r){let e={...gu,lib:["ES2023"],types:["node"]};if(r?.typesAbs){let t=i=>i.replace(/\\/g,"/"),n=t(et.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 yP(r,e){if(!mP(r)){await be.mkdir(e,{recursive:!0});return}await be.rm(e,{recursive:!0,force:!0});let t=process.platform==="win32"?"junction":"dir";await be.symlink(r,e,t)}di();async function py(r,e){let{bulb:t,config:n,warnings:s}=await Ae(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=dy(En(t.code,{target:"client",dependencies:n.dependencies??{}}),"client")||i),t.server&&(i=dy(En(t.server,{target:"server"}),"server")||i);let o=EP([process.cwd(),Ot.dirname(r)]);if(!o){let l=Ot.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 uy({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 fy({server:t.server,bulbDir:Ot.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 kP(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 dy(r,e){for(let t of r)for(let n of t.message.split(`
|
|
1603
|
+
`))console.log(`${e} ${n}`);return r.length>0}function kP(r,e){return new Promise(t=>{let n=bP(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 xP=vP(import.meta.url);function EP(r){let e=n=>{try{let s=xP.resolve("typescript/package.json",{paths:n}),i=Ot.join(Ot.dirname(s),"lib","tsc.js");return SP(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=wP("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}vt();Qi();qn();async function my(r,e){let{bulb:t}=await Ae(r),n=Nr(t);if(Yt(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.)")}qn();import*as es from"path";async function hy(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=vl();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=es.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),Or(t,e),console.log(e?`Trusted ${es.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${es.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}$e();import*as wy from"readline";var ts=Vg();function gy(){for(let r of Object.values(ts))try{r().ensureHarnessSupport()}catch{}}function rs(){for(let r of Object.keys(ts))try{if(ts[r]().detectsSelf())return r}catch{}}function yy(r){let e=jr(),t=new Map(e.filter(i=>ts[i]).map(i=>[i,ts[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)))}}Zi();function yu(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 vy(r){let e=yy(process.cwd());if("ambiguous"in e){let t=await AP(r,e.ambiguous);return t?by(r,t):TP(r,e.ambiguous)}return by(r,e.name)}async function by(r,e){let t,n;try{t=await ah(e)}catch(d){n=d instanceof Error?d.message:String(d)}let{lit:s,litLink:i,brand:o}=yu(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(Ir())}`,` ${s(zt())}`],c=t?[` Agent mirror (${e}) 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(`
|
|
1604
1604
|
`)+`
|
|
1605
|
-
`)}async function
|
|
1605
|
+
`)}async function AP(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:n}=yu(!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(`
|
|
1606
1606
|
`)+`
|
|
1607
|
-
`);let i=
|
|
1607
|
+
`);let i=wy.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 TP(r,e){let{lit:t,brand:n}=yu(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(`
|
|
1608
1608
|
`)+`
|
|
1609
|
-
`)}
|
|
1610
|
-
`+e)}function
|
|
1609
|
+
`)}xt();Wt();async function Sy(r){ye(r);let e=await Ye();if(e.length>0){console.log(Bm(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!ml()){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(Ar))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.")}Zi();import*as ky from"fs/promises";async function xy(r){let e=zt(),t;try{t=await ky.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(gh(t,r))}Fi();import*as Ey from"path";$e();function PP(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&&ne(o.cwd)===ne(t));return n&&i.find(o=>o.agent===n)||i[0]}return r.find(i=>ne(i.file)===ne(e))}var ns=r=>r.agent??Ey.basename(r.file);function Ay(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"}${t.dir?` --dir ${t.dir}`:""} ${t.file}`)}function bu(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),Ay(r,t=>console.log(t)),console.log(`
|
|
1610
|
+
`+e)}function wu(r,e,t,n,s){let i=PP(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>\`):`),Ay(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function Ty(r,e){if(!r){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),bu(await Q(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=wu(await Q(),r,"logs",process.cwd(),rs());if(e.clear){th(t.pid),console.log(`Cleared log for ${ns(t)} (pid ${t.pid}).`);return}let n=Ie(t.pid),s=n.text;if(e.run!==void 0&&(s=rh(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(`
|
|
1611
1611
|
`);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
|
|
1612
1612
|
`)}if(process.stdout.write(s),s&&!s.endsWith(`
|
|
1613
1613
|
`)&&process.stdout.write(`
|
|
1614
|
-
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=
|
|
1615
|
-
`);m=
|
|
1614
|
+
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=Ie(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 OP=r=>new Promise(e=>setTimeout(e,r));async function Py(r,e){if(!r){bu(await Q(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=wu(await Q(),r,"wait",process.cwd(),rs()),n=t.agent!=null,i=process.env.TYPEBULB_WAIT_SHIM==="1",o=e.timeoutSec??1800,a=e.match??"",c=Ie(t.pid).offset,l=Rl(t.pid,a)??(a?Rl(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,m="",g=0;for(;;){let x=Ie(t.pid,d);if(d=x.offset,x.text){m+=x.text;let A=m.split(`
|
|
1615
|
+
`);m=A.pop()??"";for(let P of A)P.trim()&&(e.match&&!P.includes(e.match)||(console.log(P),b??=Date.now()+f,n&&(P.includes("] compile error")||P.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 ${ns(t)} within ${o}s`),g=2;break}if(!Il(t.pid)){b||(console.error(`server ${ns(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await OP(400)}Yi(t.pid,d,a),process.exit(g)}async function Oy(r){if(!r){bu(await Q(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=wu(await Q(),r,"stop",process.cwd(),rs());await Vt(e.pid),console.log(`Stopped ${ns(e)} (pid ${e.pid}, ${e.url}).`)}async function Cy(r){let e=process.cwd(),t=r==="agent"?rs():void 0,n=r==="global"?await Q():r==="bulbs"?await Q(e):(await Q()).filter(i=>i.agent!=null&&i.cwd!=null&&ne(i.cwd)===ne(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=>Vt(i.pid))),console.log(`Stopped ${n.length} ${s}${n.length===1?"":"s"}:`);for(let i of n)console.log(` ${i.url} pid ${i.pid} ${ns(i)}`)}$e();import*as _y from"path";async function Ry(r,e,t=0){let n=e!==void 0&&e.startsWith("tb:");n&&t<=0&&(t=Yo);let s=_y.resolve(r),i=Rr(await Q(),s)[0];i||(console.error(`No running server for '${r}'. Start it first: npx typebulb ${r}`),process.exit(1));let o=async f=>{let p=await fetch(`${i.url}/__send${f>0?`?reply=${f}`:""}`,{method:"POST",headers:{"Content-Type":"text/plain"},body:e??""});return p.ok||(console.error(`send failed: HTTP ${p.status} from ${i.url}/__send`),process.exit(1)),await p.json().catch(()=>({}))},a={};try{let f=Date.now()+t;do{if(a=await o(t>0?Math.max(f-Date.now(),1e3):0),(a.clients??0)>0||Date.now()>=f)break;await new Promise(p=>setTimeout(p,150))}while(!0)}catch(f){console.error(`send failed: ${f instanceof Error?f.message:String(f)}`),process.exit(1)}let c=a.clients??0,l=`${c} page${c===1?"":"s"}`;if(c===0){t>0?console.error(`No page connected after ${t/1e3}s \u2014 is the bulb open?`):console.error("Sent, but no page is connected yet \u2014 open the bulb and retry."),n&&process.exit(1);return}console.error(`Sent to ${l}.`);let d=a.results??[],u=a.errors??[];for(let f of u)console.error(`handler error: ${f}`);if(u.length&&process.exit(1),d.length>1&&(console.error(`${d.length} replies from ${l} \u2014 one reply owns stdout: at most one tb.onMessage handler, in one page, may return a value.`),process.exit(1)),d.length===1){let f;try{f=JSON.parse(d[0])}catch{f=void 0}console.log(typeof f=="string"?f:d[0])}else a.timedOut&&(n&&(console.error(`No reply to '${e}' within ${t/1e3}s \u2014 reload the page and retry.`),process.exit(1)),console.error(`(no reply within ${t/1e3}s \u2014 a slow handler's return needs a larger --wait=ms)`))}so();Jl();xt();vt();Re();Qi();import*as _t from"fs/promises";import*as os from"path";import{EventEmitter as jy}from"events";import JP from"open";Er();Re();import{Hono as $P}from"hono";import{serve as LP}from"@hono/node-server";import{streamSSE as MP}from"hono/streaming";import*as xu from"fs/promises";import*as Ly from"path";wr();$n();br();import*as vu from"fs/promises";import*as ss from"path";var Do=class{async get(e){let t=ke(e),n=ss.join(In,t+".bin"),s=ss.join(In,t+".json");try{let[i,o]=await Promise.all([vu.readFile(n),vu.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await G();let n=ke(e),s=ss.join(In,n+".bin"),i=ss.join(In,n+".json"),o={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([he(s,t.body),he(i,JSON.stringify(o))])}};var Ny=`
|
|
1616
1616
|
const CSS = '\\n' +
|
|
1617
1617
|
/* The agent mirror's token set, verbatim (agents/core/client/styles.css) \u2014 one system across CLI
|
|
1618
1618
|
chrome: app chrome sits on --panel, content wells paint --veil, grays ride one neutral tint.
|
|
@@ -1916,17 +1916,18 @@ export function runInference(ctx) {
|
|
|
1916
1916
|
showConfirm();
|
|
1917
1917
|
document.body.appendChild(host);
|
|
1918
1918
|
}
|
|
1919
|
-
|
|
1920
|
-
${
|
|
1921
|
-
`+
|
|
1922
|
-
${s}`),console.log(` ${c}`),o!==e&&console.log(` (port ${e} was busy)`);let l=[],
|
|
1923
|
-
Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await
|
|
1919
|
+
`;$e();Wt();Di();Er();import{stream as CP}from"hono/streaming";var _P="X-TB-Stream";function is(r){return r instanceof pe?{message:r.message,code:r.code,retryable:r.retryable}:{message:r instanceof Error?r.message:"Unknown error",code:"unknown",retryable:!1}}function Bo(r,e){return r.header("Content-Type","application/x-ndjson; charset=utf-8"),r.header("Cache-Control","no-cache"),r.header(_P,"1"),CP(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:is(s)}))}finally{try{await n.return?.()}catch{}}})}var jo={log:(...r)=>console.log(...r)};function Fo(r,e){let t=r?.[e]??(Object.hasOwn(jo,e)?jo[e]:void 0);return typeof t=="function"?t:void 0}function qo(r){return r.constructor?.name==="AsyncGeneratorFunction"}hl();var RP=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,NP=/[?&]target=/,IP=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function Iy(r,e=""){return RP.test(r)?!0:IP.test(r)&&NP.test(e)}var My="127.0.0.1",DP=new Set(["localhost","127.0.0.1","::1"]);function BP(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function jP(r){let e=BP(r);return!!e&&DP.has(e)}function FP(r,e){if(!e)return!1;try{return new URL(r).host===e}catch{return!1}}function Su(r){return r instanceof Error?r.message:"Unknown error"}async function Dy(r){let{getHtml:e,basePath:t,fsBase:n,port:s,reloadEmitter:i,messageEmitter:o,getServerExports:a,getBulbBlocks:c,saveInferenceResult:l,localOverride:d,trusted:u=!1,trustHint:f,staticAssets:p,bulbAssets:b}=r,m=n??t,g=new $P;g.use("*",async(y,k)=>{if(!jP(y.req.header("host")))return y.text("Forbidden: untrusted Host",403);await k()}),g.use("*",async(y,k)=>{await k(),y.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),y.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let x=[["/__fs/*","the filesystem"],["/__api/*","server-side code (server.ts)"],["/__ai","AI (your API keys)"],["/__infer","AI (your API keys)"],["/__infer-save","the filesystem"]],A=async(y,k)=>{if(!u){let I=new URL(y.req.url).pathname,_=x.find(([W])=>W.endsWith("/*")?I.startsWith(W.slice(0,-2)):I===W)?.[1]??"server-side code (server.ts)";sh(process.pid,_);let M=f?`
|
|
1920
|
+
${f}`:"";return y.text(`Forbidden: this capability requires --trust.${M}`,403)}await k()},P=async(y,k)=>{let I=y.req.header("sec-fetch-site");if(I){if(I!=="same-origin")return y.text(`Forbidden: ${I} request`,403)}else{let _=y.req.header("origin");if(_&&!FP(_,y.req.header("host")))return y.text("Forbidden: cross-origin request",403)}await k()};for(let[y]of x)g.use(y,A),g.use(y,P);if(g.use("/__log",P),g.post("/__log",async y=>{try{let{args:k}=await y.req.json();console.log(...k||[])}catch{}return y.json({ok:!0})}),o){let y=0,k=new Map;g.use("/__send",P),g.post("/__send",async I=>{let _="";try{_=await I.req.text()}catch{}let M=Number(I.req.query("reply"))||0,W=o.listenerCount("message");if(M<=0||W===0)return o.emit("message",{payload:_}),I.json({clients:W});let K=++y,Fe=await new Promise(z=>{let V={expected:W,received:0,results:[],errors:[],finish:we=>{clearTimeout(qe),k.delete(K),z({results:V.results,errors:V.errors,timedOut:we})}},qe=setTimeout(()=>V.finish(!0),M);k.set(K,V),o.emit("message",{id:K,payload:_})});return I.json({clients:W,...Fe})}),g.use("/__send-reply",P),g.post("/__send-reply",async I=>{try{let{id:_,results:M,errors:W}=await I.req.json(),K=k.get(_);K&&(K.results.push(...M??[]),K.errors.push(...W??[]),++K.received>=K.expected&&K.finish(!1))}catch{}return I.json({ok:!0})})}g.get("/",y=>y.html(e())),g.post("/__fs/read",async y=>{try{let{path:k}=await y.req.json(),I=await jn(k,m,t);return new Response(new Uint8Array(I),{headers:{"Content-Type":"application/octet-stream"}})}catch(k){let I=Su(k);return y.json({error:I},400)}}),g.post("/__fs/write",async y=>{try{let k=y.req.query("path");return k?(await Bi(k,new Uint8Array(await y.req.arrayBuffer()),m,t),y.json({success:!0})):y.json({error:"Missing path"},400)}catch(k){let I=Su(k);return y.json({error:I},400)}}),g.post("/__api/:name",async y=>{try{let k=y.req.param("name"),I=Fo(a?.(),k);if(!I)return y.json({error:`API function '${k}' not found`},404);let{args:_}=await y.req.json();if(qo(I))return Bo(y,I(..._||[]));let M=await I(..._||[]);return y.json({result:M})}catch(k){let I=Su(k);return y.json({error:I},500)}}),g.post("/__ai",async y=>{try{let{messages:k,system:I,effort:_,provider:M,model:W,webSearch:K,stream:Fe}=await y.req.json();if(!k||!Array.isArray(k)||k.length===0)return y.json({message:"messages array is required",code:"unknown",retryable:!1},400);let z=Ve(M,W);if(typeof z=="string")return y.json({message:z,code:"unknown",retryable:!1},400);let V=await yt(z,{messages:k,system:I,effort:_,webSearch:K,signal:y.req.raw.signal});if(!V.ok){let we=await xr(V,z.protocol);return y.json(we,V.status)}if(Fe)return Bo(y,Ht(V,z.protocol));let qe=await Kt(V,z.protocol);return qe||console.warn("[tb.ai] Empty response from provider"),y.json({text:qe})}catch(k){return y.json(is(k),500)}}),g.post("/__infer",async y=>{try{let{data:k}=await y.req.json().catch(()=>({})),I=c?.();if(!I?.infer.trim())return y.json({message:"This bulb has no infer.md block.",code:"unknown",retryable:!1},400);let _=Ve();if(typeof _=="string")return y.json({message:_,code:"unknown",retryable:!1},400);let M=Array.isArray(k)?k.map(String):[],W=ll(I,M),K=await yt(_,{messages:[{role:"user",content:W}],signal:y.req.raw.signal});if(!K.ok){let z=await xr(K,_.protocol);return y.json(z,K.status)}let Fe=(async function*(){let z="";for await(let we of Ht(K,_.protocol))we.kind!=="text"||!we.text||(z+=we.text,yield{kind:"delta",text:we.text});let V=ul(z);if(V.parsed===null)throw console.warn(`[tb.infer] output not valid JSON after sanitize; raw output (last 4000 chars):
|
|
1921
|
+
`+z.slice(-4e3)),new pe("LLM output is not valid JSON","parse_error",!0);V.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",V.fixesApplied.join(", "));let qe={insight:V.parsed,insightJson:V.json,data:M};yield{kind:"complete",...qe,fixesApplied:V.fixesApplied,hash:fl(qe)}})();return Bo(y,Fe)}catch(k){return y.json(is(k),500)}});let R=async y=>{let{hash:k}=await y.req.json().catch(()=>({}));return typeof k=="string"?dl(k):null};g.post("/__infer-save",async y=>{try{if(!l)return y.json({message:"Save is not available for this server.",code:"unknown",retryable:!1},400);let k=await R(y);return k?(await l(k.data,k.insightJson),y.json({ok:!0})):y.json({message:"No decodable #tb= fragment to save.",code:"unknown",retryable:!1},400)}catch(k){return y.json(is(k),500)}}),g.get("/__infer-info",y=>{let k=c?.(),I=rt(k?.config??"").inference,_=ui(k?.data??""),M=Ve();return typeof M=="string"?y.json({error:M,inference:I,data:_}):y.json({provider:M.protocol,model:M.model,inference:I,data:_})}),g.use("/__infer-decode",P),g.post("/__infer-decode",async y=>y.json(await R(y)??{error:"invalid fragment"})),g.get("/__infer-ui.js",y=>y.body(Ny,200,{"Content-Type":"text/javascript; charset=utf-8"})),g.get("/__models",async y=>{try{let k=await Ye();return y.json(k)}catch{return y.json([],200)}}),g.get("/__has-own-keys",async y=>{try{return y.json(await Mi())}catch{return y.json(!1,200)}});let N=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],O=new Do;g.get("/proxy/*",async y=>{let k=new URL(y.req.url),_=(k.pathname+k.search).slice(7),M=_.lastIndexOf("https://");return M===-1?y.text("Invalid proxy URL",400):$(y,_.slice(M))}),d&&$y(g,`/local/${d.name}/`,d.serveDir),p&&$y(g,p.mount,p.dir),b&&g.get("/assets/*",async y=>{let{pathname:k}=new URL(y.req.url),I=k.slice(8);for(let M of b.dirs){let W;try{W=Bn(decodeURIComponent(I),M)}catch{return y.text("Not Found",404)}try{let K=await xu.readFile(W);return new Response(K,{headers:{"Content-Type":By(W),"Cache-Control":"no-cache"}})}catch{}}let _=b.getRemoteBase();return _?y.redirect(_+I,302):y.text("Not Found",404)});async function $(y,k){let I;try{I=new URL(k)}catch{return y.text("Invalid URL",400)}if(I.protocol!=="https:")return y.text("HTTPS only",400);if(!N.includes(I.hostname))return y.text("Host not allowed",403);let _=await O.get(k);if(_)return new Response(_.body,{status:200,headers:ku(_.contentType,_.cacheControl)});try{let M=await fetch(k,{headers:{Accept:y.req.header("Accept")||"*/*"},redirect:"follow"});if(!M.ok)return y.text(`Upstream ${M.status}`,M.status);let W=M.headers.get("Content-Type")||void 0,K=M.headers.get("Cache-Control")||void 0;if(M.body){let[Fe,z]=M.body.tee();return(async()=>{try{let V=await new Response(z).arrayBuffer();await O.set(k,{body:Buffer.from(V),contentType:W,cacheControl:K})}catch{}})(),new Response(Fe,{status:M.status,headers:ku(W,K)})}return new Response(null,{status:M.status,headers:ku(W,K)})}catch(M){return y.text(`Proxy fetch failed: ${M instanceof Error?M.message:M}`,502)}}(i||o)&&g.get("/__reload",y=>MP(y,async k=>{let I=()=>{k.writeSSE({event:"reload",data:""})},_=M=>{k.writeSSE({event:"message",data:JSON.stringify(M)})};for(i?.on("reload",I),o?.on("message",_),k.onAbort(()=>{i?.removeListener("reload",I),o?.removeListener("message",_)});!k.aborted;)await k.sleep(3e4)})),g.notFound(async y=>{if(y.req.method!=="GET")return y.text("Not Found",404);let k=new URL(y.req.url);return Iy(k.pathname,k.search)?$(y,"https://esm.sh"+k.pathname+k.search):y.text("Not Found",404)});let E=LP({fetch:g.fetch,port:s,hostname:My});return{port:s,close:()=>E.close()}}function ku(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 $y(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=Bn(i,t),a=await xu.readFile(o);return new Response(a,{headers:{"Content-Type":By(o)}})}catch{return n.text("Not Found",404)}})}function By(r){switch(Ly.extname(r).toLowerCase()){case".js":case".mjs":return"text/javascript";case".wasm":return"application/wasm";case".json":case".map":return"application/json";case".svg":return"image/svg+xml";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".avif":return"image/avif";case".ico":return"image/x-icon";case".mp3":return"audio/mpeg";case".wav":return"audio/wav";case".ogg":return"audio/ogg";case".m4a":return"audio/mp4";case".mp4":return"video/mp4";case".webm":return"video/webm";case".woff2":return"font/woff2";case".ttf":return"font/ttf";case".css":return"text/css";case".txt":return"text/plain; charset=utf-8";default:return"application/octet-stream"}}async function Eu(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,My,()=>{let s=n.address(),i=typeof s=="object"&&s?s.port:r;n.close(()=>t(i))}),n.on("error",()=>{t(Eu(r+1))})})}$e();async function Uo(r){let{portPreference:e,makeServerOptions:t,makeEntry:n,displayName:s,stopLog:i}=r,o=await Eu(e),a=await Dy(t(o)),c=`http://localhost:${o}`;await nh(n(o,c)),console.log(`
|
|
1922
|
+
${s}`),console.log(` ${c}`),o!==e&&console.log(` (port ${e} was busy)`);let l=[],d=async()=>{console.log(`
|
|
1923
|
+
Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await Kn(process.pid),process.exit(0)};return process.on("SIGINT",d),process.on("SIGTERM",d),{port:o,url:c,onCleanup(u){l.push(u)}}}import qP from"chokidar";var UP={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function Ct(r){let{target:e,onChange:t,events:n="change",debounceMs:s=150}=r,i,o=qP.watch(e,UP),a=()=>{i&&clearTimeout(i),i=setTimeout(t,s)};return n==="all"?o.on("all",a):o.on("change",a),()=>{i&&clearTimeout(i),o.close()}}$e();async function Fy(r,e,t,n){let s=process.cwd(),i=Vi(process.pid),o=e.watch?new jy:void 0,a=new jy;a.setMaxListeners(0);let c=ye(e.mode),l=await Ll(r);l.length&&console.log(`Replacing the running server for this bulb (pid ${l.map(O=>O.pid).join(", ")})`);let d=1;console.log(Nl(d)),console.log(`Loading ${os.basename(r)}...`);let{html:u,bulb:f,serverExports:p}=await yl(r,e.watch,e.trust,n,e.dir);kt(c,r,f.server);let b=[...e.dir?[os.join(wt(r,e.dir),"assets")]:[],os.join(wt(r),"assets")],m=rt(f.config);m.assets&&!Ur(f.config)&&console.warn(` config.json "assets" is not a valid http(s) URL \u2014 ignored: ${m.assets}`);let g=e.trust?void 0:Nr(f),{port:x,url:A,onCleanup:P}=await Uo({portPreference:e.port,displayName:f.name,stopLog:i,makeServerOptions:O=>({getHtml:()=>u,basePath:s,fsBase:wt(r,e.dir),port:O,reloadEmitter:o,messageEmitter:a,getServerExports:()=>p,getBulbBlocks:()=>({infer:f.infer,insight:f.insight,code:f.code,config:f.config,data:f.data}),saveInferenceResult:async($,E)=>{let y=await _t.readFile(r,"utf-8");y=Qo(y,"data",$.join(Qp)),y=Qo(y,"insight",E),await _t.writeFile(r,y)},localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,bulbAssets:{dirs:b,getRemoteBase:()=>Ur(f.config)},trusted:e.trust,trustHint:t}),makeEntry:(O,$)=>({pid:process.pid,port:O,url:$,file:r,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,dir:e.dir,mode:e.mode,predicted:g})});e.trust?console.log(" trust: granted (filesystem, AI, server.ts enabled)"):console.log(g?` trust: restricted \u2014 this bulb appears to use ${g}; re-run with --trust to enable it:
|
|
1924
1924
|
${t}
|
|
1925
1925
|
`:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
|
|
1926
1926
|
`),e.watch&&console.log(` Watching for changes...
|
|
1927
|
-
`);let
|
|
1928
|
-
`),o.emit("reload")}})}
|
|
1929
|
-
`)
|
|
1927
|
+
`);let R,N;if(e.watch&&o){let O=0,$=Promise.resolve();if(R=Ct({target:r,onChange:()=>{let E=++O;$=$.then(async()=>{if(E===O)try{console.log("Recompiling...");let y=await yl(r,!0,e.trust,n,e.dir);u=y.html,p=y.serverExports,f=y.bulb,d++,console.log(Nl(d)),o.emit("reload")}catch(y){console.error("Compile error:",y)}})}}),n){let{name:E,serveDir:y}=n;N=Ct({target:y,events:"all",onChange:()=>{console.log(`Local package '${E}' changed. Browser reloading...
|
|
1928
|
+
`),o.emit("reload")}})}for(let E of b)await _t.stat(E).then(y=>y.isDirectory()).catch(()=>!1)&&P(Ct({target:E,events:"all",onChange:()=>{console.log(`Assets changed. Browser reloading...
|
|
1929
|
+
`),o.emit("reload")}}))}R&&P(R),N&&P(N),P(()=>_t.rm(gl(r),{force:!0})),e.open&&(l.some(O=>O.port===x)?console.log(` Reusing the open browser tab.
|
|
1930
|
+
`):await JP(A))}xt();import{readFileSync as Uy,copyFileSync as HP,existsSync as WP}from"fs";import*as ie from"path";import{fileURLToPath as YP}from"url";import{EventEmitter as VP}from"events";import Jy from"open";$e();Qc();var Au=r=>`/agents/${r}/client.js`,KP=`
|
|
1930
1931
|
(() => {
|
|
1931
1932
|
const api = async (name, ...args) => {
|
|
1932
1933
|
const resp = await fetch('/__api/' + name, {
|
|
@@ -1961,15 +1962,15 @@ Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await In(pr
|
|
|
1961
1962
|
es.onerror = () => { es.close(); };
|
|
1962
1963
|
}
|
|
1963
1964
|
})();
|
|
1964
|
-
`;function
|
|
1965
|
+
`;function qy(r){let{name:e,agent:t,styles:n,mountHtml:s,watch:i,theme:o}=r,a=Au(t);return`<!DOCTYPE html>
|
|
1965
1966
|
<html>
|
|
1966
1967
|
<head>
|
|
1967
1968
|
<meta charset="utf-8">
|
|
1968
1969
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1969
|
-
<title>${
|
|
1970
|
-
${
|
|
1970
|
+
<title>${ki(e)} - typebulb</title>
|
|
1971
|
+
${Ei(e,o)}
|
|
1971
1972
|
<style>
|
|
1972
|
-
${
|
|
1973
|
+
${xi}
|
|
1973
1974
|
</style>
|
|
1974
1975
|
<style>
|
|
1975
1976
|
${n}
|
|
@@ -1981,17 +1982,17 @@ ${s}
|
|
|
1981
1982
|
${i?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
|
|
1982
1983
|
|
|
1983
1984
|
<script>
|
|
1984
|
-
${
|
|
1985
|
+
${KP}
|
|
1985
1986
|
</script>
|
|
1986
1987
|
|
|
1987
1988
|
<script type="module" src="${a}"></script>
|
|
1988
1989
|
</body>
|
|
1989
|
-
</html>`}async function
|
|
1990
|
-
${n.url}`),r.open&&await
|
|
1991
|
-
`);let
|
|
1992
|
-
`),i.emit("reload")}catch(
|
|
1993
|
-
`);let c=0,l=Promise.resolve();
|
|
1994
|
-
`)}catch(p){
|
|
1995
|
-
`),
|
|
1996
|
-
`),process.exit(1)}function
|
|
1997
|
-
${e}`),process.exit(1))}async function
|
|
1990
|
+
</html>`}async function Ky(r){let e=process.cwd(),t=r.agentTarget;Yg(t)||(console.error(`Unknown agent '${t}'. Known: ${jr().join(", ")}.`),process.exit(1));let n=await $l(e,t);if(n){console.log(`Mirror '${t}' is already running for this project:
|
|
1991
|
+
${n.url}`),r.open&&await Jy(n.url);return}let s=Vi(process.pid),i=r.watch?new VP:void 0,o=ye(r.mode),a=await Gg(t),c=a.displayName||`${t} mirror`;kt(o,ie.join(e,"mirror"));let l=ie.dirname(YP(import.meta.url)),d=ie.join(l,"agents",t),u=ie.join(l,"..","cli","agents"),f=ie.join(d,"styles.css"),p=ie.join(d,"index.html"),b=()=>qy({name:c,agent:t,styles:Uy(f,"utf8"),mountHtml:Uy(p,"utf8"),watch:r.watch}),{port:m,url:g,onCleanup:x}=await Uo({portPreference:r.port,displayName:c,stopLog:s,makeServerOptions:O=>({getHtml:b,basePath:e,port:O,reloadEmitter:i,getServerExports:()=>a,trusted:!0,staticAssets:{mount:`${ie.posix.dirname(Au(t))}/`,dir:d}}),makeEntry:(O,$)=>({pid:process.pid,port:O,url:$,file:`agent:${t}`,cwd:e,startedAt:Date.now(),trust:!0,agent:t})});r.watch&&console.log(` Watching for changes...
|
|
1992
|
+
`);let A=ie.join(u,t,"client"),P=ie.join(u,"core","client");async function R(){await(await import("esbuild")).build({entryPoints:[ie.join(A,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:ie.join(d,"client.js")});for(let $ of["styles.css","index.html","typebulb.png","typebulb-inv.png"])HP(ie.join(P,$),ie.join(d,$))}let N;if(r.watch&&i){let O=WP(A),$=!1;N=Ct({target:O?u:d,events:"all",onChange:async()=>{if(!$){$=!0;try{O&&await R(),console.log(`Mirror rebuilt. Browser reloading...
|
|
1993
|
+
`),i.emit("reload")}catch(E){console.error("Mirror rebuild failed:",E instanceof Error?E.message:E)}finally{$=!1}}}})}r.open&&await Jy(g),x(()=>a.shutdownSwitcher?.()),x(()=>a.shutdownComposer?.()),N&&x(N)}xt();vt();import*as Hy from"path";async function Wy(r,e,t,n,s){let i=ye(t),o=!1,a=async()=>{let{bulb:c,config:l}=await Ae(r);o||(kt(i,r,c.server),o=!0),await Fn(c.server,r,n,l.dependencies,s)};if(console.log(`Running ${Hy.basename(r)}...`),await a(),e){console.log(`Watching for changes...
|
|
1994
|
+
`);let c=0,l=Promise.resolve();Ct({target:r,onChange:()=>{let d=++c;l=l.then(async()=>{if(d===c)try{console.log("Re-running..."),await a()}catch(u){console.error("Error:",u)}})}})}}xt();vt();import{Console as GP}from"node:console";$e();async function Gy(r,e,t,n,s){eO();try{let p=Rr(await Q(),r)[0];p&&(Yi(p.pid,Ie(p.pid).offset),console.error(`note: 'call' boots a fresh server.ts instance; the running server (${p.url}) is not contacted \u2014 state shared with it must live on disk.`))}catch{}let i=ye(t),{bulb:o,config:a}=await Ae(r);o.server||as("This bulb has no **server.ts** block; nothing to call."),kt(i,r,o.server);let c;try{c=await Fn(o.server,r,n,a.dependencies,s)}catch(p){as(p instanceof Error?p.message:String(p))}let l=Fo(c,e.fn);if(!l){let p=[...Object.keys(c).filter(b=>typeof c[b]=="function"),...Object.keys(jo)];as(`Function '${e.fn}' not found. Available: ${p.length?p.join(", "):"(none)"}.`)}let d=await zP(e);if(qo(l)){try{for await(let p of l(...d))await Vy(JSON.stringify(p,zy)+`
|
|
1995
|
+
`)}catch(p){as(p instanceof Error?p.stack??p.message:String(p))}return Yy(0)}let u;try{u=await l(...d)}catch(p){as(p instanceof Error?p.stack??p.message:String(p))}let f=ZP(u);f!==void 0&&await Vy(f+`
|
|
1996
|
+
`),Yy(0)}function Yy(r){process.exitCode=r,setTimeout(()=>process.exit(r),2e3).unref?.()}async function zP(r){if(r.hasArgsFlag){let e=r.argsJson??"";return e==="-"&&(e=await tO()),QP(e)}return XP(r.positional)}function XP(r){return r.map(e=>{try{return JSON.parse(e)}catch{return e}})}function QP(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 ZP(r){if(r!==void 0)return JSON.stringify(r,zy,2)}function zy(r,e){return typeof e=="bigint"?e.toString():e}function as(r){process.stderr.write(r+`
|
|
1997
|
+
`),process.exit(1)}function eO(){let r=new GP(process.stderr,process.stderr);console.log=r.log.bind(r),console.info=r.info.bind(r),console.debug=r.debug.bind(r),console.dir=r.dir.bind(r)}function Vy(r){return new Promise((e,t)=>{process.stdout.write(r,n=>n?t(n):e())})}async function tO(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}var Tu="0.32.0";function Xy(r,e){r||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
|
|
1998
|
+
${e}`),process.exit(1))}async function rO(){let r=qu(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${Tu}`),process.exit(0)),r.help&&(Uu(),process.exit(0)),gy(),r.subcommand==="logs"){await Ty(r.file||void 0,{follow:r.follow,clear:r.clear,run:r.run,lines:r.lines});return}if(r.subcommand==="wait"){await Py(r.file||void 0,{match:r.match,timeoutSec:r.timeoutSec});return}if(r.subcommand==="stop"){r.stopScope?await Cy(r.stopScope):await Oy(r.file||void 0);return}if(r.subcommand==="send"){await Ry(r.file,r.sendMessage,r.sendWaitMs??0);return}if(r.subcommand==="skill"){await xy(Tu);return}if(r.subcommand==="models"){await Sy(r.mode);return}if(r.subcommand==="pull"){await vh(r.file||void 0,{force:r.force,mode:r.mode});return}if(r.subcommand==="push"){await xh(r.file||void 0,{force:r.force,mode:r.mode});return}if(r.subcommand==="agent"){await(r.agentTarget?Ky(r):vy(Tu));return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await hy(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let c=await Um(process.cwd());c||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=c}else e=rr.resolve(r.file);await Qy.access(e).then(()=>!0,()=>!1)||(jr().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:rr.relative(process.cwd(),e)||rr.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await my(e,s);return}let i=!r.noTrust&&Yt(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 Ae(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 Bu(r.local)}catch(c){console.error(c instanceof Error?c.message:String(c)),process.exit(1)}console.error(`replace: ${a.name} \u2192 ${rr.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await py(e,a);return}if(r.subcommand==="call"){Xy(r.trust,s),await Gy(e,{fn:r.fn,positional:r.callArgs,argsJson:r.argsJson,hasArgsFlag:r.hasArgsFlag},r.mode,a,r.dir);return}if(o&&o.bulb.server&&(fi(o.bulb)||r.server)){Xy(r.trust,s),await Wy(e,r.watch,r.mode,a,r.dir);return}await Fy(e,r,s,a)}rO().catch(r=>{console.error("Error:",r.message),process.exit(1)});
|