typebulb 0.34.0 → 0.36.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 +1 -1
- package/dist/agents/claude/client.js +149 -149
- package/dist/agents/claude/styles.css +2 -0
- package/dist/agents/pi/client.js +150 -150
- package/dist/agents/pi/matchu-patchu.ts +1 -1
- package/dist/agents/pi/styles.css +2 -0
- package/dist/format/config.d.ts +16 -0
- package/dist/format/config.d.ts.map +1 -1
- package/dist/format/config.js +49 -0
- package/dist/format/config.js.map +1 -1
- package/dist/index.js +929 -929
- package/dist/render.js +29 -29
- package/dist/servers.js +102 -102
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,54 +1,54 @@
|
|
|
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 wb=Object.create;var Ho=Object.defineProperty;var vb=Object.getOwnPropertyDescriptor;var Sb=Object.getOwnPropertyNames;var xb=Object.getPrototypeOf,kb=Object.prototype.hasOwnProperty;var ls=(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),Lu=(r,e)=>{for(var t in e)Ho(r,t,{get:e[t],enumerable:!0})},Eb=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Sb(e))!kb.call(r,s)&&s!==t&&Ho(r,s,{get:()=>e[s],enumerable:!(n=vb(e,s))||n.enumerable});return r};var Ab=(r,e,t)=>(t=r!=null?wb(xb(r)):{},Eb(e||!r||!r.__esModule?Ho(t,"default",{value:r,enumerable:!0}):t,r));import*as Du from"fs/promises";import{existsSync as tr,readFileSync as Tb}from"fs";import*as Z from"path";import{pathToFileURL as Pb}from"url";import{resolve as Yo}from"resolve.exports";import{init as Bu,parse as ju}from"es-module-lexer";function Fu(r,e){let t=Z.join(r,"package.json");try{return JSON.parse(Tb(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}function qu(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 Uu(r){let{name:e,dir:t}=r;if(!tr(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=Fu(t,e),s=Ob(n,e),i=Z.resolve(t,s);if(!tr(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=_b(n,t);return await Cb(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function Ob(r,e){if(r.exports!==void 0){let n;try{n=Yo(r,".",{browser:!0,conditions:Wo})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${Wo.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=Vo(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${Wo.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 _b(r,e){if(r.exports!==void 0)try{let n=Yo(r,".",{conditions:["types"]}),s=Vo(n);if(s){let i=Z.resolve(e,s);if(tr(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=Z.resolve(e,t);if(tr(n))return n}}function Vo(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function Cb(r,e,t){await Bu;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 Du.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=ju(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=Rb(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 Rb(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)&&tr(o))return o}function Nb(r,e,t){let n=Fu(r,e),s;if(n.exports!==void 0)try{s=Vo(Yo(n,t,{conditions:Mu}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${Mu.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(!tr(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return Pb(i).href}async function Ju(r,e){await Bu;let t;try{[t]=ju(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=Nb(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var Wo,Mu,us=S(()=>{Wo=["browser","import","default"],Mu=["node","import","default"]});function Yu(r){return tt.find(e=>_e[e].path===r)}function Gu(r){return!!r?.startsWith("typebulb")}var _e,tt,Vu,ds=S(()=>{_e={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"];Vu="typebulb/v1"});function zo(r){return/[:\n"']/.test(r)||r.startsWith(" ")||r.endsWith(" ")?`"${r.replace(/"/g,'\\"')}"`:r}function Xo(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 pe(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=Mb(n);if(!s)return null;let i=new Map,o=[],a=t;for(;t<e.length;){let l=e[t]?.trim()?.match(zu);if(l){let f=l[1].trim();for(t++;t<e.length&&e[t]?.trim()==="";)t++;let u=e[t]?.match(ps);if(!u){o.push(`**${f}** has no code fence \u2014 block skipped`);continue}let d=u[1];t++;let p=[],b=Qo(d);for(;t<e.length&&!e[t]?.match(b);)p.push(e[t]),t++;let m=t<e.length;t++,o.push(...$b(f,p,m)),i.set(f,p.join(`
|
|
5
|
+
`)),a=t}else t++}return{frontmatter:s,files:i,warnings:o,bodyEndLine:a}}catch{return null}}function $b(r,e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s]?.trim().match(zu);i&&Ib.has(i[1].trim())&&Lb(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 Lb(r,e){let t=e+1;for(;t<r.length&&r[t]?.trim()==="";)t++;return!!r[t]?.match(ps)}function Mb(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=Xo(i);break}}return!Gu(e.format)||!e.name?null:e}function Xu(r){return pe(r)?.warnings??[]}function Qu(r){let e=Object.fromEntries(tt.map(t=>[t,r.files.get(_e[t].path)||""]));return{name:r.frontmatter.name,...e}}var zu,ps,Ib,Qo,Zo=S(()=>{ds();fs();zu=/^\*\*(.+)\*\*$/,ps=/^(`{3,})(\w*)\s*$/,Ib=new Set(tt.map(r=>_e[r].path)),Qo=r=>new RegExp(`^${r}\\s*$`)});function Zu(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 ed(r,e){let{path:t}=_e[r],n=t.split(".").pop(),s=Zu(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(ps);if(!a)continue;let c=
|
|
9
|
+
${s}`}function td(r){let e=tt.filter(t=>r[t]).map(t=>ed(t,r[t]));return["---",`format: ${Vu}`,`name: ${zo(r.name)}`,"---","",...e].join(`
|
|
10
|
+
`)}function ea(r,e,t){let{path:n}=_e[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(ps);if(!a)continue;let c=Qo(a[1]),l=o+1;for(;l<s.length&&!s[l]?.match(c);)l++;if(l>=s.length)return r;let f=Zu(t),u=f.length>a[1].length?f:a[1];return[...s.slice(0,o),u+a[2],...t.split(`
|
|
12
12
|
`),u,...s.slice(l+1)].join(`
|
|
13
13
|
`)}return`${r.replace(/\s*$/,"")}
|
|
14
14
|
|
|
15
|
-
${
|
|
16
|
-
`}var
|
|
15
|
+
${ed(e,t)}
|
|
16
|
+
`}var rd=S(()=>{ds();Zo();fs()});function Fr(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}function ta(r){switch(nd(r)){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"}}function sd(r){let e=nd(r);return e!==void 0&&Bb.has(e)?e:void 0}function Fb(r){return r.replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"")}function ra(r){let e=Fr(r??"").description?.trim();if(!e)return jb;let t=Fb(e);return(t.length>200?t.slice(0,197)+"...":t).replace(/\n/g," ")}var Db,ms,nd,Bb,jb,id=S(()=>{Db="https://assets.typebulb.com",ms=(r,e)=>`${Db}/u/${encodeURIComponent(r)}/${encodeURIComponent(e)}/`,nd=r=>/\.[^./\\]+$/.exec(r)?.[0]?.toLowerCase();Bb=new Set([".html",".htm",".xhtml",".js",".mjs",".cjs",".ts",".tsx",".css"]);jb="A Typebulb bulb."});var od=S(()=>{});function na(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index:-1}var ad=S(()=>{});function qr(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index+s[0].length-1:-1}var cd=S(()=>{});function hs(r,e){let t=new RegExp(e,"g"),n=r.match(t);return n?n.length:0}var ld=S(()=>{});function Ur(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=na(r,`<${e}[
|
|
17
17
|
>/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=qr(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=qr(a,"[ /]"+e+">",p))!==-1;){let g=a.substring(p,c+1);if(b+=hs(g,"<"+e+`[
|
|
18
|
-
>]`),m+=hs(g,"</"+e+">"),m>=b)break;p=c}}else c=qr(a,"[ /]"+e+">",0);let f=o+e.length+c+1;if(n&&console.log("[xml-utils] end:",f),f===-1)return;let u=r.slice(o,f),d;return l?d=null:d=u.slice(u.indexOf(">")+1,u.lastIndexOf("<")),{inner:d,outer:u,start:o,end:f}}var sa=
|
|
19
|
-
`)}};Kr.defaultYaml={explicit:!1,version:"1.2"};Kr.defaultTags={"!!":"tag:yaml.org,2002:"};xd.Directives=Kr});var vs=T(Hr=>{"use strict";var kd=F(),
|
|
18
|
+
>]`),m+=hs(g,"</"+e+">"),m>=b)break;p=c}}else c=qr(a,"[ /]"+e+">",0);let f=o+e.length+c+1;if(n&&console.log("[xml-utils] end:",f),f===-1)return;let u=r.slice(o,f),d;return l?d=null:d=u.slice(u.indexOf(">")+1,u.lastIndexOf("<")),{inner:d,outer:u,start:o,end:f}}var sa=S(()=>{ad();cd();ld()});var ia=S(()=>{sa()});var oa=S(()=>{ia()});var ud=S(()=>{oa()});var dd=S(()=>{});var fd=S(()=>{od();sa();ia();ud();oa();dd()});var F=T(re=>{"use strict";var aa=Symbol.for("yaml.alias"),pd=Symbol.for("yaml.document"),gs=Symbol.for("yaml.map"),md=Symbol.for("yaml.pair"),ca=Symbol.for("yaml.scalar"),ys=Symbol.for("yaml.seq"),Je=Symbol.for("yaml.node.type"),Jb=r=>!!r&&typeof r=="object"&&r[Je]===aa,Kb=r=>!!r&&typeof r=="object"&&r[Je]===pd,Hb=r=>!!r&&typeof r=="object"&&r[Je]===gs,Wb=r=>!!r&&typeof r=="object"&&r[Je]===md,hd=r=>!!r&&typeof r=="object"&&r[Je]===ca,Yb=r=>!!r&&typeof r=="object"&&r[Je]===ys;function gd(r){if(r&&typeof r=="object")switch(r[Je]){case gs:case ys:return!0}return!1}function Vb(r){if(r&&typeof r=="object")switch(r[Je]){case aa:case gs:case ca:case ys:return!0}return!1}var Gb=r=>(hd(r)||gd(r))&&!!r.anchor;re.ALIAS=aa;re.DOC=pd;re.MAP=gs;re.NODE_TYPE=Je;re.PAIR=md;re.SCALAR=ca;re.SEQ=ys;re.hasAnchor=Gb;re.isAlias=Jb;re.isCollection=gd;re.isDocument=Kb;re.isMap=Hb;re.isNode=Vb;re.isPair=Wb;re.isScalar=hd;re.isSeq=Yb});var Jr=T(la=>{"use strict";var ee=F(),ce=Symbol("break visit"),yd=Symbol("skip children"),Ce=Symbol("remove node");function bs(r,e){let t=bd(e);ee.isDocument(r)?rr(null,r.contents,t,Object.freeze([r]))===Ce&&(r.contents=null):rr(null,r,t,Object.freeze([]))}bs.BREAK=ce;bs.SKIP=yd;bs.REMOVE=Ce;function rr(r,e,t,n){let s=wd(r,e,t,n);if(ee.isNode(s)||ee.isPair(s))return vd(r,n,s),rr(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=rr(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ce)return ce;o===Ce&&(e.items.splice(i,1),i-=1)}}}else if(ee.isPair(e)){n=Object.freeze(n.concat(e));let i=rr("key",e.key,t,n);if(i===ce)return ce;i===Ce&&(e.key=null);let o=rr("value",e.value,t,n);if(o===ce)return ce;o===Ce&&(e.value=null)}}return s}async function ws(r,e){let t=bd(e);ee.isDocument(r)?await nr(null,r.contents,t,Object.freeze([r]))===Ce&&(r.contents=null):await nr(null,r,t,Object.freeze([]))}ws.BREAK=ce;ws.SKIP=yd;ws.REMOVE=Ce;async function nr(r,e,t,n){let s=await wd(r,e,t,n);if(ee.isNode(s)||ee.isPair(s))return vd(r,n,s),nr(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 nr(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ce)return ce;o===Ce&&(e.items.splice(i,1),i-=1)}}}else if(ee.isPair(e)){n=Object.freeze(n.concat(e));let i=await nr("key",e.key,t,n);if(i===ce)return ce;i===Ce&&(e.key=null);let o=await nr("value",e.value,t,n);if(o===ce)return ce;o===Ce&&(e.value=null)}}return s}function bd(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 wd(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 vd(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`)}}la.visit=bs;la.visitAsync=ws});var ua=T(xd=>{"use strict";var Sd=F(),zb=Jr(),Xb={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Qb=r=>r.replace(/[!,[\]{}]/g,e=>Xb[e]),Kr=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+Qb(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&&Sd.isNode(e.contents)){let i={};zb.visit(e.contents,(o,a)=>{Sd.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
|
+
`)}};Kr.defaultYaml={explicit:!1,version:"1.2"};Kr.defaultTags={"!!":"tag:yaml.org,2002:"};xd.Directives=Kr});var vs=T(Hr=>{"use strict";var kd=F(),Zb=Jr();function ew(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 Ed(r){let e=new Set;return Zb.visit(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function Ad(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function tw(r,e){let t=[],n=new Map,s=null;return{onAnchor:i=>{t.push(i),s??(s=Ed(r));let o=Ad(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(kd.isScalar(o.node)||kd.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}}Hr.anchorIsValid=ew;Hr.anchorNames=Ed;Hr.createNodeAnchors=tw;Hr.findNewAnchor=Ad});var da=T(Td=>{"use strict";function Wr(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=Wr(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=Wr(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=Wr(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=Wr(r,n,s,i);o===void 0?delete n[s]:o!==i&&(n[s]=o)}return r.call(e,t,n)}Td.applyReviver=Wr});var rt=T(Od=>{"use strict";var rw=F();function Pd(r,e,t){if(Array.isArray(r))return r.map((n,s)=>Pd(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!rw.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}Od.toJS=Pd});var Ss=T(Cd=>{"use strict";var nw=da(),_d=F(),sw=rt(),fa=class{constructor(e){Object.defineProperty(this,_d.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(!_d.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=sw.toJS(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?nw.applyReviver(i,{"":a},"",a):a}};Cd.NodeBase=fa});var Yr=T(Rd=>{"use strict";var iw=vs(),ow=Jr(),sr=F(),aw=Ss(),cw=rt(),pa=class extends aw.NodeBase{constructor(e){super(sr.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=[],ow.visit(e,{Node:(i,o)=>{(sr.isAlias(o)||sr.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||(cw.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=xs(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(iw.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 xs(r,e,t){if(sr.isAlias(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(sr.isCollection(e)){let n=0;for(let s of e.items){let i=xs(r,s,t);i>n&&(n=i)}return n}else if(sr.isPair(e)){let n=xs(r,e.key,t),s=xs(r,e.value,t);return Math.max(n,s)}return 1}Rd.Alias=pa});var X=T(ma=>{"use strict";var lw=F(),uw=Ss(),dw=rt(),fw=r=>!r||typeof r!="function"&&typeof r!="object",nt=class extends uw.NodeBase{constructor(e){super(lw.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:dw.toJS(this.value,e,t)}toString(){return String(this.value)}};nt.BLOCK_FOLDED="BLOCK_FOLDED";nt.BLOCK_LITERAL="BLOCK_LITERAL";nt.PLAIN="PLAIN";nt.QUOTE_DOUBLE="QUOTE_DOUBLE";nt.QUOTE_SINGLE="QUOTE_SINGLE";ma.Scalar=nt;ma.isScalarValue=fw});var Vr=T(Id=>{"use strict";var pw=Yr(),_t=F(),Nd=X(),mw="tag:yaml.org,2002:";function hw(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 gw(r,e,t){if(_t.isDocument(r)&&(r=r.contents),_t.isNode(r))return r;if(_t.isPair(r)){let u=t.schema[_t.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 pw.Alias(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=mw+e.slice(2));let l=hw(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let u=new Nd.Scalar(r);return c&&(c.node=u),u}l=r instanceof Map?o[_t.MAP]:Symbol.iterator in Object(r)?o[_t.SEQ]:o[_t.MAP]}i&&(i(l),delete t.onTagObj);let f=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new Nd.Scalar(r);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}Id.createNode=gw});var Es=T(ks=>{"use strict";var yw=Vr(),Re=F(),bw=Ss();function ha(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 yw.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 $d=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,ga=class extends bw.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=>Re.isNode(n)||Re.isPair(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if($d(e))this.add(t);else{let[n,...s]=e,i=this.get(n,!0);if(Re.isCollection(i))i.addIn(s,t);else if(i===void 0&&this.schema)this.set(n,ha(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(Re.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&&Re.isScalar(i)?i.value:i:Re.isCollection(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!Re.isPair(t))return!1;let n=t.value;return n==null||e&&Re.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 Re.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(Re.isCollection(i))i.setIn(s,t);else if(i===void 0&&this.schema)this.set(n,ha(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}};ks.Collection=ga;ks.collectionFromPath=ha;ks.isEmptyPath=$d});var Gr=T(As=>{"use strict";var ww=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function ya(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var vw=(r,e,t)=>r.endsWith(`
|
|
20
20
|
`)?ya(t,e):t.includes(`
|
|
21
21
|
`)?`
|
|
22
|
-
`+ya(t,e):(r.endsWith(" ")?"":" ")+t;As.indentComment=ya;As.lineComment=
|
|
22
|
+
`+ya(t,e):(r.endsWith(" ")?"":" ")+t;As.indentComment=ya;As.lineComment=vw;As.stringifyComment=ww});var Md=T(zr=>{"use strict";var Sw="flow",ba="block",Ts="quoted";function xw(r,e,t="flow",{indentAtStart:n,lineWidth:s=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!s||s<0)return r;s<i&&(i=0);let c=Math.max(1+i,1+s-e.length);if(r.length<=c)return r;let l=[],f={},u=s-e.length;typeof n=="number"&&(n>s-Math.max(2,i)?l.push(0):u=s-n);let d,p,b=!1,m=-1,g=-1,k=-1;t===ba&&(m=Ld(r,m,e.length),m!==-1&&(u=m+c));for(let P;P=r[m+=1];){if(t===Ts&&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}k=m}if(P===`
|
|
23
23
|
`)t===ba&&(m=Ld(r,m,e.length)),u=m+e.length+c,d=void 0;else{if(P===" "&&p&&p!==" "&&p!==`
|
|
24
24
|
`&&p!==" "){let R=r[m+1];R&&R!==" "&&R!==`
|
|
25
25
|
`&&R!==" "&&(d=m)}if(m>=u)if(d)l.push(d),u=d+c,d=void 0;else if(t===Ts){for(;p===" "||p===" ";)p=P,P=r[m+=1],b=!0;let R=m>k+1?m-2:g-1;if(f[R])return r;l.push(R),f[R]=!0,u=R+c,d=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
26
|
${e}${r.slice(0,N)}`:(t===Ts&&f[R]&&(A+=`${r[R]}\\`),A+=`
|
|
27
27
|
${e}${r.slice(R+1,N)}`)}return A}function Ld(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}zr.FOLD_BLOCK=ba;zr.FOLD_FLOW=
|
|
29
|
-
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function Xr(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(
|
|
28
|
+
`);n=e,s=e+1,i=r[s]}return n}zr.FOLD_BLOCK=ba;zr.FOLD_FLOW=Sw;zr.FOLD_QUOTED=Ts;zr.foldFlowLines=xw});var Qr=T(Dd=>{"use strict";var Se=X(),st=Md(),Os=(r,e)=>({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),_s=r=>/^(%|---|\.\.\.)/m.test(r);function kw(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 Xr(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(_s(r)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let f=t.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length<s)c+=1;else{for(o+=t.slice(a,c)+`
|
|
30
30
|
|
|
31
31
|
`;t[c+2]==="\\"&&t[c+3]==="n"&&t[c+4]!=='"';)o+=`
|
|
32
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:st.foldFlowLines(o,i,st.FOLD_QUOTED,Os(e,!1))}function wa(r,e){if(e.options.singleQuote===!1||e.implicitKey&&r.includes(`
|
|
33
|
-
`)||/[ \t]\n|\n[ \t]/.test(r))return Xr(r,e);let t=e.indent||(
|
|
33
|
+
`)||/[ \t]\n|\n[ \t]/.test(r))return Xr(r,e);let t=e.indent||(_s(r)?" ":""),n="'"+r.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
34
34
|
${t}`)+"'";return e.implicitKey?n:st.foldFlowLines(n,t,st.FOLD_FLOW,Os(e,!1))}function ir(r,e){let{singleQuote:t}=e.options,n;if(t===!1)n=Xr;else{let s=r.includes('"'),i=r.includes("'");s&&!i?n=wa:i&&!s?n=Xr:n=t?wa:Xr}return n(r,e)}var va;try{va=new RegExp(`(^|(?<!
|
|
35
35
|
))
|
|
36
36
|
+(?!
|
|
37
|
-
|$)`,"g")}catch{va=/\n+(?!\n|$)/g}function Ps({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 ir(t,n);let l=n.indent||(n.forceBlockIndent||
|
|
37
|
+
|$)`,"g")}catch{va=/\n+(?!\n|$)/g}function Ps({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 ir(t,n);let l=n.indent||(n.forceBlockIndent||_s(t)?" ":""),f=o==="literal"?!0:o==="folded"||e===Se.Scalar.BLOCK_FOLDED?!1:e===Se.Scalar.BLOCK_LITERAL?!0:!kw(t,c,l.length);if(!t)return f?`|
|
|
38
38
|
`:`>
|
|
39
39
|
`;let u,d;for(d=t.length;d>0;--d){let N=t[d-1];if(N!==`
|
|
40
40
|
`&&N!==" "&&N!==" ")break}let p=t.substring(d),b=p.indexOf(`
|
|
41
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
42
|
`&&(p=p.slice(0,-1)),p=p.replace(va,`$&${l}`));let m=!1,g,k=-1;for(g=0;g<t.length;++g){let N=t[g];if(N===" ")m=!0;else if(N===`
|
|
43
43
|
`)k=g;else break}let A=t.substring(0,k<g?k+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()),!f){let N=t.replace(/\n+/g,`
|
|
44
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),O=!1,$=Os(n,!0);o!=="folded"&&e!==
|
|
44
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),O=!1,$=Os(n,!0);o!=="folded"&&e!==Se.Scalar.BLOCK_FOLDED&&($.onOverflow=()=>{O=!0});let E=st.foldFlowLines(`${A}${N}${p}`,l,st.FOLD_BLOCK,$);if(!O)return`>${R}
|
|
45
45
|
${l}${E}`}return t=t.replace(/\n+/g,`$&${l}`),`|${R}
|
|
46
|
-
${l}${A}${t}${p}`}function
|
|
46
|
+
${l}${A}${t}${p}`}function Ew(r,e,t,n){let{type:s,value:i}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:f}=e;if(a&&i.includes(`
|
|
47
47
|
`)||f&&/[[\]{},]/.test(i))return ir(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||f||!i.includes(`
|
|
48
|
-
`)?ir(i,e):Ps(r,e,t,n);if(!a&&!f&&s!==
|
|
49
|
-
`))return Ps(r,e,t,n);if(
|
|
50
|
-
${c}`);if(o){let d=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(u),{compat:p,tags:b}=e.doc.schema;if(b.some(d)||p?.some(d))return ir(i,e)}return a?u:st.foldFlowLines(u,c,st.FOLD_FLOW,Os(e,!1))}function
|
|
51
|
-
${e.indent}${a}`:a}Sa.createStringifyContext=
|
|
48
|
+
`)?ir(i,e):Ps(r,e,t,n);if(!a&&!f&&s!==Se.Scalar.PLAIN&&i.includes(`
|
|
49
|
+
`))return Ps(r,e,t,n);if(_s(i)){if(c==="")return e.forceBlockIndent=!0,Ps(r,e,t,n);if(a&&c===l)return ir(i,e)}let u=i.replace(/\n+/g,`$&
|
|
50
|
+
${c}`);if(o){let d=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(u),{compat:p,tags:b}=e.doc.schema;if(b.some(d)||p?.some(d))return ir(i,e)}return a?u:st.foldFlowLines(u,c,st.FOLD_FLOW,Os(e,!1))}function Aw(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!==Se.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Se.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case Se.Scalar.BLOCK_FOLDED:case Se.Scalar.BLOCK_LITERAL:return s||i?ir(o.value,e):Ps(o,e,t,n);case Se.Scalar.QUOTE_DOUBLE:return Xr(o.value,e);case Se.Scalar.QUOTE_SINGLE:return wa(o.value,e);case Se.Scalar.PLAIN:return Ew(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:f,defaultStringType:u}=e.options,d=s&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Dd.stringifyString=Aw});var Zr=T(Sa=>{"use strict";var Tw=vs(),it=F(),Pw=Gr(),Ow=Qr();function _w(r,e){let t=Object.assign({blockQuote:!0,commentString:Pw.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 Cw(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(it.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 Rw(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let s=[],i=(it.isScalar(r)||it.isCollection(r))&&r.anchor;i&&Tw.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 Nw(r,e,t,n){if(it.isPair(r))return r.toString(e,t,n);if(it.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=it.isNode(r)?r:e.doc.createNode(r,{onTagObj:c=>s=c});s??(s=Cw(e.doc.schema.tags,i));let o=Rw(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):it.isScalar(i)?Ow.stringifyString(i,e,t,n):i.toString(e,t,n);return o?it.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
51
|
+
${e.indent}${a}`:a}Sa.createStringifyContext=_w;Sa.stringify=Nw});var qd=T(Fd=>{"use strict";var Ke=F(),Bd=X(),jd=Zr(),en=Gr();function Iw({key:r,value:e},t,n,s){let{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=t,d=Ke.isNode(r)&&r.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(Ke.isCollection(r)||!Ke.isNode(r)&&typeof r=="object"){let $="With simple keys, collection cannot be used as a key value";throw new Error($)}}let p=!u&&(!r||d&&e==null&&!t.inFlow||Ke.isCollection(r)||(Ke.isScalar(r)?r.type===Bd.Scalar.BLOCK_FOLDED||r.type===Bd.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=jd.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}`,d&&!b?g+=en.lineComment(g,t.indent,l(d)):m&&s&&s(),g;b&&(d=null),p?(d&&(g+=en.lineComment(g,t.indent,l(d))),g=`? ${g}
|
|
52
52
|
${a}:`):(g=`${g}:`,d&&(g+=en.lineComment(g,t.indent,l(d))));let k,A,P;Ke.isNode(e)?(k=!!e.spaceBefore,A=e.commentBefore,P=e.comment):(k=!1,A=null,P=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!d&&Ke.isScalar(e)&&(t.indentAtStart=g.length+1),m=!1,!f&&c.length>=2&&!t.inFlow&&!p&&Ke.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let R=!1,N=jd.stringify(e,t,()=>R=!0,()=>m=!0),O=" ";if(d||k||A){if(O=k?`
|
|
53
53
|
`:"",A){let $=l(A);O+=`
|
|
54
54
|
${en.indentComment($,t.indent)}`}N===""&&!t.inFlow?O===`
|
|
@@ -56,34 +56,34 @@ ${en.indentComment($,t.indent)}`}N===""&&!t.inFlow?O===`
|
|
|
56
56
|
|
|
57
57
|
`):O+=`
|
|
58
58
|
${t.indent}`}else if(!p&&Ke.isCollection(e)){let $=N[0],E=N.indexOf(`
|
|
59
|
-
`),y=E!==-1,x=t.inFlow??e.flow??e.items.length===0;if(y||!x){let I=!1;if(y&&($==="&"||$==="!")){let
|
|
59
|
+
`),y=E!==-1,x=t.inFlow??e.flow??e.items.length===0;if(y||!x){let I=!1;if(y&&($==="&"||$==="!")){let C=N.indexOf(" ");$==="&"&&C!==-1&&C<E&&N[C+1]==="!"&&(C=N.indexOf(" ",C+1)),(C===-1||E<C)&&(I=!0)}I||(O=`
|
|
60
60
|
${t.indent}`)}}else(N===""||N[0]===`
|
|
61
|
-
`)&&(O="");return g+=O+N,t.inFlow?R&&n&&n():P&&!R?g+=en.lineComment(g,t.indent,l(P)):m&&s&&s(),g}Fd.stringifyPair=
|
|
61
|
+
`)&&(O="");return g+=O+N,t.inFlow?R&&n&&n():P&&!R?g+=en.lineComment(g,t.indent,l(P)):m&&s&&s(),g}Fd.stringifyPair=Iw});var ka=T(xa=>{"use strict";var Ud=ls("process");function $w(r,...e){r==="debug"&&console.log(...e)}function Lw(r,e){(r==="debug"||r==="warn")&&(typeof Ud.emitWarning=="function"?Ud.emitWarning(e):console.warn(e))}xa.debug=$w;xa.warn=Lw});var Is=T(Ns=>{"use strict";var tn=F(),Jd=X(),Cs="<<",Rs={identify:r=>r===Cs||typeof r=="symbol"&&r.description===Cs,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Jd.Scalar(Symbol(Cs)),{addToJSMap:Kd}),stringify:()=>Cs},Mw=(r,e)=>(Rs.identify(e)||tn.isScalar(e)&&(!e.type||e.type===Jd.Scalar.PLAIN)&&Rs.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===Rs.tag&&t.default);function Kd(r,e,t){if(t=r&&tn.isAlias(t)?t.resolve(r.doc):t,tn.isSeq(t))for(let n of t.items)Ea(r,e,n);else if(Array.isArray(t))for(let n of t)Ea(r,e,n);else Ea(r,e,t)}function Ea(r,e,t){let n=r&&tn.isAlias(t)?t.resolve(r.doc):t;if(!tn.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}Ns.addMergeToJSMap=Kd;Ns.isMergeKey=Mw;Ns.merge=Rs});var Ta=T(Yd=>{"use strict";var Dw=ka(),Hd=Is(),Bw=Zr(),Wd=F(),Aa=rt();function jw(r,e,{key:t,value:n}){if(Wd.isNode(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(Hd.isMergeKey(r,t))Hd.addMergeToJSMap(r,e,n);else{let s=Aa.toJS(t,"",r);if(e instanceof Map)e.set(s,Aa.toJS(n,s,r));else if(e instanceof Set)e.add(s);else{let i=Fw(t,s,r),o=Aa.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 Fw(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(Wd.isNode(r)&&t?.doc){let n=Bw.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)+'..."'),Dw.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)}Yd.addPairToJSMap=jw});var ot=T(Pa=>{"use strict";var Vd=Vr(),qw=qd(),Uw=Ta(),$s=F();function Jw(r,e,t){let n=Vd.createNode(r,void 0,t),s=Vd.createNode(e,void 0,t);return new Ls(n,s)}var Ls=class r{constructor(e,t=null){Object.defineProperty(this,$s.NODE_TYPE,{value:$s.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return $s.isNode(t)&&(t=t.clone(e)),$s.isNode(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return Uw.addPairToJSMap(t,n,this)}toString(e,t,n){return e?.doc?qw.stringifyPair(this,e,t,n):JSON.stringify(this)}};Pa.Pair=Ls;Pa.createPair=Jw});var Oa=T(zd=>{"use strict";var Ct=F(),Gd=Zr(),Ms=Gr();function Kw(r,e,t){return(e.inFlow??r.flow?Ww:Hw)(r,e,t)}function Hw({comment:r,items:e},t,{blockItemPrefix:n,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,f=Object.assign({},t,{indent:i,type:null}),u=!1,d=[];for(let b=0;b<e.length;++b){let m=e[b],g=null;if(Ct.isNode(m))!u&&m.spaceBefore&&d.push(""),Ds(t,d,m.commentBefore,u),m.comment&&(g=m.comment);else if(Ct.isPair(m)){let A=Ct.isNode(m.key)?m.key:null;A&&(!u&&A.spaceBefore&&d.push(""),Ds(t,d,A.commentBefore,u))}u=!1;let k=Gd.stringify(m,f,()=>g=null,()=>u=!0);g&&(k+=Ms.lineComment(k,i,l(g))),u&&g&&(u=!1),d.push(n+k)}let p;if(d.length===0)p=s.start+s.end;else{p=d[0];for(let b=1;b<d.length;++b){let m=d[b];p+=m?`
|
|
62
62
|
${c}${m}`:`
|
|
63
63
|
`}}return r?(p+=`
|
|
64
|
-
`+Ms.indentComment(l(r),c),a&&a()):u&&o&&o(),p}function
|
|
64
|
+
`+Ms.indentComment(l(r),c),a&&a()):u&&o&&o(),p}function Ww({items:r},e,{flowChars:t,itemIndent:n}){let{indent:s,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;n+=i;let c=Object.assign({},e,{indent:n,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let b=0;b<r.length;++b){let m=r[b],g=null;if(Ct.isNode(m))m.spaceBefore&&u.push(""),Ds(e,u,m.commentBefore,!1),m.comment&&(g=m.comment);else if(Ct.isPair(m)){let A=Ct.isNode(m.key)?m.key:null;A&&(A.spaceBefore&&u.push(""),Ds(e,u,A.commentBefore,!1),A.comment&&(l=!0));let P=Ct.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 k=Gd.stringify(m,c,()=>g=null);b<r.length-1&&(k+=","),g&&(k+=Ms.lineComment(k,n,a(g))),!l&&(u.length>f||k.includes(`
|
|
65
65
|
`))&&(l=!0),u.push(k),f=u.length}let{start:d,end:p}=t;if(u.length===0)return d+p;if(!l){let b=u.reduce((m,g)=>m+g.length+2,2);l=e.options.lineWidth>0&&b>e.options.lineWidth}if(l){let b=d;for(let m of u)b+=m?`
|
|
66
66
|
${i}${s}${m}`:`
|
|
67
67
|
`;return`${b}
|
|
68
|
-
${s}${p}`}else return`${d}${o}${u.join(" ")}${o}${p}`}function Ds({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=Ms.indentComment(e(n),r);t.push(i.trimStart())}}zd.stringifyCollection=
|
|
69
|
-
`:" ")}return
|
|
68
|
+
${s}${p}`}else return`${d}${o}${u.join(" ")}${o}${p}`}function Ds({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=Ms.indentComment(e(n),r);t.push(i.trimStart())}}zd.stringifyCollection=Kw});var ct=T(Ca=>{"use strict";var Yw=Oa(),Vw=Ta(),Gw=Es(),at=F(),Bs=ot(),zw=X();function rn(r,e){let t=at.isScalar(e)?e.value:e;for(let n of r)if(at.isPair(n)&&(n.key===e||n.key===t||at.isScalar(n.key)&&n.key.value===t))return n}var _a=class extends Gw.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(at.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(Bs.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;at.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Bs.Pair(e,e?.value):n=new Bs.Pair(e.key,e.value);let s=rn(this.items,n.key),i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);at.isScalar(s.value)&&zw.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=rn(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let s=rn(this.items,e)?.value;return(!t&&at.isScalar(s)?s.value:s)??void 0}has(e){return!!rn(this.items,e)}set(e,t){this.add(new Bs.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)Vw.addPairToJSMap(t,s,i);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(let s of this.items)if(!at.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})),Yw.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};Ca.YAMLMap=_a;Ca.findPair=rn});var or=T(Qd=>{"use strict";var Xw=F(),Xd=ct(),Qw={collection:"map",default:!0,nodeClass:Xd.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(r,e){return Xw.isMap(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Xd.YAMLMap.from(r,e,t)};Qd.map=Qw});var lt=T(Zd=>{"use strict";var Zw=Vr(),ev=Oa(),tv=Es(),Fs=F(),rv=X(),nv=rt(),Ra=class extends tv.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Fs.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=js(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=js(e);if(typeof n!="number")return;let s=this.items[n];return!t&&Fs.isScalar(s)?s.value:s}has(e){let t=js(e);return typeof t=="number"&&t<this.items.length}set(e,t){let n=js(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let s=this.items[n];Fs.isScalar(s)&&rv.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(nv.toJS(i,String(s++),t));return n}toString(e,t,n){return e?ev.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(Zw.createNode(a,void 0,n))}}return i}};function js(r){let e=Fs.isScalar(r)?r.value:r;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Zd.YAMLSeq=Ra});var ar=T(tf=>{"use strict";var sv=F(),ef=lt(),iv={collection:"seq",default:!0,nodeClass:ef.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(r,e){return sv.isSeq(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>ef.YAMLSeq.from(r,e,t)};tf.seq=iv});var nn=T(rf=>{"use strict";var ov=Qr(),av={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),ov.stringifyString(r,e,t,n)}};rf.string=av});var qs=T(of=>{"use strict";var nf=X(),sf={identify:r=>r==null,createNode:()=>new nf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new nf.Scalar(null),stringify:({source:r},e)=>typeof r=="string"&&sf.test.test(r)?r:e.options.nullStr};of.nullTag=sf});var Na=T(cf=>{"use strict";var cv=X(),af={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new cv.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&af.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};cf.boolTag=af});var cr=T(lf=>{"use strict";function lv({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}lf.stringifyNumber=lv});var $a=T(Us=>{"use strict";var uv=X(),Ia=cr(),dv={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:Ia.stringifyNumber},fv={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():Ia.stringifyNumber(r)}},pv={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 uv.Scalar(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:Ia.stringifyNumber};Us.float=pv;Us.floatExp=fv;Us.floatNaN=dv});var Ma=T(Ks=>{"use strict";var uf=cr(),Js=r=>typeof r=="bigint"||Number.isInteger(r),La=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function df(r,e,t){let{value:n}=r;return Js(n)&&n>=0?t+n.toString(e):uf.stringifyNumber(r)}var mv={identify:r=>Js(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>La(r,2,8,t),stringify:r=>df(r,8,"0o")},hv={identify:Js,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>La(r,0,10,t),stringify:uf.stringifyNumber},gv={identify:r=>Js(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>La(r,2,16,t),stringify:r=>df(r,16,"0x")};Ks.int=hv;Ks.intHex=gv;Ks.intOct=mv});var pf=T(ff=>{"use strict";var yv=or(),bv=qs(),wv=ar(),vv=nn(),Sv=Na(),Da=$a(),Ba=Ma(),xv=[yv.map,wv.seq,vv.string,bv.nullTag,Sv.boolTag,Ba.intOct,Ba.int,Ba.intHex,Da.floatNaN,Da.floatExp,Da.float];ff.schema=xv});var gf=T(hf=>{"use strict";var kv=X(),Ev=or(),Av=ar();function mf(r){return typeof r=="bigint"||Number.isInteger(r)}var Hs=({value:r})=>JSON.stringify(r),Tv=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Hs},{identify:r=>r==null,createNode:()=>new kv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Hs},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Hs},{identify:mf,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})=>mf(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:Hs}],Pv={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},Ov=[Ev.map,Av.seq].concat(Tv,Pv);hf.schema=Ov});var Fa=T(yf=>{"use strict";var sn=ls("buffer"),ja=X(),_v=Qr(),Cv={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof sn.Buffer=="function")return sn.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 sn.Buffer=="function")a=o instanceof sn.Buffer?o.toString("base64"):sn.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=ja.Scalar.BLOCK_LITERAL),e!==ja.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(a.length/c),f=new Array(l);for(let u=0,d=0;u<l;++u,d+=c)f[u]=a.substr(d,c);a=f.join(e===ja.Scalar.BLOCK_LITERAL?`
|
|
69
|
+
`:" ")}return _v.stringifyString({comment:r,type:e,value:a},n,s,i)}};yf.binary=Cv});var Vs=T(Ys=>{"use strict";var Ws=F(),qa=ot(),Rv=X(),Nv=lt();function bf(r,e){if(Ws.isSeq(r))for(let t=0;t<r.items.length;++t){let n=r.items[t];if(!Ws.isPair(n)){if(Ws.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let s=n.items[0]||new qa.Pair(new Rv.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]=Ws.isPair(n)?n:new qa.Pair(n)}}else e("Expected a sequence for this tag");return r}function wf(r,e,t){let{replacer:n}=t,s=new Mv.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(qa.createPair(a,c,t))}return s}var Dv={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:bf,createNode:wf};Ys.createPairs=wf;Ys.pairs=Dv;Ys.resolvePairs=bf});var Ka=T(Ja=>{"use strict";var vf=F(),Ua=rt(),on=ct(),Bv=lt(),Sf=Vs(),Rt=class r extends Bv.YAMLSeq{constructor(){super(),this.add=on.YAMLMap.prototype.add.bind(this),this.delete=on.YAMLMap.prototype.delete.bind(this),this.get=on.YAMLMap.prototype.get.bind(this),this.has=on.YAMLMap.prototype.has.bind(this),this.set=on.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(vf.isPair(s)?(i=Ua.toJS(s.key,"",t),o=Ua.toJS(s.value,i,t)):i=Ua.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=Sf.createPairs(e,t,n),i=new this;return i.items=s.items,i}};Rt.tag="tag:yaml.org,2002:omap";var jv={collection:"seq",identify:r=>r instanceof Map,nodeClass:Rt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Sf.resolvePairs(r,e),n=[];for(let{key:s}of t.items)vf.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new Rt,t)},createNode:(r,e,t)=>Rt.from(r,e,t)};Ja.YAMLOMap=Rt;Ja.omap=jv});var Tf=T(Ha=>{"use strict";var xf=X();function kf({value:r,source:e},t){return e&&(r?Ef:Af).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Ef={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 xf.Scalar(!0),stringify:kf},Af={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 xf.Scalar(!1),stringify:kf};Ha.falseTag=Af;Ha.trueTag=Ef});var Pf=T(Gs=>{"use strict";var Fv=X(),Wa=cr(),qv={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:Wa.stringifyNumber},Uv={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():Wa.stringifyNumber(r)}},Jv={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 Fv.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:Wa.stringifyNumber};Gs.float=Jv;Gs.floatExp=Uv;Gs.floatNaN=qv});var Cf=T(cn=>{"use strict";var Of=cr(),an=r=>typeof r=="bigint"||Number.isInteger(r);function zs(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 Ya(r,e,t){let{value:n}=r;if(an(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return Of.stringifyNumber(r)}var Kv={identify:an,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>zs(r,2,2,t),stringify:r=>Ya(r,2,"0b")},Hv={identify:an,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>zs(r,1,8,t),stringify:r=>Ya(r,8,"0")},Wv={identify:an,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>zs(r,0,10,t),stringify:Of.stringifyNumber},Yv={identify:an,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>zs(r,2,16,t),stringify:r=>Ya(r,16,"0x")};cn.int=Wv;cn.intBin=Kv;cn.intHex=Yv;cn.intOct=Hv});var Ga=T(Va=>{"use strict";var Zs=F(),Xs=ot(),Qs=ct(),Nt=class r extends Qs.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;Zs.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Xs.Pair(e.key,null):t=new Xs.Pair(e,null),Qs.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=Qs.findPair(this.items,e);return!t&&Zs.isPair(n)?Zs.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=Qs.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Xs.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(Xs.createPair(o,null,n));return i}};Nt.tag="tag:yaml.org,2002:set";var Vv={collection:"map",identify:r=>r instanceof Set,nodeClass:Nt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>Nt.from(r,e,t),resolve(r,e){if(Zs.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new Nt,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Va.YAMLSet=Nt;Va.set=Vv});var Xa=T(ei=>{"use strict";var Gv=cr();function za(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 _f(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Gv.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 zv={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})=>za(r,t),stringify:_f},Xv={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=>za(r,!1),stringify:_f},Rf={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(Rf.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=za(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$/,"")??""};ei.floatTime=Xv;ei.intTime=zv;ei.timestamp=Rf});var $f=T(If=>{"use strict";var Qv=or(),Zv=qs(),eS=ar(),tS=nn(),rS=Fa(),Nf=Tf(),Qa=Pf(),ti=Cf(),nS=Is(),sS=Ka(),iS=Vs(),oS=Ga(),Za=Xa(),aS=[Qv.map,eS.seq,tS.string,Zv.nullTag,Nf.trueTag,Nf.falseTag,ti.intBin,ti.intOct,ti.int,ti.intHex,Qa.floatNaN,Qa.floatExp,Qa.float,rS.binary,nS.merge,sS.omap,iS.pairs,oS.set,Za.intTime,Za.floatTime,Za.timestamp];If.schema=aS});var Kf=T(rc=>{"use strict";var Bf=or(),cS=qs(),jf=ar(),lS=nn(),uS=Na(),ec=$a(),tc=Ma(),dS=pf(),fS=gf(),Ff=Fa(),ln=Is(),qf=Ka(),Uf=Vs(),Lf=$f(),Jf=Ga(),ri=Xa(),Mf=new Map([["core",dS.schema],["failsafe",[Bf.map,jf.seq,lS.string]],["json",fS.schema],["yaml11",Lf.schema],["yaml-1.1",Lf.schema]]),Df={binary:Ff.binary,bool:uS.boolTag,float:ec.float,floatExp:ec.floatExp,floatNaN:ec.floatNaN,floatTime:ri.floatTime,int:tc.int,intHex:tc.intHex,intOct:tc.intOct,intTime:ri.intTime,map:Bf.map,merge:ln.merge,null:cS.nullTag,omap:qf.omap,pairs:Uf.pairs,seq:jf.seq,set:Jf.set,timestamp:ri.timestamp},pS={"tag:yaml.org,2002:binary":Ff.binary,"tag:yaml.org,2002:merge":ln.merge,"tag:yaml.org,2002:omap":qf.omap,"tag:yaml.org,2002:pairs":Uf.pairs,"tag:yaml.org,2002:set":Jf.set,"tag:yaml.org,2002:timestamp":ri.timestamp};function mS(r,e,t){let n=Mf.get(e);if(n&&!r)return t&&!n.includes(ln.merge)?n.concat(ln.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(Mf.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(ln.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?Df[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Df).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},[])}rc.coreKnownTags=pS;rc.getTags=mS});var ic=T(Hf=>{"use strict";var nc=F(),hS=or(),gS=ar(),yS=nn(),ni=Kf(),bS=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,sc=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ni.getTags(e,"compat"):e?ni.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?ni.coreKnownTags:{},this.tags=ni.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,nc.MAP,{value:hS.map}),Object.defineProperty(this,nc.SCALAR,{value:yS.string}),Object.defineProperty(this,nc.SEQ,{value:gS.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?bS:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Hf.Schema=sc});var Yf=T(Wf=>{"use strict";var wS=F(),oc=Zr(),un=Gr();function vS(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=oc.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(un.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(wS.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let f=i(r.contents.commentBefore);t.push(un.indentComment(f,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=oc.stringify(r.contents,s,()=>a=null,c);a&&(l+=un.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(oc.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
71
|
+
${i.comment}`:n.comment}n=s}r.items[t]=Ws.isPair(n)?n:new qa.Pair(n)}}else e("Expected a sequence for this tag");return r}function wf(r,e,t){let{replacer:n}=t,s=new Nv.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(qa.createPair(a,c,t))}return s}var Iv={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:bf,createNode:wf};Ys.createPairs=wf;Ys.pairs=Iv;Ys.resolvePairs=bf});var Ka=T(Ja=>{"use strict";var vf=F(),Ua=rt(),on=ct(),$v=lt(),Sf=Vs(),Rt=class r extends $v.YAMLSeq{constructor(){super(),this.add=on.YAMLMap.prototype.add.bind(this),this.delete=on.YAMLMap.prototype.delete.bind(this),this.get=on.YAMLMap.prototype.get.bind(this),this.has=on.YAMLMap.prototype.has.bind(this),this.set=on.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(vf.isPair(s)?(i=Ua.toJS(s.key,"",t),o=Ua.toJS(s.value,i,t)):i=Ua.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=Sf.createPairs(e,t,n),i=new this;return i.items=s.items,i}};Rt.tag="tag:yaml.org,2002:omap";var Lv={collection:"seq",identify:r=>r instanceof Map,nodeClass:Rt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Sf.resolvePairs(r,e),n=[];for(let{key:s}of t.items)vf.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new Rt,t)},createNode:(r,e,t)=>Rt.from(r,e,t)};Ja.YAMLOMap=Rt;Ja.omap=Lv});var Tf=T(Ha=>{"use strict";var xf=X();function kf({value:r,source:e},t){return e&&(r?Ef:Af).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Ef={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 xf.Scalar(!0),stringify:kf},Af={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 xf.Scalar(!1),stringify:kf};Ha.falseTag=Af;Ha.trueTag=Ef});var Pf=T(Gs=>{"use strict";var Mv=X(),Wa=cr(),Dv={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:Wa.stringifyNumber},Bv={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():Wa.stringifyNumber(r)}},jv={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 Mv.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:Wa.stringifyNumber};Gs.float=jv;Gs.floatExp=Bv;Gs.floatNaN=Dv});var _f=T(cn=>{"use strict";var Of=cr(),an=r=>typeof r=="bigint"||Number.isInteger(r);function zs(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 Ya(r,e,t){let{value:n}=r;if(an(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return Of.stringifyNumber(r)}var Fv={identify:an,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>zs(r,2,2,t),stringify:r=>Ya(r,2,"0b")},qv={identify:an,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>zs(r,1,8,t),stringify:r=>Ya(r,8,"0")},Uv={identify:an,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>zs(r,0,10,t),stringify:Of.stringifyNumber},Jv={identify:an,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>zs(r,2,16,t),stringify:r=>Ya(r,16,"0x")};cn.int=Uv;cn.intBin=Fv;cn.intHex=Jv;cn.intOct=qv});var Ga=T(Va=>{"use strict";var Zs=F(),Xs=ot(),Qs=ct(),Nt=class r extends Qs.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;Zs.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Xs.Pair(e.key,null):t=new Xs.Pair(e,null),Qs.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=Qs.findPair(this.items,e);return!t&&Zs.isPair(n)?Zs.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=Qs.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Xs.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(Xs.createPair(o,null,n));return i}};Nt.tag="tag:yaml.org,2002:set";var Kv={collection:"map",identify:r=>r instanceof Set,nodeClass:Nt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>Nt.from(r,e,t),resolve(r,e){if(Zs.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new Nt,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Va.YAMLSet=Nt;Va.set=Kv});var Xa=T(ei=>{"use strict";var Hv=cr();function za(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 Cf(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Hv.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 Wv={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})=>za(r,t),stringify:Cf},Yv={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=>za(r,!1),stringify:Cf},Rf={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(Rf.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=za(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$/,"")??""};ei.floatTime=Yv;ei.intTime=Wv;ei.timestamp=Rf});var $f=T(If=>{"use strict";var Vv=or(),Gv=qs(),zv=ar(),Xv=nn(),Qv=Fa(),Nf=Tf(),Qa=Pf(),ti=_f(),Zv=Is(),eS=Ka(),tS=Vs(),rS=Ga(),Za=Xa(),nS=[Vv.map,zv.seq,Xv.string,Gv.nullTag,Nf.trueTag,Nf.falseTag,ti.intBin,ti.intOct,ti.int,ti.intHex,Qa.floatNaN,Qa.floatExp,Qa.float,Qv.binary,Zv.merge,eS.omap,tS.pairs,rS.set,Za.intTime,Za.floatTime,Za.timestamp];If.schema=nS});var Kf=T(rc=>{"use strict";var Bf=or(),sS=qs(),jf=ar(),iS=nn(),oS=Na(),ec=$a(),tc=Ma(),aS=pf(),cS=gf(),Ff=Fa(),ln=Is(),qf=Ka(),Uf=Vs(),Lf=$f(),Jf=Ga(),ri=Xa(),Mf=new Map([["core",aS.schema],["failsafe",[Bf.map,jf.seq,iS.string]],["json",cS.schema],["yaml11",Lf.schema],["yaml-1.1",Lf.schema]]),Df={binary:Ff.binary,bool:oS.boolTag,float:ec.float,floatExp:ec.floatExp,floatNaN:ec.floatNaN,floatTime:ri.floatTime,int:tc.int,intHex:tc.intHex,intOct:tc.intOct,intTime:ri.intTime,map:Bf.map,merge:ln.merge,null:sS.nullTag,omap:qf.omap,pairs:Uf.pairs,seq:jf.seq,set:Jf.set,timestamp:ri.timestamp},lS={"tag:yaml.org,2002:binary":Ff.binary,"tag:yaml.org,2002:merge":ln.merge,"tag:yaml.org,2002:omap":qf.omap,"tag:yaml.org,2002:pairs":Uf.pairs,"tag:yaml.org,2002:set":Jf.set,"tag:yaml.org,2002:timestamp":ri.timestamp};function uS(r,e,t){let n=Mf.get(e);if(n&&!r)return t&&!n.includes(ln.merge)?n.concat(ln.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(Mf.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(ln.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?Df[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Df).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},[])}rc.coreKnownTags=lS;rc.getTags=uS});var ic=T(Hf=>{"use strict";var nc=F(),dS=or(),fS=ar(),pS=nn(),ni=Kf(),mS=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,sc=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ni.getTags(e,"compat"):e?ni.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?ni.coreKnownTags:{},this.tags=ni.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,nc.MAP,{value:dS.map}),Object.defineProperty(this,nc.SCALAR,{value:pS.string}),Object.defineProperty(this,nc.SEQ,{value:fS.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?mS:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Hf.Schema=sc});var Yf=T(Wf=>{"use strict";var hS=F(),oc=Zr(),un=Gr();function gS(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=oc.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(un.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(hS.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let f=i(r.contents.commentBefore);t.push(un.indentComment(f,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=oc.stringify(r.contents,s,()=>a=null,c);a&&(l+=un.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(oc.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
72
72
|
`)?(t.push("..."),t.push(un.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(un.indentComment(i(c),"")))}return t.join(`
|
|
73
73
|
`)+`
|
|
74
|
-
`}Wf.stringifyDocument=
|
|
74
|
+
`}Wf.stringifyDocument=gS});var dn=T(Vf=>{"use strict";var yS=Yr(),lr=Es(),me=F(),bS=ot(),wS=rt(),vS=ic(),SS=Yf(),ac=vs(),xS=da(),kS=Vr(),cc=ua(),lc=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 cc.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){ur(this.contents)&&this.contents.add(e)}addIn(e,t){ur(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=ac.anchorNames(this);e.anchor=!t||n.has(t)?ac.findNewAnchor(t||"a",n):t}return new yS.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,k=t.filter(g).map(String);k.length>0&&(t=t.concat(k)),s=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=ac.createNodeAnchors(this,o||"a"),b={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:p},m=kS.createNode(e,f,b);return a&&me.isCollection(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){let s=this.createNode(e,null,n),i=this.createNode(t,null,n);return new bS.Pair(s,i)}delete(e){return ur(this.contents)?this.contents.delete(e):!1}deleteIn(e){return lr.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):ur(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 lr.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 lr.isEmptyPath(e)?this.contents!==void 0:me.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=lr.collectionFromPath(this.schema,[e],t):ur(this.contents)&&this.contents.set(e,t)}setIn(e,t){lr.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=lr.collectionFromPath(this.schema,Array.from(e),t):ur(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 cc.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 cc.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 vS.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=wS.toJS(this.contents,t??"",a);if(typeof i=="function")for(let{count:l,res:f}of a.anchors.values())i(f,l);return typeof o=="function"?xS.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 SS.stringifyDocument(this,e)}};function ur(r){if(me.isCollection(r))return!0;throw new Error("Expected a YAML collection as document contents")}Vf.Document=lc});var mn=T(pn=>{"use strict";var fn=class extends Error{constructor(e,t,n,s){super(),this.name=e,this.code=n,this.message=s,this.pos=t}},uc=class extends fn{constructor(e,t,n){super("YAMLParseError",e,t,n)}},dc=class extends fn{constructor(e,t,n){super("YAMLWarning",e,t,n)}},ES=(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
|
-
`}};pn.YAMLError=fn;pn.YAMLParseError=uc;pn.YAMLWarning=dc;pn.prettifyError=
|
|
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(fc(e.key)||fc(e.value))return!0}return!1;default:return!0}}zf.containsNewline=fc});var pc=T(Xf=>{"use strict";var
|
|
81
|
-
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp
|
|
82
|
-
`+P.comment:A.comment=P.comment);let R=new ep.Pair(A);t.options.keepSourceTokens&&(R.srcToken=f),a.items.push(R)}}return l&&l<c&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,l??c],a}sp.resolveBlockMap=
|
|
83
|
-
`+O.comment:l.comment=O.comment),u=O.end;continue}!o&&t.options.strict&&
|
|
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],gc(N)&&s($.range,"BLOCK_IN_FLOW",hc)}else{t.atKey=!0;let $=O.end,E=P?r(t,P,O,s):e(t,$,A,null,O,s);gc(P)&&s(E.range,"BLOCK_IN_FLOW",hc),t.atKey=!1;let y=up.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
|
|
85
|
-
`+y.comment:E.comment=y.comment);let I=new
|
|
86
|
-
`+g.comment:l.comment=g.comment),l.range=[n.offset,m,g.offset]}else l.range=[n.offset,m,m];return l}dp.resolveFlowCollection=
|
|
79
|
+
`}};pn.YAMLError=fn;pn.YAMLParseError=uc;pn.YAMLWarning=dc;pn.prettifyError=ES});var hn=T(Gf=>{"use strict";function AS(r,{flow:e,indicator:t,next:n,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,f=a,u="",d="",p=!1,b=!1,m=null,g=null,k=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),f=!0;break;case"comment":{f||i(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let y=E.source.substring(1)||" ";u?u+=d+y:u=y,d="",l=!1;break}case"newline":l?u?u+=E.source:(!R||t!=="seq-item-ind")&&(c=!0):d+=E.source,l=!0,p=!0,(g||k)&&(A=E),f=!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,f=!1,b=!0;break;case"tag":{k&&i(E,"MULTIPLE_TAGS","A node can have at most one tag"),k=E,N??(N=E.offset),l=!1,f=!1,b=!0;break}case t:(g||k)&&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",f=!1;break;case"comma":if(e){P&&i(E,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),P=E,l=!1,f=!1;break}default:i(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),l=!1,f=!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:k,newlineAfterProp:A,end:$,start:N??$}}Gf.resolveProps=AS});var si=T(zf=>{"use strict";function fc(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(fc(e.key)||fc(e.value))return!0}return!1;default:return!0}}zf.containsNewline=fc});var pc=T(Xf=>{"use strict";var TS=si();function PS(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&TS.containsNewline(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Xf.flowIndentCheck=PS});var mc=T(Zf=>{"use strict";var Qf=F();function OS(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let s=typeof n=="function"?n:(i,o)=>i===o||Qf.isScalar(i)&&Qf.isScalar(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}Zf.mapIncludes=OS});var ip=T(sp=>{"use strict";var ep=ot(),_S=ct(),tp=hn(),CS=si(),rp=pc(),RS=mc(),np="All mapping items must start at the same column";function NS({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??_S.YAMLMap,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let f of n.items){let{start:u,key:d,sep:p,value:b}=f,m=tp.resolveProps(u,{indicator:"explicit-key-ind",next:d??p?.[0],offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0}),g=!m.found;if(g){if(d&&(d.type==="block-seq"?s(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==n.indent&&s(c,"BAD_INDENT",np)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(a.comment?a.comment+=`
|
|
81
|
+
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||CS.containsNewline(d))&&s(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==n.indent&&s(c,"BAD_INDENT",np);t.atKey=!0;let k=m.end,A=d?r(t,d,m,s):e(t,k,u,null,m,s);t.schema.compat&&rp.flowIndentCheck(n.indent,d,s),t.atKey=!1,RS.mapIncludes(t,a.items,A)&&s(k,"DUPLICATE_KEY","Map keys must be unique");let P=tp.resolveProps(p??[],{indicator:"map-value-ind",next:b,offset:A.range[2],onError:s,parentIndent:n.indent,startOnNewline:!d||d.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&&rp.flowIndentCheck(n.indent,b,s),c=R.range[2];let N=new ep.Pair(A,R);t.options.keepSourceTokens&&(N.srcToken=f),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 ep.Pair(A);t.options.keepSourceTokens&&(R.srcToken=f),a.items.push(R)}}return l&&l<c&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,l??c],a}sp.resolveBlockMap=NS});var ap=T(op=>{"use strict";var IS=lt(),$S=hn(),LS=pc();function MS({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??IS.YAMLSeq,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let c=n.offset,l=null;for(let{start:f,value:u}of n.items){let d=$S.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?s(d.end,"BAD_INDENT","All sequence items must start at the same column"):s(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let p=u?r(t,u,d,s):e(t,d.end,f,null,d,s);t.schema.compat&&LS.flowIndentCheck(n.indent,u,s),c=p.range[2],a.items.push(p)}return a.range=[n.offset,c,l??c],a}op.resolveBlockSeq=MS});var dr=T(cp=>{"use strict";function DS(r,e,t,n){let s="";if(r){let i=!1,o="";for(let a of r){let{source:c,type:l}=a;switch(l){case"space":i=!0;break;case"comment":{t&&!i&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";s?s+=o+f:s=f,o="";break}case"newline":s&&(o+=c),i=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:s,offset:e}}cp.resolveEnd=DS});var fp=T(dp=>{"use strict";var BS=F(),jS=ot(),lp=ct(),FS=lt(),qS=dr(),up=hn(),US=si(),JS=mc(),hc="Block collections are not allowed within flow collections",gc=r=>r&&(r.type==="block-map"||r.type==="block-seq");function KS({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?lp.YAMLMap:FS.YAMLSeq),l=new c(t.schema);l.flow=!0;let f=t.atRoot;f&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=n.offset+n.start.source.length;for(let g=0;g<n.items.length;++g){let k=n.items[g],{start:A,key:P,sep:R,value:N}=k,O=up.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&&US.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];BS.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],gc(N)&&s($.range,"BLOCK_IN_FLOW",hc)}else{t.atKey=!0;let $=O.end,E=P?r(t,P,O,s):e(t,$,A,null,O,s);gc(P)&&s(E.range,"BLOCK_IN_FLOW",hc),t.atKey=!1;let y=up.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 C of R){if(C===y.found)break;if(C.type==="newline"){s(C,"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 x=N?r(t,N,y,s):y.found?e(t,y.end,R,null,y,s):null;x?gc(N)&&s(x.range,"BLOCK_IN_FLOW",hc):y.comment&&(E.comment?E.comment+=`
|
|
85
|
+
`+y.comment:E.comment=y.comment);let I=new jS.Pair(E,x);if(t.options.keepSourceTokens&&(I.srcToken=k),o){let C=l;JS.mapIncludes(t,C.items,E)&&s($,"DUPLICATE_KEY","Map keys must be unique"),C.items.push(I)}else{let C=new lp.YAMLMap(t.schema);C.flow=!0,C.items.push(I);let M=(x??E).range;C.range=[E.range[0],M[1],M[2]],l.items.push(C)}u=x?x.range[2]:y.end}}let d=o?"}":"]",[p,...b]=n.end,m=u;if(p?.source===d)m=p.offset+p.source.length;else{let g=a[0].toUpperCase()+a.substring(1),k=f?`${g} must end with a ${d}`:`${g} in block collection must be sufficiently indented and end with a ${d}`;s(u,f?"MISSING_CHAR":"BAD_INDENT",k),p&&p.source.length!==1&&b.unshift(p)}if(b.length>0){let g=qS.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}dp.resolveFlowCollection=KS});var mp=T(pp=>{"use strict";var HS=F(),WS=X(),YS=ct(),VS=lt(),GS=ip(),zS=ap(),XS=fp();function yc(r,e,t,n,s,i){let o=t.type==="block-map"?GS.resolveBlockMap(r,e,t,n,i):t.type==="block-seq"?zS.resolveBlockSeq(r,e,t,n,i):XS.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 QS(r,e,t,n,s){let i=n.tag,o=i?e.directives.tagName(i.source,d=>s(i,"TAG_RESOLVE_FAILED",d)):null;if(t.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=n,b=d&&i?d.offset>i.offset?d:i:d??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===YS.YAMLMap.tagName&&a==="map"||o===VS.YAMLSeq.tagName&&a==="seq")return yc(r,e,t,s,o);let c=e.schema.tags.find(d=>d.tag===o&&d.collection===a);if(!c){let d=e.schema.knownTags[o];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?s(i,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),yc(r,e,t,s,o)}let l=yc(r,e,t,s,o,c),f=c.resolve?.(l,d=>s(i,"TAG_RESOLVE_FAILED",d),e.options)??l,u=HS.isNode(f)?f:new WS.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}pp.composeCollection=QS});var wc=T(hp=>{"use strict";var bc=X();function ZS(r,e,t){let n=e.offset,s=ex(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let i=s.mode===">"?bc.Scalar.BLOCK_FOLDED:bc.Scalar.BLOCK_LITERAL,o=e.source?tx(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
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,f=0;for(let m=0;m<a;++m){let[g,k]=o[m];if(k===""||k==="\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),f=m,c===0&&!r.atRoot&&t(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=g.length+k.length+1}for(let m=o.length-1;m>=a;--m)o[m][0].length>c&&(a=m+1);let u="",d="",p=!1;for(let m=0;m<f;++m)u+=o[m][0].slice(c)+`
|
|
88
88
|
`;for(let m=f;m<a;++m){let[g,k]=o[m];l+=g.length+k.length+1;let A=k[k.length-1]==="\r";if(A&&(k=k.slice(0,-1)),k&&g.length<c){let R=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;t(l-k.length-(A?2:1),"BAD_INDENT",R),g=""}i===bc.Scalar.BLOCK_LITERAL?(u+=d+g.slice(c)+k,d=`
|
|
89
89
|
`):g.length>c||k[0]===" "?(d===" "?d=`
|
|
@@ -98,72 +98,72 @@ ${l}
|
|
|
98
98
|
`+o[m][0].slice(c);u[u.length-1]!==`
|
|
99
99
|
`&&(u+=`
|
|
100
100
|
`);break;default:u+=`
|
|
101
|
-
`}let b=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,b,b]}}function
|
|
101
|
+
`}let b=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,b,b]}}function ex({offset:r,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:s}=e[0],i=s[0],o=0,a="",c=-1;for(let d=1;d<s.length;++d){let p=s[d];if(!a&&(p==="-"||p==="+"))a=p;else{let b=Number(p);!o&&b?o=b:c===-1&&(c=r+d)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,f="",u=s.length;for(let d=1;d<e.length;++d){let p=e[d];switch(p.type){case"space":l=!0;case"newline":u+=p.source.length;break;case"comment":t&&!l&&n(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=p.source.length,f=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),u+=p.source.length;break;default:{let 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:f,length:u}}function tx(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}hp.resolveBlockScalar=ZS});var Sc=T(yp=>{"use strict";var vc=X(),rx=dr();function nx(r,e,t){let{offset:n,type:s,source:i,end:o}=r,a,c,l=(d,p,b)=>t(n+d,p,b);switch(s){case"scalar":a=vc.Scalar.PLAIN,c=sx(i,l);break;case"single-quoted-scalar":a=vc.Scalar.QUOTE_SINGLE,c=ix(i,l);break;case"double-quoted-scalar":a=vc.Scalar.QUOTE_DOUBLE,c=ox(i,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[n,n+i.length,n+i.length]}}let f=n+i.length,u=rx.resolveEnd(o,f,e,t);return{value:c,type:a,comment:u.comment,range:[n,f,u.offset]}}function sx(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}`),gp(r)}function ix(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),gp(r.slice(1,-1)).replace(/''/g,"'")}function gp(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 ox(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}=ax(r,n);t+=i,n=o}else if(s==="\\"){let i=r[++n],o=cx[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+=lx(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 ax(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 cx={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 lx(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)}yp.resolveFlowScalar=nx});var vp=T(wp=>{"use strict";var It=F(),bp=X(),ux=wc(),dx=Sc();function fx(r,e,t,n){let{value:s,type:i,comment:o,range:a}=e.type==="block-scalar"?ux.resolveBlockScalar(r,e,n):dx.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[It.SCALAR]:c?l=px(r.schema,s,c,t,n):e.type==="scalar"?l=mx(r,s,e,n):l=r.schema[It.SCALAR];let f;try{let u=l.resolve(s,d=>n(t??e,"TAG_RESOLVE_FAILED",d),r.options);f=It.isScalar(u)?u:new bp.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);n(t??e,"TAG_RESOLVE_FAILED",d),f=new bp.Scalar(s)}return f.range=a,f.source=s,i&&(f.type=i),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function px(r,e,t,n,s){if(t==="!")return r[It.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[It.SCALAR])}function mx({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[It.SCALAR];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[It.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),f=`Value may be parsed as either ${c} or ${l}`;i(s,"TAG_RESOLVE_FAILED",f,!0)}}return o}wp.composeScalar=fx});var xp=T(Sp=>{"use strict";function hx(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}Sp.emptyScalarPosition=hx});var Ap=T(kc=>{"use strict";var gx=Yr(),yx=F(),bx=mp(),kp=vp(),wx=dr(),vx=xp(),Sx={composeNode:Ep,composeEmptyNode:xc};function Ep(r,e,t,n){let s=r.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=t,l,f=!0;switch(e.type){case"alias":l=xx(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=kp.composeScalar(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=bx.composeCollection(Sx,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=xc(r,e.offset,void 0,null,t,n),f=!1}}return a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&r.options.stringKeys&&(!yx.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&f&&(l.srcToken=e),l}function xc(r,e,t,n,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:vx.emptyScalarPosition(e,t,n),indent:-1,source:""},u=kp.composeScalar(r,f,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=c),u}function xx({options:r},{offset:e,source:t,end:n},s){let i=new gx.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=wx.resolveEnd(n,o,r.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}kc.composeEmptyNode=xc;kc.composeNode=Ep});var Op=T(Pp=>{"use strict";var kx=dn(),Tp=Ap(),Ex=dr(),Ax=hn();function Tx(r,e,{offset:t,start:n,value:s,end:i},o){let a=Object.assign({_directives:e},r),c=new kx.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Ax.resolveProps(n,{indicator:"doc-start",next:s??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?Tp.composeNode(l,s,f,o):Tp.composeEmptyNode(l,f.end,n,null,f,o);let u=c.contents.range[2],d=Ex.resolveEnd(i,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[t,u,d.offset],c}Pp.composeDoc=Tx});var Ac=T(Rp=>{"use strict";var Px=ls("process"),Ox=ua(),_x=dn(),gn=mn(),_p=F(),Cx=Op(),Rx=dr();function yn(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 Cp(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 Ec=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,s,i)=>{let o=yn(t);i?this.warnings.push(new gn.YAMLWarning(o,n,s)):this.errors.push(new gn.YAMLParseError(o,n,s))},this.directives=new
|
|
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 Ec=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,s,i)=>{let o=yn(t);i?this.warnings.push(new gn.YAMLWarning(o,n,s)):this.errors.push(new gn.YAMLParseError(o,n,s))},this.directives=new Ox.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:s}=Cp(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(_p.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];_p.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 gn.YAMLParseError(yn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),s=new
|
|
122
|
+
${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Cp(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(Px.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,n,s)=>{let i=yn(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,s)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=Cx.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 gn.YAMLParseError(yn(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 gn.YAMLParseError(yn(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=Rx.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 gn.YAMLParseError(yn(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 _x.Document(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),s.range=[0,t,t],this.decorate(s,!1),yield s}}};Rp.Composer=Ec});var $p=T(ii=>{"use strict";var Nx=wc(),Ix=Sc(),$x=mn(),Np=Qr();function Lx(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 $x.YAMLParseError([a,a+1],i,o)};switch(r.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Ix.resolveFlowScalar(r,e,n);case"block-scalar":return Nx.resolveBlockScalar({options:{strict:e}},r,n)}}return null}function Mx(r,e){let{implicitKey:t=!1,indent:n,inFlow:s=!1,offset:i=-1,type:o="PLAIN"}=e,a=Np.stringifyString({type:o,value:r},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:`
|
|
124
124
|
`}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
|
|
125
125
|
`),f=a.substring(0,l),u=a.substring(l+1)+`
|
|
126
126
|
`,d=[{type:"block-scalar-header",offset:i,indent:n,source:f}];return Ip(d,c)||d.push({type:"newline",offset:-1,indent:n,source:`
|
|
127
|
-
`}),{type:"block-scalar",offset:i,indent:n,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:n,source:a,end:c};default:return{type:"scalar",offset:i,indent:n,source:a,end:c}}}function
|
|
127
|
+
`}),{type:"block-scalar",offset:i,indent:n,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:n,source:a,end:c};default:return{type:"scalar",offset:i,indent:n,source:a,end:c}}}function Dx(r,e,t={}){let{afterKey:n=!1,implicitKey:s=!1,inFlow:i=!1,type:o}=t,a="indent"in r?r.indent:null;if(n&&typeof a=="number"&&(a+=2),!o)switch(r.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=r.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Np.stringifyString({type:o,value:e},{implicitKey:s||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Bx(r,c);break;case'"':Tc(r,c,"double-quoted-scalar");break;case"'":Tc(r,c,"single-quoted-scalar");break;default:Tc(r,c,"scalar")}}function Bx(r,e){let t=e.indexOf(`
|
|
128
128
|
`),n=e.substring(0,t),s=e.substring(t+1)+`
|
|
129
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}];Ip(a,"end"in r?r.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
|
|
130
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 Ip(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 Tc(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})}}}ii.createScalarToken=
|
|
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})}}}ii.createScalarToken=Mx;ii.resolveAsScalar=Lx;ii.setScalarValue=Dx});var Mp=T(Lp=>{"use strict";var jx=r=>"type"in r?ai(r):oi(r);function ai(r){switch(r.type){case"block-scalar":{let e="";for(let t of r.props)e+=ai(t);return e+r.source}case"block-map":case"block-seq":{let e="";for(let t of r.items)e+=oi(t);return e}case"flow-collection":{let e=r.start.source;for(let t of r.items)e+=oi(t);for(let t of r.end)e+=t.source;return e}case"document":{let e=oi(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 oi({start:r,key:e,sep:t,value:n}){let s="";for(let i of r)s+=i.source;if(e&&(s+=ai(e)),t)for(let i of t)s+=i.source;return n&&(s+=ai(n)),s}Lp.stringify=jx});var Fp=T(jp=>{"use strict";var Pc=Symbol("break visit"),Fx=Symbol("skip children"),Dp=Symbol("remove item");function $t(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),Bp(Object.freeze([]),r,e)}$t.BREAK=Pc;$t.SKIP=Fx;$t.REMOVE=Dp;$t.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};$t.parentCollection=(r,e)=>{let t=$t.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 Bp(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=Bp(Object.freeze(r.concat([[s,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===Pc)return Pc;a===Dp&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&s==="key"&&(n=n(e,r))}}return typeof n=="function"?n(e,r):n}jp.visit=$t});var ci=T(le=>{"use strict";var Oc=$p(),qx=Mp(),Ux=Fp(),_c="\uFEFF",Cc="",Rc="",Nc="",Jx=r=>!!r&&"items"in r,Kx=r=>!!r&&(r.type==="scalar"||r.type==="single-quoted-scalar"||r.type==="double-quoted-scalar"||r.type==="block-scalar");function Hx(r){switch(r){case _c:return"<BOM>";case Cc:return"<DOC>";case Rc:return"<FLOW_END>";case Nc:return"<SCALAR>";default:return JSON.stringify(r)}}function Wx(r){switch(r){case _c:return"byte-order-mark";case Cc:return"doc-mode";case Rc:return"flow-error-end";case Nc: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}le.createScalarToken=Oc.createScalarToken;le.resolveAsScalar=Oc.resolveAsScalar;le.setScalarValue=Oc.setScalarValue;le.stringify=
|
|
134
|
-
`:case"\r":case" ":return!0;default:return!1}}var qp=new Set("0123456789ABCDEFabcdef"),
|
|
135
|
-
\r `),Ic=r=>!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}le.createScalarToken=Oc.createScalarToken;le.resolveAsScalar=Oc.resolveAsScalar;le.setScalarValue=Oc.setScalarValue;le.stringify=qx.stringify;le.visit=Ux.visit;le.BOM=_c;le.DOCUMENT=Cc;le.FLOW_END=Rc;le.SCALAR=Nc;le.isCollection=Jx;le.isScalar=Kx;le.prettyToken=Hx;le.tokenType=Wx});var Lc=T(Up=>{"use strict";var bn=ci();function xe(r){switch(r){case void 0:case" ":case`
|
|
134
|
+
`:case"\r":case" ":return!0;default:return!1}}var qp=new Set("0123456789ABCDEFabcdef"),Yx=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),li=new Set(",[]{}"),Vx=new Set(` ,[]{}
|
|
135
|
+
\r `),Ic=r=>!r||Vx.has(r),$c=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]===bn.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 bn.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==="...")&&
|
|
139
|
+
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&xe(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]===bn.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 bn.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==="...")&&xe(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&&!xe(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===":")&&xe(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(Ic),"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("..."))&&xe(s[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield bn.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(Ic),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||xe(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=>xe(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 bn.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(
|
|
147
|
+
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield bn.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(xe(i)||e&&li.has(i))break;t=n}else if(xe(s)){let i=this.buffer[n+1];if(s==="\r"&&(i===`
|
|
148
148
|
`?(n+=1,s=`
|
|
149
149
|
`,i=this.buffer[n+1]):t=n),i==="#"||e&&li.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&&li.has(s))break;t=n}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield bn.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(Ic))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(
|
|
150
|
+
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&li.has(s))break;t=n}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield bn.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(Ic))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(xe(t)||e&&li.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(;!xe(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(Yx.has(t))t=this.buffer[++e];else if(t==="%"&&qp.has(this.buffer[e+1])&&qp.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)}};Up.Lexer=$c});var Dc=T(Jp=>{"use strict";var Mc=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}}}};Jp.LineCounter=Mc});var jc=T(Vp=>{"use strict";var
|
|
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)}};Up.Lexer=$c});var Dc=T(Jp=>{"use strict";var Mc=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}}}};Jp.LineCounter=Mc});var jc=T(Vp=>{"use strict";var Gx=ls("process"),Kp=ci(),zx=Lc();function ut(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function Hp(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 Yp(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 ui(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 fr(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 Wp(r){if(r.start.type==="flow-seq-start")for(let e of r.items)e.sep&&!e.value&&!ut(e.start,"explicit-key-ind")&&!ut(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Yp(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 Bc=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 zx.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,Gx.env.LOG_TOKENS&&console.log("|",Kp.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Kp.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"&&Wp(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&&Hp(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":{Hp(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=ui(this.peek(2)),n=fr(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
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(ut(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(Yp(t.key)&&!ut(t.sep,"newline")){let o=fr(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(ut(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=fr(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]}):ut(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&&!ut(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||ut(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=ui(n),i=fr(s);Wp(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=ui(e),n=fr(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=ui(e),n=fr(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())}}};Vp.Parser=Bc});var Zp=T(vn=>{"use strict";var Gp=Ac(),
|
|
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=ui(e),n=fr(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=ui(e),n=fr(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())}}};Vp.Parser=Bc});var Zp=T(vn=>{"use strict";var Gp=Ac(),Xx=dn(),wn=mn(),Qx=ka(),Zx=F(),ek=Dc(),zp=jc();function Xp(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new ek.LineCounter||null,prettyErrors:e}}function tk(r,e={}){let{lineCounter:t,prettyErrors:n}=Xp(e),s=new zp.Parser(t?.addNewLine),i=new Gp.Composer(e),o=Array.from(i.compose(s.parse(r)));if(n&&t)for(let a of o)a.errors.forEach(wn.prettifyError(r,t)),a.warnings.forEach(wn.prettifyError(r,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Qp(r,e={}){let{lineCounter:t,prettyErrors:n}=Xp(e),s=new zp.Parser(t?.addNewLine),i=new Gp.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 wn.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(wn.prettifyError(r,t)),o.warnings.forEach(wn.prettifyError(r,t))),o}function rk(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=Qp(r,t);if(!s)return null;if(s.warnings.forEach(i=>Qx.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 nk(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 Zx.isDocument(r)&&!n?r.toString(t):new Xx.Document(r,n,t).toString(t)}vn.parse=rk;vn.parseAllDocuments=tk;vn.parseDocument=Qp;vn.stringify=nk});var tm=T(q=>{"use strict";var sk=Ac(),ik=dn(),ok=ic(),Fc=mn(),ak=Yr(),dt=F(),ck=ot(),lk=X(),uk=ct(),dk=lt(),fk=ci(),pk=Lc(),mk=Dc(),hk=jc(),di=Zp(),em=Jr();q.Composer=sk.Composer;q.Document=ik.Document;q.Schema=ok.Schema;q.YAMLError=Fc.YAMLError;q.YAMLParseError=Fc.YAMLParseError;q.YAMLWarning=Fc.YAMLWarning;q.Alias=ak.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=ck.Pair;q.Scalar=lk.Scalar;q.YAMLMap=uk.YAMLMap;q.YAMLSeq=dk.YAMLSeq;q.CST=fk;q.Lexer=pk.Lexer;q.LineCounter=mk.LineCounter;q.Parser=hk.Parser;q.parse=di.parse;q.parseAllDocuments=di.parseAllDocuments;q.parseDocument=di.parseDocument;q.stringify=di.stringify;q.visit=em.visit;q.visitAsync=em.visitAsync});function yk(r){try{return JSON.parse(r.trim()),!0}catch{return!1}}function bk(r){let e=r.trim();if(!e.startsWith("<"))return!1;let t=e.match(gk);return t?Ur(e,t[1])!==null:!1}function wk(r){let e=r.trim();if(!e.match(/^(---|#|\w+:|-)/)||"[{<".includes(e[0]))return!1;try{let t=rm.parse(e);return t!==null&&typeof t=="object"}catch{return!1}}function nm(r){return yk(r)||bk(r)||wk(r)}var rm,gk,qc=S(()=>{fd();rm=Ab(tm(),1),gk=/<([a-zA-Z_][\w.-]*)/});function vk(r){if(!r?.trim())return[];let e=r.replace(/\r\n/g,`
|
|
157
157
|
`),t=e.trim();if(nm(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 fi(r){return
|
|
160
|
+
`).trim();l&&s.push({text:l,startLine:i+1,endLine:o+1})}};for(let l=0;l<n.length;l++)n[l].trim()?(a>=2&&o>=i&&(c(),i=l),a=0,o=l):a++;return c(),s}function fi(r){return vk(r).map(e=>e.text)}var sm,im=S(()=>{qc();sm=`
|
|
161
161
|
|
|
162
162
|
|
|
163
|
-
`});var
|
|
163
|
+
`});var Ne=S(()=>{ds();Zo();rd();id();qc();im();fs()});function pr(r){return{...Qu(r),server:r.files.get("server.ts")??""}}function pi(r){return!!r.server&&!r.code}var Sn=S(()=>{Ne();Ne()});import{transform as Sk}from"sucrase";function Uc(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=Sk(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}var om=S(()=>{});function Ek(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 am(r){let e=[];for(let s of kk)for(let i of r.matchAll(s)){let o=Ek(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
164
|
`).length-1}));return n}function cm(r){return am(r).map(e=>e.root)}function xn(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
|
|
166
|
-
`)).filter(({root:n})=>!t.has(n)).map(({root:n,lineIndex:s})=>({type:"UNDECLARED_IMPORT",severity:"error",message:
|
|
165
|
+
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;for(let l of xk)l.targets.includes(t)&&l.pattern.test(a)&&s.push({type:l.type,severity:"error",message:Pk(l.type,c),lineNumber:c,lineContent:a})}return t==="client"&&n&&s.push(...Ak(i,n)),s}function Ak(r,e){let t=new Set(Object.keys(e));return am(r.join(`
|
|
166
|
+
`)).filter(({root:n})=>!t.has(n)).map(({root:n,lineIndex:s})=>({type:"UNDECLARED_IMPORT",severity:"error",message:Tk(n,s+1),lineNumber:s+1,lineContent:r[s]}))}function Tk(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 Pk(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,11 +331,11 @@ 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 Lt,Mt,
|
|
334
|
+
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var Lt,Mt,xk,kk,mi=S(()=>{Lt=["client"],Mt=["client","server"],xk=[{type:"DYNAMIC_IMPORT",pattern:/\bimport\s*\(\s*['"`]/,targets:Lt},{type:"COMMONJS_REQUIRE",pattern:/\brequire\s*\(\s*['"`]/,targets:Mt},{type:"JS_EXTENSION_IMPORT",pattern:/from\s+['"][^'"]*\/[^'"]*\.js['"]/,targets:Lt},{type:"URL_IMPORT",pattern:/from\s+['"]https?:\/\//,targets:Lt},{type:"VERSION_SPECIFIER_IMPORT",pattern:/from\s+['"][^'"]*@[\d^~]/,targets:Lt},{type:"REDUNDANT_TB_DECLARATION",pattern:/declare\s+(const|var|let)\s+tb\b/,targets:Mt},{type:"CONST_ENUM",pattern:/\bconst\s+enum\b/,targets:Mt},{type:"NAMESPACE_DECLARATION",pattern:/\bnamespace\s+\w+/,targets:Mt},{type:"COMMONJS_EXPORT_EQUALS",pattern:/\bexport\s*=/,targets:Mt},{type:"COMMONJS_IMPORT_EQUALS",pattern:/\bimport\s+\w+\s*=/,targets:Mt},{type:"MODULE_DECLARATION",pattern:/\bmodule\s+\w+\s*\{/,targets:Mt},{type:"CSS_FILE_IMPORT",pattern:/(?:from|import)\s+['"][^'"]*\.css['"]/,targets:Lt},{type:"NAVIGATION",pattern:/window\.(location\.(reload|assign|replace)\s*\(|open\s*\()/,targets:Lt},{type:"NAVIGATION",pattern:/window\.location(\.href)?\s*=[^=]/,targets:Lt}],kk=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});function Ok(r){return r.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
|
|
335
335
|
`)[0]}`).join(`
|
|
336
336
|
`)}function lm(r,e){let t=xn(r,{target:"client",dependencies:e}).filter(n=>n.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
337
|
-
${Nk(t)}`)}var um=w(()=>{mi()});var ft,kn,Jc,En=w(()=>{ft="https://esm.sh",kn="https://cdn.jsdelivr.net/npm/",Jc="https://data.jsdelivr.com/v1/package/npm/"});function dm(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var B,mr,fm,An=w(()=>{En();B=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=mr(t??s.version),this.subpath=mr(n??s.subpath)}static parse(e){let t=dm(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=fm(t[1]??""),a=mr(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=fm(t[0]),o=mr(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(ft).host,s=new URL(kn).host;if(t.host===n){let i=dm(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:mr(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://")}},mr=r=>r&&r.length?r:void 0,fm=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),mr(r.slice(e+1))]}});async function ue(r){try{return await r()}catch{return}}var hi=w(()=>{});function Dt(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function Kc(r){return r.startsWith("./")?r:`./${r}`}var Tn,Hc=w(()=>{An();hi();En();Tn=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`${kn}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(Dt(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(",")),`${ft}/${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),`${ft}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await ue(()=>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 ue(()=>this.http.getJson(`${Jc}${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:f,peerDependencies:u,peerDependenciesMeta:d}=n;return{name:e,version:t,dependencies:f,peerDependencies:u,peerDependenciesMeta:d}}let s=this.packageJson(new B(`${e}@${t}`)),i=await ue(()=>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 pm,Pn,Wc,Ik,On,gi=w(()=>{pm=r=>r.startsWith("@types/"),Pn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!pm(e)),Wc=r=>Object.keys(r?.dependencies||{}).filter(e=>!pm(e)),Ik=r=>Pn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),On=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 Ik(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=>Pn(i.meta))),n=new Map;for(let i of e)for(let o of Wc(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:Pn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}}});var Cn,Yc=w(()=>{An();hi();Cn=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await ue(()=>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 ue(()=>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 ue(()=>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 ue(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}}});import{init as $k,parse as Lk}from"es-module-lexer";var hr,Vc=w(()=>{An();En();gi();hr=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 $k;let[s]=Lk(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)),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 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,f=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:k,isSharedDep:A}=n.get(b),P=a.has(b),R=p!==b,O=!(g||A)&&(P||!k),$=this.singletonDepsOf(m,o),E=R&&f.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 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}/`,`${ft}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...Pn(e.meta),...Wc(e.meta)])].filter(n=>t.has(n))}};hr.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});import{gt as mm,satisfies as Mk,maxSatisfying as hm,major as Dk,valid as Bk}from"semver";var yi,Bt,Gc=w(()=>{yi=class{cmp(e,t){return e===t?0:mm(e,t)?1:mm(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Mk(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=hm(e,n,{includePrerelease:!1});if(a)return a}return hm(e,n,{includePrerelease:!0})??void 0}majorOf(e){return Dk(e)}isExactVersion(e){return Bk(e)!==null}},Bt=new yi});function jk(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}var jt,gm=w(()=>{hi();jt=class{constructor(e){this.store=e}async isNegative(e){let t=await ue(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await ue(()=>this.store.get(e)))?.attempts||0)+1;await ue(()=>this.store.set(e,{until:Date.now()+jk(n),attempts:n}))}async clearNegative(e){await ue(()=>this.store.delete(e))}}});function ym(r,e){let t=new Tn(r,e),n=new On(t),s=new Cn(r,t,Bt);return{packageService:new hr(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}var He=w(()=>{Hc();gi();Yc();Vc();Gc();An();Gc();En();Hc();gi();Yc();Vc();gm()});import*as zc from"fs/promises";import*as bm from"crypto";function xe(r){return bm.createHash("sha1").update(r).digest("hex")}async function We(r){try{return JSON.parse(await zc.readFile(r,"utf8"))}catch{return}}async function bi(r){try{return await zc.readFile(r,"utf8")}catch{return}}var gr=w(()=>{});import*as mt from"fs/promises";import*as Ye from"path";import*as vm from"os";function G(){return Xc||(Xc=qk()),Xc}function vi(r,e){return Ye.join(Fk,xe(r),e)}async function qk(){await mt.mkdir(pt,{recursive:!0});let r=Ye.join(pt,"version.json");if((await We(r))?.version===wm)return;let t=await mt.readdir(pt).catch(()=>[]);await Promise.all(t.map(n=>mt.rm(Ye.join(pt,n),{recursive:!0,force:!0}))),await mt.writeFile(r,JSON.stringify({version:wm})+`
|
|
338
|
-
`,"utf8")}var wm,pt,
|
|
337
|
+
${Ok(t)}`)}var um=S(()=>{mi()});var ft,kn,Jc,En=S(()=>{ft="https://esm.sh",kn="https://cdn.jsdelivr.net/npm/",Jc="https://data.jsdelivr.com/v1/package/npm/"});function dm(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var B,mr,fm,An=S(()=>{En();B=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=mr(t??s.version),this.subpath=mr(n??s.subpath)}static parse(e){let t=dm(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=fm(t[1]??""),a=mr(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=fm(t[0]),o=mr(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(ft).host,s=new URL(kn).host;if(t.host===n){let i=dm(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:mr(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://")}},mr=r=>r&&r.length?r:void 0,fm=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),mr(r.slice(e+1))]}});async function ue(r){try{return await r()}catch{return}}var hi=S(()=>{});function Dt(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function Kc(r){return r.startsWith("./")?r:`./${r}`}var Tn,Hc=S(()=>{An();hi();En();Tn=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`${kn}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(Dt(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(",")),`${ft}/${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),`${ft}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await ue(()=>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 ue(()=>this.http.getJson(`${Jc}${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:f,peerDependencies:u,peerDependenciesMeta:d}=n;return{name:e,version:t,dependencies:f,peerDependencies:u,peerDependenciesMeta:d}}let s=this.packageJson(new B(`${e}@${t}`)),i=await ue(()=>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 pm,Pn,Wc,_k,On,gi=S(()=>{pm=r=>r.startsWith("@types/"),Pn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!pm(e)),Wc=r=>Object.keys(r?.dependencies||{}).filter(e=>!pm(e)),_k=r=>Pn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),On=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 _k(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=>Pn(i.meta))),n=new Map;for(let i of e)for(let o of Wc(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:Pn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}}});var _n,Yc=S(()=>{An();hi();_n=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await ue(()=>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 ue(()=>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 ue(()=>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 ue(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}}});import{init as Ck,parse as Rk}from"es-module-lexer";var hr,Vc=S(()=>{An();En();gi();hr=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 Ck;let[s]=Rk(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)),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 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,f=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:k,isSharedDep:A}=n.get(b),P=a.has(b),R=p!==b,O=!(g||A)&&(P||!k),$=this.singletonDepsOf(m,o),E=R&&f.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 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}/`,`${ft}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...Pn(e.meta),...Wc(e.meta)])].filter(n=>t.has(n))}};hr.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});import{gt as mm,satisfies as Nk,maxSatisfying as hm,major as Ik,valid as $k}from"semver";var yi,Bt,Gc=S(()=>{yi=class{cmp(e,t){return e===t?0:mm(e,t)?1:mm(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Nk(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=hm(e,n,{includePrerelease:!1});if(a)return a}return hm(e,n,{includePrerelease:!0})??void 0}majorOf(e){return Ik(e)}isExactVersion(e){return $k(e)!==null}},Bt=new yi});function Lk(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}var jt,gm=S(()=>{hi();jt=class{constructor(e){this.store=e}async isNegative(e){let t=await ue(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await ue(()=>this.store.get(e)))?.attempts||0)+1;await ue(()=>this.store.set(e,{until:Date.now()+Lk(n),attempts:n}))}async clearNegative(e){await ue(()=>this.store.delete(e))}}});function ym(r,e){let t=new Tn(r,e),n=new On(t),s=new _n(r,t,Bt);return{packageService:new hr(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}var He=S(()=>{Hc();gi();Yc();Vc();Gc();An();Gc();En();Hc();gi();Yc();Vc();gm()});import*as zc from"fs/promises";import*as bm from"crypto";function ke(r){return bm.createHash("sha1").update(r).digest("hex")}async function We(r){try{return JSON.parse(await zc.readFile(r,"utf8"))}catch{return}}async function bi(r){try{return await zc.readFile(r,"utf8")}catch{return}}var gr=S(()=>{});import*as mt from"fs/promises";import*as Ye from"path";import*as vm from"os";function G(){return Xc||(Xc=Dk()),Xc}function vi(r,e){return Ye.join(Mk,ke(r),e)}async function Dk(){await mt.mkdir(pt,{recursive:!0});let r=Ye.join(pt,"version.json");if((await We(r))?.version===wm)return;let t=await mt.readdir(pt).catch(()=>[]);await Promise.all(t.map(n=>mt.rm(Ye.join(pt,n),{recursive:!0,force:!0}))),await mt.writeFile(r,JSON.stringify({version:wm})+`
|
|
338
|
+
`,"utf8")}var wm,pt,Cn,Rn,wi,Mk,Xc,yr=S(()=>{gr();wm=1,pt=Ye.join(vm.homedir(),".typebulb","cache"),Cn=Ye.join(pt,"packages"),Rn=Ye.join(pt,"proxy"),wi=Ye.join(pt,"dts"),Mk=Ye.join(pt,"emit")});import*as ht from"fs/promises";import*as Sm from"path";async function he(r,e){await ht.mkdir(Sm.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await ht.writeFile(t,e,"utf8"),await ht.rename(t,r).catch(async n=>{throw await ht.rm(t,{force:!0}).catch(()=>{}),n})}var Nn=S(()=>{});var br,Qc=S(()=>{Nn();gr();br=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=We(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 Em from"fs/promises";import*as Ee from"path";function km(r,e){return Ee.join(Bk,Si(r),encodeURIComponent(e)+".json")}function Si(r){return r.replace(/\//g,"__")}var Zc,xm,Bk,jk,xi,Am=S(()=>{He();yr();Nn();Qc();gr();Zc=Ee.join(Cn,"indexes"),xm=Ee.join(Cn,"pinned"),Bk=Ee.join(Cn,"meta"),jk=Ee.join(Cn,"negative.json"),xi=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new jt(new br(jk));async getPinnedExact(e,t){let n=`${e}@${t}`;if(this.pinnedMem.has(n))return this.pinnedMem.get(n);await G();let s=await bi(Ee.join(xm,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(Ee.join(xm,ke(s)+".txt"),n)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await G();let t=await We(Ee.join(Zc,Si(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(Ee.join(Zc,Si(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await Em.rm(Ee.join(Zc,Si(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 We(km(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(km(e,t),JSON.stringify(o))}}});var Tm,Pm=S(()=>{Tm={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 Fk,ki,Om,_m,BR,el=S(()=>{He();Am();Pm();Fk=new xi,{packageService:ki,versionResolver:Om,cdnClient:_m,peerResolver:BR}=ym(Fk,Tm)});var Cm,Rm=S(()=>{Cm=`
|
|
339
339
|
(() => {
|
|
340
340
|
// Embedded (bulb-in-a-bulb): runs inside a sandboxed iframe with no parent
|
|
341
341
|
// bridge, so privileged tb.* (AI, fs, server RPC) can't reach a host and would
|
|
@@ -859,12 +859,12 @@ ${Nk(t)}`)}var um=w(()=>{mi()});var ft,kn,Jc,En=w(()=>{ft="https://esm.sh",kn="h
|
|
|
859
859
|
});
|
|
860
860
|
} catch (e) {}
|
|
861
861
|
})();
|
|
862
|
-
</script>`}var Ft,Ai,tl=
|
|
862
|
+
</script>`}var Ft,Ai,tl=S(()=>{Ft=r=>r.replace(/<\/script/gi,"<\\/script");Ai=` *, *::before, *::after { box-sizing: border-box; }
|
|
863
863
|
canvas { max-width: 100%; }
|
|
864
864
|
body { margin: 0; display: flow-root; font-family: system-ui, -apple-system, sans-serif; }
|
|
865
865
|
html[data-theme="dark"] { color-scheme: dark; }
|
|
866
866
|
html[data-theme="light"] { color-scheme: light; }`});function Nm(r){let{name:e,code:t,css:n,html:s,data:i,insight:o,importMap:a,theme:c,embedded:l,dir:f}=r,u=s.trim()||'<div id="app"></div>',d=l?"":`
|
|
867
|
-
html, body { height: 100%; }`,p={imports:
|
|
867
|
+
html, body { height: 100%; }`,p={imports:Uk(a.imports)};return`<!DOCTYPE html>
|
|
868
868
|
<html>
|
|
869
869
|
<head>
|
|
870
870
|
<meta charset="utf-8">
|
|
@@ -889,10 +889,10 @@ ${o?`<script>window.__TB_INSIGHT__ = ${Ft(JSON.stringify(o))};</script>`:""}
|
|
|
889
889
|
${f?`<script>window.__TB_DIR__ = ${Ft(JSON.stringify(f))};</script>`:""}
|
|
890
890
|
|
|
891
891
|
<script>
|
|
892
|
-
${
|
|
892
|
+
${Cm}
|
|
893
893
|
</script>
|
|
894
894
|
|
|
895
|
-
${
|
|
895
|
+
${qk}
|
|
896
896
|
|
|
897
897
|
<script type="module">
|
|
898
898
|
globalThis.__tbEntryRan = true; /* import graph resolved \u2014 the load-failure backstop's signal (imports hoist above this line) */
|
|
@@ -900,7 +900,7 @@ await globalThis.__tbBoot; /* #tb= fragment restore, set by the shim when presen
|
|
|
900
900
|
${Ft(t)}
|
|
901
901
|
</script>
|
|
902
902
|
</body>
|
|
903
|
-
</html>`}function
|
|
903
|
+
</html>`}function Uk(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}var qk,Im=S(()=>{Rm();tl();qk=`<script>
|
|
904
904
|
(function () {
|
|
905
905
|
var framed = window.parent !== window;
|
|
906
906
|
var post = function (m) { try { parent.postMessage(m, '*'); } catch (e) {} }; /* framed only */
|
|
@@ -996,22 +996,22 @@ ${Ft(t)}
|
|
|
996
996
|
}
|
|
997
997
|
});
|
|
998
998
|
})();
|
|
999
|
-
</script>`});import*as Oi from"fs/promises";import*as Pi from"path";import{existsSync as $m,readFileSync as
|
|
1000
|
-
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await Oi.mkdir(e,{recursive:!0});let a=Pi.join(e,"package.json");$m(a)||await Oi.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
|
|
999
|
+
</script>`});import*as Oi from"fs/promises";import*as Pi from"path";import{existsSync as $m,readFileSync as Jk}from"fs";import{execFile as Kk}from"child_process";import{promisify as Hk}from"util";import{satisfies as Wk}from"semver";async function _i(r,e,t,n){let i=r.map(l=>Gk(l,t)).filter(l=>!zk(l,e));if(i.length===0)return;let o=i.filter(l=>!Vk.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 Oi.mkdir(e,{recursive:!0});let a=Pi.join(e,"package.json");$m(a)||await Oi.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 Yk("npm",["install",...c,...i],{cwd:e,shell:!0})}function Gk(r,e){if(!e||B.parse(r).version)return r;let t=e[r];return t?`${r}@${t}`:r}function zk(r,e){let{name:t,version:n}=B.parse(r),s=Pi.join(e,"node_modules",t);if(!$m(s))return!1;if(!n)return!0;try{let i=JSON.parse(Jk(Pi.join(s,"package.json"),"utf-8")).version;return Wk(i,n)}catch{return!1}}function Ci(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 Yk,Vk,rl=S(()=>{He();Yk=Hk(Kk),Vk=/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+(@[a-zA-Z0-9.^~*x-]+)?$/i});var Lm=S(()=>{});var fe,Ae,wr=S(()=>{fe=class extends Error{constructor(e,t="unknown",n=!1){super(e),this.code=t,this.retryable=n}},Ae=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
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 fe(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 fe(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 Ri,nl=
|
|
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 fe(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 fe(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 Ri,nl=S(()=>{wr();Ri=class extends Ae{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
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 fe(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
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 vr,Ni=
|
|
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 vr,Ni=S(()=>{wr();vr=class extends Ae{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 Ii,sl=S(()=>{Ni();Ii=class extends vr{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 $i,il=S(()=>{wr();$i=class extends Ae{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
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 Li,ol=
|
|
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 Li,ol=S(()=>{wr();Li=class extends Ae{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
1008
|
`),c={contents:o.map(f=>({role:f.role==="assistant"?"model":"user",parts:[{text:f.content}]}))};n?.webSearch!==!1&&(c.tools=[{google_search:{}}]),i&&(c.systemInstruction={role:"system",parts:[{text:i}]});let l=n?.effort;if(l!==void 0){let f=this.geminiVersion(t),u=f!==null&&f>=3?{thinkingLevel:this.thinkingLevelFor(f,l)}:{thinkingBudget:this.budgetMap[l]};c.generationConfig={thinkingConfig:l===0?u:{includeThoughts:!0,...u}}}return c}parseError(e,t){if(!e)return{message:`HTTP ${t}`};try{let n=JSON.parse(e),s=Array.isArray(n)?n[0]?.error:n?.error;return s&&typeof s=="object"?{message:(s.message||`HTTP ${t}`).split(`
|
|
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 fe(`Prompt blocked: ${t}`)}}}});var Mi,al=
|
|
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 fe(`Prompt blocked: ${t}`)}}}});var Mi,al=S(()=>{Ni();Mi=class extends vr{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 qt(r){let e=Xk.get(r);if(!e)throw new Error(`Unsupported protocol: ${r}`);return e}function Qk(r,e){return r.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function cl(r,e){let t=qt(r.protocol),n=t.getPath(r.model,e.stream),s=Qk(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 Zk(r){return/prompt is too long|context[_ ](length|window)|maximum context|token count exceeds|too many tokens/i.test(r)}async function Sr(r,e){let t=qt(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||Zk(s))&&(o="context_exceeded"),{code:o,message:s,retryable:i===429||i>=500}}var Mm,Xk,ll=S(()=>{nl();sl();il();ol();al();Mm=new Mi,Xk=new Map([["openai",new Ri],["openrouter",new Ii],["anthropic",new $i],["gemini",new Li],["ollama",Mm],["openai-compat",Mm]])});function Dm(r){let e=r.indexOf(`\r
|
|
1010
1010
|
\r
|
|
1011
1011
|
`),t=r.indexOf(`
|
|
1012
1012
|
|
|
1013
1013
|
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function ul(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*Bm(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=ul(s);u!==null&&u!=="done"&&(yield u)}return}t?.(),s+=n.decode(c,{stream:!0});let{pos:l,len:f}=Dm(s);for(;l!==-1;){let u=s.slice(0,l);s=s.slice(l+f);let d=ul(u);if(d==="done")return;d!==null&&(yield d),{pos:l,len:f}=Dm(s)}}}finally{i&&e?.removeEventListener("abort",i);try{await r.cancel()}catch{}}}async function Ut(r,e){if(!r.body)throw new Error("Response body is missing");let t="";for await(let n of Jt(r,e))n.kind==="text"&&(t+=n.text);return t}async function*Jt(r,e){let t=e??(r.headers.get("X-Provider-Protocol")||"openai"),n=qt(t);if(!r.body)return;let s=r.body.getReader();for await(let i of Bm(s)){let o=n.parseStreamChunk(i);o?.reasoning&&(yield{kind:"reasoning",text:o.reasoning}),o?.text&&(yield{kind:"text",text:o.text})}}var jm=
|
|
1014
|
+
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*Bm(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=ul(s);u!==null&&u!=="done"&&(yield u)}return}t?.(),s+=n.decode(c,{stream:!0});let{pos:l,len:f}=Dm(s);for(;l!==-1;){let u=s.slice(0,l);s=s.slice(l+f);let d=ul(u);if(d==="done")return;d!==null&&(yield d),{pos:l,len:f}=Dm(s)}}}finally{i&&e?.removeEventListener("abort",i);try{await r.cancel()}catch{}}}async function Ut(r,e){if(!r.body)throw new Error("Response body is missing");let t="";for await(let n of Jt(r,e))n.kind==="text"&&(t+=n.text);return t}async function*Jt(r,e){let t=e??(r.headers.get("X-Provider-Protocol")||"openai"),n=qt(t);if(!r.body)return;let s=r.body.getReader();for await(let i of Bm(s)){let o=n.parseStreamChunk(i);o?.reasoning&&(yield{kind:"reasoning",text:o.reasoning}),o?.text&&(yield{kind:"text",text:o.text})}}var jm=S(()=>{ll()});import{strToU8 as e0,strFromU8 as t0,deflateSync as r0,inflateSync as n0}from"fflate";function fl(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
1015
|
|
|
1016
1016
|
---
|
|
1017
1017
|
Instructions:
|
|
@@ -1029,906 +1029,906 @@ ${n}
|
|
|
1029
1029
|
</data>`)}return t.push(`
|
|
1030
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
1031
|
|
|
1032
|
-
`)}function In(r){try{return JSON.parse(r)}catch{return null}}function
|
|
1033
|
-
`)}var kr,
|
|
1034
|
-
\u2026[${r.length-5e4} more characters truncated]`:r}function Qe(r){let e=r.replace(
|
|
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
|
|
1036
|
-
`):r==null?"":
|
|
1037
|
-
`).length,"line")}`;if(t.mode==="content")return
|
|
1032
|
+
`)}function In(r){try{return JSON.parse(r)}catch{return null}}function i0(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 o0(r){let e=i0(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 a0(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 c0(r){let e=null,t=0;for(;t<r.length;){let n=r[t];if(n==="{"||n==="["){let s=a0(r,t);if(s!==-1){let i=r.slice(t,s+1),o=In(i);o!==null&&(e={parsed:o,json:i}),t=s+1;continue}}t++}return e}function pl(r){let e=[],t=r.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*\n?/,"").replace(/\n?```\s*$/,""),e.push("markdown fences"));let n=In(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=In(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=In(t),n!==null))return{parsed:n,json:t,fixesApplied:e}}for(let[o,a]of s0){let c=a(t);if(c!==null){let l=In(c);if(l!==null)return{parsed:l,json:c,fixesApplied:[...e,o]}}}let i=c0(r);return i!==null?{...i,fixesApplied:[...e,"extracted last JSON value"]}:{parsed:null,json:t,fixesApplied:e}}function ml(r){try{let e={i:r.insight,d:r.data},t=JSON.stringify(e),n=r0(e0(t),{level:9}),s=u0(n),i=`${Fm}:${s}`;return i.length>l0?"":"#"+dl+i}catch{return""}}function hl(r){try{let e=r.startsWith("#")?r.slice(1):r;if(!e.startsWith(dl))return null;let t=e.slice(dl.length),n=t.indexOf(":");if(n===-1||t.slice(0,n)!==Fm)return null;let s=d0(t.slice(n+1)),i=JSON.parse(t0(n0(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 u0(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 d0(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 s0,dl,Fm,l0,qm=S(()=>{s0=[["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",o0]];dl="tb=",Fm="1",l0=6e4});var xr=S(()=>{Lm();wr();ll();jm();qm();Ni();il();ol();nl();sl();al()});function Er(r){return(r.includes("://")?r:`http://${r}`).replace(/\/+$/,"")}function gl(){return Ln}async function Ve(){let[r,e]=await Promise.all([Jm(),y0()]);return g0([...b0(e),...r],process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL)}function g0(r,e,t){return!e||!t?r:r.map(n=>n.provider===e&&n.name===t?{...n,default:!0}:n)}async function Um(){let r;try{r=await fetch(f0,{signal:AbortSignal.timeout(m0)})}catch(e){return Ln=`catalog fetch failed: ${e?.message??e}`,null}if(!r.ok)return Ln=`catalog fetch failed: HTTP ${r.status}`,null;try{return await r.json()}catch(e){return Ln=`catalog returned an unreadable body: ${e?.message??e}`,null}}async function y0(){if($n&&Date.now()-$n.fetchedAt<=p0)return $n.models;let r=await Um()??await Um();return r?($n={models:r,fetchedAt:Date.now()},Ln=null,r):$n?.models??[]}async function Jm(){if(Di&&Date.now()-Di.fetchedAt<=h0)return Di.models;let r=Er(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 Di={models:e,fetchedAt:Date.now()},e}function b0(r){let e=new Set(Object.entries(kr).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function yl(){return Object.values(kr).some(r=>!!process.env[r])}async function Bi(){return yl()||process.env.TB_AI_BASE_URL?!0:(await Jm()).length>0}function Km(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 kr,f0,p0,m0,h0,$n,Di,Ln,Kt=S(()=>{kr={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};f0="https://api.typebulb.com/api/models",p0=1440*60*1e3,m0=5e3,h0=60*1e3,$n=null,Di=null,Ln=null});function Ge(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=qt(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${Er(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=kr[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 gt(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 cl(r,{messages:t,stream:!0,effort:n!=null&&n>=0&&n<=3?n:void 0,webSearch:e.webSearch??!0,signal:e.signal})}var ji=S(()=>{xr();Kt()});import*as Ar from"fs/promises";import*as ze from"path";function Mn(r,e,t=e){let n=ze.resolve(e,r),s=ze.normalize(t),i=ze.normalize(n);if(i!==s&&!i.startsWith(s+ze.sep))throw new Error("Path traversal detected - access denied");return n}async function Dn(r,e,t){return Ar.readFile(Mn(r,e,t))}async function Fi(r,e,t,n){let s=Mn(r,t,n);await Ar.mkdir(ze.dirname(s),{recursive:!0}),await Ar.writeFile(s,typeof e=="string"?e:Buffer.from(e))}var bl=S(()=>{});async function Hm(r){let e=Ge(r.provider,r.model);if(typeof e=="string")throw new Error(e);let t=await gt(e,r);if(!t.ok){let n=await Sr(t,e.protocol);throw new Error(n.message)}return{response:t,protocol:e.protocol}}async function w0(r){let{response:e,protocol:t}=await Hm(r);return{text:await Ut(e,t)}}async function*v0(r){let{response:e,protocol:t}=await Hm(r);yield*Jt(e,t)}function Wm(r,e=process.cwd()){let t=Object.assign(w0,{stream:v0}),n={read:async s=>{let i=await Dn(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 Dn(s,r,e)),write:async(s,i)=>(await Fi(s,i,r,e),!0)};globalThis.tb=Object.freeze({ai:t,fs:n,dir:r,models:()=>Ve(),hasOwnKeys:Bi,mode:"local"})}var Ym=S(()=>{xr();ji();Kt();bl()});import*as yt from"fs/promises";import*as se from"path";import{pathToFileURL as S0}from"url";async function Vm(r){let t=(await yt.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?se.join(r,t):null}function Bn(r,e){let t=se.resolve(r),n=se.join(se.dirname(t),se.basename(t).replace(/\.bulb\.md$/,""));return e?se.join(n,e):n}async function Te(r){let e=await yt.readFile(r,"utf-8"),t=pe(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=pr(t);return{bulb:n,config:Fr(n.config),warnings:Xu(e)}}function wl(r){let e=se.basename(r).replace(/\.bulb\.md$/i,"");return se.join(se.dirname(r),".typebulb",`${e}.server.mjs`)}async function Fn(r,e,t,n,s){let i=Uc(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=se.join(se.dirname(e),".typebulb");await yt.mkdir(a,{recursive:!0});let c=Ci(o);c.length>0&&await _i(c,a,n);let l=wl(e);return await yt.writeFile(l,o,"utf-8"),Wm(Bn(e,s)),await import(`${S0(l).href}?t=${Date.now()}`)}async function vl(r,e,t,n,s){let{bulb:i,config:o}=await Te(r),a=fi(i.data);lm(i.code,o.dependencies??{});let c=Uc(i.code,{jsxImportSource:o.ts?.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:l}=await ki.buildImportMap(c.code,o.dependencies??{},n?new Set([n.name]):void 0);n&&(l.imports[n.name]=n.entryUrl);let f=Nm({name:i.name,code:c.code,css:i.css,html:i.html,data:a,insight:i.insight,importMap:l,dir:Bn(r,s),watch:e}),u=null;return i.server&&t&&(u=await Fn(i.server,r,n,o.dependencies,s)),{html:f,bulb:i,serverExports:u}}var jn,bt=S(()=>{Sn();om();um();el();Im();rl();us();Ym();jn=(r,e)=>se.join(Bn(r,e),"assets")});import{realpathSync as x0}from"fs";import{join as Sl,resolve as k0}from"path";import{homedir as E0}from"os";function qi(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?Sl(r,".."):Sl(E0(),".typebulb")}function Xe(){return process.env.TYPEBULB_SERVERS_DIR||Sl(qi(),"servers")}function ne(r){let e=k0(r),t=e;try{t=x0.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function Gm(r,e){let t=ne(r),n=ne(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var Ui=S(()=>{});import{readFileSync as A0,writeFileSync as T0,mkdirSync as P0}from"fs";import{join as O0}from"path";function zm(){return O0(qi(),"trust.json")}function xl(){try{let r=JSON.parse(A0(zm(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function _0(r){P0(qi(),{recursive:!0}),T0(zm(),JSON.stringify([...r]))}function Ht(r){return xl().has(ne(r))}function Tr(r,e){let t=xl(),n=ne(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),_0(t))}function kl(){return[...xl()]}var qn=S(()=>{Ui()});function Ie(r){return r.length>5e4?r.slice(0,5e4)+`
|
|
1034
|
+
\u2026[${r.length-5e4} more characters truncated]`:r}function Qe(r){let e=r.replace(C0,"").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 C0,Ji,Ki=S(()=>{C0=/\u001b\[[0-9;]*m/g;Ji=(r,e)=>``});import{existsSync as R0,readdirSync as N0,statSync as I0}from"fs";import{join as $0}from"path";function Hi(r){if(!R0(r))return[];let e;try{e=N0(r)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(".jsonl"))continue;let s=$0(r,n);try{let i=I0(s);i.isFile()&&t.push({sessionId:n.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var El=S(()=>{});var Pr,Al=S(()=>{Pr=class{ensureHarnessSupport(){}}});import{openSync as L0,readSync as M0,closeSync as D0,statSync as B0,readdirSync as j0,readFileSync as F0,existsSync as q0}from"fs";import{join as Jn}from"path";import{homedir as Ol}from"os";function U0(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function Wi(r){let e=r?.type==="image"?r.source:void 0;return e?.type==="base64"&&e.data?Ji(e.data,e.media_type):""}function Tl(r){return typeof r=="string"?Ie(r):Array.isArray(r)?r.map(e=>{if(typeof e=="string")return Ie(e);let t=e;return typeof t?.text=="string"?Ie(t.text):t?.content!=null?Tl(t.content):Wi(t)}).join(`
|
|
1036
|
+
`):r==null?"":Ie(JSON.stringify(r))}function K0(r){let e=r.trim();return!!e&&eh.some(t=>t.test(e))}function H0(r){let e=r.trim();return e?eh.some(t=>{let n=t.exec(e);return!!n&&n.index===0}):!0}function Y0(r){return r.replace(W0,"")}function V0(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 wt(r){let e=Y0(r).trim();return e?V0(e)??(K0(e)?"":e):""}function Pl(r){return r?.type==="text"&&typeof r.text=="string"?wt(r.text):""}function _l(r,e){if(typeof r=="string")return Qe(r);if(!r||typeof r!="object")return Qe(e);let t=r;if(t.type==="text"&&typeof t.file?.numLines=="number")return Pe(t.file.numLines,"line");if(t.type==="image"){let n=Qm(t.file?.originalSize);return n?`image (${n})`:"image"}if(t.type==="pdf"){let n=Qm(t.file?.originalSize);return n?`PDF (${n})`:"PDF"}if(t.type==="parts"&&typeof t.file?.count=="number")return Pe(t.file.count,"page");if(t.type==="file_unchanged")return"unchanged since last read";if(t.type==="create"&&typeof t.content=="string")return`created, ${Pe(t.content.split(`
|
|
1037
|
+
`).length,"line")}`;if(t.mode==="content")return Pe(t.numLines??0,"line");if(t.mode==="count")return`${Pe(t.numMatches??0,"match","matches")} (${Pe(t.numFiles??0,"file")})`;if(t.mode==="files_with_matches")return Pe(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":Qe(t.stdout||t.stderr||"")||"no output":typeof t.code=="number"&&typeof t.codeText=="string"?`${t.code} ${t.codeText}`:typeof t.searchCount=="number"?Pe(t.searchCount,"search","searches"):Array.isArray(t.matches)&&typeof t.total_deferred_tools=="number"?Pe(t.matches.length,"tool"):Array.isArray(t.newTodos)?Pe(t.newTodos.length,"todo"):typeof t.numFiles=="number"?Pe(t.numFiles,"file"):Qe(e)}function Un(r){return!!r.isSidechain||!!r.isMeta}function G0(r){let e;try{e=L0(r,"r")}catch{return""}try{let n=65536;try{n=B0(r).size}catch{}let s=(l,f)=>{if(f<=0)return"";let u=Buffer.alloc(f),d=M0(e,u,0,f,l);return u.subarray(0,d).toString("utf8")},i=(l,f,u)=>{let d="";for(let p of l.split(`
|
|
1038
1038
|
`)){if(!p.includes(`"${f}"`))continue;let b;try{b=JSON.parse(p)}catch{continue}let m=b?.[u];b?.type===f&&typeof m=="string"&&m&&(d=m)}return d},o=s(0,Math.min(65536,n)),a=n>65536?s(n-65536,65536):"",c=i(a,"custom-title","customTitle")||i(o,"custom-title","customTitle")||i(a,"ai-title","aiTitle")||i(o,"ai-title","aiTitle");if(c)return c.replace(/\s+/g," ").trim().slice(0,200);for(let l of o.split(`
|
|
1039
|
-
`)){if(!l.trim())continue;let f;try{f=JSON.parse(l)}catch{continue}if(!f||Un(f)||f.type!=="user")continue;let u=f.message?.content,d="";typeof u=="string"?d=wt(u):Array.isArray(u)&&(d=u.map(Pl).filter(Boolean).join(" "));let p=d.replace(/\s+/g," ").trim();if(p)return(p.replace(/^Continuing from a prior session\. Here is the summary of our work so far:\s*/i,"").trim()||p).slice(0,200)}return""}finally{
|
|
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??""),d=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:d})}let l=e.message?.usage??e.usage,f=l&&{in:l.input_tokens??0,out:l.output_tokens??0,cached:l.cache_read_input_tokens??0,cacheCreate:l.cache_creation_input_tokens??0};return{events:n,usage:f,model:e.message?.model}}return{events:n}}chainWorking(e){let t;for(let o of e)(o.type==="user"||o.type==="assistant")&&(t=o);if(!t)return!1;if(t.type==="user"){try{let o=t.message?.content,a=typeof o=="string"?o:Array.isArray(o)?o.filter(l=>l&&l.type==="text").map(l=>l.text??"").join(""):"";if(!(Array.isArray(o)&&o.some(l=>l&&l.type==="tool_result"))&&a.trim()&&wt(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
|
|
1041
|
-
`),n=[];if(t.forEach((o,a)=>{let c=
|
|
1042
|
-
`)}function Ml(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function lh(r){await
|
|
1039
|
+
`)){if(!l.trim())continue;let f;try{f=JSON.parse(l)}catch{continue}if(!f||Un(f)||f.type!=="user")continue;let u=f.message?.content,d="";typeof u=="string"?d=wt(u):Array.isArray(u)&&(d=u.map(Pl).filter(Boolean).join(" "));let p=d.replace(/\s+/g," ").trim();if(p)return(p.replace(/^Continuing from a prior session\. Here is the summary of our work so far:\s*/i,"").trim()||p).slice(0,200)}return""}finally{D0(e)}}function z0(r){let e;try{e=j0(Zm)}catch{return!1}for(let t of e)if(t.endsWith(".json"))try{let n=JSON.parse(F0(Jn(Zm,t),"utf8"));if(n?.sessionId!==r)continue;return process.kill(n.pid,0),!0}catch{}return!1}var J0,Xm,eh,W0,Pe,Qm,Zm,Or,Yi=S(()=>{Ki();El();Al();J0=Jn(Ol(),".claude","projects"),Xm=r=>Jn(J0,U0(r));eh=[/\[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];W0=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;Pe=(r,e,t=e+"s")=>`${r} ${r===1?e:t}`,Qm=r=>typeof r!="number"?"":r<1024?`${r}B`:r<1048576?`${Math.round(r/1024)}KB`:`${(r/1048576).toFixed(1)}MB`;Zm=Jn(Ol(),".claude","sessions");Or=class extends Pr{displayName="Claude Mirror";detectsSelf(){return process.env.CLAUDECODE==="1"}detectsInstalled(){return q0(Jn(Ol(),".claude"))}sessionsDir(e){return Xm(e)}listSessionFiles(e){return Hi(Xm(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=wt(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=Tl(i.content);n.push({type:"tool_result",id:i.tool_use_id??"",content:o,isError:!!i.is_error,digest:_l(e.toolUseResult,o)})}else{let o=Pl(i)||Wi(i);o&&n.push({type:"user",text:o})}return{events:n}}if(e.type==="attachment"&&e.attachment?.type==="queued_command"){let s=wt(Tl(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=>!H0(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??""),d=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:d})}let l=e.message?.usage??e.usage,f=l&&{in:l.input_tokens??0,out:l.output_tokens??0,cached:l.cache_read_input_tokens??0,cacheCreate:l.cache_creation_input_tokens??0};return{events:n,usage:f,model:e.message?.model}}return{events:n}}chainWorking(e){let t;for(let o of e)(o.type==="user"||o.type==="assistant")&&(t=o);if(!t)return!1;if(t.type==="user"){try{let o=t.message?.content,a=typeof o=="string"?o:Array.isArray(o)?o.filter(l=>l&&l.type==="text").map(l=>l.text??"").join(""):"";if(!(Array.isArray(o)&&o.some(l=>l&&l.type==="tool_result"))&&a.trim()&&wt(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 z0(e)}readPreview(e){return G0(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=wt(t);else if(Array.isArray(t)){let s=t;n=e.type==="user"?s.map(Pl).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 th}from"child_process";import{readdir as X0,readFile as nh,writeFile as sh,unlink as Cl,mkdir as Q0}from"fs/promises";import{mkdirSync as ih,writeFileSync as Vi,appendFileSync as Z0,readFileSync as Rl}from"fs";import*as ge from"path";import{fileURLToPath as eE}from"url";function Nl(r){return ge.join(Xe(),`${r}.json`)}function Hn(r){return ge.join(Xe(),`${r}.log`)}function Il(r){return ge.join(Xe(),`${r}.wait.json`)}function oh(r){try{let e=JSON.parse(Rl(Il(r),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function $l(r,e=""){let t=oh(r)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Gi(r,e,t=""){try{ih(Xe(),{recursive:!0});let n=oh(r);n[t]=e,Vi(Il(r),JSON.stringify({cursors:n}))}catch{}}function zi(r){let e=Hn(r);try{ih(Xe(),{recursive:!0}),Vi(e,"")}catch{return()=>{}}let t=process.stdout.write.bind(process.stdout),n=process.stderr.write.bind(process.stderr),s=0,i=!1,o=a=>{if(!i)try{let c=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if(Z0(e,c),s+=c.length,s>2*rh){let l=Rl(e),f=l.subarray(Math.max(0,l.length-rh));Vi(e,f),s=f.length}}catch{i=!0}};return process.stdout.write=((a,...c)=>(o(a),t(a,...c))),process.stderr.write=((a,...c)=>(o(a),n(a,...c))),()=>{process.stdout.write=t,process.stderr.write=n}}function ah(r){try{Vi(Hn(r),"")}catch{}}function $e(r,e=0){try{let t=Rl(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 Ll(r){return`\u2500\u2500 run ${r} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function rE(r){let e=tE.exec(r);return e?Number(e[1]):void 0}function ch(r,e){let t=r.split(`
|
|
1041
|
+
`),n=[];if(t.forEach((o,a)=>{let c=rE(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 Ml(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function lh(r){await Q0(Xe(),{recursive:!0}),await sh(Nl(r.pid),JSON.stringify(r))}async function uh(r,e){let t=Nl(r);try{let n=JSON.parse(await nh(t,"utf8"));if(n.denied===e)return;n.denied=e,await sh(t,JSON.stringify(n))}catch{}}async function Kn(r){await Cl(Nl(r)).catch(()=>{}),await Cl(Hn(r)).catch(()=>{}),await Cl(Il(r)).catch(()=>{})}async function Q(r){let e;try{e=await X0(Xe())}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 nh(ge.join(Xe(),s),"utf8"))}catch{await Kn(i);return}o&&typeof o.pid=="number"&&Ml(o.pid)?t.push(o):await Kn(i)})),(r?t.filter(s=>s.agent==null&&Gm(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function Dl(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 Wt(r){try{process.kill(r,"SIGTERM")}catch{}await Kn(r)}function _r(r,e){let t=ne(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&ne(n.file)===t)}async function Bl(r){let e=_r(await Q(),r);for(let t of e)await Wt(t.pid);return e}function sE(r,e,t){(process.platform==="win32"?th("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):th(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function dh(){return ge.join(ge.dirname(eE(import.meta.url)),"index.js")}function iE(r,e={}){return{command:process.execPath,args:[dh(),...e.trust?["--trust"]:[],...e.dir?["--dir",e.dir]:[],...e.mode?["--mode",e.mode]:[],r,...e.open===!1?["--no-open"]:[]]}}function oE(r){return{command:process.execPath,args:[dh(),`agent:${r}`,"--no-open"]}}async function fh(r,e,t,n){let s=await r();if(s)return s;sE(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await nE(150);let o=await r();if(o)return o}throw new Error(`Launched ${n} but it did not register within 20s.`)}async function Xi(r,e={}){let t=e.cwd??process.cwd(),n=ge.resolve(t,r),[s]=await Bl(n),i={...e,dir:e.dir??s?.dir,mode:e.mode??s?.mode};return fh(async()=>_r(await Q(),n)[0],iE(r,i),t,ge.basename(r))}async function ph(r,e=process.cwd()){return fh(()=>Dl(e,r),oE(r),e,`the ${r} mirror`)}var rh,tE,nE,Le=S(()=>{Ui();rh=1e6;tE=/^── run (\d+) ── /;nE=r=>new Promise(e=>setTimeout(e,r))});function Qi(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 jl(r){return(Qi(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var Fl=S(()=>{});import{readdirSync as aE,readFileSync as cE,statSync as lE}from"fs";import{join as mh,basename as uE}from"path";function hh(r,e,t){if(e>8)return t;let n;try{n=aE(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;hh(mh(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(mh(r,s.name));return t}function Zi(r){return hh(r,0,[]).map(e=>{let t=0;try{t=lE(e).mtimeMs}catch{}let n,s=!1;try{let i=cE(e,"utf8");n=Qi(i.slice(0,1024));let o=pe(i);s=!!o&&pi(pr(o))}catch{}return{path:e,name:n??uE(e).replace(/\.bulb\.md$/,""),mtime:t,serverOnly:s}})}var gh=S(()=>{Ne();Sn();Fl()});function Cr(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 eo=S(()=>{});import{readFile as dE}from"fs/promises";async function ql(r){try{let e=pe(await dE(r,"utf-8"));return e?Cr(pr(e)):void 0}catch{return}}var yh=S(()=>{Sn();eo()});function Ul(r){let e=pe(r);if(!e)return r;let t=e.files.get("code.tsx");if(!t)return r;let n=cm(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=Yu(l);u&&(c[u]=f)}return c.config=JSON.stringify(i,null,2),td(c)}var bh=S(()=>{Ne();mi()});import{spawn as wh}from"child_process";import{basename as fE}from"path";function pE(){return process.env.TYPEBULB_EDITOR||"code"}function hE(r,e,t){return t==null?[e]:mE.test(fE(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function gE(r,e){let t=pE();return{command:t,args:hE(t,r,e)}}function Jl(r,e){let{command:t,args:n}=gE(r,e),s=process.platform==="win32"?wh("cmd.exe",["/d","/s","/c",t,...n],{detached:!0,stdio:"ignore",windowsHide:!0}):wh(t,n,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var mE,vh=S(()=>{mE=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as yE,existsSync as bE}from"fs";import*as Yt from"path";import{fileURLToPath as wE}from"url";function Sh(){let r=Yt.dirname(wE(import.meta.url));for(;!bE(Yt.join(r,"package.json"));){let e=Yt.dirname(r);if(e===r)break;r=e}return r}function Vt(){return Yt.join(Sh(),"README.md")}function Rr(){return Yt.join(Sh(),"description.md")}function vE(r){let e=yE(Rr(),"utf8").trim().replace(/\s+/g," ");return`---
|
|
1043
1043
|
name: typebulb
|
|
1044
1044
|
description: ${JSON.stringify(e)}
|
|
1045
1045
|
version: ${r}
|
|
1046
|
-
---`}function
|
|
1046
|
+
---`}function SE(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 xh(r,e){return`${vE(e)}
|
|
1047
1047
|
|
|
1048
|
-
${
|
|
1048
|
+
${SE(e)}
|
|
1049
1049
|
|
|
1050
1050
|
${r.trim()}
|
|
1051
|
-
`}var to=
|
|
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 ro(r,e=process.cwd()){for(let t of Eh()){let n;try{n=kh(
|
|
1053
|
-
Expected <origin>/u/<user>/<slug>`);let c=a[1],l=a[2].replace(/(\.bulb)?\.md$/,"");return{origin:i.origin,userSlug:c,slug:l,dest:
|
|
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,...s,dest:n}}async function io(r,e={}){let t=await fetch(Hl(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
|
|
1055
|
-
`),n=pe(t(r)),s=pe(t(e));return!n||!s?t(r)===t(e):n.frontmatter.name===s.frontmatter.name&&tt.every(i=>(n.files.get(
|
|
1051
|
+
`}var to=S(()=>{});import{readFileSync as kh,existsSync as xE}from"fs";import*as Me from"path";function Eh(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function ye(r,e=process.cwd()){let t={},n=[];for(let s of Eh(r)){let i;try{i=kh(Me.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[o,a]of Ah(i))process.env[o]===void 0&&(process.env[o]=a,t[o]=s)}return{mode:r,sources:t,loaded:n}}function*Ah(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 ro(r,e=process.cwd()){for(let t of Eh()){let n;try{n=kh(Me.resolve(e,t),"utf-8")}catch{continue}for(let[s,i]of Ah(n))if(s===r)return i}return process.env[r]}function kE(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 vt(r,e,t){let{sources:n,mode:s,loaded:i}=r,o=process.cwd(),a=Me.dirname(e),c=`(mode: ${s??"none"})`,l=t?kE(t):[],f=l.filter(p=>n[p]).map(p=>`${p} \u2190 ${n[p]}`);f.length?console.log(`env: ${f.join(", ")} ${c}`):i.length&&console.log(`env: loaded ${i.join(", ")} ${c}`),s&&!i.some(p=>p===`.env.${s}`||p===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let u=Me.resolve(a)!==Me.resolve(o);if(u)for(let p of[".env.local",".env"])xE(Me.join(a,p))&&console.log(`env: ${Me.join(a,p)} present but not loaded (cwd is ${o})`);let d=l.filter(p=>process.env[p]===void 0);if(d.length){let p=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${d.join(", ")} but ${d.length>1?"they are":"it's"} unset${p}`)}}var St=S(()=>{});import*as De from"fs/promises";import*as Oe from"path";function Kl(r){let[e,t,n,s]=r.split(Oe.sep).slice(-4);if(!(e!=="typebulbs"||t!=="u"||!n||!s?.endsWith(".bulb.md")))return{userSlug:n,slug:s.slice(0,-8)}}function Wl(r,e){ye(e);let t=process.env.TYPEBULB_ORIGIN||EE;try{return so(r,process.cwd(),t)}catch(n){console.error(n instanceof Error?n.message:String(n)),process.exit(1)}}function so(r,e,t){if(/^https?:\/\//i.test(r)){let i=new URL(r),o=i.pathname.split("/").filter(Boolean).map(decodeURIComponent),a=o[0]==="api"&&o[1]==="scripts"?o.slice(2):o;if(a[0]!=="u"||!a[1]||!a[2])throw new Error(`Not a bulb URL: ${r}
|
|
1053
|
+
Expected <origin>/u/<user>/<slug>`);let c=a[1],l=a[2].replace(/(\.bulb)?\.md$/,"");return{origin:i.origin,userSlug:c,slug:l,dest:Oe.join(e,no(c,l))}}let n=Oe.resolve(e,r),s=Kl(n);if(!s)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,...s,dest:n}}async function io(r,e={}){let t=await fetch(Hl(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 De.readFile(r.dest,"utf-8")}catch{}if(i!==void 0){if(AE(i,s))return{kind:"up-to-date",dest:r.dest};if(!e.force){let{mtime:a}=await De.stat(r.dest);return{kind:"conflict",dest:r.dest,localMtime:a,remoteLastModified:t.headers.get("last-modified")}}}await De.mkdir(Oe.dirname(r.dest),{recursive:!0}),await De.writeFile(r.dest,s);let o=new Date(t.headers.get("last-modified")??"");return isNaN(o.getTime())||await De.utimes(r.dest,new Date,o),{kind:"written",dest:r.dest,created:i===void 0}}function AE(r,e){let t=i=>i.replace(/\r\n/g,`
|
|
1055
|
+
`),n=pe(t(r)),s=pe(t(e));return!n||!s?t(r)===t(e):n.frontmatter.name===s.frontmatter.name&&tt.every(i=>(n.files.get(_e[i].path)||"")===(s.files.get(_e[i].path)||""))}async function Th(r,e){r||(console.error("Usage: typebulb pull <bulb url | typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1));let t=Wl(r,e.mode),n=`${t.origin}/u/${t.userSlug}/${t.slug}`,s;try{s=await io(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=Oe.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
1056
|
local file modified ${s.localMtime.toISOString()}
|
|
1057
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
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
'.overlay { --fg: rgb(28, 28, 30); --muted: rgb(96, 96, 100); --panel: rgb(242, 242, 242);\\n' +
|
|
1065
|
-
' --border: rgb(221, 221, 221); --accent: rgb(58, 125, 232); --accent-contrast: #fff;\\n' +
|
|
1066
|
-
' --veil: rgba(0, 0, 0, 0.05); --err: rgb(206, 60, 60); }\\n' +
|
|
1067
|
-
'.dark .overlay { --fg: rgb(190, 190, 190); --muted: rgb(150, 150, 150); --panel: rgb(32, 32, 32);\\n' +
|
|
1068
|
-
' --border: rgb(52, 52, 52); --accent: rgb(122, 162, 250); --accent-contrast: #1c1e21;\\n' +
|
|
1069
|
-
' --veil: rgba(255, 255, 255, 0.06); --err: rgb(230, 60, 60); }\\n' +
|
|
1070
|
-
'.overlay { position: fixed; inset: 0; background: rgba(0,0,0,.45); z-index: 2147483000;\\n' +
|
|
1071
|
-
' display: flex; align-items: center; justify-content: center; padding: 16px;\\n' +
|
|
1072
|
-
' font: 14px/1.45 system-ui, sans-serif; color: var(--fg); }\\n' +
|
|
1073
|
-
'.card { background: var(--panel); border-radius: 10px; box-shadow: 0 12px 40px rgba(0,0,0,.35);\\n' +
|
|
1074
|
-
' width: min(560px, 100%); max-height: min(80vh, 640px); display: flex; flex-direction: column; }\\n' +
|
|
1075
|
-
'.head { display: flex; align-items: center; gap: 8px; padding: 14px 16px 10px; }\\n' +
|
|
1076
|
-
'.head h1 { font-size: 18px; font-weight: 600; margin: 0; flex: 1; color: var(--accent); }\\n' +
|
|
1077
|
-
'.x { border: 0; background: none; color: inherit; font-size: 18px; cursor: pointer; opacity: .6; padding: 2px 6px; }\\n' +
|
|
1078
|
-
'.x:hover { opacity: 1; }\\n' +
|
|
1079
|
-
'.body { padding: 0 16px; overflow-y: auto; flex: 1; display: flex; flex-direction: column; gap: 10px; }\\n' +
|
|
1080
|
-
'.model { color: var(--muted); }\\n' +
|
|
1081
|
-
'.model.err { color: var(--err); }\\n' +
|
|
1082
|
-
'label { font-weight: 600; }\\n' +
|
|
1083
|
-
'.tabs { display: flex; gap: 4px; }\\n' +
|
|
1084
|
-
'.tab { font: inherit; padding: 4px 10px; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; color: inherit; cursor: pointer; opacity: .6; }\\n' +
|
|
1085
|
-
'.tab.on { opacity: 1; border-bottom-color: var(--accent); }\\n' +
|
|
1086
|
-
'.tab .cnt { opacity: .6; font-size: 12px; margin-left: 4px; }\\n' +
|
|
1087
|
-
'textarea { width: 100%; box-sizing: border-box; min-height: 160px; max-height: 320px; resize: vertical;\\n' +
|
|
1088
|
-
' font: 13px/1.4 ui-monospace, monospace; padding: 8px; border-radius: 6px;\\n' +
|
|
1089
|
-
' border: 1px solid var(--border); background: var(--veil); color: inherit; }\\n' +
|
|
1090
|
-
'pre.stream { font: 13px/1.4 ui-monospace, monospace; white-space: pre-wrap; word-break: break-word;\\n' +
|
|
1091
|
-
' background: var(--veil); border-radius: 6px; padding: 10px; margin: 0; min-height: 120px; }\\n' +
|
|
1092
|
-
'.error { color: var(--err); white-space: pre-wrap; }\\n' +
|
|
1093
|
-
'.foot { display: flex; gap: 8px; padding: 12px 16px 14px; justify-content: flex-end; align-items: center; }\\n' +
|
|
1094
|
-
'.leftgrp { margin-right: auto; display: flex; gap: 8px; }\\n' +
|
|
1095
|
-
'button { font: inherit; padding: 6px 14px; border-radius: 6px; cursor: pointer;\\n' +
|
|
1096
|
-
' border: 1px solid var(--border); background: transparent; color: inherit; }\\n' +
|
|
1097
|
-
'button.run { background: var(--accent); border-color: var(--accent); color: var(--accent-contrast); }\\n' +
|
|
1098
|
-
'button.run:disabled { opacity: .5; cursor: default; }\\n' +
|
|
1099
|
-
'@keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }\\n' +
|
|
1100
|
-
'.shimmer { display: inline-block; background-image: linear-gradient(90deg, var(--muted), var(--fg), var(--muted));\\n' +
|
|
1101
|
-
' background-size: 200% 100%; -webkit-background-clip: text; background-clip: text;\\n' +
|
|
1102
|
-
' -webkit-text-fill-color: transparent; color: transparent; animation: shimmer 2s linear infinite; }\\n';
|
|
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 EE,no,Hl,Wn=S(()=>{St();Ne();EE="https://typebulb.com",no=(r,e)=>Oe.join("typebulbs","u",r,`${e}.bulb.md`);Hl=r=>`${r.origin}/u/${encodeURIComponent(r.userSlug)}/${encodeURIComponent(r.slug)}.md`});import*as Be from"fs/promises";import*as Vn from"path";import{createHash as TE}from"crypto";async function Oh(r,e=""){let t=await Be.readdir(r,{withFileTypes:!0}).catch(()=>[]),n=[];for(let s of t)s.isDirectory()?n.push(...await Oh(Vn.join(r,s.name),`${e}${s.name}/`)):s.isFile()&&n.push(e+s.name);return n}async function PE(r,e){let t=e.timeoutMs??3e4,n=_h(r),s={Authorization:`Bearer ${e.token}`},i=jn(r.dest);if(!await Be.stat(i).then(p=>p.isDirectory()).catch(()=>!1))return{kind:"skipped"};let o=await Oh(i),a;try{let p=await fetch(n,{headers:s,signal:AbortSignal.timeout(t)});if(!p.ok)return{kind:"sync-error",message:`manifest request failed (${p.status}): ${Yn(await p.text())}`};a=await p.json()}catch(p){return{kind:"sync-error",message:p instanceof Error?p.message:String(p)}}if(!o.length&&!a.length)return{kind:"skipped"};let c=new Map(a.map(p=>[p.path,p.md5])),l=new Set(o),f=a.map(p=>p.path).filter(p=>!l.has(p)),u=0,d=0;try{await _E(o,4,async p=>{let b=await Be.readFile(Vn.join(i,...p.split("/")));if(c.get(p)===TE("md5").update(b).digest("hex")){d++;return}let m=await fetch(`${n}/${Ph(p)}`,{method:"PUT",body:new Uint8Array(b),headers:s,signal:AbortSignal.timeout(t)});if(!m.ok)throw new Error(`upload of '${p}' refused (${m.status}): ${Yn(await m.text())}`);u++})}catch(p){return{kind:"sync-error",message:p instanceof Error?p.message:String(p)}}return{kind:"synced",uploaded:u,unchanged:d,toDelete:f,base:ms(r.userSlug,r.slug)}}async function OE(r,e,t){let n=t.timeoutMs??3e4,s=_h(r),i=[];for(let o of e)try{let a=await fetch(`${s}/${Ph(o)}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(n)});if(!a.ok)return{deleted:i,error:`delete of '${o}' refused (${a.status}): ${Yn(await a.text())}`};i.push(o)}catch(a){return{deleted:i,error:a instanceof Error?a.message:String(a)}}return{deleted:i}}async function _E(r,e,t){let n=[...r],s=async()=>{for(let i=n.shift();i!==void 0;i=n.shift())await t(i)};await Promise.all(Array.from({length:Math.min(e,r.length)},s))}async function CE(r,e){let t=await PE(r,{token:e});return t.kind==="sync-error"?(console.error(`assets sync failed: ${t.message}
|
|
1059
|
+
push refused: the bulb text was not pushed.`),{proceed:!1}):t.kind==="synced"?(console.log(`assets: ${t.uploaded} uploaded, ${t.unchanged} unchanged \u2192 ${t.base}`),{proceed:!0,toDelete:t.toDelete}):{proceed:!0}}async function oo(r,e){let t=await Be.readFile(r.dest,"utf-8"),{mtime:n}=await Be.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(Hl(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:Yn(o)};if(!i.ok)return{kind:"http-error",status:i.status,message:Yn(o)};let a=JSON.parse(o);return await Be.utimes(r.dest,new Date,new Date(a.updatedAt)),{kind:"pushed",created:a.created,serverStripped:a.serverStripped,updatedAt:a.updatedAt}}function Yn(r){try{return JSON.parse(r).error||r}catch{return r}}async function Ch(r,e){r||(console.error("Usage: typebulb push <typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1)),/^https?:\/\//i.test(r)&&(console.error("push takes a local .bulb.md file, not a URL (the path is its remote identity)"),process.exit(1));let t=Wl(r,e.mode),n=process.env.TYPEBULB_TOKEN;n||(console.error("push needs TYPEBULB_TOKEN in your .env \u2014 create one on your typebulb.com settings page."),process.exit(1));let s=`${t.origin}/u/${t.userSlug}/${t.slug}`,i=Vn.relative(process.cwd(),t.dest)||t.dest,o,a;try{let c=await CE(t,n);if(!c.proceed){process.exitCode=1;return}a=c.toDelete,o=await oo(t,{token:n,force:e.force})}catch(c){let l=c instanceof Error?c.message:String(c);console.error(c?.code==="ENOENT"?`File not found: ${i}`:`Could not push to ${t.origin}: ${l}`),process.exitCode=1;return}switch(o.kind){case"pushed":{if(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."),a?.length){let c=await OE(t,a,{token:n});for(let l of c.deleted)console.log(` deleted ${l} (no longer in assets/)`);c.error&&console.log(`note: asset cleanup incomplete \u2014 ${c.error}; the next push will retry.`)}return}case"conflict":console.error(`${o.message}
|
|
1060
|
+
pull to see the remote: typebulb pull ${i}
|
|
1061
|
+
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 Ph,_h,Yl=S(()=>{Ne();Wn();bt();Ph=r=>r.split("/").map(encodeURIComponent).join("/");_h=r=>`${r.origin}/u/${encodeURIComponent(r.userSlug)}/${encodeURIComponent(r.slug)}/assets`});var Nr=S(()=>{Le();gh();yh();Fl();bh();vh();qn();Kt();Kt();ji();to();Wn();Yl();St()});import{copyFileSync as RE,existsSync as Rh,mkdirSync as Nh,rmSync as NE,writeFileSync as IE}from"fs";import{homedir as $E}from"os";import*as je from"path";import{fileURLToPath as LE}from"url";function qE(){return FE.replace('"__TB_DESCRIPTION_PATH__"',JSON.stringify(Rr())).replace('"__TB_README_PATH__"',JSON.stringify(Vt()))}function Ih(){try{if(!Rh(ao()))return}catch{return}try{let r=ME();Nh(je.dirname(r),{recursive:!0}),IE(r,qE()),NE(DE(),{force:!0})}catch{}try{let r=BE();if(!Rh(r))return;let e=jE();Nh(je.dirname(e),{recursive:!0}),RE(r,e)}catch{}}var ao,ME,DE,BE,jE,FE,$h=S(()=>{Nr();ao=()=>je.join($E(),".pi","agent"),ME=()=>je.join(ao(),"extensions","typebulb.ts"),DE=()=>je.join(ao(),"extensions","typebulb-wait.ts"),BE=()=>je.join(je.dirname(LE(import.meta.url)),"agents","pi","matchu-patchu.ts"),jE=()=>je.join(ao(),"extensions","matchu-patchu.ts"),FE=String.raw`// Generated by typebulb — do not edit; overwritten on each run.
|
|
1062
|
+
import { spawn } from "node:child_process";
|
|
1063
|
+
import { existsSync } from "node:fs";
|
|
1103
1064
|
|
|
1104
|
-
function
|
|
1105
|
-
var t = document.documentElement.getAttribute('data-theme');
|
|
1106
|
-
if (t) return t === 'dark';
|
|
1107
|
-
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
|
|
1108
|
-
}
|
|
1065
|
+
function logErr(...a) { try { console.error("[typebulb]", ...a); } catch (e) {} }
|
|
1109
1066
|
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
if (cls) e.className = cls;
|
|
1113
|
-
if (text != null) e.textContent = text;
|
|
1114
|
-
return e;
|
|
1115
|
-
}
|
|
1067
|
+
// Matches "typebulb wait", "npx typebulb wait", "/path/to/typebulb wait", "pnpm exec typebulb wait", etc.
|
|
1068
|
+
function isWaitCommand(command) { return /\btypebulb\s+wait\b/.test(String(command || "")); }
|
|
1116
1069
|
|
|
1117
|
-
//
|
|
1118
|
-
//
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1070
|
+
// pi's bash tool runs every command under Git Bash on Windows (its getShellConfig), so the
|
|
1071
|
+
// intercepted string is POSIX. Re-running it under node's shell:true (cmd.exe on Windows) breaks
|
|
1072
|
+
// that syntax — cmd doesn't split on ";", so a trailing "; echo ..." rides along as extra ARGS to
|
|
1073
|
+
// typebulb wait, which resolves a garbage target and dies code 1 before the event (field: a wait
|
|
1074
|
+
// that resolved the target 'exit: $?'). Resolve bash the way pi does; null → shell:true (POSIX sh).
|
|
1075
|
+
function resolveBash() {
|
|
1076
|
+
try {
|
|
1077
|
+
if (process.platform !== "win32") return existsSync("/bin/bash") ? "/bin/bash" : null;
|
|
1078
|
+
var dirs = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]];
|
|
1079
|
+
for (var i = 0; i < dirs.length; i++) {
|
|
1080
|
+
if (dirs[i] && existsSync(dirs[i] + "\\Git\\bin\\bash.exe")) return dirs[i] + "\\Git\\bin\\bash.exe";
|
|
1081
|
+
}
|
|
1082
|
+
return "bash.exe"; // PATH fallback (Cygwin/MSYS2); a spawn miss lands in the "error" handler
|
|
1083
|
+
} catch (e) { return null; }
|
|
1125
1084
|
}
|
|
1126
1085
|
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
* exactly one copy of the transport decoder. onComplete fires on every successful run (a retry
|
|
1132
|
-
* after an error included); onError on each displayed terminal error; onCancel when the user
|
|
1133
|
-
* closes before any completion.
|
|
1134
|
-
*/
|
|
1135
|
-
export function runInference(ctx) {
|
|
1136
|
-
var host = document.createElement('div');
|
|
1137
|
-
var root = host.attachShadow({ mode: 'closed' });
|
|
1138
|
-
var style = document.createElement('style');
|
|
1139
|
-
style.textContent = CSS;
|
|
1140
|
-
root.appendChild(style);
|
|
1141
|
-
|
|
1142
|
-
var wrap = el('div', isDark() ? 'dark' : '');
|
|
1143
|
-
root.appendChild(wrap);
|
|
1144
|
-
var overlay = el('div', 'overlay');
|
|
1145
|
-
wrap.appendChild(overlay);
|
|
1146
|
-
var card = el('div', 'card');
|
|
1147
|
-
overlay.appendChild(card);
|
|
1086
|
+
// Resolved at shim-write time to this install's absolute skill-part paths (same files
|
|
1087
|
+
// commands/agent.ts prints — readable without a permission prompt, unlike the npx command).
|
|
1088
|
+
var TB_DESCRIPTION_PATH = "__TB_DESCRIPTION_PATH__";
|
|
1089
|
+
var TB_README_PATH = "__TB_README_PATH__";
|
|
1148
1090
|
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1091
|
+
// Orientation for a MIRROR-DRIVEN session (TYPEBULB_MIRROR=1 — set only by the mirror's composer
|
|
1092
|
+
// driver). A composer-driven agent never runs "typebulb agent", so the guaranteed-delivery block
|
|
1093
|
+
// that command prints (commands/agent.ts) never reaches it; this re-delivers it via the system
|
|
1094
|
+
// prompt. The wording below is copied from agent.ts, hard-won across many failed interactions —
|
|
1095
|
+
// only the mirror-link lines differ (the user is already IN the mirror). Change it there first.
|
|
1096
|
+
var TB_MIRROR_BLOCK = [
|
|
1097
|
+
"Typebulb: the user is prompting you from the typebulb agent mirror (already open in front of them).",
|
|
1098
|
+
" Embedded bulbs render live in this conversation.",
|
|
1099
|
+
" • do not run npx typebulb agent — the mirror is already running",
|
|
1100
|
+
" • no need to end your reply with a mirror link",
|
|
1101
|
+
" Reusable app/tool → write a .bulb.md",
|
|
1102
|
+
" Show something inline → embed a bulb",
|
|
1103
|
+
" arm a wait for its render verdict — run it plainly:",
|
|
1104
|
+
' • typebulb wait agent --match "[embed <name>"',
|
|
1105
|
+
" Read the authoring skill before writing a bulb:",
|
|
1106
|
+
" • npx typebulb skill — assembles one SKILL.md",
|
|
1107
|
+
" • or, open its parts:",
|
|
1108
|
+
" " + TB_DESCRIPTION_PATH,
|
|
1109
|
+
" " + TB_README_PATH,
|
|
1110
|
+
].join("\n");
|
|
1156
1111
|
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
host.remove();
|
|
1161
|
-
if (kind === 'cancel' && !completed) ctx.onCancel();
|
|
1162
|
-
}
|
|
1163
|
-
overlay.addEventListener('click', function (e) { if (e.target === overlay) close('cancel'); });
|
|
1112
|
+
export default function (pi) {
|
|
1113
|
+
try {
|
|
1114
|
+
const pending = new Set();
|
|
1164
1115
|
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
card.appendChild(head);
|
|
1116
|
+
pi.on("before_agent_start", (event) => {
|
|
1117
|
+
try {
|
|
1118
|
+
if (process.env.TYPEBULB_MIRROR !== "1") return undefined;
|
|
1119
|
+
return { systemPrompt: event.systemPrompt + "\n\n" + TB_MIRROR_BLOCK };
|
|
1120
|
+
} catch (e) { logErr("before_agent_start", e && e.message); return undefined; }
|
|
1121
|
+
});
|
|
1172
1122
|
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1123
|
+
pi.on("tool_call", (event, ctx) => {
|
|
1124
|
+
try {
|
|
1125
|
+
if (!event || event.toolName !== "bash") return undefined;
|
|
1126
|
+
const command = event.input && event.input.command;
|
|
1127
|
+
if (!isWaitCommand(command)) return undefined;
|
|
1177
1128
|
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1129
|
+
// Run the REAL typebulb wait in the background instead of foreground (which would deadlock the
|
|
1130
|
+
// turn). It does the mirror/registry lookup, --match and offsets itself. The marker tells it this
|
|
1131
|
+
// is a shim-backgrounded (non-blocking) wait, so it runs as a pure subscription: no give-up clock,
|
|
1132
|
+
// it waits for the event however long (bounded by the session-shutdown reap below) — an embed's
|
|
1133
|
+
// first paint OR a running bulb's next event line alike.
|
|
1134
|
+
// The agent may self-background ("… &") — the generic-shell reading of "arm it in the
|
|
1135
|
+
// background", but here the SHIM is the backgrounder: bash would exit 0 instantly with empty
|
|
1136
|
+
// output, firing the wake before the event while the detached wait delivers to nobody
|
|
1137
|
+
// (field: Toroidal Life, '> /tmp/x.log 2>&1 &'). Strip a trailing "&" so the wait runs
|
|
1138
|
+
// foreground inside the shim's already-backgrounded child.
|
|
1139
|
+
const cmd = String(command).replace(/(?<!&)\s*&\s*$/, "");
|
|
1140
|
+
const bash = resolveBash();
|
|
1141
|
+
const opts = {
|
|
1142
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1143
|
+
env: { ...process.env, TYPEBULB_WAIT_SHIM: "1" },
|
|
1144
|
+
};
|
|
1145
|
+
const child = bash ? spawn(bash, ["-c", cmd], opts) : spawn(cmd, { ...opts, shell: true });
|
|
1146
|
+
pending.add(child);
|
|
1147
|
+
let out = "";
|
|
1148
|
+
let errOut = "";
|
|
1149
|
+
if (child.stdout) child.stdout.on("data", (b) => { out += b.toString(); });
|
|
1150
|
+
if (child.stderr) child.stderr.on("data", (b) => { errOut += b.toString(); });
|
|
1151
|
+
child.on("error", (e) => {
|
|
1152
|
+
pending.delete(child);
|
|
1153
|
+
logErr("spawn", e && e.message);
|
|
1154
|
+
// Same class as a failure exit: the subscription never armed, so silence is a deadlock.
|
|
1155
|
+
try { pi.sendUserMessage("typebulb wait FAILED to spawn: " + (e && e.message) + "\nNothing is watching — fix and re-arm the wait.", { deliverAs: "followUp" }); } catch (e2) {}
|
|
1156
|
+
});
|
|
1157
|
+
child.on("exit", (code) => {
|
|
1158
|
+
pending.delete(child);
|
|
1159
|
+
try {
|
|
1160
|
+
const text = out.trim();
|
|
1161
|
+
// Exit 0 with output is a real outcome (embed ok/error, a turn-based move) -> wake the
|
|
1162
|
+
// agent (followUp delivers immediately when idle and queues when streaming — the same call
|
|
1163
|
+
// git-merge-and-resolve.ts makes from agent_end). A late wake is fine; it just reports
|
|
1164
|
+
// something true. Exit 2/3 (no render yet / server gone) surface passively, no turn.
|
|
1165
|
+
// Any OTHER non-zero exit means the subscription itself broke (bad args, no resolvable
|
|
1166
|
+
// mirror): the agent parked on a wake that can never come, so that failure must wake too —
|
|
1167
|
+
// missed wakes are fatal, spurious wakes cheap (TB-Wait.md). null (reap-killed) stays silent.
|
|
1168
|
+
// EXCEPT an embed's clean ok verdict ("[embed <name> vN] ok" — core/client/bulbEmbed.ts):
|
|
1169
|
+
// the user already sees the bulb and the skill orders silence on ok, so a wake would spend
|
|
1170
|
+
// a whole turn saying nothing and render a noise message. Silence IS the ok. Anything else
|
|
1171
|
+
// (an embed error, a turn-based loop event) still wakes; an unrecognized shape wakes too.
|
|
1172
|
+
// Checked PER LINE, not over the whole blob: wait lingers 10s and bursts every matching line
|
|
1173
|
+
// into one payload, and a version-agnostic --match ("[embed <name>") replays v1+v2+... from
|
|
1174
|
+
// log start, so an all-ok payload is routinely multi-line. Suppress iff EVERY line is an ok;
|
|
1175
|
+
// one error line among oks still wakes.
|
|
1176
|
+
var waitLines = text.split("\n").map(function (l) { return l.trim(); }).filter(Boolean);
|
|
1177
|
+
const embedOk = code === 0 && waitLines.length > 0 && waitLines.every(function (l) { return /^\[embed .*\] ok$/.test(l); });
|
|
1178
|
+
if (code === 0 && text && !embedOk) {
|
|
1179
|
+
pi.sendUserMessage("typebulb wait result:\n" + text, { deliverAs: "followUp" });
|
|
1180
|
+
} else if (code === 0 && !text) {
|
|
1181
|
+
// A successful wait always prints its matched line(s), so exit 0 with nothing captured
|
|
1182
|
+
// means the agent redirected stdout (e.g. '> /tmp/x.log 2>&1') — the verdict landed in a
|
|
1183
|
+
// file nobody reads. The line is still in the mirror's log; point the agent there.
|
|
1184
|
+
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" });
|
|
1185
|
+
} else if (code !== null && code !== 0 && code !== 2 && code !== 3) {
|
|
1186
|
+
var diag = (text + "\n" + errOut.trim()).trim();
|
|
1187
|
+
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" });
|
|
1188
|
+
} else if (ctx.ui && typeof ctx.ui.notify === "function") {
|
|
1189
|
+
// INVARIANT: this notify must never quote the "[embed <name>" tag verbatim. In a
|
|
1190
|
+
// composer-driven session the mirror's driver echoes extension notifies into the
|
|
1191
|
+
// mirror's own log (driver.ts) — the very log wait watches by substring — so a
|
|
1192
|
+
// verbatim tag re-fires the next same-match wait with a non-ok line: a self-
|
|
1193
|
+
// sustaining wake loop that defeats this suppression (TB-Wait.md). Stripping the
|
|
1194
|
+
// brackets kills the matchable substring while keeping the verdict readable.
|
|
1195
|
+
ctx.ui.notify("typebulb wait: " + (embedOk ? text.replace(/[\[\]]/g, "") : code === 2 ? "timed out, nothing to report" : "ended (code " + code + ")"), "info");
|
|
1196
|
+
}
|
|
1197
|
+
} catch (e) { logErr("exit", e && e.message); }
|
|
1198
|
+
});
|
|
1182
1199
|
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1200
|
+
return {
|
|
1201
|
+
block: true,
|
|
1202
|
+
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.",
|
|
1203
|
+
};
|
|
1204
|
+
} catch (e) { logErr("tool_call", e && e.message); return undefined; }
|
|
1205
|
+
});
|
|
1189
1206
|
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1207
|
+
try { pi.on("session_shutdown", () => { for (const c of pending) { try { c.kill(); } catch (e) {} } pending.clear(); }); } catch (e) {}
|
|
1208
|
+
} catch (e) { logErr("load", e && e.message); }
|
|
1209
|
+
}
|
|
1210
|
+
`});function K(r){return r?.message??String(r)}var W,xt=S(()=>{W=process.cwd()});import{spawn as Lh}from"child_process";import{StringDecoder as UE}from"string_decoder";function zE(r,e){let t=new UE("utf8"),n="";r.on("data",s=>{n+=typeof s=="string"?s:t.write(s);let i;for(;(i=n.indexOf(`
|
|
1211
|
+
`))>=0;){let o=n.slice(0,i);n=n.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var JE,KE,Mh,HE,WE,YE,VE,GE,co,lo,Dh,Bh=S(()=>{xt();JE=3e4,KE=5e3,Mh=2e3,HE=2e3,WE=12e4,YE=8e3,VE=15e3,GE=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"]),co=new Set;process.on("exit",()=>{for(let r of co)try{r.kill()}catch{}});lo=class{#e;#a=!1;#c=0;#i=!1;#l=null;#m=null;#t=null;#n=null;#u=new Map;#r=[];#h=null;#w=null;#g=null;#d;#f;#y="";#A=1;#s=new Map;#v;#b;constructor(e,t,n=(s,i)=>Lh(s,{cwd:i,shell:!0,stdio:["pipe","pipe","pipe"],env:{...process.env,TYPEBULB_MIRROR:"1"}})){if(this.#v=new Promise(o=>{this.#b=o}),t?.includes('"')){this.#f="session path contains a quote \u2014 cannot drive it",this.#b();return}let s=t?`pi --mode rpc --session "${t}"`:"pi --mode rpc",i;try{i=n(s,e)}catch(o){this.#f=`could not start pi: ${K(o)}`,this.#b();return}this.#e=i,this.#d=t,co.add(i),i.stdout&&zE(i.stdout,o=>this.#T(o)),i.stderr&&i.stderr.on("data",o=>{this.#y=(this.#y+o.toString()).slice(-HE)}),i.on("error",o=>this.#k(`could not start pi: ${o.message}`)),i.on("exit",o=>{this.#e===i&&this.#k(o?`pi exited (code ${o})${this.#y.trim()?`: ${this.#y.trim()}`:""}`:"pi exited"),co.delete(i),this.#b()}),this.#o({type:"get_state"}).then(o=>{let a=o.data?.sessionFile;typeof a=="string"&&a&&(this.#d=a);let c=o.data?.model;c&&typeof c.id=="string"&&c.id&&(this.#g=c.id)}).catch(()=>{}),this.#S()}get streaming(){return this.#a||Date.now()<this.#c}get draft(){return this.#l}get echo(){return this.#m}get queue(){return this.#h}get stats(){return this.#w}get model(){return this.#g}get sessionFile(){return this.#d}get error(){return this.#f}get status(){if(this.#t)return this.#t;if(this.#n){if(Date.now()<this.#n.until)return{text:this.#n.text,kind:this.#n.kind};this.#n=null}return this.#u.size?{text:[...this.#u.values()].join(" \xB7 "),kind:"info"}:null}get dialog(){let e=Date.now();for(;this.#r.length;){let t=this.#r[0];if(e<t.until)return t.req;this.#r.shift(),t.ownTimeout||this.#x({type:"extension_ui_response",id:t.req.id,cancelled:!0})}return null}notice(e,t){this.#p(e,t)}respondUi(e,t){let n=this.#r.findIndex(o=>o.req.id===e);if(n<0)return{ok:!1,error:"dialog expired or already answered"};let[s]=this.#r.splice(n,1),i={type:"extension_ui_response",id:e};return t.cancelled?i.cancelled=!0:s.req.method==="confirm"?i.confirmed=!!t.confirmed:i.value=t.value??"",this.#x(i),{ok:!0}}async rpc(e){if(!GE.has(e.type))return{ok:!1,error:`command not allowed: ${e.type}`};try{let t=await this.#o(e);if(t.success&&e.type==="set_model"){let n=t.data?.id;typeof n=="string"&&n&&(this.#g=n)}if(t.success&&(e.type==="fork"||e.type==="clone")){try{let s=(await this.#o({type:"get_state"})).data?.sessionFile;typeof s=="string"&&s&&(this.#d=s)}catch{}return{ok:!0,data:{...t.data??{},sessionFile:this.#d}}}return t.success?{ok:!0,data:t.data}:{ok:!1,error:t.error??`pi rejected ${e.type}`}}catch(t){return{ok:!1,error:K(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:K(o)}}return i.success&&!n&&(this.#c=Date.now()+KE),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"})+`
|
|
1212
|
+
`)}catch{}await Promise.race([this.#v,Dh(Mh)])}try{e.stdin?.end()}catch{}if(await Promise.race([this.#v,Dh(Mh)]),e.exitCode===null&&!e.killed)if(process.platform==="win32"&&e.pid)try{Lh("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}else try{e.kill("SIGKILL")}catch{}co.delete(e),this.#r=[],this.#E("pi was shut down")}}#x(e){try{this.#e?.stdin?.write(JSON.stringify(e)+`
|
|
1213
|
+
`)}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"?YE:VE)})}#S(){this.#o({type:"get_session_stats"}).then(e=>{if(!e.success||!e.data)return;let t=e.data;this.#w={cost:typeof t.cost=="number"?t.cost:0,contextTokens:typeof t.contextUsage?.tokens=="number"?t.contextUsage.tokens:null,contextPercent:typeof t.contextUsage?.percent=="number"?t.contextUsage.percent:null}}).catch(()=>{})}#o(e){let t=this.#e;if(!t?.stdin?.writable)return Promise.reject(new Error(this.#f??"pi is not running"));let n=`tb-${this.#A++}`;return new Promise((s,i)=>{let o=setTimeout(()=>{this.#s.delete(n),i(new Error("pi did not respond (30s)"))},JE);o.unref?.(),this.#s.set(n,{resolve:s,timer:o});try{t.stdin.write(JSON.stringify({id:n,...e})+`
|
|
1214
|
+
`)}catch(a){clearTimeout(o),this.#s.delete(n),i(new Error(K(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(`
|
|
1215
|
+
`),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??WE),ownTimeout:s!==void 0})}else if(n==="notify"){let s=t.notifyType==="warning"?"warning":t.notifyType==="error"?"error":"info";this.#p(String(t.message??""),s),console.log(`[composer] pi extension: ${String(t.message??"")}`)}else if(n==="setStatus"){let s=String(t.statusKey??"");typeof t.statusText=="string"&&t.statusText?this.#u.set(s,t.statusText):this.#u.delete(s)}return}default:return}}#k(e){this.#f=e,this.#a=!1,this.#c=0,this.#i=!1,this.#l=null,this.#m=null,this.#t=null,this.#n=null,this.#u.clear(),this.#r=[],this.#h=null,this.#w=null,this.#g=null,this.#e=void 0,this.#E(e)}#E(e){for(let[,t]of this.#s)clearTimeout(t.timer),t.resolve({type:"response",success:!1,error:e});this.#s.clear()}},Dh=r=>new Promise(e=>{setTimeout(e,r).unref?.()})});import{existsSync as jh,readFileSync as XE,realpathSync as QE}from"fs";import{join as Gt,dirname as Jh,resolve as ZE}from"path";import{homedir as Fh}from"os";function tA(r,e){let t=Gt(r,".pi");if(eA.some(s=>jh(Gt(t,s))))return!0;let n=Gt(e,".agents","skills");for(let s=r;;){let i=Gt(s,".agents","skills");if(i!==n&&jh(i))return!0;let o=Jh(s);if(o===s)return!1;s=o}}function rA(r,e){for(let t=e;;){if(r[t]===!0||r[t]===!1)return!0;let n=Jh(t);if(n===t)return!1;t=n}}function Kh(r,e){try{let t=e?.agentDir??Gt(Fh(),".pi","agent"),n=qh(e?.home??process.env.HOME??Fh()),s=qh(ZE(r));if(!tA(s,n))return null;let i=Uh(Gt(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||rA(Uh(Gt(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 eA,qh,Uh,Hh=S(()=>{eA=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],qh=r=>{try{return QE(r)}catch{return r}},Uh=r=>{try{return JSON.parse(XE(r,"utf8"))}catch{return{}}}});import{statSync as nA,openSync as sA,readSync as iA,closeSync as oA,existsSync as Yh}from"fs";import{join as uo}from"path";import{homedir as Vl}from"os";import{execFile as aA}from"child_process";async function lA(r){let e=uo(Vl(),".pi","agent","bin",process.platform==="win32"?"fd.exe":"fd");for(let t of["fd","fdfind",...Yh(e)?[e]:[]]){let n=await new Promise(s=>{aA(t,["--base-directory",r,"--type","f","--follow","--hidden","--exclude",".git"],{maxBuffer:67108864},(i,o)=>s(i?null:o))});if(n!==null)return n.split(`
|
|
1216
|
+
`).filter(Boolean).map(s=>s.replace(/\\/g,"/"))}return null}function uA(r){return`--${r.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function Wh(r){return r.type==="message"?dA(r.message?.role):r.type==="custom_message"?r.display!==!1:!1}var cA,dA,Ir,Gl=S(()=>{Ki();El();Al();$h();Bh();Hh();cA=uo(Vl(),".pi","agent","sessions");dA=r=>r==="user"||r==="assistant"||r==="toolResult"||r==="bashExecution";Ir=class extends Pr{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}detectsInstalled(){return Yh(uo(Vl(),".pi","agent"))}ensureHarnessSupport(){Ih()}createDriver(e,t){let n=new lo(e,t),s=Kh(e);return s&&n.notice(s,"warning"),n}walkFiles(e){return lA(e)}sessionsDir(e){return uo(cA,uA(e))}listSessionFiles(e){return Hi(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 Wh(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:Qe(i)}),{events:n}}if(s.role==="bashExecution")return s.command&&!s.excludeFromContext&&n.push({type:"user",text:`$ ${s.command}`}),{events:n};if(s.role==="assistant"){let i=Array.isArray(s.content)?s.content:[],o=i.filter(d=>d.type==="text").map(d=>d.text??"").join(""),a=i.filter(d=>d.type==="thinking").map(d=>d.thinking??"").join(`
|
|
1217
|
+
`),c=i.filter(d=>d.type==="toolCall").map(d=>({id:d.id??"",name:d.name??"",input:d.arguments??{}}));if(o||a||c.length){let d=Date.parse(e.timestamp??""),p=!isNaN(d)&&d>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:p})}let l=s.usage,f=l?(l.input??0)+(l.output??0)+(l.cacheRead??0)+(l.cacheWrite??0):0,u=l&&f>0&&s.stopReason!=="aborted"&&s.stopReason!=="error"?{in:l.input??0,out:l.output??0,cached:l.cacheRead??0,cacheCreate:l.cacheWrite??0}:void 0;return{events:n,usage:u,model:s.model,cost:l?.cost?.total}}return{events:n}}chainWorking(e){let t;for(let a of e)Wh(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=sA(e,"r")}catch{return""}try{let s=65536;try{s=nA(e).size}catch{}let i=(u,d)=>{let p=Buffer.alloc(d),b=iA(t,p,0,d,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 d="";for(let p of u.split(`
|
|
1218
|
+
`))if(p.includes('"session_info"'))try{let b=JSON.parse(p);b?.type==="session_info"&&typeof b.name=="string"&&b.name&&(d=b.name)}catch{}return d},l="";for(let u of o.split(`
|
|
1219
|
+
`))if(!(l||!u.includes('"type"')))try{let d=JSON.parse(u);d?.type==="message"&&d.message?.role==="user"&&(l=this.contentText(d.message.content).replace(/\s+/g," ").trim())}catch{}let f=c(a)||c(o)||l;return f?f.slice(0,200):""}finally{oA(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"?Ie(e):Array.isArray(e)?e.map(t=>typeof t?.text=="string"?Ie(t.text):t?.type==="image"&&t.data?Ji(t.data,t.mimeType):"").filter(Boolean).join(`
|
|
1220
|
+
`):""}}});var fo,Vh=S(()=>{fo=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});import{execFile as fA}from"child_process";import{promisify as pA}from"util";import{readFile as mA}from"fs/promises";import{resolve as Gh,sep as hA}from"path";async function Fe(r,e){let{stdout:t}=await gA("git",r,{cwd:e,maxBuffer:67108864});return t}async function $r(){if(po)return po;try{po=(await Fe(["rev-parse","--show-toplevel"],W)).trim()}catch{}return po}function yA(r,e){let t=e===" "?r:e;return t==="?"?"U":t}async function Xh(){let r=await $r();if(!r)return{repo:!1,root:"",files:[]};try{let e=await Fe(["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:yA(i[0],i[1])}))}try{let s=await Fe(["diff","--numstat","HEAD"],r),i=new Map;for(let o of s.split(`
|
|
1221
|
+
`)){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:K(e)}}}async function Qh(r){let e=await $r();if(!e)return{ok:!1,error:"not a git repository"};try{if((await Fe(["status","--porcelain","-z","--",r],e)).startsWith("??")){let s=Gh(e,r);if(!s.startsWith(Gh(e)+hA))return{ok:!1,error:"outside repository"};let i=await mA(s);return i.includes(0)?zl("Binary file (not shown)",!1):zl(i.toString("utf8"),!0)}let n;try{n=await Fe(["diff","--no-color","--unified=999999","HEAD","--",r],e)}catch{n=await Fe(["diff","--no-color","--unified=999999","--",r],e)}return zl(n,!1)}catch(t){return{ok:!1,error:K(t)}}}var gA,zh,po,zl,mo=S(()=>{xt();gA=pA(fA),zh=2e6;zl=(r,e)=>({ok:!0,text:r.slice(0,zh),untracked:e,truncated:r.length>zh})});function ho(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 Xl=S(()=>{});var go,yo,Zh=S(()=>{go=".typebulb/paste",yo={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 bA,mkdirSync as wA,writeFileSync as vA,readFileSync as SA}from"fs";import{join as bo}from"path";function eg(){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 AA(r){return r.trim().toLowerCase().replace(/\.[a-z0-9]{1,4}$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function TA(r){let e=AbortSignal.timeout(xA);for(let[t,n]of EA){let s=Ge(t,n);if(typeof s!="string"){try{let i=await gt(s,{messages:[{role:"user",content:`Reply with ONLY a short kebab-case filename (2-5 words, lowercase, no extension) describing this text:
|
|
1222
|
+
|
|
1223
|
+
${r.slice(0,kA)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=AA(await Ut(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function tg(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=bo(r,go);try{wA(t,{recursive:!0})}catch(a){return{ok:!1,error:K(a)}}let n,s,i;if(e.kind==="image"){if(n=`img-${eg()}`,s=Object.keys(yo).find(a=>yo[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else n=await TA(e.data)??`paste-${eg()}`,s="md",i=e.data;let o=`${n}.${s}`;for(let a=2;bA(bo(t,o));a++)o=`${n}-${a}.${s}`;try{vA(bo(t,o),i)}catch(a){return{ok:!1,error:K(a)}}return{ok:!0,path:`${go}/${o}`}}function rg(r,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),n=yo[t];if(!n)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:n,base64:SA(bo(r,go,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var xA,kA,EA,ng=S(()=>{xr();Nr();xt();Zh();xA=4e3,kA=4e3,EA=[["openrouter","google/gemini-3.1-flash-lite-preview"],["gemini","gemini-3.1-flash-lite"]]});import{existsSync as sg,openSync as PA,readSync as OA,closeSync as _A,statSync as Lr,readdirSync as ig,watchFile as CA,unwatchFile as og,mkdirSync as RA,writeFileSync as NA,readFileSync as wo,unlinkSync as IA,rmSync as $A}from"fs";import{stat as LA}from"fs/promises";import{dirname as MA,join as zt,resolve as ag}from"path";function FA(r){if(!Number.isInteger(r))return!0;try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}function vo(r){let e={cwd:W,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:",K(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=>zt(h,BA),f=(h,w)=>zt(l(h),`${w}.lock`);function u(h,w){try{let v=f(h,w);if(Date.now()-Lr(v).mtimeMs>=cg)return!1;try{let _=parseInt(wo(v,"utf8").trim(),10);if(_===process.pid||!FA(_))return!1}catch{}return!0}catch{return!1}}function d(h,w){if(w)try{RA(l(h),{recursive:!0}),NA(f(h,w),String(process.pid))}catch(v){console.error("[lock] claim failed:",K(v))}}function p(h){try{$A(zt(h,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function b(h){let w=l(h);if(!sg(w))return;let v;try{v=ig(w)}catch{return}let _=Date.now();for(let D of v){if(!D.endsWith(".lock"))continue;let j=zt(w,D);try{let L=Lr(j);_-L.mtimeMs>jA&&IA(j)}catch{}}}function m(h){try{return Lr(h),!1}catch(w){return w.code==="ENOENT"}}function g(){let h=e;if(h.file&&!m(h.file)){d(h.cwd,h.sessionId);return}let w=k(h);w&&N(w)}function k(h){if(!h.everAttached)return A(h.cwd)??P(h.cwd,()=>!0)}function A(h){let w=l(h);if(!sg(w))return;let v;try{v=ig(w)}catch{return}let _;for(let j of v)if(j.endsWith(".lock"))try{let L=Lr(zt(w,j));if(Date.now()-L.mtimeMs>=cg||parseInt(wo(zt(w,j),"utf8").trim(),10)!==process.pid)continue;(!_||L.mtimeMs>_.mtime)&&(_={sessionId:j.slice(0,-5),mtime:L.mtimeMs})}catch{}if(!_)return;let D=r.listSessionFiles(h).find(j=>j.sessionId===_.sessionId);if(!(!D||m(D.file)))return D}function P(h,w){return r.listSessionFiles(h).sort((v,_)=>_.mtime-v.mtime).find(v=>!u(h,v.sessionId)&&w(v))}function R(h,w){let v=e;if(v.file)try{og(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,d(w.cwd,h.sessionId),$();try{og(h.file)}catch{}CA(h.file,{interval:200},()=>$())}function O(){R(void 0,"")}function $(){let h=e;if(!h.file)return;let w;try{w=Lr(h.file).size}catch{return}if(w<=h.offset)return;let v;try{v=PA(h.file,"r")}catch{return}try{let J=w-h.offset,de=Buffer.alloc(J),te=0;for(;te<J;){let $u=OA(v,de,te,J-te,h.offset+te);if(!$u)break;te+=$u}h.offset+=te,h.partial+=de.subarray(0,te).toString("utf8")}finally{_A(v)}let _,D;for(;(D=h.partial.indexOf(`
|
|
1224
|
+
`))>=0;){let J=h.partial.slice(0,D);if(h.partial=h.partial.slice(D+1),!J.trim())continue;let de=r.parseEntry(J);if(!de)continue;let te=r.idOf(de);te&&(h.entries.set(te,de),!r.isSidechain(de)&&r.isLeafType(de)&&(_=te))}if(!_)return;let j=[],L=h.entries.get(_),H=!1;for(;L;){if(j.push(L),r.idOf(L)===h.chainLastId){H=!0;break}let J=r.parentOf(L);L=J?h.entries.get(J):void 0}if(H)for(let J=j.length-2;J>=0;J--)I(j[J]);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 J=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,J)}h.chainLastId=_}function E(h){let w=new Map;for(let v of h.values()){let _=r.parentOf(v);if(!_)continue;let D=w.get(_);D?D.push(v):w.set(_,[v])}return w}function y(h,w,v){if(!h)return;let _=w.get(h);if(!_)return;let D=_.filter(J=>!r.isSidechain(J));if(D.length<2)return;let j=D.filter(J=>!v.has(r.idOf(J)));if(!j.length)return;let L=[],H=0;for(let J of j){let de=x(J,w);L.push(...de.events),H+=de.count}H>0&&e.buffer.push({type:"fork",atId:h,count:H,events:L})}function x(h,w){let v=[],_=[h];for(;_.length;){let L=_.pop();if(r.isSidechain(L))continue;v.push(L);let H=w.get(r.idOf(L)??"");if(H)for(let J of H)_.push(J)}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:_,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(),_&&(e.latestModel=_),v&&(e.latest=v),(v||D)&&e.buffer.push({type:"usage",...e.latest,cost:D})}catch(w){console.error("[mirror] skipped malformed entry:",K(w))}}async function C(){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 $r();if(!h)return;let w=ag(h).toLowerCase();for(let v=ag(e.cwd);v.toLowerCase()!==w;){let _=MA(v);if(_===v)return;v=_;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 Y=new fo;async function U(h,w){Y.accept(h,w)&&console.log(w)}function we(){let h=r.sessionAlive(e.sessionId,e.cwd);if(h!==void 0)return h;if(!e.file)return!1;try{return Date.now()-Lr(e.file).mtimeMs<1e4}catch{return!1}}function z(){return r.chainWorking([...e.entries.values()])&&we()}function V(){!r.createDriver||s()||e.latestModel||z()||i(e.file)}async function Ue(h){let w=e;g(),c(),V(),a();let v=s();for(let L of t)L!==v&&L.d.dialog;let _=new Set([...t].filter(L=>L.d.streaming&&L.file).map(L=>L.file)),D=_.size?r.listSessionFiles(w.cwd).filter(L=>_.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 ve(){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 sb(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 _=await ve();return _.ok?_.d.send(v,w):_}async function ib(h,w){let v=s();return v?v.d.respondUi(String(h??""),w??{}):{ok:!1,error:"no dialog pending"}}async function ob(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 _=await ve();return _.ok?_.d.rpc(h):_}let v=s();return!v||v.d.error?{ok:!1,error:"not running"}:v.d.rpc(h)}async function ab(){let h=s();if(h)try{await h.d.stop()}catch(w){console.error("[composer] stop:",K(w))}return{ok:!0}}async function cb(){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 lb(){if(!r.createDriver)return[];let h=await Fe(["ls-files","--cached","--others","--exclude-standard"],e.cwd).catch(()=>null),w=h!==null?h.split(`
|
|
1225
|
+
`).filter(Boolean):await r.walkFiles?.(e.cwd)??[];return(await Promise.all(w.map(async _=>{try{return{f:_,m:(await LA(zt(e.cwd,_))).mtimeMs}}catch{return{f:_,m:0}}}))).sort((_,D)=>D.m-_.m).map(_=>_.f)}function ub(){for(let h of[...t])o(h)}async function db(h){return r.createDriver?tg(e.cwd,h):{ok:!1,error:"not supported"}}async function fb(h){return rg(e.cwd,String(h??""))}async function pb(){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 Ru=new Map;function mb(h,w){let v=Ru.get(h);if(v&&v.mtime===w)return v.turns;let _=[],D="";try{D=wo(h,"utf8")}catch{return[]}for(let j of D.split(`
|
|
1226
|
+
`)){if(!j.trim())continue;let L=r.parseEntry(j);if(!L)continue;let H=r.searchText(L);H&&_.push({text:H,lower:H.toLowerCase()})}return Ru.set(h,{mtime:w,turns:_}),_}async function hb(h){let w=h.toLowerCase(),v=[];for(let{sessionId:_,file:D,mtime:j}of r.listSessionFiles(e.cwd).sort((L,H)=>H.mtime-L.mtime)){let{hitCount:L,snippet:H}=ho(mb(D,j),w);if(L&&(v.push({sessionId:_,mtime:j,preview:r.readPreview(D),hitCount:L,snippet:H}),v.length>=qA))break}return v}let Nu=800,Iu=new Map;function gb(h,w){let v=Iu.get(h);if(v&&v.mtime===w)return v.text;let _="";try{_=wo(h,"utf8")}catch{return""}let D="";for(let L of _.split(`
|
|
1227
|
+
`)){if(!L.trim())continue;let H=r.parseEntry(L);if(H)for(let J of r.apply(H,e.sessionStartMs).events)J.type==="assistant"&&J.text.trim()&&(D=J.text.trim())}let j=D.length>Nu?D.slice(0,Nu).trimEnd()+"\u2026":D;return Iu.set(h,{mtime:w,text:j}),j}async function yb(h){let w=r.listSessionFiles(e.cwd).find(v=>v.sessionId===h);return{text:w?gb(w.file,w.mtime):""}}async function bb(h){let w=e,v=r.listSessionFiles(w.cwd).find(_=>_.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:C,poll:Ue,logEmbedStatus:U,listSessions:pb,searchSessions:hb,sessionPeek:yb,attach:bb,composerSend:sb,composerStop:ab,composerNew:cb,composerFiles:lb,composerUiRespond:ib,composerRpc:ob,composerPaste:db,composerPasteRead:fb,shutdownComposer:ub}}var DA,BA,cg,jA,qA,Ql=S(()=>{xt();Vh();mo();Xl();ng();DA=".typebulb",BA=`${DA}/locks`,cg=5e3,jA=6e4;qA=50});import{existsSync as ru,mkdirSync as UA,readFileSync as lg,writeFileSync as JA}from"fs";import{join as Xt,isAbsolute as KA}from"path";async function ug(r,e){let t=KA(r)?r:Xt(W,r);return ru(t)?(Jl(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function dg(r){let e=W,t=Ul(r),n=Xt(e,"typebulbs");UA(n,{recursive:!0});let s=jl(t),i=`${s}.bulb.md`;for(let l=2;ru(Xt(n,i))&&lg(Xt(n,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=Xt(n,i);ru(o)||JA(o,t);let a=Xt("typebulbs",i),c=await Xi(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function fg(){return Q(W)}async function pg(r){return await Wt(r),{ok:!0}}async function mg(){return Zi(W).filter(r=>!r.serverOnly).map(r=>({...r,trusted:Ht(r.path)}))}async function hg(r){let e=r.toLowerCase(),t=[];for(let n of Zi(W).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=lg(n.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
|
|
1228
|
+
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=ho(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function gg(r,e){let t=W;e!=null&&Tr(r,e);let n=await Xi(r,{cwd:t,open:!1,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function yg(r){return{cap:await ql(r)}}async function bg(r,e){return Tr(r,e),{ok:!0}}async function wg(r,e){return $e(r,e)}async function kg(){return Gn&&Date.now()-Gn.fetchedAt<=WA?Gn.samples:(Zl??=YA().finally(()=>{Zl=null}),Zl)}async function YA(){try{let r=await fetch(`${HA}/api/scripts/u/samples?stubs`,{signal:AbortSignal.timeout(Sg)});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:ra(i.config)}));return Gn={samples:s,fetchedAt:Date.now()},s}catch{return Gn?.samples??[]}}async function Eg(r){return nu.test(r)?Pg(vg,"samples",r,!0):{ok:!1,error:"bad slug"}}async function Ag(){let r=su();if(!r)return{bulbs:[]};let e=`${So()}
|
|
1229
|
+
${r}`;return kt?.key===e&&Date.now()-kt.fetchedAt<=VA?{user:kt.user,bulbs:kt.bulbs}:(eu??=GA(e,r).finally(()=>{eu=null}),eu)}async function tu(r,e,t){let n=await fetch(`${r}${e}`,{headers:t,signal:AbortSignal.timeout(Sg)});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 GA(r,e){let t={Authorization:`Bearer ${e}`};try{let n=So(),s;try{s=await tu(n,"/api/me",t)}catch{let a=new URL(n);n=`${a.protocol}//api.${a.host}`,s=await tu(n,"/api/me",t)}let o=(await tu(n,"/api/scripts/list",t)).filter(a=>a.userSlug===s.slug&&!a.isTemplate).map(a=>({slug:a.slug,name:a.name,description:ra(a.config)}));return kt={key:r,user:s.slug,bulbs:o,fetchedAt:Date.now()},{user:s.slug,bulbs:o}}catch{return kt?.key===r?{user:kt.user,bulbs:kt.bulbs}:{bulbs:[]}}}async function Tg(r,e,t=!1){return!nu.test(e)||!nu.test(r)?{ok:!1,error:"bad slug"}:Pg(So(),r,e,t)}async function Pg(r,e,t,n){let s=no(e,t);try{let i=await io({origin:r,userSlug:e,slug:t,dest:Xt(W,s)},{force:n,token:su(),timeoutMs:xg});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 Og(r,e=!1){let t=su();if(!t)return{ok:!1,error:"no TYPEBULB_TOKEN in .env"};try{let n=so(r,W,So()),s=await oo(n,{token:t,force:e,timeoutMs:xg});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 HA,vg,WA,Sg,xg,Gn,Zl,nu,VA,kt,eu,So,su,iu=S(()=>{Nr();xt();Xl();Ne();HA="https://api.typebulb.com",vg="https://typebulb.com",WA=3600*1e3,Sg=5e3,xg=15e3,Gn=null,Zl=null;nu=/^[a-z0-9][a-z0-9-]*$/,VA=300*1e3,kt=null,eu=null,So=()=>ro("TYPEBULB_ORIGIN",W)||vg,su=()=>ro("TYPEBULB_TOKEN",W)});import{readFileSync as cu,writeFileSync as Cg,mkdirSync as zA,appendFileSync as Rg,rmSync as _g}from"fs";import{join as Eo,dirname as XA}from"path";import{createServer as QA}from"http";function Et(r){try{return JSON.parse(cu(r,"utf8"))}catch{return null}}function ko(r,e){zA(XA(r),{recursive:!0}),Cg(r,JSON.stringify(e,null,2)+`
|
|
1230
|
+
`)}function Ig(r,e,t){let n=Eo(r,".gitignore"),s="";try{s=cu(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(`
|
|
1231
|
+
`)?`
|
|
1232
|
+
`:"";try{Rg(n,a+t+`
|
|
1233
|
+
`+o.join(`
|
|
1234
|
+
`)+`
|
|
1235
|
+
`)}catch(c){console.error("[switcher] .gitignore update failed",K(c))}}function nT(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?Qn="live":s>rT&&(Qn="uncached")}function Lg(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 sT(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 Mg(r){let e;try{e=JSON.parse(r)}catch{return r}Xn=typeof e?.model=="string"?e.model:null,qe&&(e.model=qe),Zt&&(e.provider=$g(Zt));let t=/haiku/i.test(Xn||"");return Zn!=null&&!t&&(e.reasoning={effort:ou[Zn]}),delete e.thinking,e.output_config&&delete e.output_config.effort,sT(e),JSON.stringify(e)}function iT(){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}
|
|
1236
|
+
data: ${JSON.stringify(a)}
|
|
1197
1237
|
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
inferCfg = info.inference || {};
|
|
1201
|
-
if (inferCfg.title) title.textContent = inferCfg.title;
|
|
1238
|
+
`}case"content_block_delta":case"content_block_stop":{let c=t.get(a.index);return c==null?null:(a.index=c,`event: ${a.type}
|
|
1239
|
+
data: ${JSON.stringify(a)}
|
|
1202
1240
|
|
|
1203
|
-
|
|
1204
|
-
var runBtn = el('button', 'run', inferCfg.submitTitle || 'Run');
|
|
1205
|
-
if (info.error) { model.textContent = info.error; model.className = 'model err'; runBtn.disabled = true; }
|
|
1206
|
-
else if (info.model) model.textContent = info.model + ' \\u00b7 ' + info.provider;
|
|
1207
|
-
else model.textContent = 'Model info unavailable';
|
|
1241
|
+
`)}default:return i}};return i=>{r+=i;let o="",a;for(;(a=r.indexOf(`
|
|
1208
1242
|
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
var counts = [];
|
|
1216
|
-
var strip = multi ? el('div', 'tabs') : null;
|
|
1217
|
-
if (strip) body.appendChild(strip);
|
|
1218
|
-
function formatCount(n) { return n < 10000 ? String(n) : Math.round(n / 1000) + 'K'; }
|
|
1219
|
-
function selectTab(i) {
|
|
1220
|
-
tabBtns.forEach(function (b, j) { b.className = j === i ? 'tab on' : 'tab'; });
|
|
1221
|
-
areas.forEach(function (a, j) { a.style.display = j === i ? '' : 'none'; });
|
|
1222
|
-
}
|
|
1223
|
-
chunks.forEach(function (chunk, i) {
|
|
1224
|
-
if (multi) {
|
|
1225
|
-
var tab = el('button', 'tab');
|
|
1226
|
-
tab.appendChild(el('span', '', chunkLabel(chunk, i, titles)));
|
|
1227
|
-
var cnt = el('span', 'cnt', '(' + formatCount(chunk.length) + ')');
|
|
1228
|
-
counts.push(cnt);
|
|
1229
|
-
tab.appendChild(cnt);
|
|
1230
|
-
tab.addEventListener('click', function () { selectTab(i); });
|
|
1231
|
-
tabBtns.push(tab);
|
|
1232
|
-
strip.appendChild(tab);
|
|
1233
|
-
} else {
|
|
1234
|
-
body.appendChild(el('label', '', titles[0] || 'Data to process'));
|
|
1235
|
-
}
|
|
1236
|
-
var ta = document.createElement('textarea');
|
|
1237
|
-
ta.value = chunk;
|
|
1238
|
-
if (!chunk) ta.placeholder = 'Paste data to process (optional)\\u2026';
|
|
1239
|
-
ta.addEventListener('input', function () {
|
|
1240
|
-
// 2 blank lines IS the chunk separator \u2014 collapse pasted 3+ so text can't silently split (.com parity)
|
|
1241
|
-
var v = ta.value.replace(/\\n{3,}/g, '\\n\\n');
|
|
1242
|
-
if (v !== ta.value) ta.value = v;
|
|
1243
|
-
if (multi) counts[i].textContent = '(' + formatCount(ta.value.length) + ')';
|
|
1244
|
-
});
|
|
1245
|
-
areas.push(ta);
|
|
1246
|
-
body.appendChild(ta);
|
|
1247
|
-
});
|
|
1248
|
-
if (multi) selectTab(0);
|
|
1249
|
-
// The model line reads as a footnote to the action, not a header to the data \u2014 under the
|
|
1250
|
-
// textareas, above the buttons.
|
|
1251
|
-
body.appendChild(model);
|
|
1243
|
+
`))!==-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 oT(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 zn(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 aT(r,e,t){if(!qe){zn(e,400,"invalid_request_error",tT);return}let n=process.env.OPENROUTER_API_KEY;if(!n){zn(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(lu,{method:"POST",headers:Lg(r,n),body:Mg(t),signal:s.signal})}catch(u){zn(e,502,"api_error",`proxy upstream failed: ${K(u)}`);return}let o=i.headers.get("content-type")||"application/json";if(e.writeHead(i.status,{"content-type":o}),!i.body){e.end();return}let a=o.includes("event-stream"),c=i.body.getReader(),l=new TextDecoder,f=a?iT():null;try{for(;;){let{done:u,value:d}=await c.read();if(u)break;if(d)if(f){let p=l.decode(d,{stream:!0});nT(p);let b=f(p);b&&e.write(b)}else e.write(Buffer.from(d))}}catch{}finally{e.writableEnded||e.end()}}async function cT(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(!qe||!n)return s();try{let i=await fetch(`${lu}/count_tokens`,{method:"POST",headers:Lg(r,n),body:Mg(t)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function lT(r,e){let t=r.url||"/";if(r.method==="HEAD"){e.writeHead(200),e.end();return}if(r.method!=="POST"){zn(e,404,"not_found_error",t);return}oT(r).then(n=>{if(t.includes("count_tokens"))return cT(r,e,n);if(t.includes("/v1/messages"))return aT(r,e,n);zn(e,404,"not_found_error",t)})}function uT(){return Mr&&Qt?Promise.resolve(Qt):new Promise((r,e)=>{let t=QA(lT);t.on("error",e),t.listen(0,"127.0.0.1",()=>{Mr=t,Qt=t.address().port,console.log(`[switcher] wire proxy listening on ${xo(Qt)}`),r(Qt)})})}function dT(){try{Mr?.close()}catch{}Mr=null,Qt=null}function fT(r,e){let t=Ao(r),n=Et(t),s=n||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===xo(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=To(r);if(!Et(i)){let a={};for(let c of Ng)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=xo(e),s.env.ANTHROPIC_AUTH_TOKEN=eT,ko(t,s),Ig(r,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function pT(r,e,t){let n=To(r),s=Et(n)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:t},ko(n,s)}function Dg(r){let e=Ao(r),t=To(r),n=Et(t),s=Et(e);if(s?.env){let i=n?.snapshot||{};for(let o of Ng){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{_g(e,{force:!0})}catch{}else ko(e,s)}try{_g(t,{force:!0})}catch{}}async function mT(){let r=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await Ve()).filter(n=>n.provider==="openrouter"&&!uu(n.name)).map(n=>({id:n.name,label:n.friendlyName||n.name}))}catch(n){console.error("[switcher] model list failed",K(n))}let t=e.length?void 0:gl()??void 0;return{hasKey:r,models:e,error:t}}async function hT(){if(Mr&&qe)return{active:!0,managed:!0,model:qe,port:Qt,provider:Zt,routedModel:Xn,caching:Qn,reasoning:Zn,externalBaseUrl:null};let r=Et(Ao(W))?.env||{};return{active:!1,managed:!1,model:null,port:null,provider:null,routedModel:null,caching:"unknown",reasoning:Zn,externalBaseUrl:r.ANTHROPIC_BASE_URL||null}}async function Bg(r,e){let t=await uT();return qe=r,Zt=e,fT(W,t),t}async function gT({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(uu(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 Bg(r,du[r]??null),Xn=null,Qn="unknown",pT(W,r,Zt)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${K(e)}`}}return{ok:!0}}async function yT({level:r}){return r!=null&&(!Number.isInteger(r)||r<0||r>=ou.length)?{ok:!1,error:`reasoning level must be 0\u2013${ou.length-1} or null`}:(Zn=r,{ok:!0,level:r})}async function bT(){return Dg(W),qe=null,Zt=null,Xn=null,Qn="unknown",{ok:!0}}async function wT({key:r}){let e=(r||"").trim();if(!e)return{ok:!1,error:"empty key"};let t=W,n=Eo(t,".env"),s="";try{s=cu(n,"utf8")}catch{}try{if(/^\s*OPENROUTER_API_KEY\s*=/m.test(s))Cg(n,s.replace(/^\s*OPENROUTER_API_KEY\s*=.*$/m,`OPENROUTER_API_KEY=${e}`));else{let i=s&&!s.endsWith(`
|
|
1244
|
+
`)?`
|
|
1245
|
+
`:"";Rg(n,i+`OPENROUTER_API_KEY=${e}
|
|
1246
|
+
`)}}catch(i){return{ok:!1,error:K(i)}}return process.env.OPENROUTER_API_KEY=e,Ig(t,[".env"],"# secrets"),{ok:!0}}function vT(){if(!(!Mr&&!qe)){try{Dg(W)}catch{}dT()}}function ST(r,e){return jg.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 xT(r){if(jg.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 kT(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=au(e?.cache_read_input_tokens)||au(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 ET({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(uu(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:$g(a)}:i),u=await fetch(lu,{method:"POST",signal:c.signal,headers:s,body:f}),d=await u.json().catch(()=>({}));return{r:u,j:d}}finally{clearTimeout(l)}};try{let{r:a,j:c}=await o();if(!a.ok){let k=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:ST(a.status,k),restriction:xT(k)}}let l=typeof c?.provider=="string"?c.provider:void 0,f=c?.content?.find?.(k=>k.type==="text")?.text??c?.content?.[0]?.text??"ok",u=au(c?.usage?.cache_creation_input_tokens),{r:d,j:p}=await o(l),{works:b,read:m,note:g}=kT(d.ok,p?.usage,l);return b===!0&&l&&(du[r]=l,qe===r&&(Zt=l)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-t,provider:l,sample:String(f).trim().slice(0,60),cache:{works:b,created:u,read:m,note:g}}}catch(a){let c=K(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(c)?"timed out (20s)":c}}}var ZA,lu,eT,tT,Ng,rT,ou,Ao,To,xo,uu,Mr,Qt,qe,Zt,Xn,Qn,Zn,du,au,$g,jg,Fg=S(()=>{Nr();xt();ZA="https://openrouter.ai/api",lu=`${ZA}/v1/messages`,eT="typebulb-proxy-managed",tT="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.",Ng=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],rT=5e3,ou=["low","medium","high"],Ao=r=>Eo(r,".claude","settings.local.json"),To=r=>Eo(r,".claude",".cc-switcher.json"),xo=r=>`http://127.0.0.1:${r}`;uu=r=>/^anthropic\//i.test(r)||/claude/i.test(r),Mr=null,Qt=null,qe=null,Zt=null,Xn=null,Qn="unknown",Zn=1,du={},au=r=>typeof r=="number"?r:0,$g=r=>({order:[r],allow_fallbacks:!1});jg=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=Et(To(W)),t=e?.active?.model;if(!t)return;let s=(Et(Ao(W))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await Bg(t,e.active.provider??du[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${xo(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",K(e))}})()});var Ug={};Lu(Ug,{attach:()=>NT,blockToMarkdown:()=>Wi,breakout:()=>dg,capText:()=>Ie,cleanUserText:()=>wt,clearSwitchModel:()=>bT,composerPasteRead:()=>IT,displayName:()=>AT,downloadSample:()=>Eg,firstLineDigest:()=>Qe,git:()=>Fe,gitChangedFiles:()=>Xh,gitDiff:()=>Qh,info:()=>TT,isHiddenTurn:()=>Un,launchBulb:()=>gg,listBreakouts:()=>fg,listBulbFiles:()=>mg,listMyBulbs:()=>Ag,listSamples:()=>kg,listSessions:()=>_T,listSwitchModels:()=>mT,logEmbedStatus:()=>OT,openFile:()=>ug,poll:()=>PT,predictTrustOf:()=>yg,probeModel:()=>ET,pullRemoteBulb:()=>Tg,pushLocalBulb:()=>Og,readBulbLog:()=>wg,repoRoot:()=>$r,saveOpenRouterKey:()=>wT,searchBulbs:()=>hg,searchSessions:()=>CT,sessionPeek:()=>RT,setBulbTrust:()=>bg,setReasoning:()=>yT,setSwitchModel:()=>gT,shutdownSwitcher:()=>vT,stopBreakout:()=>pg,switchState:()=>hT,toolResultDigest:()=>_l});var qg,AT,TT,PT,OT,_T,CT,RT,NT,IT,Jg=S(()=>{Ql();Yi();iu();mo();Fg();Yi();Ki();qg=new Or,AT=qg.displayName,{info:TT,poll:PT,logEmbedStatus:OT,listSessions:_T,searchSessions:CT,sessionPeek:RT,attach:NT,composerPasteRead:IT}=vo(qg)});import{readFileSync as $T,writeFileSync as LT,mkdirSync as MT}from"fs";import{homedir as DT}from"os";import*as Po from"path";async function Wg(){try{let r=await fetch(new URL("/api/tags",Hg()).toString(),{signal:AbortSignal.timeout(BT)});return r.ok?((await r.json()).models??[]).map(t=>t.name).filter(t=>!!t):[]}catch{return[]}}function Yg(r){let e;try{e=$T(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&&!fu(n)}}}catch{}return{json:void 0,unreadable:!0}}function fu(r){let e=r?.providers;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function jT(r){let e=fu(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 Vg(){let{json:r,unreadable:e}=Yg(Kg());return e?{installed:[],configured:null}:{installed:await Wg(),configured:jT(r)}}async function Gg(){let r=await Wg();return r.length?FT(Kg(),r,Hg()):{ok:!1,error:"Ollama is not running (or has no models installed)"}}function FT(r,e,t){let{json:n,unreadable:s}=Yg(r);if(s)return{ok:!1,error:`could not parse ${r} \u2014 edit the ollama provider there yourself`};let i={...n??{},providers:{...fu(n)??{},ollama:{baseUrl:`${t}/v1`,api:"openai-completions",apiKey:"ollama",models:e.map(o=>({id:o}))}}};try{MT(Po.dirname(r),{recursive:!0}),LT(r,JSON.stringify(i,null,2)+`
|
|
1247
|
+
`)}catch(o){return{ok:!1,error:`could not write ${r}: ${K(o)}`}}return{ok:!0,count:e.length}}var BT,Kg,Hg,zg=S(()=>{xt();Nr();BT=1500,Kg=()=>Po.join(DT(),".pi","agent","models.json"),Hg=()=>Er(process.env.OLLAMA_HOST??"http://localhost:11434")});var Qg={};Lu(Qg,{attach:()=>VT,breakout:()=>dg,composerFiles:()=>QT,composerNew:()=>XT,composerPaste:()=>tP,composerPasteRead:()=>rP,composerRpc:()=>eP,composerSend:()=>GT,composerStop:()=>zT,composerUiRespond:()=>ZT,displayName:()=>qT,downloadSample:()=>Eg,git:()=>Fe,gitChangedFiles:()=>Xh,gitDiff:()=>Qh,info:()=>UT,launchBulb:()=>gg,listBreakouts:()=>fg,listBulbFiles:()=>mg,listMyBulbs:()=>Ag,listSamples:()=>kg,listSessions:()=>HT,logEmbedStatus:()=>KT,ollamaOffer:()=>Vg,ollamaSync:()=>Gg,openFile:()=>ug,poll:()=>JT,predictTrustOf:()=>yg,pullRemoteBulb:()=>Tg,pushLocalBulb:()=>Og,readBulbLog:()=>wg,repoRoot:()=>$r,searchBulbs:()=>hg,searchSessions:()=>WT,sessionPeek:()=>YT,setBulbTrust:()=>bg,shutdownComposer:()=>nP,stopBreakout:()=>pg});var Xg,qT,UT,JT,KT,HT,WT,YT,VT,GT,zT,XT,QT,ZT,eP,tP,rP,nP,Zg=S(()=>{Ql();Gl();iu();mo();zg();Xg=new Ir,qT=Xg.displayName,{info:UT,poll:JT,logEmbedStatus:KT,listSessions:HT,searchSessions:WT,sessionPeek:YT,attach:VT,composerSend:GT,composerStop:zT,composerNew:XT,composerFiles:QT,composerUiRespond:ZT,composerRpc:eP,composerPaste:tP,composerPasteRead:rP,shutdownComposer:nP}=vo(Xg)});import*as nb from"fs/promises";import*as er from"path";us();import*as Ku from"path";var Go=5e3;function Hu(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||Ku.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=Go;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=qu(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(`
|
|
1248
|
+
typebulb - Local bulb runner for Typebulb
|
|
1252
1249
|
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1250
|
+
Usage:
|
|
1251
|
+
typebulb [file.bulb.md] Run a bulb (defaults to .bulb.md in cwd)
|
|
1252
|
+
typebulb agent An agent's first command \u2014 auto-detects the calling
|
|
1253
|
+
harness, brings up the agent mirror without opening a
|
|
1254
|
+
browser, prints its URL and the authoring-skill paths.
|
|
1255
|
+
Always exits 0 (a status report).
|
|
1256
|
+
typebulb agent:{claude|pi} Open a named harness's mirror in the foreground (a browser
|
|
1257
|
+
view of your coding agent's sessions) \u2014 explicit / override.
|
|
1258
|
+
typebulb skill Print this README as an Agent Skill (stdout), for the
|
|
1259
|
+
agent to read and copy into its own skills folder.
|
|
1260
|
+
typebulb call <file> <fn> [\u2026] Invoke one server.ts export headlessly: prints
|
|
1261
|
+
its return as JSON to stdout, logs/errors to
|
|
1262
|
+
stderr. Gated by trust like --server. Args after
|
|
1263
|
+
<fn> are JSON-or-string; --args '<json-array>'
|
|
1264
|
+
(or --args - for stdin) is the escape hatch.
|
|
1265
|
+
typebulb check [file.bulb.md] Type-check a bulb without running it
|
|
1266
|
+
typebulb predict [file] Report the capability a bulb probably needs
|
|
1267
|
+
(fs / AI / server.ts) without running it.
|
|
1268
|
+
typebulb models List AI models for tb.ai, filtered by the API
|
|
1269
|
+
keys in your .env (the exact ids to pass).
|
|
1270
|
+
typebulb logs [file|agent] Print a running bulb server's (or the 'agent' mirror's) console
|
|
1271
|
+
(no arg: list this project's running servers;
|
|
1272
|
+
--run latest|N shows just one hot-reload run;
|
|
1273
|
+
--clear empties it). For agents: fetch
|
|
1274
|
+
tb.server.log / errors of a bulb you launched
|
|
1275
|
+
without watching its terminal.
|
|
1276
|
+
typebulb send <file> [msg] Push a message into a running bulb's page \u2014
|
|
1277
|
+
its tb.onMessage(cb) handlers receive it. The
|
|
1278
|
+
client-side twin of 'call'; msg is JSON-or-
|
|
1279
|
+
string, omit it for a bare trigger. No --trust.
|
|
1280
|
+
With --wait, a handler's non-undefined return
|
|
1281
|
+
prints on stdout (JSON; a bare string raw).
|
|
1282
|
+
msg 'tb:snapshot' instead prints the page's
|
|
1283
|
+
rendered outline (roles, names, visible text).
|
|
1284
|
+
typebulb pull <url|file> Fetch a bulb from typebulb.com into
|
|
1285
|
+
typebulbs/u/<user>/<slug>.bulb.md (a local file
|
|
1286
|
+
at that path re-pulls in place). Unlisted and
|
|
1287
|
+
public bulbs need no login; a differing local
|
|
1288
|
+
file is refused unless --force.
|
|
1289
|
+
typebulb push <file> Upload a typebulbs/u/<user>/<slug>.bulb.md to
|
|
1290
|
+
typebulb.com as you (needs TYPEBULB_TOKEN in
|
|
1291
|
+
.env, minted on the settings page). Refused if
|
|
1292
|
+
the remote changed since your last pull/push,
|
|
1293
|
+
unless --force. A new slug is created unlisted.
|
|
1294
|
+
typebulb wait [file|agent] Block until the target server logs a new line,
|
|
1295
|
+
print it, exit (2: timeout; 3: server died).
|
|
1296
|
+
For agents: run it in the background \u2014 the exit
|
|
1297
|
+
is your wake-up ('wait agent': embed outcomes;
|
|
1298
|
+
'wait <file>': the bulb's own console.log).
|
|
1299
|
+
Resumes where your last wait/call left off, so
|
|
1300
|
+
an event that beats the wait still fires it.
|
|
1301
|
+
typebulb stop [file|pid|agent] Stop a running bulb or mirror (no arg: list this
|
|
1302
|
+
project's running servers; a pid/path/agent stops any).
|
|
1303
|
+
Batch flags: --bulbs (this project's bulbs, the
|
|
1304
|
+
mirror survives), --agent (this project's mirror),
|
|
1305
|
+
--global (every bulb + mirror, all projects).
|
|
1306
|
+
typebulb trust [file] Remember a bulb as Trusted, so a later run grants
|
|
1307
|
+
fs/AI/server.ts without --trust (no arg: list the
|
|
1308
|
+
remembered-trusted bulbs).
|
|
1309
|
+
typebulb untrust <file> Forget a bulb's trust (back to Restricted).
|
|
1288
1310
|
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1311
|
+
Options:
|
|
1312
|
+
-f, --follow Stream new log output until interrupted (logs)
|
|
1313
|
+
--run <latest|N> Show only one hot-reload run's output: 'latest'
|
|
1314
|
+
(the current run) or run number N (logs)
|
|
1315
|
+
--clear Empty the target server's log instead of
|
|
1316
|
+
printing it, for a clean run (logs)
|
|
1317
|
+
-n, --lines <n> Print only the last n lines (logs)
|
|
1318
|
+
--match <substring> Only lines containing this literal substring end
|
|
1319
|
+
the wait \u2014 not a regex (wait)
|
|
1320
|
+
--force Overwrite the side the command writes to: a
|
|
1321
|
+
differing local file (pull), or a remote that
|
|
1322
|
+
changed since your last sync (push)
|
|
1323
|
+
--timeout <sec> Give up after this long; exit 2 \u2014 bounds only a
|
|
1324
|
+
manual (foreground) bulb wait, default 1800 (wait)
|
|
1325
|
+
--wait[=ms] For 'send': bound the whole exchange \u2014 retry while
|
|
1326
|
+
no page is connected (a hot reload's gap), then
|
|
1327
|
+
hold for the handlers' replies (default 5000).
|
|
1328
|
+
Use it right after an edit, and for any send
|
|
1329
|
+
whose reply you read.
|
|
1330
|
+
--no-watch Disable hot reload (watch is on by default)
|
|
1331
|
+
-p, --port <port> Use a specific port (default: 3000)
|
|
1332
|
+
--open Force-open the external browser (default off
|
|
1333
|
+
inside VS Code's integrated terminal)
|
|
1334
|
+
--no-open Don't auto-open browser
|
|
1335
|
+
--trust Grant privileged capabilities (filesystem, AI,
|
|
1336
|
+
and server.ts) for this run. Without it a bulb runs
|
|
1337
|
+
Restricted: tb.fs / tb.ai / tb.server are blocked and
|
|
1338
|
+
the page shows the exact --trust command to unlock
|
|
1339
|
+
them. A bulb remembered via 'typebulb trust' runs
|
|
1340
|
+
trusted without this flag.
|
|
1341
|
+
--no-trust Force a Restricted run even if the bulb is
|
|
1342
|
+
remembered-trusted (overrides the trust store).
|
|
1343
|
+
--mode <name> Also load .env.<name> (+ .env.<name>.local) on top
|
|
1344
|
+
of .env / .env.local. Free-form name; loads no mode
|
|
1345
|
+
file by default.
|
|
1346
|
+
--dir <sub> Scope the bulb's dir to a subfolder for this run:
|
|
1347
|
+
tb.dir and relative tb.fs paths land in
|
|
1348
|
+
<bulb-folder>/<sub>. Batch runs without touching
|
|
1349
|
+
the bulb's code (e.g. --dir batch2). Relative
|
|
1350
|
+
subpaths only \u2014 no absolute paths or '..'.
|
|
1351
|
+
--server Run server.ts only, no web server (needs --trust)
|
|
1352
|
+
--args <json-array> For 'call': the whole argument list as one JSON
|
|
1353
|
+
array (strict). '--args -' reads it from stdin,
|
|
1354
|
+
sidestepping shell quoting.
|
|
1355
|
+
--replace <name>=<path> Replace a declared dependency with a local built
|
|
1356
|
+
package folder instead of a CDN (dev only).
|
|
1357
|
+
Applies to both run and check. Watched for
|
|
1358
|
+
rebuilds under --watch; --no-watch freezes it.
|
|
1359
|
+
e.g. --replace tensorgrad=../tensorgrad
|
|
1360
|
+
-V, --version Show version number
|
|
1361
|
+
-h, --help Show this help message
|
|
1295
1362
|
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1363
|
+
Filesystem API:
|
|
1364
|
+
Bulbs can read and write local files via tb.fs:
|
|
1365
|
+
await tb.fs.read('file.txt') // UTF-8 text (throws on non-UTF-8)
|
|
1366
|
+
await tb.fs.readBytes('image.png') // raw bytes (Uint8Array)
|
|
1367
|
+
await tb.fs.write('output.html', content) // text or bytes
|
|
1301
1368
|
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
cancel.addEventListener('click', function () { close('cancel'); });
|
|
1309
|
-
foot.appendChild(cancel);
|
|
1369
|
+
Server API:
|
|
1370
|
+
Add a **server.ts** section to run Node.js code server-side.
|
|
1371
|
+
Exported functions become callable from the browser:
|
|
1372
|
+
// in **server.ts**: export async function query(sql) { ... }
|
|
1373
|
+
// in **code.tsx**: const rows = await tb.server.query(sql)
|
|
1374
|
+
.env / .env.local load from the working directory; --mode <name> adds .env.<name>.
|
|
1310
1375
|
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
var resp = await fetch('/__infer', {
|
|
1314
|
-
method: 'POST',
|
|
1315
|
-
headers: { 'Content-Type': 'application/json' },
|
|
1316
|
-
body: JSON.stringify({ data: data }),
|
|
1317
|
-
signal: aborter.signal
|
|
1318
|
-
});
|
|
1319
|
-
if (resp.headers.get('X-TB-Stream') !== '1') {
|
|
1320
|
-
// Non-stream response: a 403 trust denial (plain text) or a 400/500 JSON error.
|
|
1321
|
-
var text = await resp.text();
|
|
1322
|
-
var err; try { err = JSON.parse(text); } catch (e) { err = { message: text, code: 'unknown', retryable: false }; }
|
|
1323
|
-
var e2 = new Error(err.message || 'Inference failed'); e2.code = err.code; e2.retryable = !!err.retryable;
|
|
1324
|
-
throw e2;
|
|
1325
|
-
}
|
|
1326
|
-
var final = null;
|
|
1327
|
-
for await (var v of ctx.readStream(resp)) {
|
|
1328
|
-
if (v.kind === 'delta') {
|
|
1329
|
-
if (waiting) { waiting.remove(); waiting = null; textNode = document.createTextNode(''); pre.appendChild(textNode); }
|
|
1330
|
-
textNode.appendData(v.text); pre.scrollTop = pre.scrollHeight;
|
|
1331
|
-
}
|
|
1332
|
-
else if (v.kind === 'complete') final = v;
|
|
1333
|
-
}
|
|
1334
|
-
if (!final) { var e3 = new Error('Stream ended without a result'); e3.code = 'network'; e3.retryable = true; throw e3; }
|
|
1335
|
-
completed = true;
|
|
1336
|
-
ctx.onComplete(final);
|
|
1337
|
-
close('complete');
|
|
1338
|
-
})().catch(function (err) {
|
|
1339
|
-
if (canceled) return; // user canceled; close() already ran and the abort rejection is expected
|
|
1340
|
-
showError(err);
|
|
1341
|
-
});
|
|
1342
|
-
}
|
|
1376
|
+
Built-in server functions (available without a **server.ts** section):
|
|
1377
|
+
tb.server.log(...) Print to the CLI's stdout
|
|
1343
1378
|
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1379
|
+
AI API:
|
|
1380
|
+
Bulbs can call AI providers via tb.ai(). Set API keys in .env:
|
|
1381
|
+
ANTHROPIC_API_KEY=sk-ant-...
|
|
1382
|
+
OPENAI_API_KEY=sk-...
|
|
1383
|
+
GOOGLE_API_KEY=AIza...
|
|
1384
|
+
OPENROUTER_API_KEY=sk-or-...
|
|
1385
|
+
Set provider and model (required):
|
|
1386
|
+
TB_AI_PROVIDER=anthropic
|
|
1387
|
+
TB_AI_MODEL=claude-haiku-4-5-20251001
|
|
1388
|
+
Both can be overridden per-call: tb.ai({ provider: "openai", model: "gpt-5.4-mini", ... })
|
|
1389
|
+
Don't guess a model id \u2014 run 'typebulb models' to list the exact ids your keys cover.
|
|
1390
|
+
Optional effort level (1=low, 2=med, 3=high; omit for the model's native default):
|
|
1391
|
+
tb.ai({ ..., effort: 2 })
|
|
1348
1392
|
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1393
|
+
Examples:
|
|
1394
|
+
typebulb my-editor.bulb.md
|
|
1395
|
+
typebulb --no-watch --port 8080 my-editor.bulb.md
|
|
1396
|
+
typebulb .
|
|
1397
|
+
`)}bt();Sn();us();qn();Yi();Gl();var Oo={claude:{adapter:()=>new Or,server:()=>Promise.resolve().then(()=>(Jg(),Ug))},pi:{adapter:()=>new Ir,server:()=>Promise.resolve().then(()=>(Zg(),Qg))}};function ey(r){return r in Oo}function Dr(){return Object.keys(Oo)}function ty(){return Object.fromEntries(Object.entries(Oo).map(([r,e])=>[r,e.adapter]))}function ry(r){return Oo[r].server()}bt();import*as Tt from"path";import{spawn as OP,execSync as _P}from"child_process";import{createRequire as CP}from"module";import{existsSync as RP}from"fs";import*as ae from"fs/promises";import*as ie from"path";var pu=[{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"}],mu=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function hu(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 sP=`
|
|
1398
|
+
/**
|
|
1399
|
+
* Get raw data chunk from the Data tab.
|
|
1400
|
+
* @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
|
|
1401
|
+
*/
|
|
1402
|
+
data(index: number): string;
|
|
1403
|
+
/**
|
|
1404
|
+
* Get data chunk parsed as JSON (handles JSON-ish with unquoted keys).
|
|
1405
|
+
* @param index - Chunk index (0-based)
|
|
1406
|
+
* @throws If chunk is not valid JSON/JSON-ish
|
|
1407
|
+
*/
|
|
1408
|
+
json<T = unknown>(index: number): T;`,iP=`
|
|
1409
|
+
/**
|
|
1410
|
+
* Get the insight data produced by the inference layer.
|
|
1411
|
+
*
|
|
1412
|
+
* Returns the parsed JSON from insight.json, populated by the inference LLM.
|
|
1413
|
+
* Use a type parameter to get typed access to the insight data.
|
|
1414
|
+
*
|
|
1415
|
+
* @returns The parsed insight JSON, or undefined if no insight is available
|
|
1416
|
+
*/
|
|
1417
|
+
insight<T = unknown>(): T | undefined;`,ny=`options: {
|
|
1418
|
+
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
1419
|
+
system?: string;
|
|
1420
|
+
/** 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. */
|
|
1421
|
+
effort?: 0 | 1 | 2 | 3;
|
|
1422
|
+
provider?: string;
|
|
1423
|
+
model?: string;
|
|
1424
|
+
/** Enable/disable web search. Default: on for BYOK, always off for free model. */
|
|
1425
|
+
webSearch?: boolean;
|
|
1426
|
+
/** Abort the request. On abort the promise rejects / the stream ends. */
|
|
1427
|
+
signal?: AbortSignal;
|
|
1428
|
+
}`,sy=`
|
|
1429
|
+
/** A single streamed delta from \`tb.ai.stream()\`. Discriminated by \`kind\`. */
|
|
1430
|
+
type AiChunk =
|
|
1431
|
+
| { kind: "text"; text: string }
|
|
1432
|
+
| { kind: "reasoning"; text: string };
|
|
1433
|
+
`,iy=`
|
|
1434
|
+
/**
|
|
1435
|
+
* General-purpose AI call. \`tb.ai(opts)\` resolves with the full text; \`tb.ai.stream(opts)\`
|
|
1436
|
+
* returns an async iterable of {@link AiChunk} deltas you consume with \`for await\`.
|
|
1437
|
+
*
|
|
1438
|
+
* @returns Promise resolving to { text: string }
|
|
1439
|
+
* @throws On rate limit, network error, or provider error
|
|
1440
|
+
*/
|
|
1441
|
+
ai: {
|
|
1442
|
+
(${ny}): Promise<{ text: string }>;
|
|
1443
|
+
/**
|
|
1444
|
+
* Streaming counterpart of \`tb.ai()\`. Yields \`{ kind: "text" | "reasoning", text }\` deltas
|
|
1445
|
+
* as they arrive; break the loop (or abort \`signal\`) to cancel and stop the upstream.
|
|
1446
|
+
*
|
|
1447
|
+
* \`kind: "reasoning"\` deltas only arrive when you pass \`effort: 1-3\` AND use a
|
|
1448
|
+
* thinking-capable model; otherwise the stream is \`text\`-only.
|
|
1449
|
+
*
|
|
1450
|
+
* @example
|
|
1451
|
+
* let answer = "";
|
|
1452
|
+
* for await (const c of tb.ai.stream({ messages })) {
|
|
1453
|
+
* if (c.kind === "text") answer += c.text;
|
|
1454
|
+
* }
|
|
1455
|
+
*/
|
|
1456
|
+
stream(${ny}): AsyncIterable<AiChunk>;
|
|
1457
|
+
};`,oy=`
|
|
1458
|
+
/**
|
|
1459
|
+
* Returns AI models available to the current user.
|
|
1460
|
+
* Models are filtered by the user's configured API keys.
|
|
1461
|
+
* If no keys are configured, returns only the courtesy model.
|
|
1462
|
+
*/
|
|
1463
|
+
models(): Promise<Array<{
|
|
1464
|
+
/** Provider protocol: "anthropic", "openai", "gemini", "openrouter" */
|
|
1465
|
+
provider: string;
|
|
1466
|
+
/** Model identifier, e.g. "claude-sonnet-4-6" */
|
|
1467
|
+
name: string;
|
|
1468
|
+
/** Human-readable display name, e.g. "Sonnet 4.6" */
|
|
1469
|
+
friendlyName: string;
|
|
1470
|
+
/** Provider display name, e.g. "Anthropic" */
|
|
1471
|
+
providerName: string;
|
|
1472
|
+
/** True on the .env-configured default model (TB_AI_PROVIDER + TB_AI_MODEL); absent otherwise */
|
|
1473
|
+
default?: boolean;
|
|
1474
|
+
}>>;
|
|
1475
|
+
/**
|
|
1476
|
+
* Whether the user's own AI keys back \`tb.ai\`. False means only the
|
|
1477
|
+
* quota-limited courtesy model is available (or no AI at all) \u2014 a bulb
|
|
1478
|
+
* making many AI calls should check this and show a "use your own keys"
|
|
1479
|
+
* notice instead of running.
|
|
1480
|
+
*/
|
|
1481
|
+
hasOwnKeys(): Promise<boolean>;`,oP="\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;",ay=`
|
|
1482
|
+
/**
|
|
1483
|
+
* The mode this bulb is running in.
|
|
1484
|
+
*
|
|
1485
|
+
* - \`'local'\` \u2014 Running via the typebulb CLI
|
|
1486
|
+
* - \`'editor'\` \u2014 Running in the typebulb.com editor
|
|
1487
|
+
* - \`'published'\` \u2014 Running as a published/standalone bulb on typebulb.com
|
|
1488
|
+
* - \`'embedded'\` \u2014 Running as a bulb embedded inside another bulb (sandboxed,
|
|
1489
|
+
* client-only: AI, filesystem, and server RPC are unavailable)
|
|
1490
|
+
*/
|
|
1491
|
+
mode: 'local' | 'editor' | 'published' | 'embedded';`,cy=`
|
|
1492
|
+
/**
|
|
1493
|
+
* Local filesystem access (CLI only).
|
|
1494
|
+
*
|
|
1495
|
+
* Relative paths resolve against the bulb's folder (\`tb.dir\` \u2014
|
|
1496
|
+
* \`<bulb-dir>/<filename-stem>/\`, created on demand), so
|
|
1497
|
+
* \`tb.fs.write('results.json')\` lands beside the bulb. \`../\` reaches sibling
|
|
1498
|
+
* bulbs' folders; everything stays confined to the project (the launch cwd).
|
|
1499
|
+
* Throws in editor/published mode.
|
|
1500
|
+
*/
|
|
1501
|
+
fs: {
|
|
1502
|
+
/** Read a file as UTF-8 text. Throws if the file is not valid UTF-8 \u2014 use readBytes for binary. */
|
|
1503
|
+
read(path: string): Promise<string>;
|
|
1504
|
+
/** Read a file as raw bytes. */
|
|
1505
|
+
readBytes(path: string): Promise<Uint8Array>;
|
|
1506
|
+
/** Write text or raw bytes to a file. Creates parent directories if needed. */
|
|
1507
|
+
write(path: string, content: string | Uint8Array): Promise<boolean>;
|
|
1508
|
+
};`,ly=`
|
|
1509
|
+
/**
|
|
1510
|
+
* The bulb's folder \u2014 absolute path to \`<bulb-dir>/<filename-stem>/\`
|
|
1511
|
+
* (or its subfolder when the run is scoped with \`--dir\`).
|
|
1512
|
+
*
|
|
1513
|
+
* For interop only (handing a path to \`server.ts\` or a spawned tool):
|
|
1514
|
+
* \`tb.fs\` already resolves relative paths against it, so bulb code writing
|
|
1515
|
+
* its own files never needs it. CLI only \u2014 throws in editor/published/embedded mode.
|
|
1516
|
+
*/
|
|
1517
|
+
readonly dir: string;`,aP=`
|
|
1518
|
+
/**
|
|
1519
|
+
* Async value inspector for tensor-like objects.
|
|
1520
|
+
*
|
|
1521
|
+
* Materializes lazy values (like GPU tensors) and logs them with metadata.
|
|
1522
|
+
* Handles objects with \`.js()\`, \`.data()\`, \`.array()\`, \`.arraySync()\`, etc.
|
|
1523
|
+
*
|
|
1524
|
+
* @remarks
|
|
1525
|
+
* - Always use \`await\` - materialization may be async (GPU\u2192CPU readback)
|
|
1526
|
+
* - Large values are truncated (max 1000 elements)
|
|
1527
|
+
* - Promises are logged as \`[Promise]\` (not awaited - could hang)
|
|
1528
|
+
*/
|
|
1529
|
+
dump(...args: any[]): Promise<void>;
|
|
1530
|
+
/**
|
|
1531
|
+
* Trigger inference to generate new insight data.
|
|
1532
|
+
*
|
|
1533
|
+
* Opens a confirmation modal showing the data to be analyzed, then streams
|
|
1534
|
+
* the inference result. On success, updates the insight so subsequent
|
|
1535
|
+
* \`tb.insight()\` calls return the new value.
|
|
1536
|
+
*
|
|
1537
|
+
* @param opts - Options for inference
|
|
1538
|
+
* @param opts.data - Data to pre-populate in the modal (string or array of strings). If omitted, modal opens with empty textarea for user to paste.
|
|
1539
|
+
* @returns Promise that resolves with the parsed insight JSON
|
|
1540
|
+
* @throws If inference is already in progress, or on network/parse/rate limit errors
|
|
1541
|
+
*/
|
|
1542
|
+
infer<T = unknown>(opts?: { data?: string | string[] }): Promise<T>;
|
|
1543
|
+
/**
|
|
1544
|
+
* Get the current inference state.
|
|
1545
|
+
*
|
|
1546
|
+
* @returns 'idle' | 'running' | 'complete' | 'error'
|
|
1547
|
+
*/
|
|
1548
|
+
inferenceState(): 'idle' | 'running' | 'complete' | 'error';
|
|
1549
|
+
/**
|
|
1550
|
+
* Set a data chunk for the next inference call.
|
|
1551
|
+
*
|
|
1552
|
+
* Use this to programmatically set data that will be sent when \`tb.infer()\` is called
|
|
1553
|
+
* without the \`data\` option.
|
|
1554
|
+
*
|
|
1555
|
+
* @param index - The chunk index (0-based)
|
|
1556
|
+
* @param content - The content for this chunk
|
|
1557
|
+
*/
|
|
1558
|
+
setData(index: number, content: string): void;
|
|
1559
|
+
/**
|
|
1560
|
+
* Proxy a CDN URL through the sandbox origin for Web Worker/WASM same-origin loading.
|
|
1561
|
+
*
|
|
1562
|
+
* In the sandbox, prepends \`/proxy/\` so the URL is served from the same origin.
|
|
1563
|
+
* Outside the sandbox (exported HTML, CLI), returns the URL unchanged.
|
|
1564
|
+
*
|
|
1565
|
+
* @param url - Full HTTPS URL to an allowlisted CDN (esm.sh, unpkg.com, cdn.jsdelivr.net, cdnjs.cloudflare.com)
|
|
1566
|
+
* @returns The proxied URL (sandbox) or the original URL (standalone/CLI)
|
|
1567
|
+
*/
|
|
1568
|
+
proxy(url: string): string;
|
|
1569
|
+
/**
|
|
1570
|
+
* Copy text to clipboard.
|
|
1571
|
+
* Must be called synchronously within a user gesture (click/keydown).
|
|
1572
|
+
* @returns true if successful, false otherwise
|
|
1573
|
+
*/
|
|
1574
|
+
copy(text: string): Promise<boolean>;
|
|
1575
|
+
/**
|
|
1576
|
+
* Get the canonical URL of this bulb.
|
|
1577
|
+
*
|
|
1578
|
+
* Returns the parent typebulb.com URL (including path, query, and \`#tb=\` fragment),
|
|
1579
|
+
* resolving correctly from inside the cross-origin sandbox iframe.
|
|
1580
|
+
* Use this instead of \`location.href\` or \`document.referrer\`.
|
|
1581
|
+
*
|
|
1582
|
+
* @returns The full canonical URL
|
|
1583
|
+
*/
|
|
1584
|
+
url(): Promise<string>;`,cP="\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;",lP="\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>>;",gu=`${sy}
|
|
1585
|
+
/**
|
|
1586
|
+
* Typebulb utilities namespace.
|
|
1587
|
+
* Type \`tb.\` to discover available helpers.
|
|
1588
|
+
*/
|
|
1589
|
+
declare const tb: {${sP}${aP}${iP}${lP}${cP}${iy}${cy}${ly}${oy}${oP}${ay}
|
|
1590
|
+
};
|
|
1591
|
+
`,yu=`${sy}
|
|
1592
|
+
/**
|
|
1593
|
+
* Typebulb utilities namespace (server-side).
|
|
1594
|
+
* Type \`tb.\` to discover available helpers.
|
|
1595
|
+
*/
|
|
1596
|
+
declare const tb: {${iy}${cy}${ly}${oy}${ay}
|
|
1597
|
+
};
|
|
1598
|
+
`;He();import pP from"p-limit";He();import{resolve as dy}from"resolve.exports";var Ze={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},es=["index.d.ts","index.d.mts"],bu=/\.d\.(ts|mts|cts)$/i;function _o(r){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(r)||/[?&]dts(?:[&#]|$)/i.test(r)}function uy(r){return[`${r}.d.ts`,`${r}.d.mts`]}function At(r){if(!r||r==="./"||r==="/")return[...es];let e=r.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=uy(e),n=e.endsWith("/")?e:`${e}/`;return t.push(...uy(`${n}index`)),t}async function Br(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(uP(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function uP(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)||_o(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 Br(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=Dt(e.path);if(!o||o==="/"||o===".")return this.tryUntilSuccess([...es],t);if(!bu.test(o)){let a=await this.tryUntilSuccess(At(o),t);if(a)return a}return t(o)}let s=At(e.path),i=n?.subpath?[...s,...es]:[...es,...s];return this.tryUntilSuccess(i,t)}toResolutionResult(e){return{kind:bu.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(dy(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(dy(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=Kc(t.subpath),d=this.resolveExportsPath(n,u);if(d){let b=await this.resolveFromSelected(this.toResolutionResult(d),c,{subpath:!0});if(b)return{...b,resolvedPkg:a}}let p=await this.tryUntilSuccess(At(u),c);if(p)return{...p,resolvedPkg:a}}let l=n.types??n.typings;if(l){let u=await this.resolveFromSelected({kind:"types",path:l},c);if(u)return{...u,resolvedPkg:o}}let f=this.resolveExportsPath(n,".");if(f){let u=await this.resolveFromSelected(this.toResolutionResult(f),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=Dt(n),i=new URL(s,e).toString(),o=await this.tryUrls([i]);return o?{dts:o.dts,url:o.url,resolvedPkg:t}:void 0}};He();import{gunzipSync as dP}from"fflate";var Ro=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Br(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=dP(e),s=new TextDecoder("utf-8"),i=0;for(;i<n.length-512;){let o=n.slice(i,i+512);if(o[0]===0)break;let a=o.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),f=o.slice(124,136),u=s.decode(f).trim().replace(/\0/g,""),d=parseInt(u,8)||0,p=String.fromCharCode(o[156]);if(i+=512,(p==="0"||p==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let b=n.slice(i,i+d);t.set(this.normalizeTarPath(l),s.decode(b))}i+=Math.ceil(d/512)*512}}catch{}return t}};var No=class{constructor(e,t,n=new Ro){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=Bt.majorOf(n),o=e.filter(a=>Bt.majorOf(a)===i);if(o.length)return o.sort((a,c)=>Bt.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=At(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 Io=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(`
|
|
1599
|
+
`).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
|
|
1600
|
+
`),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://"))}};He();var fy="file:///node_modules",$o=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${fy}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=Dt(t);return`${fy}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as fP}from"lru-cache";function py(r){let e=new fP({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 Br(s,{init:{cache:"no-store"}});if(!c?.ok){c?.status===404&&(e.set(s,!0),await r.recordNegative(s));return}let l=await c.text(),f=c.url||s;return await r.clearNegative(s),await r.setCachedFile(f,l),{dts:l,url:f}})();return t.set(s,a),await a.finally(()=>t.delete(s))}catch{return}}}var ts=class{constructor(e){this.inFlight=new Map,this.scanner=new Io,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=py(e.cache),this.typescriptProvider=new Co(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new No(e.cdnClient,e.cache),this.virtualFs=new $o}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 f of l)await this.tryRelativeRef(f,c,o,n,s,i)}catch{}}async tryRelativeRef(e,t,n,s,i,o){try{let a=new URL(e,t),c=a.pathname+a.search,l=_o(c)?[c]:At(c);for(let f of l){let d=new URL(f,a).toString();if(o.has(d))return;let p=await this.fetchDts(d);if(p?.dts){let 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=pP(Ze.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,Ze.maxBareDepth,a,i).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,i,o){if(s<=0||i.has(e))return;i.add(e);let a=await this.fetchRootDts(e,o);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):n.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let f=this.scanner.collectBareModuleRefs(a.dts).slice(0,Ze.maxBareDeps).filter(u=>!i.has(u));for(let u of f)await this.prefetchBareDepsRecursive(u,t,n,s-1,i,o)}async resolve(e,t,n){let s=await this.packageService.extractImports(e),i=n?[...s,...n]:s;return(await Promise.all(i.map(a=>this.resolveOne(a,t)))).filter(a=>!!a)}async resolveOne(e,t){let{effectivePackage:n}=await this.versionResolver.effectivePackage(e,t);return this.withInFlight(n,async()=>{let s=new 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:f,packageRootUrl:u}=this.computeEntryPath(o,l),d=[{path:f,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,d,void 0,u);let b=d.map(A=>A.content).join(`
|
|
1601
|
+
`);await this.prefetchBareDeps(b,l,d,p,s);let m=c.format(),g=e===m?[e]:[e,m],k=g.some(A=>this.ambientlyDeclares(i,A));return k?this.markFileAmbient(d,f):p.push(...g.map(A=>({module:A,path:f}))),{pkg:e,mainPath:f,files:d,shims:p,ambient:k}}};el();He();yr();Nn();Qc();gr();import*as jr from"path";var mP=jr.join(wi,"pkg"),hP=jr.join(wi,"files"),gP=jr.join(wi,"negative.json"),Mo=class{pkgMem=new Map;fileMem=new Map;negativeCache=new jt(new br(gP));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await G();let t=await We(my(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 Lo(async()=>{await G(),await he(my(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await G();let t=await bi(hy(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await Lo(async()=>{await G(),await he(hy(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await Lo(async()=>{await G(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return Lo(()=>this.negativeCache.clearNegative(e))}};async function Lo(r){try{await r()}catch{}}function my(r){return jr.join(mP,ke(r)+".json")}function hy(r){return jr.join(hP,ke(r)+".txt")}yr();var wu;function yP(){return wu||(wu=new ts({cache:new Mo,cdnClient:_m,packageService:ki,versionResolver:Om})),wu}var gy="file:///node_modules/";async function yy(r){let e=vi(r.emitKey,"typecheck");await G(),await ae.rm(e,{recursive:!0,force:!0}),await ae.mkdir(e,{recursive:!0});let t=SP(r.jsxImportSource,r.dependencies),n=await yP().resolve(r.code,r.dependencies,t),s=r.local?.name,i=s?n.filter(f=>f.pkg!==s):n,o=new Set;for(let f of i)for(let u of f.files){let d=Do(u.path);if(!d||o.has(d))continue;o.add(d);let p=ie.join(e,"node_modules",d);await ae.mkdir(ie.dirname(p),{recursive:!0}),await ae.writeFile(p,u.content,"utf8")}let a={};for(let f of i)for(let u of f.shims){let d=Do(u.path);d&&(a[u.module]=[`./node_modules/${d}`])}for(let f of i){if(f.ambient)continue;let u=Do(f.mainPath);u&&(a[f.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let f of i)for(let u of f.files){if(!u.ambient)continue;let d=Do(u.path);d&&c.add(`node_modules/${d}`)}if(r.local){delete a[r.local.name];let f=await xP(r.local,e);f?a[r.local.name]=[`./node_modules/${r.local.name}/${f}`]:console.warn(` local: '${r.local.name}' ships no type defs; check cannot type against it.`)}let l=bP(r.jsxImportSource,a,[...c]);return await ae.writeFile(ie.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
|
|
1602
|
+
`,"utf8"),await ae.writeFile(ie.join(e,"code.tsx"),r.code,"utf8"),await ae.writeFile(ie.join(e,"tb.d.ts"),gu,"utf8"),{dir:e}}var vu={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function bP(r,e,t=[]){return{compilerOptions:{...vu,lib:wP([...pu,...mu]),jsx:"react-jsx",jsxImportSource:r??"react",paths:e},include:["code.tsx","tb.d.ts",...t]}}function wP(r){return hu(r).map(e=>vP(e.name))}function vP(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 SP(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function Do(r){if(!r.startsWith(gy))return;let e=r.slice(gy.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function xP(r,e){if(!r.typesAbs)return;let t=ie.dirname(r.typesAbs),n=ie.join(e,"node_modules",r.name);for(let s of await kP(t)){let i=ie.join(n,ie.relative(t,s));await ae.mkdir(ie.dirname(i),{recursive:!0}),await ae.copyFile(s,i)}return ie.basename(r.typesAbs)}async function kP(r){let e=[];async function t(n){let s=await ae.readdir(n,{withFileTypes:!0});for(let i of s){let o=ie.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 EP}from"fs";yr();rl();var AP="^22";async function by(r){let e=vi(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=Ci(r.server).filter(o=>o!==r.local?.name);await _i([`@types/node@${AP}`,...n],t,r.dependencies,{ignoreScripts:!0});let s=et.join(t,"node_modules"),i=et.join(e,"node_modules");return await PP(s,i),await be.writeFile(et.join(e,"server.ts"),r.server,"utf8"),await be.writeFile(et.join(e,"tb.d.ts"),yu,"utf8"),await be.writeFile(et.join(e,"tsconfig.json"),JSON.stringify(TP(r.local),null,2)+`
|
|
1603
|
+
`,"utf8"),{dir:e}}function TP(r){let e={...vu,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 PP(r,e){if(!EP(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)}mi();async function vy(r,e){let{bulb:t,config:n,warnings:s}=await Te(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=wy(xn(t.code,{target:"client",dependencies:n.dependencies??{}}),"client")||i),t.server&&(i=wy(xn(t.server,{target:"server"}),"server")||i);let o=$P([process.cwd(),Tt.dirname(r)]);if(!o){let l=Tt.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 yy({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 by({server:t.server,bulbDir:Tt.dirname(r),emitKey:r,local:e?{name:e.name,typesAbs:e.typesAbs}:void 0,dependencies:n.dependencies});a.push({role:"server",dir:l})}for(let{role:l,dir:f}of a){let{stdout:u,exitCode:d}=await NP(o,f);for(let p of u.split(/\r?\n/))p.trim()&&console.log(`${l} ${p}`);d!==0&&(i=!0)}i&&process.exit(1);let c=[t.code&&"code.tsx",t.server&&"server.ts"].filter(Boolean).join(", ");console.error(`\u2713 no issues (${c})`)}function wy(r,e){for(let t of r)for(let n of t.message.split(`
|
|
1604
|
+
`))console.log(`${e} ${n}`);return r.length>0}function NP(r,e){return new Promise(t=>{let n=OP(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 IP=CP(import.meta.url);function $P(r){let e=n=>{try{let s=IP.resolve("typescript/package.json",{paths:n}),i=Tt.join(Tt.dirname(s),"lib","tsc.js");return RP(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=_P("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}bt();eo();qn();async function Sy(r,e){let{bulb:t}=await Te(r),n=Cr(t);if(Ht(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 rs from"path";async function xy(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=kl();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=rs.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),Tr(t,e),console.log(e?`Trusted ${rs.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${rs.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}Le();import*as Ty from"readline";var ns=ty();function ky(){for(let r of Object.values(ns))try{r().ensureHarnessSupport()}catch{}}function ss(){for(let r of Object.keys(ns))try{if(ns[r]().detectsSelf())return r}catch{}}function Ey(r){let e=Dr(),t=new Map(e.filter(i=>ns[i]).map(i=>[i,ns[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)))}}to();function Su(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 Py(r){let e=Ey(process.cwd());if("ambiguous"in e){let t=await LP(r,e.ambiguous);return t?Ay(r,t):MP(r,e.ambiguous)}return Ay(r,e.name)}async function Ay(r,e){let t,n;try{t=await ph(e)}catch(f){n=f instanceof Error?f.message:String(f)}let{lit:s,litLink:i,brand:o}=Su(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(Rr())}`,` ${s(Vt())}`],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(`
|
|
1605
|
+
`)+`
|
|
1606
|
+
`)}async function LP(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:n}=Su(!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(`
|
|
1607
|
+
`)+`
|
|
1608
|
+
`);let i=Ty.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 MP(r,e){let{lit:t,brand:n}=Su(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(`
|
|
1609
|
+
`)+`
|
|
1610
|
+
`)}St();Kt();async function Oy(r){ye(r);let e=await Ve();if(e.length>0){console.log(Km(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!yl()){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(kr))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.")}to();import*as _y from"fs/promises";async function Cy(r){let e=Vt(),t;try{t=await _y.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(xh(t,r))}Ui();import*as Ry from"path";Le();function DP(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 is=r=>r.agent??Ry.basename(r.file);function Ny(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 xu(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),Ny(r,t=>console.log(t)),console.log(`
|
|
1611
|
+
`+e)}function ku(r,e,t,n,s){let i=DP(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>\`):`),Ny(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function Iy(r,e){if(!r){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),xu(await Q(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=ku(await Q(),r,"logs",process.cwd(),ss());if(e.clear){ah(t.pid),console.log(`Cleared log for ${is(t)} (pid ${t.pid}).`);return}let n=$e(t.pid),s=n.text;if(e.run!==void 0&&(s=ch(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(`
|
|
1612
|
+
`);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
|
|
1613
|
+
`)}if(process.stdout.write(s),s&&!s.endsWith(`
|
|
1614
|
+
`)&&process.stdout.write(`
|
|
1615
|
+
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=$e(t.pid,i);i=c.offset,c.text&&process.stdout.write(c.text)},500),a=()=>{clearInterval(o),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a),await new Promise(()=>{})}}var BP=r=>new Promise(e=>setTimeout(e,r));async function $y(r,e){if(!r){xu(await Q(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=ku(await Q(),r,"wait",process.cwd(),ss()),n=t.agent!=null,i=process.env.TYPEBULB_WAIT_SHIM==="1",o=e.timeoutSec??1800,a=e.match??"",c=$e(t.pid).offset,l=$l(t.pid,a)??(a?$l(t.pid):void 0),f=l!==void 0&&l<=c?l:a?0:c,u=Date.now()+o*1e3,d=n?1e4:1e3,p=2e3,b,m="",g=0;for(;;){let k=$e(t.pid,f);if(f=k.offset,k.text){m+=k.text;let A=m.split(`
|
|
1616
|
+
`);m=A.pop()??"";for(let P of A)P.trim()&&(e.match&&!P.includes(e.match)||(console.log(P),b??=Date.now()+d,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 ${is(t)} within ${o}s`),g=2;break}if(!Ml(t.pid)){b||(console.error(`server ${is(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await BP(400)}Gi(t.pid,f,a),process.exit(g)}async function Ly(r){if(!r){xu(await Q(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=ku(await Q(),r,"stop",process.cwd(),ss());await Wt(e.pid),console.log(`Stopped ${is(e)} (pid ${e.pid}, ${e.url}).`)}async function My(r){let e=process.cwd(),t=r==="agent"?ss():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=>Wt(i.pid))),console.log(`Stopped ${n.length} ${s}${n.length===1?"":"s"}:`);for(let i of n)console.log(` ${i.url} pid ${i.pid} ${is(i)}`)}Le();import*as Dy from"path";async function By(r,e,t=0){let n=e!==void 0&&e.startsWith("tb:");n&&t<=0&&(t=Go);let s=Dy.resolve(r),i=_r(await Q(),s)[0];i||(console.error(`No running server for '${r}'. Start it first: npx typebulb ${r}`),process.exit(1));let o=async d=>{let p=await fetch(`${i.url}/__send${d>0?`?reply=${d}`:""}`,{method:"POST",headers:{"Content-Type":"text/plain"},body:e??""});return p.ok||(console.error(`send failed: HTTP ${p.status} from ${i.url}/__send`),process.exit(1)),await p.json().catch(()=>({}))},a={};try{let d=Date.now()+t;do{if(a=await o(t>0?Math.max(d-Date.now(),1e3):0),(a.clients??0)>0||Date.now()>=d)break;await new Promise(p=>setTimeout(p,150))}while(!0)}catch(d){console.error(`send failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}let c=a.clients??0,l=`${c} page${c===1?"":"s"}`;if(c===0){t>0?console.error(`No page connected after ${t/1e3}s \u2014 is the bulb open?`):console.error("Sent, but no page is connected yet \u2014 open the bulb and retry."),n&&process.exit(1);return}console.error(`Sent to ${l}.`);let f=a.results??[],u=a.errors??[];for(let d of u)console.error(`handler error: ${d}`);if(u.length&&process.exit(1),f.length>1&&(console.error(`${f.length} replies from ${l} \u2014 one reply owns stdout: at most one tb.onMessage handler, in one page, may return a value.`),process.exit(1)),f.length===1){let d;try{d=JSON.parse(f[0])}catch{d=void 0}console.log(typeof d=="string"?d:f[0])}else a.timedOut&&(n&&(console.error(`No reply to '${e}' within ${t/1e3}s \u2014 reload the page and retry.`),process.exit(1)),console.error(`(no reply within ${t/1e3}s \u2014 a slow handler's return needs a larger --wait=ms)`))}Wn();Yl();St();bt();Ne();eo();Wn();import*as Ot from"fs/promises";import*as Ko from"path";import{EventEmitter as Ky}from"events";import ZP from"open";xr();Ne();import{Hono as KP}from"hono";import{serve as HP}from"@hono/node-server";import{streamSSE as WP}from"hono/streaming";import*as Pu from"fs/promises";yr();Nn();gr();import*as Eu from"fs/promises";import*as os from"path";var Bo=class{async get(e){let t=ke(e),n=os.join(Rn,t+".bin"),s=os.join(Rn,t+".json");try{let[i,o]=await Promise.all([Eu.readFile(n),Eu.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=os.join(Rn,n+".bin"),i=os.join(Rn,n+".json"),o={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([he(s,t.body),he(i,JSON.stringify(o))])}};var jy=`
|
|
1617
|
+
const CSS = '\\n' +
|
|
1618
|
+
/* The agent mirror's token set, verbatim (agents/core/client/styles.css) \u2014 one system across CLI
|
|
1619
|
+
chrome: app chrome sits on --panel, content wells paint --veil, grays ride one neutral tint.
|
|
1620
|
+
The lone extension is --accent-contrast (text on a filled accent; the mirror never fills a
|
|
1621
|
+
button, and the dark theme's lighter accent needs dark text). */
|
|
1622
|
+
'.overlay { --fg: rgb(28, 28, 30); --muted: rgb(96, 96, 100); --panel: rgb(242, 242, 242);\\n' +
|
|
1623
|
+
' --border: rgb(221, 221, 221); --accent: rgb(58, 125, 232); --accent-contrast: #fff;\\n' +
|
|
1624
|
+
' --veil: rgba(0, 0, 0, 0.05); --err: rgb(206, 60, 60); }\\n' +
|
|
1625
|
+
'.dark .overlay { --fg: rgb(190, 190, 190); --muted: rgb(150, 150, 150); --panel: rgb(32, 32, 32);\\n' +
|
|
1626
|
+
' --border: rgb(52, 52, 52); --accent: rgb(122, 162, 250); --accent-contrast: #1c1e21;\\n' +
|
|
1627
|
+
' --veil: rgba(255, 255, 255, 0.06); --err: rgb(230, 60, 60); }\\n' +
|
|
1628
|
+
'.overlay { position: fixed; inset: 0; background: rgba(0,0,0,.45); z-index: 2147483000;\\n' +
|
|
1629
|
+
' display: flex; align-items: center; justify-content: center; padding: 16px;\\n' +
|
|
1630
|
+
' font: 14px/1.45 system-ui, sans-serif; color: var(--fg); }\\n' +
|
|
1631
|
+
'.card { background: var(--panel); border-radius: 10px; box-shadow: 0 12px 40px rgba(0,0,0,.35);\\n' +
|
|
1632
|
+
' width: min(560px, 100%); max-height: min(80vh, 640px); display: flex; flex-direction: column; }\\n' +
|
|
1633
|
+
'.head { display: flex; align-items: center; gap: 8px; padding: 14px 16px 10px; }\\n' +
|
|
1634
|
+
'.head h1 { font-size: 18px; font-weight: 600; margin: 0; flex: 1; color: var(--accent); }\\n' +
|
|
1635
|
+
'.x { border: 0; background: none; color: inherit; font-size: 18px; cursor: pointer; opacity: .6; padding: 2px 6px; }\\n' +
|
|
1636
|
+
'.x:hover { opacity: 1; }\\n' +
|
|
1637
|
+
'.body { padding: 0 16px; overflow-y: auto; flex: 1; display: flex; flex-direction: column; gap: 10px; }\\n' +
|
|
1638
|
+
'.model { color: var(--muted); }\\n' +
|
|
1639
|
+
'.model.err { color: var(--err); }\\n' +
|
|
1640
|
+
'label { font-weight: 600; }\\n' +
|
|
1641
|
+
'.tabs { display: flex; gap: 4px; }\\n' +
|
|
1642
|
+
'.tab { font: inherit; padding: 4px 10px; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; color: inherit; cursor: pointer; opacity: .6; }\\n' +
|
|
1643
|
+
'.tab.on { opacity: 1; border-bottom-color: var(--accent); }\\n' +
|
|
1644
|
+
'.tab .cnt { opacity: .6; font-size: 12px; margin-left: 4px; }\\n' +
|
|
1645
|
+
'textarea { width: 100%; box-sizing: border-box; min-height: 160px; max-height: 320px; resize: vertical;\\n' +
|
|
1646
|
+
' font: 13px/1.4 ui-monospace, monospace; padding: 8px; border-radius: 6px;\\n' +
|
|
1647
|
+
' border: 1px solid var(--border); background: var(--veil); color: inherit; }\\n' +
|
|
1648
|
+
'pre.stream { font: 13px/1.4 ui-monospace, monospace; white-space: pre-wrap; word-break: break-word;\\n' +
|
|
1649
|
+
' background: var(--veil); border-radius: 6px; padding: 10px; margin: 0; min-height: 120px; }\\n' +
|
|
1650
|
+
'.error { color: var(--err); white-space: pre-wrap; }\\n' +
|
|
1651
|
+
'.foot { display: flex; gap: 8px; padding: 12px 16px 14px; justify-content: flex-end; align-items: center; }\\n' +
|
|
1652
|
+
'.leftgrp { margin-right: auto; display: flex; gap: 8px; }\\n' +
|
|
1653
|
+
'button { font: inherit; padding: 6px 14px; border-radius: 6px; cursor: pointer;\\n' +
|
|
1654
|
+
' border: 1px solid var(--border); background: transparent; color: inherit; }\\n' +
|
|
1655
|
+
'button.run { background: var(--accent); border-color: var(--accent); color: var(--accent-contrast); }\\n' +
|
|
1656
|
+
'button.run:disabled { opacity: .5; cursor: default; }\\n' +
|
|
1657
|
+
'@keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }\\n' +
|
|
1658
|
+
'.shimmer { display: inline-block; background-image: linear-gradient(90deg, var(--muted), var(--fg), var(--muted));\\n' +
|
|
1659
|
+
' background-size: 200% 100%; -webkit-background-clip: text; background-clip: text;\\n' +
|
|
1660
|
+
' -webkit-text-fill-color: transparent; color: transparent; animation: shimmer 2s linear infinite; }\\n';
|
|
1358
1661
|
|
|
1359
|
-
|
|
1360
|
-
document.
|
|
1662
|
+
function isDark() {
|
|
1663
|
+
var t = document.documentElement.getAttribute('data-theme');
|
|
1664
|
+
if (t) return t === 'dark';
|
|
1665
|
+
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
|
|
1361
1666
|
}
|
|
1362
|
-
`});import{stream as _E}from"hono/streaming";function Vn(r){return r instanceof fe?{message:r.message,code:r.code,retryable:r.retryable}:{message:r instanceof Error?r.message:"Unknown error",code:"unknown",retryable:!1}}function ao(r,e){return r.header("Content-Type","application/x-ndjson; charset=utf-8"),r.header("Cache-Control","no-cache"),r.header(RE,"1"),_E(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:Vn(s)}))}finally{try{await n.return?.()}catch{}}})}var RE,_h=w(()=>{xr();RE="X-TB-Stream"});function lo(r,e){let t=r?.[e]??(Object.hasOwn(co,e)?co[e]:void 0);return typeof t=="function"?t:void 0}function uo(r){return r.constructor?.name==="AsyncGeneratorFunction"}var co,Vl=w(()=>{co={log:(...r)=>console.log(...r)}});function Rh(r,e=""){return NE.test(r)?!0:$E.test(r)&&IE.test(e)}var NE,IE,$E,Nh=w(()=>{NE=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,IE=/[?&]target=/,$E=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/});import{Hono as LE}from"hono";import{serve as ME}from"@hono/node-server";import{streamSSE as DE}from"hono/streaming";import*as Xl from"fs/promises";import*as $h from"path";function jE(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function FE(r){let e=jE(r);return!!e&&BE.has(e)}function qE(r,e){if(!e)return!1;try{return new URL(r).host===e}catch{return!1}}function Gl(r){return r instanceof Error?r.message:"Unknown error"}async function Mh(r){let{getHtml:e,basePath:t,fsBase:n,port:s,reloadEmitter:i,messageEmitter:o,getServerExports:a,getBulbBlocks:c,saveInferenceResult:l,localOverride:f,trusted:u=!1,trustHint:d,staticAssets:p,bulbAssets:b}=r,m=n??t,g=new LE;g.use("*",async(y,x)=>{if(!FE(y.req.header("host")))return y.text("Forbidden: untrusted Host",403);await x()}),g.use("*",async(y,x)=>{await x(),y.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),y.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let k=[["/__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,x)=>{if(!u){let I=new URL(y.req.url).pathname,_=k.find(([W])=>W.endsWith("/*")?I.startsWith(W.slice(0,-2)):I===W)?.[1]??"server-side code (server.ts)";uh(process.pid,_);let M=d?`
|
|
1363
|
-
${d}`:"";return y.text(`Forbidden: this capability requires --trust.${M}`,403)}await x()},P=async(y,x)=>{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(_&&!qE(_,y.req.header("host")))return y.text("Forbidden: cross-origin request",403)}await x()};for(let[y]of k)g.use(y,A),g.use(y,P);if(g.use("/__log",P),g.post("/__log",async y=>{try{let{args:x}=await y.req.json();console.log(...x||[])}catch{}return y.json({ok:!0})}),o){let y=0,x=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,qe=await new Promise(z=>{let V={expected:W,received:0,results:[],errors:[],finish:we=>{clearTimeout(Ue),x.delete(K),z({results:V.results,errors:V.errors,timedOut:we})}},Ue=setTimeout(()=>V.finish(!0),M);x.set(K,V),o.emit("message",{id:K,payload:_})});return I.json({clients:W,...qe})}),g.use("/__send-reply",P),g.post("/__send-reply",async I=>{try{let{id:_,results:M,errors:W}=await I.req.json(),K=x.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:x}=await y.req.json(),I=await Dn(x,m,t);return new Response(new Uint8Array(I),{headers:{"Content-Type":"application/octet-stream"}})}catch(x){let I=Gl(x);return y.json({error:I},400)}}),g.post("/__fs/write",async y=>{try{let x=y.req.query("path");return x?(await Fi(x,new Uint8Array(await y.req.arrayBuffer()),m,t),y.json({success:!0})):y.json({error:"Missing path"},400)}catch(x){let I=Gl(x);return y.json({error:I},400)}}),g.post("/__api/:name",async y=>{try{let x=y.req.param("name"),I=lo(a?.(),x);if(!I)return y.json({error:`API function '${x}' not found`},404);let{args:_}=await y.req.json();if(uo(I))return ao(y,I(..._||[]));let M=await I(..._||[]);return y.json({result:M})}catch(x){let I=Gl(x);return y.json({error:I},500)}}),g.post("/__ai",async y=>{try{let{messages:x,system:I,effort:_,provider:M,model:W,webSearch:K,stream:qe}=await y.req.json();if(!x||!Array.isArray(x)||x.length===0)return y.json({message:"messages array is required",code:"unknown",retryable:!1},400);let z=Ge(M,W);if(typeof z=="string")return y.json({message:z,code:"unknown",retryable:!1},400);let V=await gt(z,{messages:x,system:I,effort:_,webSearch:K,signal:y.req.raw.signal});if(!V.ok){let we=await Sr(V,z.protocol);return y.json(we,V.status)}if(qe)return ao(y,Jt(V,z.protocol));let Ue=await Ut(V,z.protocol);return Ue||console.warn("[tb.ai] Empty response from provider"),y.json({text:Ue})}catch(x){return y.json(Vn(x),500)}}),g.post("/__infer",async y=>{try{let{data:x}=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 _=Ge();if(typeof _=="string")return y.json({message:_,code:"unknown",retryable:!1},400);let M=Array.isArray(x)?x.map(String):[],W=fl(I,M),K=await gt(_,{messages:[{role:"user",content:W}],signal:y.req.raw.signal});if(!K.ok){let z=await Sr(K,_.protocol);return y.json(z,K.status)}let qe=(async function*(){let z="";for await(let we of Jt(K,_.protocol))we.kind!=="text"||!we.text||(z+=we.text,yield{kind:"delta",text:we.text});let V=pl(z);if(V.parsed===null)throw console.warn(`[tb.infer] output not valid JSON after sanitize; raw output (last 4000 chars):
|
|
1364
|
-
`+z.slice(-4e3)),new fe("LLM output is not valid JSON","parse_error",!0);V.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",V.fixesApplied.join(", "));let Ue={insight:V.parsed,insightJson:V.json,data:M};yield{kind:"complete",...Ue,fixesApplied:V.fixesApplied,hash:ml(Ue)}})();return ao(y,qe)}catch(x){return y.json(Vn(x),500)}});let R=async y=>{let{hash:x}=await y.req.json().catch(()=>({}));return typeof x=="string"?hl(x):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 x=await R(y);return x?(await l(x.data,x.insightJson),y.json({ok:!0})):y.json({message:"No decodable #tb= fragment to save.",code:"unknown",retryable:!1},400)}catch(x){return y.json(Vn(x),500)}}),g.get("/__infer-info",y=>{let x=c?.(),I=Fr(x?.config??"").inference,_=fi(x?.data??""),M=Ge();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(Oh,200,{"Content-Type":"text/javascript; charset=utf-8"})),g.get("/__models",async y=>{try{let x=await Ve();return y.json(x)}catch{return y.json([],200)}}),g.get("/__has-own-keys",async y=>{try{return y.json(await Bi())}catch{return y.json(!1,200)}});let N=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],O=new oo;g.get("/proxy/*",async y=>{let x=new URL(y.req.url),_=(x.pathname+x.search).slice(7),M=_.lastIndexOf("https://");return M===-1?y.text("Invalid proxy URL",400):$(y,_.slice(M))}),f&&Ih(g,`/local/${f.name}/`,f.serveDir),p&&Ih(g,p.mount,p.dir),b&&g.get("/assets/*",async y=>{let{pathname:x}=new URL(y.req.url),I=x.slice(8);for(let M of b.dirs){let W;try{W=Mn(decodeURIComponent(I),M)}catch{return y.text("Not Found",404)}try{let K=await Xl.readFile(W);return new Response(K,{headers:{"Content-Type":fo(W),"Cache-Control":"no-cache"}})}catch{}}let _=b.remoteBase;return _?y.redirect(_+I,302):y.text("Not Found",404)});async function $(y,x){let I;try{I=new URL(x)}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(x);if(_)return new Response(_.body,{status:200,headers:zl(_.contentType,_.cacheControl)});try{let M=await fetch(x,{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[qe,z]=M.body.tee();return(async()=>{try{let V=await new Response(z).arrayBuffer();await O.set(x,{body:Buffer.from(V),contentType:W,cacheControl:K})}catch{}})(),new Response(qe,{status:M.status,headers:zl(W,K)})}return new Response(null,{status:M.status,headers:zl(W,K)})}catch(M){return y.text(`Proxy fetch failed: ${M instanceof Error?M.message:M}`,502)}}(i||o)&&g.get("/__reload",y=>DE(y,async x=>{let I=()=>{x.writeSSE({event:"reload",data:""})},_=M=>{x.writeSSE({event:"message",data:JSON.stringify(M)})};for(i?.on("reload",I),o?.on("message",_),x.onAbort(()=>{i?.removeListener("reload",I),o?.removeListener("message",_)});!x.aborted;)await x.sleep(3e4)})),g.notFound(async y=>{if(y.req.method!=="GET")return y.text("Not Found",404);let x=new URL(y.req.url);return Rh(x.pathname,x.search)?$(y,"https://esm.sh"+x.pathname+x.search):y.text("Not Found",404)});let E=ME({fetch:g.fetch,port:s,hostname:Lh});return{port:s,close:()=>E.close()}}function zl(r,e){let t=new Headers;return r&&t.set("Content-Type",r),e&&t.set("Cache-Control",e),t.set("Access-Control-Allow-Origin","*"),t.set("Cross-Origin-Resource-Policy","cross-origin"),t}function Ih(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=Mn(i,t),a=await Xl.readFile(o);return new Response(a,{headers:{"Content-Type":fo(o)}})}catch{return n.text("Not Found",404)}})}function fo(r){switch($h.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 Ql(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,Lh,()=>{let s=n.address(),i=typeof s=="object"&&s?s.port:r;n.close(()=>t(i))}),n.on("error",()=>{t(Ql(r+1))})})}var Lh,BE,Zl=w(()=>{xr();Re();Ph();Ch();$e();Kt();ji();_h();Vl();bl();Nh();Lh="127.0.0.1",BE=new Set(["localhost","127.0.0.1","::1"])});import*as De from"fs/promises";import*as zn from"path";import{createHash as UE}from"crypto";async function Bh(r,e=""){let t=await De.readdir(r,{withFileTypes:!0}).catch(()=>[]),n=[];for(let s of t)s.isDirectory()?n.push(...await Bh(zn.join(r,s.name),`${e}${s.name}/`)):s.isFile()&&n.push(e+s.name);return n}async function JE(r,e){let t=e.timeoutMs??3e4,n=jh(r),s={Authorization:`Bearer ${e.token}`},i=jn(r.dest);if(!await De.stat(i).then(p=>p.isDirectory()).catch(()=>!1))return{kind:"skipped"};let o=await Bh(i),a;try{let p=await fetch(n,{headers:s,signal:AbortSignal.timeout(t)});if(!p.ok)return{kind:"sync-error",message:`manifest request failed (${p.status}): ${Gn(await p.text())}`};a=await p.json()}catch(p){return{kind:"sync-error",message:p instanceof Error?p.message:String(p)}}if(!o.length&&!a.length)return{kind:"skipped"};let c=new Map(a.map(p=>[p.path,p.md5])),l=new Set(o),f=a.map(p=>p.path).filter(p=>!l.has(p)),u=0,d=0;try{await HE(o,4,async p=>{let b=await De.readFile(zn.join(i,...p.split("/")));if(c.get(p)===UE("md5").update(b).digest("hex")){d++;return}let m=await fetch(`${n}/${Dh(p)}`,{method:"PUT",body:new Uint8Array(b),headers:{...s,"Content-Type":fo(p)},signal:AbortSignal.timeout(t)});if(!m.ok)throw new Error(`upload of '${p}' refused (${m.status}): ${Gn(await m.text())}`);u++})}catch(p){return{kind:"sync-error",message:p instanceof Error?p.message:String(p)}}return{kind:"synced",uploaded:u,unchanged:d,toDelete:f,base:ms(r.userSlug,r.slug)}}async function KE(r,e,t){let n=t.timeoutMs??3e4,s=jh(r),i=[];for(let o of e)try{let a=await fetch(`${s}/${Dh(o)}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(n)});if(!a.ok)return{deleted:i,error:`delete of '${o}' refused (${a.status}): ${Gn(await a.text())}`};i.push(o)}catch(a){return{deleted:i,error:a instanceof Error?a.message:String(a)}}return{deleted:i}}async function HE(r,e,t){let n=[...r],s=async()=>{for(let i=n.shift();i!==void 0;i=n.shift())await t(i)};await Promise.all(Array.from({length:Math.min(e,r.length)},s))}async function WE(r,e){let t=await JE(r,{token:e});return t.kind==="sync-error"?(console.error(`assets sync failed: ${t.message}
|
|
1365
|
-
push refused: the bulb text was not pushed.`),{proceed:!1}):t.kind==="synced"?(console.log(`assets: ${t.uploaded} uploaded, ${t.unchanged} unchanged \u2192 ${t.base}`),{proceed:!0,toDelete:t.toDelete}):{proceed:!0}}async function po(r,e){let t=await De.readFile(r.dest,"utf-8"),{mtime:n}=await De.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(Hl(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:Gn(o)};if(!i.ok)return{kind:"http-error",status:i.status,message:Gn(o)};let a=JSON.parse(o);return await De.utimes(r.dest,new Date,new Date(a.updatedAt)),{kind:"pushed",created:a.created,serverStripped:a.serverStripped,updatedAt:a.updatedAt}}function Gn(r){try{return JSON.parse(r).error||r}catch{return r}}async function Fh(r,e){r||(console.error("Usage: typebulb push <typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1)),/^https?:\/\//i.test(r)&&(console.error("push takes a local .bulb.md file, not a URL (the path is its remote identity)"),process.exit(1));let t=Wl(r,e.mode),n=process.env.TYPEBULB_TOKEN;n||(console.error("push needs TYPEBULB_TOKEN in your .env \u2014 create one on your typebulb.com settings page."),process.exit(1));let s=`${t.origin}/u/${t.userSlug}/${t.slug}`,i=zn.relative(process.cwd(),t.dest)||t.dest,o,a;try{let c=await WE(t,n);if(!c.proceed){process.exitCode=1;return}a=c.toDelete,o=await po(t,{token:n,force:e.force})}catch(c){let l=c instanceof Error?c.message:String(c);console.error(c?.code==="ENOENT"?`File not found: ${i}`:`Could not push to ${t.origin}: ${l}`),process.exitCode=1;return}switch(o.kind){case"pushed":{if(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."),a?.length){let c=await KE(t,a,{token:n});for(let l of c.deleted)console.log(` deleted ${l} (no longer in assets/)`);c.error&&console.log(`note: asset cleanup incomplete \u2014 ${c.error}; the next push will retry.`)}return}case"conflict":console.error(`${o.message}
|
|
1366
|
-
pull to see the remote: typebulb pull ${i}
|
|
1367
|
-
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 Dh,jh,eu=w(()=>{Re();Wn();bt();Zl();Dh=r=>r.split("/").map(encodeURIComponent).join("/");jh=r=>`${r.origin}/u/${encodeURIComponent(r.userSlug)}/${encodeURIComponent(r.slug)}/assets`});var Nr=w(()=>{$e();gh();yh();Fl();bh();vh();qn();Kt();Kt();ji();to();Wn();eu();St()});import{copyFileSync as YE,existsSync as qh,mkdirSync as Uh,rmSync as VE,writeFileSync as GE}from"fs";import{homedir as zE}from"os";import*as Be from"path";import{fileURLToPath as XE}from"url";function nA(){return rA.replace('"__TB_DESCRIPTION_PATH__"',JSON.stringify(Rr())).replace('"__TB_README_PATH__"',JSON.stringify(Vt()))}function Jh(){try{if(!qh(mo()))return}catch{return}try{let r=QE();Uh(Be.dirname(r),{recursive:!0}),GE(r,nA()),VE(ZE(),{force:!0})}catch{}try{let r=eA();if(!qh(r))return;let e=tA();Uh(Be.dirname(e),{recursive:!0}),YE(r,e)}catch{}}var mo,QE,ZE,eA,tA,rA,Kh=w(()=>{Nr();mo=()=>Be.join(zE(),".pi","agent"),QE=()=>Be.join(mo(),"extensions","typebulb.ts"),ZE=()=>Be.join(mo(),"extensions","typebulb-wait.ts"),eA=()=>Be.join(Be.dirname(XE(import.meta.url)),"agents","pi","matchu-patchu.ts"),tA=()=>Be.join(mo(),"extensions","matchu-patchu.ts"),rA=String.raw`// Generated by typebulb — do not edit; overwritten on each run.
|
|
1368
|
-
import { spawn } from "node:child_process";
|
|
1369
|
-
import { existsSync } from "node:fs";
|
|
1370
|
-
|
|
1371
|
-
function logErr(...a) { try { console.error("[typebulb]", ...a); } catch (e) {} }
|
|
1372
1667
|
|
|
1373
|
-
|
|
1374
|
-
|
|
1668
|
+
function el(tag, cls, text) {
|
|
1669
|
+
var e = document.createElement(tag);
|
|
1670
|
+
if (cls) e.className = cls;
|
|
1671
|
+
if (text != null) e.textContent = text;
|
|
1672
|
+
return e;
|
|
1673
|
+
}
|
|
1375
1674
|
|
|
1376
|
-
//
|
|
1377
|
-
//
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
var dirs = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]];
|
|
1385
|
-
for (var i = 0; i < dirs.length; i++) {
|
|
1386
|
-
if (dirs[i] && existsSync(dirs[i] + "\\Git\\bin\\bash.exe")) return dirs[i] + "\\Git\\bin\\bash.exe";
|
|
1387
|
-
}
|
|
1388
|
-
return "bash.exe"; // PATH fallback (Cygwin/MSYS2); a spawn miss lands in the "error" handler
|
|
1389
|
-
} catch (e) { return null; }
|
|
1675
|
+
// Per-chunk label: config dataTitle (comma-delimited) > a #/// comment-header first line > Data N.
|
|
1676
|
+
// The same fallback chain as .com's DataChunkEditor.
|
|
1677
|
+
function chunkLabel(chunk, i, titles) {
|
|
1678
|
+
if (titles[i]) return titles[i];
|
|
1679
|
+
var first = (chunk.split('\\n')[0] || '').trim();
|
|
1680
|
+
if (first.charAt(0) === '#' && first.length > 1 && first.length < 40) return first.replace(/^#+\\s*/, '');
|
|
1681
|
+
if (first.indexOf('//') === 0 && first.length > 2 && first.length < 40) return first.replace(/^\\/\\/\\s*/, '');
|
|
1682
|
+
return 'Data ' + (i + 1);
|
|
1390
1683
|
}
|
|
1391
1684
|
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1685
|
+
/**
|
|
1686
|
+
* Open the inference modal. ctx: { data: string[], readStream(resp), onComplete(final),
|
|
1687
|
+
* onError(err), onCancel() }. readStream is the SHIM's NDJSON reader (an async iterable of chunk
|
|
1688
|
+
* values that throws error envelopes as Error with code/retryable) \u2014 passed in so the page has
|
|
1689
|
+
* exactly one copy of the transport decoder. onComplete fires on every successful run (a retry
|
|
1690
|
+
* after an error included); onError on each displayed terminal error; onCancel when the user
|
|
1691
|
+
* closes before any completion.
|
|
1692
|
+
*/
|
|
1693
|
+
export function runInference(ctx) {
|
|
1694
|
+
var host = document.createElement('div');
|
|
1695
|
+
var root = host.attachShadow({ mode: 'closed' });
|
|
1696
|
+
var style = document.createElement('style');
|
|
1697
|
+
style.textContent = CSS;
|
|
1698
|
+
root.appendChild(style);
|
|
1396
1699
|
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
"Typebulb: the user is prompting you from the typebulb agent mirror (already open in front of them).",
|
|
1404
|
-
" Embedded bulbs render live in this conversation.",
|
|
1405
|
-
" • do not run npx typebulb agent — the mirror is already running",
|
|
1406
|
-
" • no need to end your reply with a mirror link",
|
|
1407
|
-
" Reusable app/tool → write a .bulb.md",
|
|
1408
|
-
" Show something inline → embed a bulb",
|
|
1409
|
-
" arm a wait for its render verdict — run it plainly:",
|
|
1410
|
-
' • typebulb wait agent --match "[embed <name>"',
|
|
1411
|
-
" Read the authoring skill before writing a bulb:",
|
|
1412
|
-
" • npx typebulb skill — assembles one SKILL.md",
|
|
1413
|
-
" • or, open its parts:",
|
|
1414
|
-
" " + TB_DESCRIPTION_PATH,
|
|
1415
|
-
" " + TB_README_PATH,
|
|
1416
|
-
].join("\n");
|
|
1700
|
+
var wrap = el('div', isDark() ? 'dark' : '');
|
|
1701
|
+
root.appendChild(wrap);
|
|
1702
|
+
var overlay = el('div', 'overlay');
|
|
1703
|
+
wrap.appendChild(overlay);
|
|
1704
|
+
var card = el('div', 'card');
|
|
1705
|
+
overlay.appendChild(card);
|
|
1417
1706
|
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1707
|
+
var completed = false;
|
|
1708
|
+
var canceled = false;
|
|
1709
|
+
var aborter = null;
|
|
1710
|
+
var inferCfg = {};
|
|
1711
|
+
var dataTitles = function () {
|
|
1712
|
+
return String(inferCfg.dataTitle || '').split(',').map(function (s) { return s.trim(); }).filter(Boolean);
|
|
1713
|
+
};
|
|
1421
1714
|
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1715
|
+
function close(kind) {
|
|
1716
|
+
if (kind === 'cancel') canceled = true;
|
|
1717
|
+
if (aborter) { aborter.abort(); aborter = null; }
|
|
1718
|
+
host.remove();
|
|
1719
|
+
if (kind === 'cancel' && !completed) ctx.onCancel();
|
|
1720
|
+
}
|
|
1721
|
+
overlay.addEventListener('click', function (e) { if (e.target === overlay) close('cancel'); });
|
|
1428
1722
|
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1723
|
+
var head = el('div', 'head');
|
|
1724
|
+
var title = el('h1', '', 'Run AI inference');
|
|
1725
|
+
head.appendChild(title);
|
|
1726
|
+
var x = el('button', 'x', '\\u00d7');
|
|
1727
|
+
x.addEventListener('click', function () { close('cancel'); });
|
|
1728
|
+
head.appendChild(x);
|
|
1729
|
+
card.appendChild(head);
|
|
1434
1730
|
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
// first paint OR a running bulb's next event line alike.
|
|
1440
|
-
// The agent may self-background ("… &") — the generic-shell reading of "arm it in the
|
|
1441
|
-
// background", but here the SHIM is the backgrounder: bash would exit 0 instantly with empty
|
|
1442
|
-
// output, firing the wake before the event while the detached wait delivers to nobody
|
|
1443
|
-
// (field: Toroidal Life, '> /tmp/x.log 2>&1 &'). Strip a trailing "&" so the wait runs
|
|
1444
|
-
// foreground inside the shim's already-backgrounded child.
|
|
1445
|
-
const cmd = String(command).replace(/(?<!&)\s*&\s*$/, "");
|
|
1446
|
-
const bash = resolveBash();
|
|
1447
|
-
const opts = {
|
|
1448
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
1449
|
-
env: { ...process.env, TYPEBULB_WAIT_SHIM: "1" },
|
|
1450
|
-
};
|
|
1451
|
-
const child = bash ? spawn(bash, ["-c", cmd], opts) : spawn(cmd, { ...opts, shell: true });
|
|
1452
|
-
pending.add(child);
|
|
1453
|
-
let out = "";
|
|
1454
|
-
let errOut = "";
|
|
1455
|
-
if (child.stdout) child.stdout.on("data", (b) => { out += b.toString(); });
|
|
1456
|
-
if (child.stderr) child.stderr.on("data", (b) => { errOut += b.toString(); });
|
|
1457
|
-
child.on("error", (e) => {
|
|
1458
|
-
pending.delete(child);
|
|
1459
|
-
logErr("spawn", e && e.message);
|
|
1460
|
-
// Same class as a failure exit: the subscription never armed, so silence is a deadlock.
|
|
1461
|
-
try { pi.sendUserMessage("typebulb wait FAILED to spawn: " + (e && e.message) + "\nNothing is watching — fix and re-arm the wait.", { deliverAs: "followUp" }); } catch (e2) {}
|
|
1462
|
-
});
|
|
1463
|
-
child.on("exit", (code) => {
|
|
1464
|
-
pending.delete(child);
|
|
1465
|
-
try {
|
|
1466
|
-
const text = out.trim();
|
|
1467
|
-
// Exit 0 with output is a real outcome (embed ok/error, a turn-based move) -> wake the
|
|
1468
|
-
// agent (followUp delivers immediately when idle and queues when streaming — the same call
|
|
1469
|
-
// git-merge-and-resolve.ts makes from agent_end). A late wake is fine; it just reports
|
|
1470
|
-
// something true. Exit 2/3 (no render yet / server gone) surface passively, no turn.
|
|
1471
|
-
// Any OTHER non-zero exit means the subscription itself broke (bad args, no resolvable
|
|
1472
|
-
// mirror): the agent parked on a wake that can never come, so that failure must wake too —
|
|
1473
|
-
// missed wakes are fatal, spurious wakes cheap (TB-Wait.md). null (reap-killed) stays silent.
|
|
1474
|
-
// EXCEPT an embed's clean ok verdict ("[embed <name> vN] ok" — core/client/bulbEmbed.ts):
|
|
1475
|
-
// the user already sees the bulb and the skill orders silence on ok, so a wake would spend
|
|
1476
|
-
// a whole turn saying nothing and render a noise message. Silence IS the ok. Anything else
|
|
1477
|
-
// (an embed error, a turn-based loop event) still wakes; an unrecognized shape wakes too.
|
|
1478
|
-
// Checked PER LINE, not over the whole blob: wait lingers 10s and bursts every matching line
|
|
1479
|
-
// into one payload, and a version-agnostic --match ("[embed <name>") replays v1+v2+... from
|
|
1480
|
-
// log start, so an all-ok payload is routinely multi-line. Suppress iff EVERY line is an ok;
|
|
1481
|
-
// one error line among oks still wakes.
|
|
1482
|
-
var waitLines = text.split("\n").map(function (l) { return l.trim(); }).filter(Boolean);
|
|
1483
|
-
const embedOk = code === 0 && waitLines.length > 0 && waitLines.every(function (l) { return /^\[embed .*\] ok$/.test(l); });
|
|
1484
|
-
if (code === 0 && text && !embedOk) {
|
|
1485
|
-
pi.sendUserMessage("typebulb wait result:\n" + text, { deliverAs: "followUp" });
|
|
1486
|
-
} else if (code === 0 && !text) {
|
|
1487
|
-
// A successful wait always prints its matched line(s), so exit 0 with nothing captured
|
|
1488
|
-
// means the agent redirected stdout (e.g. '> /tmp/x.log 2>&1') — the verdict landed in a
|
|
1489
|
-
// file nobody reads. The line is still in the mirror's log; point the agent there.
|
|
1490
|
-
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" });
|
|
1491
|
-
} else if (code !== null && code !== 0 && code !== 2 && code !== 3) {
|
|
1492
|
-
var diag = (text + "\n" + errOut.trim()).trim();
|
|
1493
|
-
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" });
|
|
1494
|
-
} else if (ctx.ui && typeof ctx.ui.notify === "function") {
|
|
1495
|
-
// INVARIANT: this notify must never quote the "[embed <name>" tag verbatim. In a
|
|
1496
|
-
// composer-driven session the mirror's driver echoes extension notifies into the
|
|
1497
|
-
// mirror's own log (driver.ts) — the very log wait watches by substring — so a
|
|
1498
|
-
// verbatim tag re-fires the next same-match wait with a non-ok line: a self-
|
|
1499
|
-
// sustaining wake loop that defeats this suppression (TB-Wait.md). Stripping the
|
|
1500
|
-
// brackets kills the matchable substring while keeping the verdict readable.
|
|
1501
|
-
ctx.ui.notify("typebulb wait: " + (embedOk ? text.replace(/[\[\]]/g, "") : code === 2 ? "timed out, nothing to report" : "ended (code " + code + ")"), "info");
|
|
1502
|
-
}
|
|
1503
|
-
} catch (e) { logErr("exit", e && e.message); }
|
|
1504
|
-
});
|
|
1731
|
+
var body = el('div', 'body');
|
|
1732
|
+
card.appendChild(body);
|
|
1733
|
+
var foot = el('div', 'foot');
|
|
1734
|
+
card.appendChild(foot);
|
|
1505
1735
|
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1736
|
+
// \u2500\u2500 Confirmation state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1737
|
+
var areas = [];
|
|
1738
|
+
function showConfirm() {
|
|
1739
|
+
body.textContent = ''; foot.textContent = ''; areas = [];
|
|
1740
|
+
|
|
1741
|
+
var model = el('div', 'model');
|
|
1742
|
+
model.appendChild(el('span', 'shimmer', 'Resolving model\\u2026'));
|
|
1743
|
+
body.appendChild(model);
|
|
1744
|
+
var cancel = el('button', '', 'Cancel');
|
|
1745
|
+
cancel.addEventListener('click', function () { close('cancel'); });
|
|
1746
|
+
foot.appendChild(cancel);
|
|
1512
1747
|
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
`)}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(`
|
|
1521
|
-
`),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??cA),ownTimeout:s!==void 0})}else if(n==="notify"){let s=t.notifyType==="warning"?"warning":t.notifyType==="error"?"error":"info";this.#p(String(t.message??""),s),console.log(`[composer] pi extension: ${String(t.message??"")}`)}else if(n==="setStatus"){let s=String(t.statusKey??"");typeof t.statusText=="string"&&t.statusText?this.#u.set(s,t.statusText):this.#u.delete(s)}return}default:return}}#k(e){this.#f=e,this.#a=!1,this.#c=0,this.#i=!1,this.#l=null,this.#m=null,this.#t=null,this.#n=null,this.#u.clear(),this.#r=[],this.#h=null,this.#w=null,this.#g=null,this.#e=void 0,this.#E(e)}#E(e){for(let[,t]of this.#s)clearTimeout(t.timer),t.resolve({type:"response",success:!1,error:e});this.#s.clear()}},Yh=r=>new Promise(e=>{setTimeout(e,r).unref?.()})});import{existsSync as Gh,readFileSync as pA,realpathSync as mA}from"fs";import{join as Gt,dirname as Zh,resolve as hA}from"path";import{homedir as zh}from"os";function yA(r,e){let t=Gt(r,".pi");if(gA.some(s=>Gh(Gt(t,s))))return!0;let n=Gt(e,".agents","skills");for(let s=r;;){let i=Gt(s,".agents","skills");if(i!==n&&Gh(i))return!0;let o=Zh(s);if(o===s)return!1;s=o}}function bA(r,e){for(let t=e;;){if(r[t]===!0||r[t]===!1)return!0;let n=Zh(t);if(n===t)return!1;t=n}}function eg(r,e){try{let t=e?.agentDir??Gt(zh(),".pi","agent"),n=Xh(e?.home??process.env.HOME??zh()),s=Xh(hA(r));if(!yA(s,n))return null;let i=Qh(Gt(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||bA(Qh(Gt(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 gA,Xh,Qh,tg=w(()=>{gA=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],Xh=r=>{try{return mA(r)}catch{return r}},Qh=r=>{try{return JSON.parse(pA(r,"utf8"))}catch{return{}}}});import{statSync as wA,openSync as vA,readSync as SA,closeSync as xA,existsSync as ng}from"fs";import{join as yo}from"path";import{homedir as tu}from"os";import{execFile as kA}from"child_process";async function AA(r){let e=yo(tu(),".pi","agent","bin",process.platform==="win32"?"fd.exe":"fd");for(let t of["fd","fdfind",...ng(e)?[e]:[]]){let n=await new Promise(s=>{kA(t,["--base-directory",r,"--type","f","--follow","--hidden","--exclude",".git"],{maxBuffer:67108864},(i,o)=>s(i?null:o))});if(n!==null)return n.split(`
|
|
1522
|
-
`).filter(Boolean).map(s=>s.replace(/\\/g,"/"))}return null}function TA(r){return`--${r.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function rg(r){return r.type==="message"?PA(r.message?.role):r.type==="custom_message"?r.display!==!1:!1}var EA,PA,Ir,ru=w(()=>{Ki();El();Al();Kh();Vh();tg();EA=yo(tu(),".pi","agent","sessions");PA=r=>r==="user"||r==="assistant"||r==="toolResult"||r==="bashExecution";Ir=class extends Pr{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}detectsInstalled(){return ng(yo(tu(),".pi","agent"))}ensureHarnessSupport(){Jh()}createDriver(e,t){let n=new go(e,t),s=eg(e);return s&&n.notice(s,"warning"),n}walkFiles(e){return AA(e)}sessionsDir(e){return yo(EA,TA(e))}listSessionFiles(e){return Hi(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 rg(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:Qe(i)}),{events:n}}if(s.role==="bashExecution")return s.command&&!s.excludeFromContext&&n.push({type:"user",text:`$ ${s.command}`}),{events:n};if(s.role==="assistant"){let i=Array.isArray(s.content)?s.content:[],o=i.filter(d=>d.type==="text").map(d=>d.text??"").join(""),a=i.filter(d=>d.type==="thinking").map(d=>d.thinking??"").join(`
|
|
1523
|
-
`),c=i.filter(d=>d.type==="toolCall").map(d=>({id:d.id??"",name:d.name??"",input:d.arguments??{}}));if(o||a||c.length){let d=Date.parse(e.timestamp??""),p=!isNaN(d)&&d>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:p})}let l=s.usage,f=l?(l.input??0)+(l.output??0)+(l.cacheRead??0)+(l.cacheWrite??0):0,u=l&&f>0&&s.stopReason!=="aborted"&&s.stopReason!=="error"?{in:l.input??0,out:l.output??0,cached:l.cacheRead??0,cacheCreate:l.cacheWrite??0}:void 0;return{events:n,usage:u,model:s.model,cost:l?.cost?.total}}return{events:n}}chainWorking(e){let t;for(let a of e)rg(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=vA(e,"r")}catch{return""}try{let s=65536;try{s=wA(e).size}catch{}let i=(u,d)=>{let p=Buffer.alloc(d),b=SA(t,p,0,d,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 d="";for(let p of u.split(`
|
|
1524
|
-
`))if(p.includes('"session_info"'))try{let b=JSON.parse(p);b?.type==="session_info"&&typeof b.name=="string"&&b.name&&(d=b.name)}catch{}return d},l="";for(let u of o.split(`
|
|
1525
|
-
`))if(!(l||!u.includes('"type"')))try{let d=JSON.parse(u);d?.type==="message"&&d.message?.role==="user"&&(l=this.contentText(d.message.content).replace(/\s+/g," ").trim())}catch{}let f=c(a)||c(o)||l;return f?f.slice(0,200):""}finally{xA(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?Ji(t.data,t.mimeType):"").filter(Boolean).join(`
|
|
1526
|
-
`):""}}});var bo,sg=w(()=>{bo=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});import{execFile as OA}from"child_process";import{promisify as CA}from"util";import{readFile as _A}from"fs/promises";import{resolve as ig,sep as RA}from"path";async function je(r,e){let{stdout:t}=await NA("git",r,{cwd:e,maxBuffer:67108864});return t}async function $r(){if(wo)return wo;try{wo=(await je(["rev-parse","--show-toplevel"],Y)).trim()}catch{}return wo}function IA(r,e){let t=e===" "?r:e;return t==="?"?"U":t}async function ag(){let r=await $r();if(!r)return{repo:!1,root:"",files:[]};try{let e=await je(["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:IA(i[0],i[1])}))}try{let s=await je(["diff","--numstat","HEAD"],r),i=new Map;for(let o of s.split(`
|
|
1527
|
-
`)){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 cg(r){let e=await $r();if(!e)return{ok:!1,error:"not a git repository"};try{if((await je(["status","--porcelain","-z","--",r],e)).startsWith("??")){let s=ig(e,r);if(!s.startsWith(ig(e)+RA))return{ok:!1,error:"outside repository"};let i=await _A(s);return i.includes(0)?nu("Binary file (not shown)",!1):nu(i.toString("utf8"),!0)}let n;try{n=await je(["diff","--no-color","--unified=999999","HEAD","--",r],e)}catch{n=await je(["diff","--no-color","--unified=999999","--",r],e)}return nu(n,!1)}catch(t){return{ok:!1,error:J(t)}}}var NA,og,wo,nu,vo=w(()=>{xt();NA=CA(OA),og=2e6;nu=(r,e)=>({ok:!0,text:r.slice(0,og),untracked:e,truncated:r.length>og})});function So(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 su=w(()=>{});var xo,ko,lg=w(()=>{xo=".typebulb/paste",ko={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 $A,mkdirSync as LA,writeFileSync as MA,readFileSync as DA}from"fs";import{join as Eo}from"path";function ug(){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 qA(r){return r.trim().toLowerCase().replace(/\.[a-z0-9]{1,4}$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function UA(r){let e=AbortSignal.timeout(BA);for(let[t,n]of FA){let s=Ge(t,n);if(typeof s!="string"){try{let i=await gt(s,{messages:[{role:"user",content:`Reply with ONLY a short kebab-case filename (2-5 words, lowercase, no extension) describing this text:
|
|
1528
|
-
|
|
1529
|
-
${r.slice(0,jA)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=qA(await Ut(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function dg(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=Eo(r,xo);try{LA(t,{recursive:!0})}catch(a){return{ok:!1,error:J(a)}}let n,s,i;if(e.kind==="image"){if(n=`img-${ug()}`,s=Object.keys(ko).find(a=>ko[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else n=await UA(e.data)??`paste-${ug()}`,s="md",i=e.data;let o=`${n}.${s}`;for(let a=2;$A(Eo(t,o));a++)o=`${n}-${a}.${s}`;try{MA(Eo(t,o),i)}catch(a){return{ok:!1,error:J(a)}}return{ok:!0,path:`${xo}/${o}`}}function fg(r,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),n=ko[t];if(!n)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:n,base64:DA(Eo(r,xo,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var BA,jA,FA,pg=w(()=>{xr();Nr();xt();lg();BA=4e3,jA=4e3,FA=[["openrouter","google/gemini-3.1-flash-lite-preview"],["gemini","gemini-3.1-flash-lite"]]});import{existsSync as mg,openSync as JA,readSync as KA,closeSync as HA,statSync as Lr,readdirSync as hg,watchFile as WA,unwatchFile as gg,mkdirSync as YA,writeFileSync as VA,readFileSync as Ao,unlinkSync as GA,rmSync as zA}from"fs";import{stat as XA}from"fs/promises";import{dirname as QA,join as zt,resolve as yg}from"path";function rT(r){if(!Number.isInteger(r))return!0;try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}function To(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 v={d:r.createDriver(e.cwd,h),file:h};return t.add(v),e.file||(n=v),v}async function o(h){t.delete(h),n===h&&(n=void 0);try{await h.d.dispose()}catch(v){console.error("[composer] dispose:",J(v))}}function a(){let h=s();for(let v of[...t])v!==h&&(v.d.streaming||v.d.queue||v.d.error||o(v))}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(v=>v.file===n.file);h&&N(h)}}let l=h=>zt(h,eT),f=(h,v)=>zt(l(h),`${v}.lock`);function u(h,v){try{let S=f(h,v);if(Date.now()-Lr(S).mtimeMs>=bg)return!1;try{let C=parseInt(Ao(S,"utf8").trim(),10);if(C===process.pid||!rT(C))return!1}catch{}return!0}catch{return!1}}function d(h,v){if(v)try{YA(l(h),{recursive:!0}),VA(f(h,v),String(process.pid))}catch(S){console.error("[lock] claim failed:",J(S))}}function p(h){try{zA(zt(h,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function b(h){let v=l(h);if(!mg(v))return;let S;try{S=hg(v)}catch{return}let C=Date.now();for(let D of S){if(!D.endsWith(".lock"))continue;let j=zt(v,D);try{let L=Lr(j);C-L.mtimeMs>tT&&GA(j)}catch{}}}function m(h){try{return Lr(h),!1}catch(v){return v.code==="ENOENT"}}function g(){let h=e;if(h.file&&!m(h.file)){d(h.cwd,h.sessionId);return}let v=k(h);v&&N(v)}function k(h){if(!h.everAttached)return A(h.cwd)??P(h.cwd,()=>!0)}function A(h){let v=l(h);if(!mg(v))return;let S;try{S=hg(v)}catch{return}let C;for(let j of S)if(j.endsWith(".lock"))try{let L=Lr(zt(v,j));if(Date.now()-L.mtimeMs>=bg||parseInt(Ao(zt(v,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,v){return r.listSessionFiles(h).sort((S,C)=>C.mtime-S.mtime).find(S=>!u(h,S.sessionId)&&v(S))}function R(h,v){let S=e;if(S.file)try{gg(S.file)}catch{}S.file=h,S.sessionId=v,S.partial="",S.offset=0,S.latest={in:0,out:0,cached:0,cacheCreate:0},S.latestModel=null,S.entries=new Map,S.chainLastId=void 0,S.buffer.push({type:"cleared"}),S.buffer.push({type:"session",sessionId:v})}function N(h){let v=e;n=void 0,R(h.file,h.sessionId),v.everAttached=!0,d(v.cwd,h.sessionId),$();try{gg(h.file)}catch{}WA(h.file,{interval:200},()=>$())}function O(){R(void 0,"")}function $(){let h=e;if(!h.file)return;let v;try{v=Lr(h.file).size}catch{return}if(v<=h.offset)return;let S;try{S=JA(h.file,"r")}catch{return}try{let U=v-h.offset,de=Buffer.alloc(U),te=0;for(;te<U;){let Mu=KA(S,de,te,U-te,h.offset+te);if(!Mu)break;te+=Mu}h.offset+=te,h.partial+=de.subarray(0,te).toString("utf8")}finally{HA(S)}let C,D;for(;(D=h.partial.indexOf(`
|
|
1530
|
-
`))>=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 v=new Map;for(let S of h.values()){let C=r.parentOf(S);if(!C)continue;let D=v.get(C);D?D.push(S):v.set(C,[S])}return v}function y(h,v,S){if(!h)return;let C=v.get(h);if(!C)return;let D=C.filter(U=>!r.isSidechain(U));if(D.length<2)return;let j=D.filter(U=>!S.has(r.idOf(U)));if(!j.length)return;let L=[],H=0;for(let U of j){let de=x(U,v);L.push(...de.events),H+=de.count}H>0&&e.buffer.push({type:"fork",atId:h,count:H,events:L})}function x(h,v){let S=[],C=[h];for(;C.length;){let L=C.pop();if(r.isSidechain(L))continue;S.push(L);let H=v.get(r.idOf(L)??"");if(H)for(let U of H)C.push(U)}S.sort((L,H)=>(Date.parse(r.timestampOf(L)??"")||0)-(Date.parse(r.timestampOf(H)??"")||0));let D=[];for(let L of S)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:v,usage:S,model:C,cost:D}=r.apply(h,e.sessionStartMs);for(let j of v)e.buffer.push(j);v.some(j=>j.type==="assistant")&&s()?.d.clearCompletedDraft(),v.some(j=>j.type==="user")&&s()?.d.clearEcho(),C&&(e.latestModel=C),S&&(e.latest=S),(S||D)&&e.buffer.push({type:"usage",...e.latest,cost:D})}catch(v){console.error("[mirror] skipped malformed entry:",J(v))}}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 $r();if(!h)return;let v=yg(h).toLowerCase();for(let S=yg(e.cwd);S.toLowerCase()!==v;){let C=QA(S);if(C===S)return;S=C;let D=r.listSessionFiles(S).length;if(D)return{dir:S,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 bo;async function K(h,v){W.accept(h,v)&&console.log(v)}function qe(){let h=r.sessionAlive(e.sessionId,e.cwd);if(h!==void 0)return h;if(!e.file)return!1;try{return Date.now()-Lr(e.file).mtimeMs<1e4}catch{return!1}}function z(){return r.chainWorking([...e.entries.values()])&&qe()}function V(){!r.createDriver||s()||e.latestModel||z()||i(e.file)}async function Ue(h){let v=e;g(),c(),V(),a();let S=s();for(let L of t)L!==S&&L.d.dialog;let C=new Set([...t].filter(L=>L.d.streaming&&L.file).map(L=>L.file)),D=C.size?r.listSessionFiles(v.cwd).filter(L=>C.has(L.file)).map(L=>L.sessionId):[],j=r.createDriver?{streaming:!!S?.d.streaming,draft:S?.d.draft??null,echo:S?.d.echo??null,status:S?.d.status??null,dialog:S?.d.dialog??null,queue:S?.d.queue??null,stats:S?.d.stats??null,model:S?.d.model??null,error:S?.d.error}:void 0;return{events:v.buffer.slice(h),cursor:v.buffer.length,working:!!S?.d.streaming||z(),latestModel:v.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 lb(h,v){if(!r.createDriver)return{ok:!1,error:"not supported"};let S=String(h??"").trim();if(!S)return{ok:!1,error:"empty message"};let C=await we();return C.ok?C.d.send(S,v):C}async function ub(h,v){let S=s();return S?S.d.respondUi(String(h??""),v??{}):{ok:!1,error:"no dialog pending"}}async function db(h,v){if(!r.createDriver)return{ok:!1,error:"not supported"};if(!h||typeof h.type!="string")return{ok:!1,error:"bad command"};if(v?.spawn){let C=await we();return C.ok?C.d.rpc(h):C}let S=s();return!S||S.d.error?{ok:!1,error:"not running"}:S.d.rpc(h)}async function fb(){let h=s();if(h)try{await h.d.stop()}catch(v){console.error("[composer] stop:",J(v))}return{ok:!0}}async function pb(){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 mb(){if(!r.createDriver)return[];let h=await je(["ls-files","--cached","--others","--exclude-standard"],e.cwd).catch(()=>null),v=h!==null?h.split(`
|
|
1531
|
-
`).filter(Boolean):await r.walkFiles?.(e.cwd)??[];return(await Promise.all(v.map(async C=>{try{return{f:C,m:(await XA(zt(e.cwd,C))).mtimeMs}}catch{return{f:C,m:0}}}))).sort((C,D)=>D.m-C.m).map(C=>C.f)}function hb(){for(let h of[...t])o(h)}async function gb(h){return r.createDriver?dg(e.cwd,h):{ok:!1,error:"not supported"}}async function yb(h){return fg(e.cwd,String(h??""))}async function bb(){return r.listSessionFiles(e.cwd).sort((h,v)=>v.mtime-h.mtime).map(({sessionId:h,file:v,mtime:S})=>({sessionId:h,mtime:S,preview:r.readPreview(v)}))}let Iu=new Map;function wb(h,v){let S=Iu.get(h);if(S&&S.mtime===v)return S.turns;let C=[],D="";try{D=Ao(h,"utf8")}catch{return[]}for(let j of D.split(`
|
|
1532
|
-
`)){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 Iu.set(h,{mtime:v,turns:C}),C}async function vb(h){let v=h.toLowerCase(),S=[];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}=So(wb(D,j),v);if(L&&(S.push({sessionId:C,mtime:j,preview:r.readPreview(D),hitCount:L,snippet:H}),S.length>=nT))break}return S}let $u=800,Lu=new Map;function Sb(h,v){let S=Lu.get(h);if(S&&S.mtime===v)return S.text;let C="";try{C=Ao(h,"utf8")}catch{return""}let D="";for(let L of C.split(`
|
|
1533
|
-
`)){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>$u?D.slice(0,$u).trimEnd()+"\u2026":D;return Lu.set(h,{mtime:v,text:j}),j}async function xb(h){let v=r.listSessionFiles(e.cwd).find(S=>S.sessionId===h);return{text:v?Sb(v.file,v.mtime):""}}async function kb(h){let v=e,S=r.listSessionFiles(v.cwd).find(C=>C.sessionId===h);return S?S.file===v.file?{ok:!0}:(N(S),c(),a(),{ok:!0}):{ok:!1,error:"session not found"}}return p(e.cwd),b(e.cwd),g(),{info:_,poll:Ue,logEmbedStatus:K,listSessions:bb,searchSessions:vb,sessionPeek:xb,attach:kb,composerSend:lb,composerStop:fb,composerNew:pb,composerFiles:mb,composerUiRespond:ub,composerRpc:db,composerPaste:gb,composerPasteRead:yb,shutdownComposer:hb}}var ZA,eT,bg,tT,nT,iu=w(()=>{xt();sg();vo();su();pg();ZA=".typebulb",eT=`${ZA}/locks`,bg=5e3,tT=6e4;nT=50});import{existsSync as lu,mkdirSync as sT,readFileSync as wg,writeFileSync as iT}from"fs";import{join as Xt,isAbsolute as oT}from"path";async function vg(r,e){let t=oT(r)?r:Xt(Y,r);return lu(t)?(Jl(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function Sg(r){let e=Y,t=Ul(r),n=Xt(e,"typebulbs");sT(n,{recursive:!0});let s=jl(t),i=`${s}.bulb.md`;for(let l=2;lu(Xt(n,i))&&wg(Xt(n,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=Xt(n,i);lu(o)||iT(o,t);let a=Xt("typebulbs",i),c=await Xi(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function xg(){return Q(Y)}async function kg(r){return await Wt(r),{ok:!0}}async function Eg(){return Zi(Y).filter(r=>!r.serverOnly).map(r=>({...r,trusted:Ht(r.path)}))}async function Ag(r){let e=r.toLowerCase(),t=[];for(let n of Zi(Y).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=wg(n.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
|
|
1534
|
-
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=So(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function Tg(r,e){let t=Y;e!=null&&Tr(r,e);let n=await Xi(r,{cwd:t,open:!1,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function Pg(r){return{cap:await ql(r)}}async function Og(r,e){return Tr(r,e),{ok:!0}}async function Cg(r,e){return Ie(r,e)}async function Ig(){return Xn&&Date.now()-Xn.fetchedAt<=cT?Xn.samples:(ou??=lT().finally(()=>{ou=null}),ou)}async function lT(){try{let r=await fetch(`${aT}/api/scripts/u/samples?stubs`,{signal:AbortSignal.timeout(Rg)});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:ra(i.config)}));return Xn={samples:s,fetchedAt:Date.now()},s}catch{return Xn?.samples??[]}}async function $g(r){return uu.test(r)?Dg(_g,"samples",r,!0):{ok:!1,error:"bad slug"}}async function Lg(){let r=du();if(!r)return{bulbs:[]};let e=`${Po()}
|
|
1535
|
-
${r}`;return kt?.key===e&&Date.now()-kt.fetchedAt<=uT?{user:kt.user,bulbs:kt.bulbs}:(au??=dT(e,r).finally(()=>{au=null}),au)}async function cu(r,e,t){let n=await fetch(`${r}${e}`,{headers:t,signal:AbortSignal.timeout(Rg)});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 dT(r,e){let t={Authorization:`Bearer ${e}`};try{let n=Po(),s;try{s=await cu(n,"/api/me",t)}catch{let a=new URL(n);n=`${a.protocol}//api.${a.host}`,s=await cu(n,"/api/me",t)}let o=(await cu(n,"/api/scripts/list",t)).filter(a=>a.userSlug===s.slug&&!a.isTemplate).map(a=>({slug:a.slug,name:a.name,description:ra(a.config)}));return kt={key:r,user:s.slug,bulbs:o,fetchedAt:Date.now()},{user:s.slug,bulbs:o}}catch{return kt?.key===r?{user:kt.user,bulbs:kt.bulbs}:{bulbs:[]}}}async function Mg(r,e,t=!1){return!uu.test(e)||!uu.test(r)?{ok:!1,error:"bad slug"}:Dg(Po(),r,e,t)}async function Dg(r,e,t,n){let s=no(e,t);try{let i=await io({origin:r,userSlug:e,slug:t,dest:Xt(Y,s)},{force:n,token:du(),timeoutMs:Ng});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 Bg(r,e=!1){let t=du();if(!t)return{ok:!1,error:"no TYPEBULB_TOKEN in .env"};try{let n=so(r,Y,Po()),s=await po(n,{token:t,force:e,timeoutMs:Ng});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 aT,_g,cT,Rg,Ng,Xn,ou,uu,uT,kt,au,Po,du,fu=w(()=>{Nr();xt();su();Re();aT="https://api.typebulb.com",_g="https://typebulb.com",cT=3600*1e3,Rg=5e3,Ng=15e3,Xn=null,ou=null;uu=/^[a-z0-9][a-z0-9-]*$/,uT=300*1e3,kt=null,au=null,Po=()=>ro("TYPEBULB_ORIGIN",Y)||_g,du=()=>ro("TYPEBULB_TOKEN",Y)});import{readFileSync as hu,writeFileSync as Fg,mkdirSync as fT,appendFileSync as qg,rmSync as jg}from"fs";import{join as _o,dirname as pT}from"path";import{createServer as mT}from"http";function Et(r){try{return JSON.parse(hu(r,"utf8"))}catch{return null}}function Co(r,e){fT(pT(r),{recursive:!0}),Fg(r,JSON.stringify(e,null,2)+`
|
|
1536
|
-
`)}function Jg(r,e,t){let n=_o(r,".gitignore"),s="";try{s=hu(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(`
|
|
1537
|
-
`)?`
|
|
1538
|
-
`:"";try{qg(n,a+t+`
|
|
1539
|
-
`+o.join(`
|
|
1540
|
-
`)+`
|
|
1541
|
-
`)}catch(c){console.error("[switcher] .gitignore update failed",J(c))}}function wT(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?es="live":s>bT&&(es="uncached")}function Hg(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 vT(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 Wg(r){let e;try{e=JSON.parse(r)}catch{return r}Zn=typeof e?.model=="string"?e.model:null,Fe&&(e.model=Fe),Zt&&(e.provider=Kg(Zt));let t=/haiku/i.test(Zn||"");return ts!=null&&!t&&(e.reasoning={effort:pu[ts]}),delete e.thinking,e.output_config&&delete e.output_config.effort,vT(e),JSON.stringify(e)}function ST(){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}
|
|
1542
|
-
data: ${JSON.stringify(a)}
|
|
1748
|
+
// Build the whole view once the seed arrives (a localhost roundtrip; the shimmer covers it).
|
|
1749
|
+
// Seeding is explicit ctx.data (an arg / setData / a retry's edits) > the bulb's SOURCE
|
|
1750
|
+
// chunks from the server \u2014 never the page's post-run runtime data.
|
|
1751
|
+
fetch('/__infer-info').then(function (r) { return r.json(); })
|
|
1752
|
+
.catch(function () { return {}; })
|
|
1753
|
+
.then(function (info) { buildConfirm(info || {}); });
|
|
1754
|
+
}
|
|
1543
1755
|
|
|
1544
|
-
|
|
1545
|
-
|
|
1756
|
+
function buildConfirm(info) {
|
|
1757
|
+
body.textContent = ''; foot.textContent = ''; areas = [];
|
|
1758
|
+
inferCfg = info.inference || {};
|
|
1759
|
+
if (inferCfg.title) title.textContent = inferCfg.title;
|
|
1546
1760
|
|
|
1547
|
-
|
|
1761
|
+
var model = el('div', 'model');
|
|
1762
|
+
var runBtn = el('button', 'run', inferCfg.submitTitle || 'Run');
|
|
1763
|
+
if (info.error) { model.textContent = info.error; model.className = 'model err'; runBtn.disabled = true; }
|
|
1764
|
+
else if (info.model) model.textContent = info.model + ' \\u00b7 ' + info.provider;
|
|
1765
|
+
else model.textContent = 'Model info unavailable';
|
|
1548
1766
|
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1767
|
+
var chunks = ctx.data && ctx.data.length ? ctx.data
|
|
1768
|
+
: (info.data && info.data.length ? info.data : ['']);
|
|
1769
|
+
var titles = dataTitles();
|
|
1770
|
+
// Multi-chunk: .com's shape \u2014 a tab per chunk (label + live char count), one textarea visible.
|
|
1771
|
+
var multi = chunks.length > 1;
|
|
1772
|
+
var tabBtns = [];
|
|
1773
|
+
var counts = [];
|
|
1774
|
+
var strip = multi ? el('div', 'tabs') : null;
|
|
1775
|
+
if (strip) body.appendChild(strip);
|
|
1776
|
+
function formatCount(n) { return n < 10000 ? String(n) : Math.round(n / 1000) + 'K'; }
|
|
1777
|
+
function selectTab(i) {
|
|
1778
|
+
tabBtns.forEach(function (b, j) { b.className = j === i ? 'tab on' : 'tab'; });
|
|
1779
|
+
areas.forEach(function (a, j) { a.style.display = j === i ? '' : 'none'; });
|
|
1780
|
+
}
|
|
1781
|
+
chunks.forEach(function (chunk, i) {
|
|
1782
|
+
if (multi) {
|
|
1783
|
+
var tab = el('button', 'tab');
|
|
1784
|
+
tab.appendChild(el('span', '', chunkLabel(chunk, i, titles)));
|
|
1785
|
+
var cnt = el('span', 'cnt', '(' + formatCount(chunk.length) + ')');
|
|
1786
|
+
counts.push(cnt);
|
|
1787
|
+
tab.appendChild(cnt);
|
|
1788
|
+
tab.addEventListener('click', function () { selectTab(i); });
|
|
1789
|
+
tabBtns.push(tab);
|
|
1790
|
+
strip.appendChild(tab);
|
|
1791
|
+
} else {
|
|
1792
|
+
body.appendChild(el('label', '', titles[0] || 'Data to process'));
|
|
1793
|
+
}
|
|
1794
|
+
var ta = document.createElement('textarea');
|
|
1795
|
+
ta.value = chunk;
|
|
1796
|
+
if (!chunk) ta.placeholder = 'Paste data to process (optional)\\u2026';
|
|
1797
|
+
ta.addEventListener('input', function () {
|
|
1798
|
+
// 2 blank lines IS the chunk separator \u2014 collapse pasted 3+ so text can't silently split (.com parity)
|
|
1799
|
+
var v = ta.value.replace(/\\n{3,}/g, '\\n\\n');
|
|
1800
|
+
if (v !== ta.value) ta.value = v;
|
|
1801
|
+
if (multi) counts[i].textContent = '(' + formatCount(ta.value.length) + ')';
|
|
1802
|
+
});
|
|
1803
|
+
areas.push(ta);
|
|
1804
|
+
body.appendChild(ta);
|
|
1805
|
+
});
|
|
1806
|
+
if (multi) selectTab(0);
|
|
1807
|
+
// The model line reads as a footnote to the action, not a header to the data \u2014 under the
|
|
1808
|
+
// textareas, above the buttons.
|
|
1809
|
+
body.appendChild(model);
|
|
1555
1810
|
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
typebulbs/u/<user>/<slug>.bulb.md (a local file
|
|
1592
|
-
at that path re-pulls in place). Unlisted and
|
|
1593
|
-
public bulbs need no login; a differing local
|
|
1594
|
-
file is refused unless --force.
|
|
1595
|
-
typebulb push <file> Upload a typebulbs/u/<user>/<slug>.bulb.md to
|
|
1596
|
-
typebulb.com as you (needs TYPEBULB_TOKEN in
|
|
1597
|
-
.env, minted on the settings page). Refused if
|
|
1598
|
-
the remote changed since your last pull/push,
|
|
1599
|
-
unless --force. A new slug is created unlisted.
|
|
1600
|
-
typebulb wait [file|agent] Block until the target server logs a new line,
|
|
1601
|
-
print it, exit (2: timeout; 3: server died).
|
|
1602
|
-
For agents: run it in the background \u2014 the exit
|
|
1603
|
-
is your wake-up ('wait agent': embed outcomes;
|
|
1604
|
-
'wait <file>': the bulb's own console.log).
|
|
1605
|
-
Resumes where your last wait/call left off, so
|
|
1606
|
-
an event that beats the wait still fires it.
|
|
1607
|
-
typebulb stop [file|pid|agent] Stop a running bulb or mirror (no arg: list this
|
|
1608
|
-
project's running servers; a pid/path/agent stops any).
|
|
1609
|
-
Batch flags: --bulbs (this project's bulbs, the
|
|
1610
|
-
mirror survives), --agent (this project's mirror),
|
|
1611
|
-
--global (every bulb + mirror, all projects).
|
|
1612
|
-
typebulb trust [file] Remember a bulb as Trusted, so a later run grants
|
|
1613
|
-
fs/AI/server.ts without --trust (no arg: list the
|
|
1614
|
-
remembered-trusted bulbs).
|
|
1615
|
-
typebulb untrust <file> Forget a bulb's trust (back to Restricted).
|
|
1811
|
+
// Fragment-driven actions (TB-Inference.md): the address bar holds the last completed run, so
|
|
1812
|
+
// both appear exactly when one exists. Copy = share it; Save = promote it to the bulb's source.
|
|
1813
|
+
if (location.hash.indexOf('tb=') !== -1) {
|
|
1814
|
+
var grp = el('div', 'leftgrp');
|
|
1815
|
+
var share = el('button', '', 'Copy share URL');
|
|
1816
|
+
share.title = 'Copies this page URL with the #tb= result fragment \\u2014 paste the fragment onto the published bulb\\u2019s URL to share the last run';
|
|
1817
|
+
share.addEventListener('click', function () {
|
|
1818
|
+
navigator.clipboard.writeText(location.href).then(function () {
|
|
1819
|
+
share.textContent = 'Copied \\u2713';
|
|
1820
|
+
setTimeout(function () { share.textContent = 'Copy share URL'; }, 1500);
|
|
1821
|
+
});
|
|
1822
|
+
});
|
|
1823
|
+
grp.appendChild(share);
|
|
1824
|
+
var save = el('button', '', 'Save to bulb');
|
|
1825
|
+
save.title = 'Write this run\\u2019s data + insight into the .bulb.md as its new defaults';
|
|
1826
|
+
save.addEventListener('click', function () {
|
|
1827
|
+
save.disabled = true;
|
|
1828
|
+
fetch('/__infer-save', {
|
|
1829
|
+
method: 'POST',
|
|
1830
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1831
|
+
body: JSON.stringify({ hash: location.hash })
|
|
1832
|
+
}).then(async function (r) {
|
|
1833
|
+
if (!r.ok) { var t = await r.text(); var err; try { err = JSON.parse(t).message; } catch (e) { err = t; } throw new Error(err || 'Save failed'); }
|
|
1834
|
+
}).then(function () {
|
|
1835
|
+
// The run is source now \u2014 clear the runtime layer. Under watch, the file write is about
|
|
1836
|
+
// to hot-reload the page onto its new defaults anyway.
|
|
1837
|
+
history.replaceState(null, '', location.pathname + location.search);
|
|
1838
|
+
save.textContent = 'Saved \\u2713';
|
|
1839
|
+
}).catch(function (e) {
|
|
1840
|
+
save.textContent = 'Save failed'; save.title = e.message; save.disabled = false;
|
|
1841
|
+
});
|
|
1842
|
+
});
|
|
1843
|
+
grp.appendChild(save);
|
|
1844
|
+
foot.appendChild(grp);
|
|
1845
|
+
}
|
|
1616
1846
|
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
-n, --lines <n> Print only the last n lines (logs)
|
|
1624
|
-
--match <substring> Only lines containing this literal substring end
|
|
1625
|
-
the wait \u2014 not a regex (wait)
|
|
1626
|
-
--force Overwrite the side the command writes to: a
|
|
1627
|
-
differing local file (pull), or a remote that
|
|
1628
|
-
changed since your last sync (push)
|
|
1629
|
-
--timeout <sec> Give up after this long; exit 2 \u2014 bounds only a
|
|
1630
|
-
manual (foreground) bulb wait, default 1800 (wait)
|
|
1631
|
-
--wait[=ms] For 'send': bound the whole exchange \u2014 retry while
|
|
1632
|
-
no page is connected (a hot reload's gap), then
|
|
1633
|
-
hold for the handlers' replies (default 5000).
|
|
1634
|
-
Use it right after an edit, and for any send
|
|
1635
|
-
whose reply you read.
|
|
1636
|
-
--no-watch Disable hot reload (watch is on by default)
|
|
1637
|
-
-p, --port <port> Use a specific port (default: 3000)
|
|
1638
|
-
--open Force-open the external browser (default off
|
|
1639
|
-
inside VS Code's integrated terminal)
|
|
1640
|
-
--no-open Don't auto-open browser
|
|
1641
|
-
--trust Grant privileged capabilities (filesystem, AI,
|
|
1642
|
-
and server.ts) for this run. Without it a bulb runs
|
|
1643
|
-
Restricted: tb.fs / tb.ai / tb.server are blocked and
|
|
1644
|
-
the page shows the exact --trust command to unlock
|
|
1645
|
-
them. A bulb remembered via 'typebulb trust' runs
|
|
1646
|
-
trusted without this flag.
|
|
1647
|
-
--no-trust Force a Restricted run even if the bulb is
|
|
1648
|
-
remembered-trusted (overrides the trust store).
|
|
1649
|
-
--mode <name> Also load .env.<name> (+ .env.<name>.local) on top
|
|
1650
|
-
of .env / .env.local. Free-form name; loads no mode
|
|
1651
|
-
file by default.
|
|
1652
|
-
--dir <sub> Scope the bulb's dir to a subfolder for this run:
|
|
1653
|
-
tb.dir and relative tb.fs paths land in
|
|
1654
|
-
<bulb-folder>/<sub>. Batch runs without touching
|
|
1655
|
-
the bulb's code (e.g. --dir batch2). Relative
|
|
1656
|
-
subpaths only \u2014 no absolute paths or '..'.
|
|
1657
|
-
--server Run server.ts only, no web server (needs --trust)
|
|
1658
|
-
--args <json-array> For 'call': the whole argument list as one JSON
|
|
1659
|
-
array (strict). '--args -' reads it from stdin,
|
|
1660
|
-
sidestepping shell quoting.
|
|
1661
|
-
--replace <name>=<path> Replace a declared dependency with a local built
|
|
1662
|
-
package folder instead of a CDN (dev only).
|
|
1663
|
-
Applies to both run and check. Watched for
|
|
1664
|
-
rebuilds under --watch; --no-watch freezes it.
|
|
1665
|
-
e.g. --replace tensorgrad=../tensorgrad
|
|
1666
|
-
-V, --version Show version number
|
|
1667
|
-
-h, --help Show this help message
|
|
1847
|
+
var cancel = el('button', '', 'Cancel');
|
|
1848
|
+
cancel.addEventListener('click', function () { close('cancel'); });
|
|
1849
|
+
foot.appendChild(cancel);
|
|
1850
|
+
runBtn.addEventListener('click', run);
|
|
1851
|
+
foot.appendChild(runBtn);
|
|
1852
|
+
}
|
|
1668
1853
|
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1854
|
+
// \u2500\u2500 Streaming / error states \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1855
|
+
function run() {
|
|
1856
|
+
var data = areas.map(function (a) { return a.value.trim(); }).filter(function (v) { return v !== ''; });
|
|
1857
|
+
ctx.data = data; // a retry's confirm re-seeds from the edited chunks, not the originals
|
|
1858
|
+
body.textContent = ''; foot.textContent = '';
|
|
1674
1859
|
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1860
|
+
var pre = el('pre', 'stream', '');
|
|
1861
|
+
var waiting = el('span', 'shimmer', 'Waiting for response\\u2026');
|
|
1862
|
+
pre.appendChild(waiting);
|
|
1863
|
+
var textNode = null;
|
|
1864
|
+
body.appendChild(pre);
|
|
1865
|
+
var cancel = el('button', '', 'Cancel');
|
|
1866
|
+
cancel.addEventListener('click', function () { close('cancel'); });
|
|
1867
|
+
foot.appendChild(cancel);
|
|
1868
|
+
|
|
1869
|
+
aborter = new AbortController();
|
|
1870
|
+
(async function () {
|
|
1871
|
+
var resp = await fetch('/__infer', {
|
|
1872
|
+
method: 'POST',
|
|
1873
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1874
|
+
body: JSON.stringify({ data: data }),
|
|
1875
|
+
signal: aborter.signal
|
|
1876
|
+
});
|
|
1877
|
+
if (resp.headers.get('X-TB-Stream') !== '1') {
|
|
1878
|
+
// Non-stream response: a 403 trust denial (plain text) or a 400/500 JSON error.
|
|
1879
|
+
var text = await resp.text();
|
|
1880
|
+
var err; try { err = JSON.parse(text); } catch (e) { err = { message: text, code: 'unknown', retryable: false }; }
|
|
1881
|
+
var e2 = new Error(err.message || 'Inference failed'); e2.code = err.code; e2.retryable = !!err.retryable;
|
|
1882
|
+
throw e2;
|
|
1883
|
+
}
|
|
1884
|
+
var final = null;
|
|
1885
|
+
for await (var v of ctx.readStream(resp)) {
|
|
1886
|
+
if (v.kind === 'delta') {
|
|
1887
|
+
if (waiting) { waiting.remove(); waiting = null; textNode = document.createTextNode(''); pre.appendChild(textNode); }
|
|
1888
|
+
textNode.appendData(v.text); pre.scrollTop = pre.scrollHeight;
|
|
1889
|
+
}
|
|
1890
|
+
else if (v.kind === 'complete') final = v;
|
|
1891
|
+
}
|
|
1892
|
+
if (!final) { var e3 = new Error('Stream ended without a result'); e3.code = 'network'; e3.retryable = true; throw e3; }
|
|
1893
|
+
completed = true;
|
|
1894
|
+
ctx.onComplete(final);
|
|
1895
|
+
close('complete');
|
|
1896
|
+
})().catch(function (err) {
|
|
1897
|
+
if (canceled) return; // user canceled; close() already ran and the abort rejection is expected
|
|
1898
|
+
showError(err);
|
|
1899
|
+
});
|
|
1900
|
+
}
|
|
1681
1901
|
|
|
1682
|
-
|
|
1683
|
-
|
|
1902
|
+
function showError(err) {
|
|
1903
|
+
body.textContent = ''; foot.textContent = '';
|
|
1904
|
+
body.appendChild(el('div', 'error', err.message || 'Inference failed'));
|
|
1905
|
+
ctx.onError({ message: err.message, code: err.code || 'unknown', retryable: !!err.retryable });
|
|
1684
1906
|
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
Both can be overridden per-call: tb.ai({ provider: "openai", model: "gpt-5.4-mini", ... })
|
|
1695
|
-
Don't guess a model id \u2014 run 'typebulb models' to list the exact ids your keys cover.
|
|
1696
|
-
Optional effort level (1=low, 2=med, 3=high; omit for the model's native default):
|
|
1697
|
-
tb.ai({ ..., effort: 2 })
|
|
1907
|
+
var closeBtn = el('button', '', 'Close');
|
|
1908
|
+
closeBtn.addEventListener('click', function () { close('cancel'); });
|
|
1909
|
+
foot.appendChild(closeBtn);
|
|
1910
|
+
if (err.retryable) {
|
|
1911
|
+
var retry = el('button', 'run', 'Retry');
|
|
1912
|
+
retry.addEventListener('click', showConfirm);
|
|
1913
|
+
foot.appendChild(retry);
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1698
1916
|
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
`)}
|
|
1704
|
-
|
|
1705
|
-
* Get raw data chunk from the Data tab.
|
|
1706
|
-
* @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
|
|
1707
|
-
*/
|
|
1708
|
-
data(index: number): string;
|
|
1709
|
-
/**
|
|
1710
|
-
* Get data chunk parsed as JSON (handles JSON-ish with unquoted keys).
|
|
1711
|
-
* @param index - Chunk index (0-based)
|
|
1712
|
-
* @throws If chunk is not valid JSON/JSON-ish
|
|
1713
|
-
*/
|
|
1714
|
-
json<T = unknown>(index: number): T;`,SP=`
|
|
1715
|
-
/**
|
|
1716
|
-
* Get the insight data produced by the inference layer.
|
|
1717
|
-
*
|
|
1718
|
-
* Returns the parsed JSON from insight.json, populated by the inference LLM.
|
|
1719
|
-
* Use a type parameter to get typed access to the insight data.
|
|
1720
|
-
*
|
|
1721
|
-
* @returns The parsed insight JSON, or undefined if no insight is available
|
|
1722
|
-
*/
|
|
1723
|
-
insight<T = unknown>(): T | undefined;`,py=`options: {
|
|
1724
|
-
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
1725
|
-
system?: string;
|
|
1726
|
-
/** 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. */
|
|
1727
|
-
effort?: 0 | 1 | 2 | 3;
|
|
1728
|
-
provider?: string;
|
|
1729
|
-
model?: string;
|
|
1730
|
-
/** Enable/disable web search. Default: on for BYOK, always off for free model. */
|
|
1731
|
-
webSearch?: boolean;
|
|
1732
|
-
/** Abort the request. On abort the promise rejects / the stream ends. */
|
|
1733
|
-
signal?: AbortSignal;
|
|
1734
|
-
}`,my=`
|
|
1735
|
-
/** A single streamed delta from \`tb.ai.stream()\`. Discriminated by \`kind\`. */
|
|
1736
|
-
type AiChunk =
|
|
1737
|
-
| { kind: "text"; text: string }
|
|
1738
|
-
| { kind: "reasoning"; text: string };
|
|
1739
|
-
`,hy=`
|
|
1740
|
-
/**
|
|
1741
|
-
* General-purpose AI call. \`tb.ai(opts)\` resolves with the full text; \`tb.ai.stream(opts)\`
|
|
1742
|
-
* returns an async iterable of {@link AiChunk} deltas you consume with \`for await\`.
|
|
1743
|
-
*
|
|
1744
|
-
* @returns Promise resolving to { text: string }
|
|
1745
|
-
* @throws On rate limit, network error, or provider error
|
|
1746
|
-
*/
|
|
1747
|
-
ai: {
|
|
1748
|
-
(${py}): Promise<{ text: string }>;
|
|
1749
|
-
/**
|
|
1750
|
-
* Streaming counterpart of \`tb.ai()\`. Yields \`{ kind: "text" | "reasoning", text }\` deltas
|
|
1751
|
-
* as they arrive; break the loop (or abort \`signal\`) to cancel and stop the upstream.
|
|
1752
|
-
*
|
|
1753
|
-
* \`kind: "reasoning"\` deltas only arrive when you pass \`effort: 1-3\` AND use a
|
|
1754
|
-
* thinking-capable model; otherwise the stream is \`text\`-only.
|
|
1755
|
-
*
|
|
1756
|
-
* @example
|
|
1757
|
-
* let answer = "";
|
|
1758
|
-
* for await (const c of tb.ai.stream({ messages })) {
|
|
1759
|
-
* if (c.kind === "text") answer += c.text;
|
|
1760
|
-
* }
|
|
1761
|
-
*/
|
|
1762
|
-
stream(${py}): AsyncIterable<AiChunk>;
|
|
1763
|
-
};`,gy=`
|
|
1764
|
-
/**
|
|
1765
|
-
* Returns AI models available to the current user.
|
|
1766
|
-
* Models are filtered by the user's configured API keys.
|
|
1767
|
-
* If no keys are configured, returns only the courtesy model.
|
|
1768
|
-
*/
|
|
1769
|
-
models(): Promise<Array<{
|
|
1770
|
-
/** Provider protocol: "anthropic", "openai", "gemini", "openrouter" */
|
|
1771
|
-
provider: string;
|
|
1772
|
-
/** Model identifier, e.g. "claude-sonnet-4-6" */
|
|
1773
|
-
name: string;
|
|
1774
|
-
/** Human-readable display name, e.g. "Sonnet 4.6" */
|
|
1775
|
-
friendlyName: string;
|
|
1776
|
-
/** Provider display name, e.g. "Anthropic" */
|
|
1777
|
-
providerName: string;
|
|
1778
|
-
/** True on the .env-configured default model (TB_AI_PROVIDER + TB_AI_MODEL); absent otherwise */
|
|
1779
|
-
default?: boolean;
|
|
1780
|
-
}>>;
|
|
1781
|
-
/**
|
|
1782
|
-
* Whether the user's own AI keys back \`tb.ai\`. False means only the
|
|
1783
|
-
* quota-limited courtesy model is available (or no AI at all) \u2014 a bulb
|
|
1784
|
-
* making many AI calls should check this and show a "use your own keys"
|
|
1785
|
-
* notice instead of running.
|
|
1786
|
-
*/
|
|
1787
|
-
hasOwnKeys(): Promise<boolean>;`,xP="\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;",yy=`
|
|
1788
|
-
/**
|
|
1789
|
-
* The mode this bulb is running in.
|
|
1790
|
-
*
|
|
1791
|
-
* - \`'local'\` \u2014 Running via the typebulb CLI
|
|
1792
|
-
* - \`'editor'\` \u2014 Running in the typebulb.com editor
|
|
1793
|
-
* - \`'published'\` \u2014 Running as a published/standalone bulb on typebulb.com
|
|
1794
|
-
* - \`'embedded'\` \u2014 Running as a bulb embedded inside another bulb (sandboxed,
|
|
1795
|
-
* client-only: AI, filesystem, and server RPC are unavailable)
|
|
1796
|
-
*/
|
|
1797
|
-
mode: 'local' | 'editor' | 'published' | 'embedded';`,by=`
|
|
1798
|
-
/**
|
|
1799
|
-
* Local filesystem access (CLI only).
|
|
1800
|
-
*
|
|
1801
|
-
* Relative paths resolve against the bulb's folder (\`tb.dir\` \u2014
|
|
1802
|
-
* \`<bulb-dir>/<filename-stem>/\`, created on demand), so
|
|
1803
|
-
* \`tb.fs.write('results.json')\` lands beside the bulb. \`../\` reaches sibling
|
|
1804
|
-
* bulbs' folders; everything stays confined to the project (the launch cwd).
|
|
1805
|
-
* Throws in editor/published mode.
|
|
1806
|
-
*/
|
|
1807
|
-
fs: {
|
|
1808
|
-
/** Read a file as UTF-8 text. Throws if the file is not valid UTF-8 \u2014 use readBytes for binary. */
|
|
1809
|
-
read(path: string): Promise<string>;
|
|
1810
|
-
/** Read a file as raw bytes. */
|
|
1811
|
-
readBytes(path: string): Promise<Uint8Array>;
|
|
1812
|
-
/** Write text or raw bytes to a file. Creates parent directories if needed. */
|
|
1813
|
-
write(path: string, content: string | Uint8Array): Promise<boolean>;
|
|
1814
|
-
};`,wy=`
|
|
1815
|
-
/**
|
|
1816
|
-
* The bulb's folder \u2014 absolute path to \`<bulb-dir>/<filename-stem>/\`
|
|
1817
|
-
* (or its subfolder when the run is scoped with \`--dir\`).
|
|
1818
|
-
*
|
|
1819
|
-
* For interop only (handing a path to \`server.ts\` or a spawned tool):
|
|
1820
|
-
* \`tb.fs\` already resolves relative paths against it, so bulb code writing
|
|
1821
|
-
* its own files never needs it. CLI only \u2014 throws in editor/published/embedded mode.
|
|
1822
|
-
*/
|
|
1823
|
-
readonly dir: string;`,kP=`
|
|
1824
|
-
/**
|
|
1825
|
-
* Async value inspector for tensor-like objects.
|
|
1826
|
-
*
|
|
1827
|
-
* Materializes lazy values (like GPU tensors) and logs them with metadata.
|
|
1828
|
-
* Handles objects with \`.js()\`, \`.data()\`, \`.array()\`, \`.arraySync()\`, etc.
|
|
1829
|
-
*
|
|
1830
|
-
* @remarks
|
|
1831
|
-
* - Always use \`await\` - materialization may be async (GPU\u2192CPU readback)
|
|
1832
|
-
* - Large values are truncated (max 1000 elements)
|
|
1833
|
-
* - Promises are logged as \`[Promise]\` (not awaited - could hang)
|
|
1834
|
-
*/
|
|
1835
|
-
dump(...args: any[]): Promise<void>;
|
|
1836
|
-
/**
|
|
1837
|
-
* Trigger inference to generate new insight data.
|
|
1838
|
-
*
|
|
1839
|
-
* Opens a confirmation modal showing the data to be analyzed, then streams
|
|
1840
|
-
* the inference result. On success, updates the insight so subsequent
|
|
1841
|
-
* \`tb.insight()\` calls return the new value.
|
|
1842
|
-
*
|
|
1843
|
-
* @param opts - Options for inference
|
|
1844
|
-
* @param opts.data - Data to pre-populate in the modal (string or array of strings). If omitted, modal opens with empty textarea for user to paste.
|
|
1845
|
-
* @returns Promise that resolves with the parsed insight JSON
|
|
1846
|
-
* @throws If inference is already in progress, or on network/parse/rate limit errors
|
|
1847
|
-
*/
|
|
1848
|
-
infer<T = unknown>(opts?: { data?: string | string[] }): Promise<T>;
|
|
1849
|
-
/**
|
|
1850
|
-
* Get the current inference state.
|
|
1851
|
-
*
|
|
1852
|
-
* @returns 'idle' | 'running' | 'complete' | 'error'
|
|
1853
|
-
*/
|
|
1854
|
-
inferenceState(): 'idle' | 'running' | 'complete' | 'error';
|
|
1855
|
-
/**
|
|
1856
|
-
* Set a data chunk for the next inference call.
|
|
1857
|
-
*
|
|
1858
|
-
* Use this to programmatically set data that will be sent when \`tb.infer()\` is called
|
|
1859
|
-
* without the \`data\` option.
|
|
1860
|
-
*
|
|
1861
|
-
* @param index - The chunk index (0-based)
|
|
1862
|
-
* @param content - The content for this chunk
|
|
1863
|
-
*/
|
|
1864
|
-
setData(index: number, content: string): void;
|
|
1865
|
-
/**
|
|
1866
|
-
* Proxy a CDN URL through the sandbox origin for Web Worker/WASM same-origin loading.
|
|
1867
|
-
*
|
|
1868
|
-
* In the sandbox, prepends \`/proxy/\` so the URL is served from the same origin.
|
|
1869
|
-
* Outside the sandbox (exported HTML, CLI), returns the URL unchanged.
|
|
1870
|
-
*
|
|
1871
|
-
* @param url - Full HTTPS URL to an allowlisted CDN (esm.sh, unpkg.com, cdn.jsdelivr.net, cdnjs.cloudflare.com)
|
|
1872
|
-
* @returns The proxied URL (sandbox) or the original URL (standalone/CLI)
|
|
1873
|
-
*/
|
|
1874
|
-
proxy(url: string): string;
|
|
1875
|
-
/**
|
|
1876
|
-
* Copy text to clipboard.
|
|
1877
|
-
* Must be called synchronously within a user gesture (click/keydown).
|
|
1878
|
-
* @returns true if successful, false otherwise
|
|
1879
|
-
*/
|
|
1880
|
-
copy(text: string): Promise<boolean>;
|
|
1881
|
-
/**
|
|
1882
|
-
* Get the canonical URL of this bulb.
|
|
1883
|
-
*
|
|
1884
|
-
* Returns the parent typebulb.com URL (including path, query, and \`#tb=\` fragment),
|
|
1885
|
-
* resolving correctly from inside the cross-origin sandbox iframe.
|
|
1886
|
-
* Use this instead of \`location.href\` or \`document.referrer\`.
|
|
1887
|
-
*
|
|
1888
|
-
* @returns The full canonical URL
|
|
1889
|
-
*/
|
|
1890
|
-
url(): Promise<string>;`,EP="\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;",AP="\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>>;",ku=`${my}
|
|
1891
|
-
/**
|
|
1892
|
-
* Typebulb utilities namespace.
|
|
1893
|
-
* Type \`tb.\` to discover available helpers.
|
|
1894
|
-
*/
|
|
1895
|
-
declare const tb: {${vP}${kP}${SP}${AP}${EP}${hy}${by}${wy}${gy}${xP}${yy}
|
|
1896
|
-
};
|
|
1897
|
-
`,Eu=`${my}
|
|
1898
|
-
/**
|
|
1899
|
-
* Typebulb utilities namespace (server-side).
|
|
1900
|
-
* Type \`tb.\` to discover available helpers.
|
|
1901
|
-
*/
|
|
1902
|
-
declare const tb: {${hy}${by}${wy}${gy}${yy}
|
|
1903
|
-
};
|
|
1904
|
-
`;He();import CP from"p-limit";He();import{resolve as Sy}from"resolve.exports";var Ze={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},rs=["index.d.ts","index.d.mts"],Au=/\.d\.(ts|mts|cts)$/i;function Lo(r){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(r)||/[?&]dts(?:[&#]|$)/i.test(r)}function vy(r){return[`${r}.d.ts`,`${r}.d.mts`]}function At(r){if(!r||r==="./"||r==="/")return[...rs];let e=r.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=vy(e),n=e.endsWith("/")?e:`${e}/`;return t.push(...vy(`${n}index`)),t}async function Br(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(TP(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function TP(r){return r===408||r===429||r>=500&&r<600}var Mo=class{constructor(e,t){this.fetchDts=e,this.cdnClient=t}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||Lo(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 Br(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=Dt(e.path);if(!o||o==="/"||o===".")return this.tryUntilSuccess([...rs],t);if(!Au.test(o)){let a=await this.tryUntilSuccess(At(o),t);if(a)return a}return t(o)}let s=At(e.path),i=n?.subpath?[...s,...rs]:[...rs,...s];return this.tryUntilSuccess(i,t)}toResolutionResult(e){return{kind:Au.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=Kc(t.subpath),d=this.resolveExportsPath(n,u);if(d){let b=await this.resolveFromSelected(this.toResolutionResult(d),c,{subpath:!0});if(b)return{...b,resolvedPkg:a}}let p=await this.tryUntilSuccess(At(u),c);if(p)return{...p,resolvedPkg:a}}let l=n.types??n.typings;if(l){let u=await this.resolveFromSelected({kind:"types",path:l},c);if(u)return{...u,resolvedPkg:o}}let f=this.resolveExportsPath(n,".");if(f){let u=await this.resolveFromSelected(this.toResolutionResult(f),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=Dt(n),i=new URL(s,e).toString(),o=await this.tryUrls([i]);return o?{dts:o.dts,url:o.url,resolvedPkg:t}:void 0}};He();import{gunzipSync as PP}from"fflate";var Do=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Br(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=PP(e),s=new TextDecoder("utf-8"),i=0;for(;i<n.length-512;){let o=n.slice(i,i+512);if(o[0]===0)break;let a=o.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),f=o.slice(124,136),u=s.decode(f).trim().replace(/\0/g,""),d=parseInt(u,8)||0,p=String.fromCharCode(o[156]);if(i+=512,(p==="0"||p==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let b=n.slice(i,i+d);t.set(this.normalizeTarPath(l),s.decode(b))}i+=Math.ceil(d/512)*512}}catch{}return t}};var Bo=class{constructor(e,t,n=new Do){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=Bt.majorOf(n),o=e.filter(a=>Bt.majorOf(a)===i);if(o.length)return o.sort((a,c)=>Bt.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=At(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 jo=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(`
|
|
1905
|
-
`).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
|
|
1906
|
-
`),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://"))}};He();var xy="file:///node_modules",Fo=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${xy}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=Dt(t);return`${xy}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as OP}from"lru-cache";function ky(r){let e=new OP({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 Br(s,{init:{cache:"no-store"}});if(!c?.ok){c?.status===404&&(e.set(s,!0),await r.recordNegative(s));return}let l=await c.text(),f=c.url||s;return await r.clearNegative(s),await r.setCachedFile(f,l),{dts:l,url:f}})();return t.set(s,a),await a.finally(()=>t.delete(s))}catch{return}}}var ns=class{constructor(e){this.inFlight=new Map,this.scanner=new jo,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=ky(e.cache),this.typescriptProvider=new Mo(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Bo(e.cdnClient,e.cache),this.virtualFs=new Fo}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 f of l)await this.tryRelativeRef(f,c,o,n,s,i)}catch{}}async tryRelativeRef(e,t,n,s,i,o){try{let a=new URL(e,t),c=a.pathname+a.search,l=Lo(c)?[c]:At(c);for(let f of l){let d=new URL(f,a).toString();if(o.has(d))return;let p=await this.fetchDts(d);if(p?.dts){let 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=CP(Ze.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,Ze.maxBareDepth,a,i).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,i,o){if(s<=0||i.has(e))return;i.add(e);let a=await this.fetchRootDts(e,o);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):n.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let f=this.scanner.collectBareModuleRefs(a.dts).slice(0,Ze.maxBareDeps).filter(u=>!i.has(u));for(let u of f)await this.prefetchBareDepsRecursive(u,t,n,s-1,i,o)}async resolve(e,t,n){let s=await this.packageService.extractImports(e),i=n?[...s,...n]:s;return(await Promise.all(i.map(a=>this.resolveOne(a,t)))).filter(a=>!!a)}async resolveOne(e,t){let{effectivePackage:n}=await this.versionResolver.effectivePackage(e,t);return this.withInFlight(n,async()=>{let s=new 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:f,packageRootUrl:u}=this.computeEntryPath(o,l),d=[{path:f,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,d,void 0,u);let b=d.map(A=>A.content).join(`
|
|
1907
|
-
`);await this.prefetchBareDeps(b,l,d,p,s);let m=c.format(),g=e===m?[e]:[e,m],k=g.some(A=>this.ambientlyDeclares(i,A));return k?this.markFileAmbient(d,f):p.push(...g.map(A=>({module:A,path:f}))),{pkg:e,mainPath:f,files:d,shims:p,ambient:k}}};el();He();yr();Nn();Qc();gr();import*as jr from"path";var _P=jr.join(wi,"pkg"),RP=jr.join(wi,"files"),NP=jr.join(wi,"negative.json"),Uo=class{pkgMem=new Map;fileMem=new Map;negativeCache=new jt(new br(NP));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await G();let t=await We(Ey(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 qo(async()=>{await G(),await he(Ey(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await G();let t=await bi(Ay(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await qo(async()=>{await G(),await he(Ay(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await qo(async()=>{await G(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return qo(()=>this.negativeCache.clearNegative(e))}};async function qo(r){try{await r()}catch{}}function Ey(r){return jr.join(_P,xe(r)+".json")}function Ay(r){return jr.join(RP,xe(r)+".txt")}yr();var Tu;function IP(){return Tu||(Tu=new ns({cache:new Uo,cdnClient:Cm,packageService:ki,versionResolver:Om})),Tu}var Ty="file:///node_modules/";async function Py(r){let e=vi(r.emitKey,"typecheck");await G(),await ae.rm(e,{recursive:!0,force:!0}),await ae.mkdir(e,{recursive:!0});let t=DP(r.jsxImportSource,r.dependencies),n=await IP().resolve(r.code,r.dependencies,t),s=r.local?.name,i=s?n.filter(f=>f.pkg!==s):n,o=new Set;for(let f of i)for(let u of f.files){let d=Jo(u.path);if(!d||o.has(d))continue;o.add(d);let p=ie.join(e,"node_modules",d);await ae.mkdir(ie.dirname(p),{recursive:!0}),await ae.writeFile(p,u.content,"utf8")}let a={};for(let f of i)for(let u of f.shims){let d=Jo(u.path);d&&(a[u.module]=[`./node_modules/${d}`])}for(let f of i){if(f.ambient)continue;let u=Jo(f.mainPath);u&&(a[f.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let f of i)for(let u of f.files){if(!u.ambient)continue;let d=Jo(u.path);d&&c.add(`node_modules/${d}`)}if(r.local){delete a[r.local.name];let f=await BP(r.local,e);f?a[r.local.name]=[`./node_modules/${r.local.name}/${f}`]:console.warn(` local: '${r.local.name}' ships no type defs; check cannot type against it.`)}let l=$P(r.jsxImportSource,a,[...c]);return await ae.writeFile(ie.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
|
|
1908
|
-
`,"utf8"),await ae.writeFile(ie.join(e,"code.tsx"),r.code,"utf8"),await ae.writeFile(ie.join(e,"tb.d.ts"),ku,"utf8"),{dir:e}}var Pu={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function $P(r,e,t=[]){return{compilerOptions:{...Pu,lib:LP([...vu,...Su]),jsx:"react-jsx",jsxImportSource:r??"react",paths:e},include:["code.tsx","tb.d.ts",...t]}}function LP(r){return xu(r).map(e=>MP(e.name))}function MP(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 DP(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function Jo(r){if(!r.startsWith(Ty))return;let e=r.slice(Ty.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function BP(r,e){if(!r.typesAbs)return;let t=ie.dirname(r.typesAbs),n=ie.join(e,"node_modules",r.name);for(let s of await jP(t)){let i=ie.join(n,ie.relative(t,s));await ae.mkdir(ie.dirname(i),{recursive:!0}),await ae.copyFile(s,i)}return ie.basename(r.typesAbs)}async function jP(r){let e=[];async function t(n){let s=await ae.readdir(n,{withFileTypes:!0});for(let i of s){let o=ie.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 FP}from"fs";yr();rl();var qP="^22";async function Oy(r){let e=vi(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=_i(r.server).filter(o=>o!==r.local?.name);await Ci([`@types/node@${qP}`,...n],t,r.dependencies,{ignoreScripts:!0});let s=et.join(t,"node_modules"),i=et.join(e,"node_modules");return await JP(s,i),await be.writeFile(et.join(e,"server.ts"),r.server,"utf8"),await be.writeFile(et.join(e,"tb.d.ts"),Eu,"utf8"),await be.writeFile(et.join(e,"tsconfig.json"),JSON.stringify(UP(r.local),null,2)+`
|
|
1909
|
-
`,"utf8"),{dir:e}}function UP(r){let e={...Pu,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 JP(r,e){if(!FP(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)}mi();async function _y(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=Cy(xn(t.code,{target:"client",dependencies:n.dependencies??{}}),"client")||i),t.server&&(i=Cy(xn(t.server,{target:"server"}),"server")||i);let o=zP([process.cwd(),Tt.dirname(r)]);if(!o){let l=Tt.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 Py({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 Oy({server:t.server,bulbDir:Tt.dirname(r),emitKey:r,local:e?{name:e.name,typesAbs:e.typesAbs}:void 0,dependencies:n.dependencies});a.push({role:"server",dir:l})}for(let{role:l,dir:f}of a){let{stdout:u,exitCode:d}=await VP(o,f);for(let p of u.split(/\r?\n/))p.trim()&&console.log(`${l} ${p}`);d!==0&&(i=!0)}i&&process.exit(1);let c=[t.code&&"code.tsx",t.server&&"server.ts"].filter(Boolean).join(", ");console.error(`\u2713 no issues (${c})`)}function Cy(r,e){for(let t of r)for(let n of t.message.split(`
|
|
1910
|
-
`))console.log(`${e} ${n}`);return r.length>0}function VP(r,e){return new Promise(t=>{let n=KP(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 GP=WP(import.meta.url);function zP(r){let e=n=>{try{let s=GP.resolve("typescript/package.json",{paths:n}),i=Tt.join(Tt.dirname(s),"lib","tsc.js");return YP(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=HP("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}bt();eo();qn();async function Ry(r,e){let{bulb:t}=await Ae(r),n=_r(t);if(Ht(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 ss from"path";async function Ny(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=kl();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=ss.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),Tr(t,e),console.log(e?`Trusted ${ss.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${ss.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}$e();import*as My from"readline";var is=dy();function Iy(){for(let r of Object.values(is))try{r().ensureHarnessSupport()}catch{}}function os(){for(let r of Object.keys(is))try{if(is[r]().detectsSelf())return r}catch{}}function $y(r){let e=Dr(),t=new Map(e.filter(i=>is[i]).map(i=>[i,is[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)))}}to();function Ou(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 Dy(r){let e=$y(process.cwd());if("ambiguous"in e){let t=await XP(r,e.ambiguous);return t?Ly(r,t):QP(r,e.ambiguous)}return Ly(r,e.name)}async function Ly(r,e){let t,n;try{t=await ph(e)}catch(f){n=f instanceof Error?f.message:String(f)}let{lit:s,litLink:i,brand:o}=Ou(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(Rr())}`,` ${s(Vt())}`],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(`
|
|
1911
|
-
`)+`
|
|
1912
|
-
`)}async function XP(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:n}=Ou(!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(`
|
|
1913
|
-
`)+`
|
|
1914
|
-
`);let i=My.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 QP(r,e){let{lit:t,brand:n}=Ou(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(`
|
|
1915
|
-
`)+`
|
|
1916
|
-
`)}St();Kt();async function By(r){ye(r);let e=await Ve();if(e.length>0){console.log(Km(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!yl()){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(kr))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.")}to();import*as jy from"fs/promises";async function Fy(r){let e=Vt(),t;try{t=await jy.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(xh(t,r))}Ui();import*as qy from"path";$e();function ZP(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 as=r=>r.agent??qy.basename(r.file);function Uy(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 Cu(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),Uy(r,t=>console.log(t)),console.log(`
|
|
1917
|
-
`+e)}function _u(r,e,t,n,s){let i=ZP(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>\`):`),Uy(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function Jy(r,e){if(!r){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),Cu(await Q(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=_u(await Q(),r,"logs",process.cwd(),os());if(e.clear){ah(t.pid),console.log(`Cleared log for ${as(t)} (pid ${t.pid}).`);return}let n=Ie(t.pid),s=n.text;if(e.run!==void 0&&(s=ch(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(`
|
|
1918
|
-
`);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
|
|
1919
|
-
`)}if(process.stdout.write(s),s&&!s.endsWith(`
|
|
1920
|
-
`)&&process.stdout.write(`
|
|
1921
|
-
`),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 eO=r=>new Promise(e=>setTimeout(e,r));async function Ky(r,e){if(!r){Cu(await Q(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=_u(await Q(),r,"wait",process.cwd(),os()),n=t.agent!=null,i=process.env.TYPEBULB_WAIT_SHIM==="1",o=e.timeoutSec??1800,a=e.match??"",c=Ie(t.pid).offset,l=$l(t.pid,a)??(a?$l(t.pid):void 0),f=l!==void 0&&l<=c?l:a?0:c,u=Date.now()+o*1e3,d=n?1e4:1e3,p=2e3,b,m="",g=0;for(;;){let k=Ie(t.pid,f);if(f=k.offset,k.text){m+=k.text;let A=m.split(`
|
|
1922
|
-
`);m=A.pop()??"";for(let P of A)P.trim()&&(e.match&&!P.includes(e.match)||(console.log(P),b??=Date.now()+d,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 ${as(t)} within ${o}s`),g=2;break}if(!Ml(t.pid)){b||(console.error(`server ${as(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await eO(400)}Gi(t.pid,f,a),process.exit(g)}async function Hy(r){if(!r){Cu(await Q(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=_u(await Q(),r,"stop",process.cwd(),os());await Wt(e.pid),console.log(`Stopped ${as(e)} (pid ${e.pid}, ${e.url}).`)}async function Wy(r){let e=process.cwd(),t=r==="agent"?os():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=>Wt(i.pid))),console.log(`Stopped ${n.length} ${s}${n.length===1?"":"s"}:`);for(let i of n)console.log(` ${i.url} pid ${i.pid} ${as(i)}`)}$e();import*as Yy from"path";async function Vy(r,e,t=0){let n=e!==void 0&&e.startsWith("tb:");n&&t<=0&&(t=zo);let s=Yy.resolve(r),i=Cr(await Q(),s)[0];i||(console.error(`No running server for '${r}'. Start it first: npx typebulb ${r}`),process.exit(1));let o=async d=>{let p=await fetch(`${i.url}/__send${d>0?`?reply=${d}`:""}`,{method:"POST",headers:{"Content-Type":"text/plain"},body:e??""});return p.ok||(console.error(`send failed: HTTP ${p.status} from ${i.url}/__send`),process.exit(1)),await p.json().catch(()=>({}))},a={};try{let d=Date.now()+t;do{if(a=await o(t>0?Math.max(d-Date.now(),1e3):0),(a.clients??0)>0||Date.now()>=d)break;await new Promise(p=>setTimeout(p,150))}while(!0)}catch(d){console.error(`send failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}let c=a.clients??0,l=`${c} page${c===1?"":"s"}`;if(c===0){t>0?console.error(`No page connected after ${t/1e3}s \u2014 is the bulb open?`):console.error("Sent, but no page is connected yet \u2014 open the bulb and retry."),n&&process.exit(1);return}console.error(`Sent to ${l}.`);let f=a.results??[],u=a.errors??[];for(let d of u)console.error(`handler error: ${d}`);if(u.length&&process.exit(1),f.length>1&&(console.error(`${f.length} replies from ${l} \u2014 one reply owns stdout: at most one tb.onMessage handler, in one page, may return a value.`),process.exit(1)),f.length===1){let d;try{d=JSON.parse(f[0])}catch{d=void 0}console.log(typeof d=="string"?d:f[0])}else a.timedOut&&(n&&(console.error(`No reply to '${e}' within ${t/1e3}s \u2014 reload the page and retry.`),process.exit(1)),console.error(`(no reply within ${t/1e3}s \u2014 a slow handler's return needs a larger --wait=ms)`))}Wn();eu();St();bt();Re();eo();Wn();import*as Ot from"fs/promises";import*as Ho from"path";import{EventEmitter as Gy}from"events";import nO from"open";Zl();$e();async function Ko(r){let{portPreference:e,makeServerOptions:t,makeEntry:n,displayName:s,stopLog:i}=r,o=await Ql(e),a=await Mh(t(o)),c=`http://localhost:${o}`;await lh(n(o,c)),console.log(`
|
|
1917
|
+
showConfirm();
|
|
1918
|
+
document.body.appendChild(host);
|
|
1919
|
+
}
|
|
1920
|
+
`;Le();Kt();ji();xr();import{stream as jP}from"hono/streaming";var FP="X-TB-Stream";function as(r){return r instanceof fe?{message:r.message,code:r.code,retryable:r.retryable}:{message:r instanceof Error?r.message:"Unknown error",code:"unknown",retryable:!1}}function jo(r,e){return r.header("Content-Type","application/x-ndjson; charset=utf-8"),r.header("Cache-Control","no-cache"),r.header(FP,"1"),jP(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:as(s)}))}finally{try{await n.return?.()}catch{}}})}var Fo={log:(...r)=>console.log(...r)};function qo(r,e){let t=r?.[e]??(Object.hasOwn(Fo,e)?Fo[e]:void 0);return typeof t=="function"?t:void 0}function Uo(r){return r.constructor?.name==="AsyncGeneratorFunction"}bl();var qP=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,UP=/[?&]target=/,JP=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function Fy(r,e=""){return qP.test(r)?!0:JP.test(r)&&UP.test(e)}var Uy="127.0.0.1",YP=new Set(["localhost","127.0.0.1","::1"]);function VP(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function GP(r){let e=VP(r);return!!e&&YP.has(e)}function zP(r,e){if(!e)return!1;try{return new URL(r).host===e}catch{return!1}}function Au(r){return r instanceof Error?r.message:"Unknown error"}async function Jy(r){let{getHtml:e,basePath:t,fsBase:n,port:s,reloadEmitter:i,messageEmitter:o,getServerExports:a,getBulbBlocks:c,saveInferenceResult:l,localOverride:f,trusted:u=!1,trustHint:d,staticAssets:p,bulbAssets:b}=r,m=n??t,g=new KP;g.use("*",async(y,x)=>{if(!GP(y.req.header("host")))return y.text("Forbidden: untrusted Host",403);await x()}),g.use("*",async(y,x)=>{await x(),y.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),y.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let k=[["/__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,x)=>{if(!u){let I=new URL(y.req.url).pathname,C=k.find(([Y])=>Y.endsWith("/*")?I.startsWith(Y.slice(0,-2)):I===Y)?.[1]??"server-side code (server.ts)";uh(process.pid,C);let M=d?`
|
|
1921
|
+
${d}`:"";return y.text(`Forbidden: this capability requires --trust.${M}`,403)}await x()},P=async(y,x)=>{let I=y.req.header("sec-fetch-site");if(I){if(I!=="same-origin")return y.text(`Forbidden: ${I} request`,403)}else{let C=y.req.header("origin");if(C&&!zP(C,y.req.header("host")))return y.text("Forbidden: cross-origin request",403)}await x()};for(let[y]of k)g.use(y,A),g.use(y,P);if(g.use("/__log",P),g.post("/__log",async y=>{try{let{args:x}=await y.req.json();console.log(...x||[])}catch{}return y.json({ok:!0})}),o){let y=0,x=new Map;g.use("/__send",P),g.post("/__send",async I=>{let C="";try{C=await I.req.text()}catch{}let M=Number(I.req.query("reply"))||0,Y=o.listenerCount("message");if(M<=0||Y===0)return o.emit("message",{payload:C}),I.json({clients:Y});let U=++y,we=await new Promise(z=>{let V={expected:Y,received:0,results:[],errors:[],finish:ve=>{clearTimeout(Ue),x.delete(U),z({results:V.results,errors:V.errors,timedOut:ve})}},Ue=setTimeout(()=>V.finish(!0),M);x.set(U,V),o.emit("message",{id:U,payload:C})});return I.json({clients:Y,...we})}),g.use("/__send-reply",P),g.post("/__send-reply",async I=>{try{let{id:C,results:M,errors:Y}=await I.req.json(),U=x.get(C);U&&(U.results.push(...M??[]),U.errors.push(...Y??[]),++U.received>=U.expected&&U.finish(!1))}catch{}return I.json({ok:!0})})}g.get("/",y=>y.html(e())),g.post("/__fs/read",async y=>{try{let{path:x}=await y.req.json(),I=await Dn(x,m,t);return new Response(new Uint8Array(I),{headers:{"Content-Type":"application/octet-stream"}})}catch(x){let I=Au(x);return y.json({error:I},400)}}),g.post("/__fs/write",async y=>{try{let x=y.req.query("path");return x?(await Fi(x,new Uint8Array(await y.req.arrayBuffer()),m,t),y.json({success:!0})):y.json({error:"Missing path"},400)}catch(x){let I=Au(x);return y.json({error:I},400)}}),g.post("/__api/:name",async y=>{try{let x=y.req.param("name"),I=qo(a?.(),x);if(!I)return y.json({error:`API function '${x}' not found`},404);let{args:C}=await y.req.json();if(Uo(I))return jo(y,I(...C||[]));let M=await I(...C||[]);return y.json({result:M})}catch(x){let I=Au(x);return y.json({error:I},500)}}),g.post("/__ai",async y=>{try{let{messages:x,system:I,effort:C,provider:M,model:Y,webSearch:U,stream:we}=await y.req.json();if(!x||!Array.isArray(x)||x.length===0)return y.json({message:"messages array is required",code:"unknown",retryable:!1},400);let z=Ge(M,Y);if(typeof z=="string")return y.json({message:z,code:"unknown",retryable:!1},400);let V=await gt(z,{messages:x,system:I,effort:C,webSearch:U,signal:y.req.raw.signal});if(!V.ok){let ve=await Sr(V,z.protocol);return y.json(ve,V.status)}if(we)return jo(y,Jt(V,z.protocol));let Ue=await Ut(V,z.protocol);return Ue||console.warn("[tb.ai] Empty response from provider"),y.json({text:Ue})}catch(x){return y.json(as(x),500)}}),g.post("/__infer",async y=>{try{let{data:x}=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 C=Ge();if(typeof C=="string")return y.json({message:C,code:"unknown",retryable:!1},400);let M=Array.isArray(x)?x.map(String):[],Y=fl(I,M),U=await gt(C,{messages:[{role:"user",content:Y}],signal:y.req.raw.signal});if(!U.ok){let z=await Sr(U,C.protocol);return y.json(z,U.status)}let we=(async function*(){let z="";for await(let ve of Jt(U,C.protocol))ve.kind!=="text"||!ve.text||(z+=ve.text,yield{kind:"delta",text:ve.text});let V=pl(z);if(V.parsed===null)throw console.warn(`[tb.infer] output not valid JSON after sanitize; raw output (last 4000 chars):
|
|
1922
|
+
`+z.slice(-4e3)),new fe("LLM output is not valid JSON","parse_error",!0);V.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",V.fixesApplied.join(", "));let Ue={insight:V.parsed,insightJson:V.json,data:M};yield{kind:"complete",...Ue,fixesApplied:V.fixesApplied,hash:ml(Ue)}})();return jo(y,we)}catch(x){return y.json(as(x),500)}});let R=async y=>{let{hash:x}=await y.req.json().catch(()=>({}));return typeof x=="string"?hl(x):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 x=await R(y);return x?(await l(x.data,x.insightJson),y.json({ok:!0})):y.json({message:"No decodable #tb= fragment to save.",code:"unknown",retryable:!1},400)}catch(x){return y.json(as(x),500)}}),g.get("/__infer-info",y=>{let x=c?.(),I=Fr(x?.config??"").inference,C=fi(x?.data??""),M=Ge();return typeof M=="string"?y.json({error:M,inference:I,data:C}):y.json({provider:M.protocol,model:M.model,inference:I,data:C})}),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(jy,200,{"Content-Type":"text/javascript; charset=utf-8"})),g.get("/__models",async y=>{try{let x=await Ve();return y.json(x)}catch{return y.json([],200)}}),g.get("/__has-own-keys",async y=>{try{return y.json(await Bi())}catch{return y.json(!1,200)}});let N=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],O=new Bo;g.get("/proxy/*",async y=>{let x=new URL(y.req.url),C=(x.pathname+x.search).slice(7),M=C.lastIndexOf("https://");return M===-1?y.text("Invalid proxy URL",400):$(y,C.slice(M))}),f&&qy(g,`/local/${f.name}/`,f.serveDir),p&&qy(g,p.mount,p.dir),b&&g.get("/assets/*",async y=>{let{pathname:x}=new URL(y.req.url),I=x.slice(8),C=sd(I);if(C)return y.text(`${C} is not an asset type: a bulb's code and markup live in the bulb; assets are media and data`,403);for(let Y of b.dirs){let U;try{U=Mn(decodeURIComponent(I),Y)}catch{return y.text("Not Found",404)}try{let we=await Pu.readFile(U);return new Response(we,{headers:{"Content-Type":ta(U),"Cache-Control":"no-cache"}})}catch{}}let M=b.remoteBase;return M?y.redirect(M+I,302):y.text("Not Found",404)});async function $(y,x){let I;try{I=new URL(x)}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 C=await O.get(x);if(C)return new Response(C.body,{status:200,headers:Tu(C.contentType,C.cacheControl)});try{let M=await fetch(x,{headers:{Accept:y.req.header("Accept")||"*/*"},redirect:"follow"});if(!M.ok)return y.text(`Upstream ${M.status}`,M.status);let Y=M.headers.get("Content-Type")||void 0,U=M.headers.get("Cache-Control")||void 0;if(M.body){let[we,z]=M.body.tee();return(async()=>{try{let V=await new Response(z).arrayBuffer();await O.set(x,{body:Buffer.from(V),contentType:Y,cacheControl:U})}catch{}})(),new Response(we,{status:M.status,headers:Tu(Y,U)})}return new Response(null,{status:M.status,headers:Tu(Y,U)})}catch(M){return y.text(`Proxy fetch failed: ${M instanceof Error?M.message:M}`,502)}}(i||o)&&g.get("/__reload",y=>WP(y,async x=>{let I=()=>{x.writeSSE({event:"reload",data:""})},C=M=>{x.writeSSE({event:"message",data:JSON.stringify(M)})};for(i?.on("reload",I),o?.on("message",C),x.onAbort(()=>{i?.removeListener("reload",I),o?.removeListener("message",C)});!x.aborted;)await x.sleep(3e4)})),g.notFound(async y=>{if(y.req.method!=="GET")return y.text("Not Found",404);let x=new URL(y.req.url);return Fy(x.pathname,x.search)?$(y,"https://esm.sh"+x.pathname+x.search):y.text("Not Found",404)});let E=HP({fetch:g.fetch,port:s,hostname:Uy});return{port:s,close:()=>E.close()}}function Tu(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 qy(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=Mn(i,t),a=await Pu.readFile(o);return new Response(a,{headers:{"Content-Type":ta(o)}})}catch{return n.text("Not Found",404)}})}async function Ou(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,Uy,()=>{let s=n.address(),i=typeof s=="object"&&s?s.port:r;n.close(()=>t(i))}),n.on("error",()=>{t(Ou(r+1))})})}Le();async function Jo(r){let{portPreference:e,makeServerOptions:t,makeEntry:n,displayName:s,stopLog:i}=r,o=await Ou(e),a=await Jy(t(o)),c=`http://localhost:${o}`;await lh(n(o,c)),console.log(`
|
|
1923
1923
|
${s}`),console.log(` ${c}`),o!==e&&console.log(` (port ${e} was busy)`);let l=[],f=async()=>{console.log(`
|
|
1924
|
-
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",f),process.on("SIGTERM",f),{port:o,url:c,onCleanup(u){l.push(u)}}}import
|
|
1924
|
+
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",f),process.on("SIGTERM",f),{port:o,url:c,onCleanup(u){l.push(u)}}}import XP from"chokidar";var QP={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function Pt(r){let{target:e,onChange:t,events:n="change",debounceMs:s=150}=r,i,o=XP.watch(e,QP);o.on("error",c=>console.warn(`watch: ${c instanceof Error?c.message:c} \u2014 continuing`));let a=()=>{i&&clearTimeout(i),i=setTimeout(t,s)};return n==="all"?o.on("all",a):o.on("change",a),()=>{i&&clearTimeout(i),o.close()}}Le();async function Hy(r,e,t,n){let s=process.cwd(),i=zi(process.pid),o=e.watch?new Ky:void 0,a=new Ky;a.setMaxListeners(0);let c=ye(e.mode),l=await Bl(r);l.length&&console.log(`Replacing the running server for this bulb (pid ${l.map(O=>O.pid).join(", ")})`);let f=1;console.log(Ll(f)),console.log(`Loading ${Ko.basename(r)}...`);let{html:u,bulb:d,serverExports:p}=await vl(r,e.watch,e.trust,n,e.dir);vt(c,r,d.server);let b=[...e.dir?[jn(r,e.dir)]:[],jn(r)],m=Kl(Ko.resolve(r)),g=e.trust?void 0:Cr(d),{port:k,url:A,onCleanup:P}=await Jo({portPreference:e.port,displayName:d.name,stopLog:i,makeServerOptions:O=>({getHtml:()=>u,basePath:s,fsBase:Bn(r,e.dir),port:O,reloadEmitter:o,messageEmitter:a,getServerExports:()=>p,getBulbBlocks:()=>({infer:d.infer,insight:d.insight,code:d.code,config:d.config,data:d.data}),saveInferenceResult:async($,E)=>{let y=await Ot.readFile(r,"utf-8");y=ea(y,"data",$.join(sm)),y=ea(y,"insight",E),await Ot.writeFile(r,y)},localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,bulbAssets:{dirs:b,remoteBase:m&&ms(m.userSlug,m.slug)},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:
|
|
1925
1925
|
${t}
|
|
1926
1926
|
`:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
|
|
1927
1927
|
`),e.watch&&console.log(` Watching for changes...
|
|
1928
1928
|
`);let R,N;if(e.watch&&o){let O=0,$=Promise.resolve();if(R=Pt({target:r,onChange:()=>{let E=++O;$=$.then(async()=>{if(E===O)try{console.log("Recompiling...");let y=await vl(r,!0,e.trust,n,e.dir);u=y.html,p=y.serverExports,d=y.bulb,f++,console.log(Ll(f)),o.emit("reload")}catch(y){console.error("Compile error:",y)}})}}),n){let{name:E,serveDir:y}=n;N=Pt({target:y,events:"all",onChange:()=>{console.log(`Local package '${E}' changed. Browser reloading...
|
|
1929
1929
|
`),o.emit("reload")}})}for(let E of b)await Ot.stat(E).then(y=>y.isDirectory()).catch(()=>!1)&&P(Pt({target:E,events:"all",onChange:()=>{console.log(`Assets changed. Browser reloading...
|
|
1930
1930
|
`),o.emit("reload")}}))}R&&P(R),N&&P(N),P(()=>Ot.rm(wl(r),{force:!0})),e.open&&(l.some(O=>O.port===k)?console.log(` Reusing the open browser tab.
|
|
1931
|
-
`):await
|
|
1931
|
+
`):await ZP(A))}St();import{readFileSync as Yy,copyFileSync as tO,existsSync as rO}from"fs";import*as oe from"path";import{fileURLToPath as nO}from"url";import{EventEmitter as sO}from"events";import Vy from"open";Le();tl();var _u=r=>`/agents/${r}/client.js`,eO=`
|
|
1932
1932
|
(() => {
|
|
1933
1933
|
const api = async (name, ...args) => {
|
|
1934
1934
|
const resp = await fetch('/__api/' + name, {
|
|
@@ -1963,7 +1963,7 @@ Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await Kn(pr
|
|
|
1963
1963
|
es.onerror = () => { es.close(); };
|
|
1964
1964
|
}
|
|
1965
1965
|
})();
|
|
1966
|
-
`;function
|
|
1966
|
+
`;function Wy(r){let{name:e,agent:t,styles:n,mountHtml:s,watch:i,theme:o}=r,a=_u(t);return`<!DOCTYPE html>
|
|
1967
1967
|
<html>
|
|
1968
1968
|
<head>
|
|
1969
1969
|
<meta charset="utf-8">
|
|
@@ -1983,17 +1983,17 @@ ${s}
|
|
|
1983
1983
|
${i?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
|
|
1984
1984
|
|
|
1985
1985
|
<script>
|
|
1986
|
-
${
|
|
1986
|
+
${eO}
|
|
1987
1987
|
</script>
|
|
1988
1988
|
|
|
1989
1989
|
<script type="module" src="${a}"></script>
|
|
1990
1990
|
</body>
|
|
1991
|
-
</html>`}async function
|
|
1992
|
-
${n.url}`),r.open&&await
|
|
1993
|
-
`);let A=oe.join(u,t,"client"),P=oe.join(u,"core","client");async function R(){await(await import("esbuild")).build({entryPoints:[oe.join(A,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:oe.join(f,"client.js")});for(let $ of["styles.css","index.html","typebulb.png","typebulb-inv.png"])
|
|
1994
|
-
`),i.emit("reload")}catch(E){console.error("Mirror rebuild failed:",E instanceof Error?E.message:E)}finally{$=!1}}}})}r.open&&await
|
|
1995
|
-
`);let c=0,l=Promise.resolve();Pt({target:r,onChange:()=>{let f=++c;l=l.then(async()=>{if(f===c)try{console.log("Re-running..."),await a()}catch(u){console.error("Error:",u)}})}})}}St();bt();
|
|
1996
|
-
`)}catch(p){cs(p instanceof Error?p.stack??p.message:String(p))}return
|
|
1997
|
-
`),
|
|
1998
|
-
`),process.exit(1)}function
|
|
1999
|
-
${e}`),process.exit(1))}async function
|
|
1991
|
+
</html>`}async function Gy(r){let e=process.cwd(),t=r.agentTarget;ey(t)||(console.error(`Unknown agent '${t}'. Known: ${Dr().join(", ")}.`),process.exit(1));let n=await Dl(e,t);if(n){console.log(`Mirror '${t}' is already running for this project:
|
|
1992
|
+
${n.url}`),r.open&&await Vy(n.url);return}let s=zi(process.pid),i=r.watch?new sO:void 0,o=ye(r.mode),a=await ry(t),c=a.displayName||`${t} mirror`;vt(o,oe.join(e,"mirror"));let l=oe.dirname(nO(import.meta.url)),f=oe.join(l,"agents",t),u=oe.join(l,"..","cli","agents"),d=oe.join(f,"styles.css"),p=oe.join(f,"index.html"),b=()=>Wy({name:c,agent:t,styles:Yy(d,"utf8"),mountHtml:Yy(p,"utf8"),watch:r.watch}),{port:m,url:g,onCleanup:k}=await Jo({portPreference:r.port,displayName:c,stopLog:s,makeServerOptions:O=>({getHtml:b,basePath:e,port:O,reloadEmitter:i,getServerExports:()=>a,trusted:!0,staticAssets:{mount:`${oe.posix.dirname(_u(t))}/`,dir:f}}),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...
|
|
1993
|
+
`);let A=oe.join(u,t,"client"),P=oe.join(u,"core","client");async function R(){await(await import("esbuild")).build({entryPoints:[oe.join(A,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:oe.join(f,"client.js")});for(let $ of["styles.css","index.html","typebulb.png","typebulb-inv.png"])tO(oe.join(P,$),oe.join(f,$))}let N;if(r.watch&&i){let O=rO(A),$=!1;N=Pt({target:O?u:f,events:"all",onChange:async()=>{if(!$){$=!0;try{O&&await R(),console.log(`Mirror rebuilt. Browser reloading...
|
|
1994
|
+
`),i.emit("reload")}catch(E){console.error("Mirror rebuild failed:",E instanceof Error?E.message:E)}finally{$=!1}}}})}r.open&&await Vy(g),k(()=>a.shutdownSwitcher?.()),k(()=>a.shutdownComposer?.()),N&&k(N)}St();bt();import*as zy from"path";async function Xy(r,e,t,n,s){let i=ye(t),o=!1,a=async()=>{let{bulb:c,config:l}=await Te(r);o||(vt(i,r,c.server),o=!0),await Fn(c.server,r,n,l.dependencies,s)};if(console.log(`Running ${zy.basename(r)}...`),await a(),e){console.log(`Watching for changes...
|
|
1995
|
+
`);let c=0,l=Promise.resolve();Pt({target:r,onChange:()=>{let f=++c;l=l.then(async()=>{if(f===c)try{console.log("Re-running..."),await a()}catch(u){console.error("Error:",u)}})}})}}St();bt();import{Console as iO}from"node:console";Le();async function eb(r,e,t,n,s){uO();try{let p=_r(await Q(),r)[0];p&&(Gi(p.pid,$e(p.pid).offset),console.error(`note: 'call' boots a fresh server.ts instance; the running server (${p.url}) is not contacted \u2014 state shared with it must live on disk.`))}catch{}let i=ye(t),{bulb:o,config:a}=await Te(r);o.server||cs("This bulb has no **server.ts** block; nothing to call."),vt(i,r,o.server);let c;try{c=await Fn(o.server,r,n,a.dependencies,s)}catch(p){cs(p instanceof Error?p.message:String(p))}let l=qo(c,e.fn);if(!l){let p=[...Object.keys(c).filter(b=>typeof c[b]=="function"),...Object.keys(Fo)];cs(`Function '${e.fn}' not found. Available: ${p.length?p.join(", "):"(none)"}.`)}let f=await oO(e);if(Uo(l)){try{for await(let p of l(...f))await Zy(JSON.stringify(p,tb)+`
|
|
1996
|
+
`)}catch(p){cs(p instanceof Error?p.stack??p.message:String(p))}return Qy(0)}let u;try{u=await l(...f)}catch(p){cs(p instanceof Error?p.stack??p.message:String(p))}let d=lO(u);d!==void 0&&await Zy(d+`
|
|
1997
|
+
`),Qy(0)}function Qy(r){process.exitCode=r,setTimeout(()=>process.exit(r),2e3).unref?.()}async function oO(r){if(r.hasArgsFlag){let e=r.argsJson??"";return e==="-"&&(e=await dO()),cO(e)}return aO(r.positional)}function aO(r){return r.map(e=>{try{return JSON.parse(e)}catch{return e}})}function cO(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 lO(r){if(r!==void 0)return JSON.stringify(r,tb,2)}function tb(r,e){return typeof e=="bigint"?e.toString():e}function cs(r){process.stderr.write(r+`
|
|
1998
|
+
`),process.exit(1)}function uO(){let r=new iO(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 Zy(r){return new Promise((e,t)=>{process.stdout.write(r,n=>n?t(n):e())})}async function dO(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}var Cu="0.36.0";function rb(r,e){r||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
|
|
1999
|
+
${e}`),process.exit(1))}async function fO(){let r=Hu(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${Cu}`),process.exit(0)),r.help&&(Wu(),process.exit(0)),ky(),r.subcommand==="logs"){await Iy(r.file||void 0,{follow:r.follow,clear:r.clear,run:r.run,lines:r.lines});return}if(r.subcommand==="wait"){await $y(r.file||void 0,{match:r.match,timeoutSec:r.timeoutSec});return}if(r.subcommand==="stop"){r.stopScope?await My(r.stopScope):await Ly(r.file||void 0);return}if(r.subcommand==="send"){await By(r.file,r.sendMessage,r.sendWaitMs??0);return}if(r.subcommand==="skill"){await Cy(Cu);return}if(r.subcommand==="models"){await Oy(r.mode);return}if(r.subcommand==="pull"){await Th(r.file||void 0,{force:r.force,mode:r.mode});return}if(r.subcommand==="push"){await Ch(r.file||void 0,{force:r.force,mode:r.mode});return}if(r.subcommand==="agent"){await(r.agentTarget?Gy(r):Py(Cu));return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await xy(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let c=await Vm(process.cwd());c||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=c}else e=er.resolve(r.file);await nb.access(e).then(()=>!0,()=>!1)||(Dr().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:er.relative(process.cwd(),e)||er.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await Sy(e,s);return}let i=!r.noTrust&&Ht(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 Te(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 Uu(r.local)}catch(c){console.error(c instanceof Error?c.message:String(c)),process.exit(1)}console.error(`replace: ${a.name} \u2192 ${er.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await vy(e,a);return}if(r.subcommand==="call"){rb(r.trust,s),await eb(e,{fn:r.fn,positional:r.callArgs,argsJson:r.argsJson,hasArgsFlag:r.hasArgsFlag},r.mode,a,r.dir);return}if(o&&o.bulb.server&&(pi(o.bulb)||r.server)){rb(r.trust,s),await Xy(e,r.watch,r.mode,a,r.dir);return}await Hy(e,r,s,a)}fO().catch(r=>{console.error("Error:",r.message),process.exit(1)});
|