New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@google-labs/breadboard

Package Overview
Dependencies
Maintainers
1
Versions
48
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@google-labs/breadboard - npm Package Compare versions

Comparing version

to
0.9.0

dist/src/new/grammar/base.d.ts

36

dist/harness.min.js

@@ -21,3 +21,3 @@ /**

* SPDX-License-Identifier: Apache-2.0
*/class s{graph;#e;#r;constructor(t,e,r=!0){this.graph=t,this.#e=e,this.#r=r}static#s(t,e){const{promiseId:r,outputs:s,newOpportunities:n}=e;t.pendingOutputs.delete(r);const o=s.$error?n.filter((t=>"$error"===t.out)):n;if(t.opportunities.push(...o),t.state.wireOutputs(o,s),s.$error){if(0===o.length)throw new Error("Uncaught exception in node handler. Catch by wiring up the $error output.",{cause:s.$error});globalThis.console.warn("Error in node handler, passinng to the wired $error output.",s.$error,o)}}static async processAllPendingNodes(t){return(await Promise.all(t.pendingOutputs.values())).forEach((e=>{s.#s(t,e)})),t}async next(){if(!this.#e.skip){const{inputs:t,outputsPromise:e,newOpportunities:r,descriptor:s}=this.#e;this.#e.state.useInputs(s.id,this.#e.inputs);const n=Symbol(),o=new Promise((o=>{(e||Promise.resolve({})).then((e=>{if(e.$error){const r=e.$error;e.$error={descriptor:s,...r,inputs:{...t,...r.inputs}}}o({promiseId:n,outputs:e,newOpportunities:r})})).catch((e=>{o({promiseId:n,outputs:{$error:{kind:"error",error:e,inputs:t,descriptor:s}},newOpportunities:r.filter((t=>"$error"===t.out))})}))}));this.#e.pendingOutputs.set(n,o)}for(;(0===this.#e.opportunities.length||this.#r)&&this.#e.pendingOutputs.size>0;)s.#s(this.#e,await Promise.race(this.#e.pendingOutputs.values()));if(0===this.#e.opportunities.length)return{done:!0,value:null};const e=this.#e.opportunities.shift(),{heads:n,nodes:o,tails:i}=this.graph,a=e.to,c=o.get(a);if(!c)throw new Error(`No node found for id "${a}"`);const u=n.get(a)||[],p=this.#e.state.getAvailableInputs(a),d=t.computeMissingInputs(u,p,c),h=i.get(a)||[],l={...c.configuration,...p};return this.#e=new r(c,l,d,this.#e.opportunities,h,this.#e.state,this.#e.pendingOutputs),{done:!1,value:this.#e}}}
*/class s{graph;#e;#r;constructor(t,e,r=!0){this.graph=t,this.#e=e,this.#r=r}static#s(t,e){const{promiseId:r,outputs:s,newOpportunities:n}=e;t.pendingOutputs.delete(r);const o=s.$error?n.filter((t=>"$error"===t.out)):n;if(t.opportunities.push(...o),t.state.wireOutputs(o,s),s.$error){if(0===o.length)throw new Error("Uncaught exception in node handler. Catch by wiring up the $error output.",{cause:s.$error});globalThis.console.warn("Error in node handler, passing to the wired $error output.",s.$error,o)}}static async processAllPendingNodes(t){return(await Promise.all(t.pendingOutputs.values())).forEach((e=>{s.#s(t,e)})),t}async next(){if(!this.#e.skip){const{inputs:t,outputsPromise:e,newOpportunities:r,descriptor:s}=this.#e;this.#e.state.useInputs(s.id,this.#e.inputs);const n=Symbol(),o=new Promise((o=>{(e||Promise.resolve({})).then((e=>{if(e.$error){const r=e.$error;e.$error={descriptor:s,...r,inputs:{...t,...r.inputs}}}o({promiseId:n,outputs:e,newOpportunities:r})})).catch((e=>{o({promiseId:n,outputs:{$error:{kind:"error",error:e,inputs:t,descriptor:s}},newOpportunities:r.filter((t=>"$error"===t.out))})}))}));this.#e.pendingOutputs.set(n,o)}for(;(0===this.#e.opportunities.length||this.#r)&&this.#e.pendingOutputs.size>0;)s.#s(this.#e,await Promise.race(this.#e.pendingOutputs.values()));if(0===this.#e.opportunities.length)return{done:!0,value:null};const e=this.#e.opportunities.shift(),{heads:n,nodes:o,tails:i}=this.graph,a=e.to,c=o.get(a);if(!c)throw new Error(`No node found for id "${a}"`);const u=n.get(a)||[],p=this.#e.state.getAvailableInputs(a),d=t.computeMissingInputs(u,p,c),h=i.get(a)||[],l={...c.configuration,...p};return this.#e=new r(c,l,d,this.#e.opportunities,h,this.#e.state,this.#e.pendingOutputs),{done:!1,value:this.#e}}}
/**

@@ -57,3 +57,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/const k=async(t,e,r)=>t instanceof Function?t(e,r):t.invoke?t.invoke(e,r):void 0,$=t=>t.reduce(((t,e)=>({...e.handlers,...t})),{}),S=t=>t&&t.replace(/-/g,""),E=(t,e="")=>{if(!t)return"";const r=t.id,s=`${e?`${S(e)}_`:""}${S(r)}`,n=t.type,o=`"${n} <br> id='${r}'"`;switch(n){case"include":return`${s}[[${o}]]:::include`;case"slot":return`${s}((${o})):::slot`;case"passthrough":return`${s}((${o})):::passthrough`;case"input":return`${s}[/${o}/]:::input`;case"secrets":return`${s}(${o}):::secrets`;case"output":return`${s}{{${o}}}:::output`;default:return`${s}[${o}]`}};class O{nodeMap;edges;nodes;idPrefix;subgraphs;constructor(t,e=""){const{edges:r,nodes:s}=t;this.nodeMap=new Map(s.map((t=>[t.id,t]))),this.edges=r,this.nodes=s,this.idPrefix=e,this.subgraphs=t.graphs||{}}handleSlotted(t,e){const r=e?`${S(e)}_`:"";if("include"!==t.type)return"";const s=t.configuration?.slotted;if(!s)return"";return Object.entries(s).map((([e,s])=>this.describeSubgraph(s,e,"slotted",t,`${r}${t.id}`))).join("\n")}handleLambda(t,e){const r=e?`${S(e)}_`:"",s=t.configuration?.board;if(!s)return"";const n=s;if("board"!==n.kind)return"";const o=n.board;return this.describeSubgraph(o,t.id,"lamdba",t,`${r}${t.id}`)}describeSubgraphs(t,e=""){const r=this.nodeMap.get(t.from);if(!r)return"";const s=this.handleLambda(r,e);return`${this.handleSlotted(r,e)}${s}`}describeSubgraph(t,e,r,s,n){const o=new O(t,n).describeGraph(),i=this.idPrefix?`${S(this.idPrefix)}_`:"",a=r&&s?`sg_${S(e)}:::slotted -- "${r}->${r}" --o ${i}${S(s.id)}\n`:"";return`\nsubgraph sg_${S(e)} [${e}]\n${o}\nend\n${a}`}describeGraph(){return[...this.edges.map((t=>{const e=((t,e,r="")=>{const s=t.from,n=E(e.get(s),r),o=t.to,i=E(e.get(o),r),a=t.in,c=t.out,u=t.optional,p=t.constant;return"*"===c?`${n} -- all --\x3e ${i}`:c&&a?u?`${n} -. "${c}->${a}" .-> ${i}`:p?`${n} -- "${c}->${a}" --o ${i}`:`${n} -- "${c}->${a}" --\x3e ${i}`:`${n} --\x3e ${i}`})(t,this.nodeMap,this.idPrefix);return`${e}${this.describeSubgraphs(t,this.idPrefix)}`})),...Object.entries(this.subgraphs).map((([t,e])=>this.describeSubgraph(e,t,void 0,void 0,`${t}${this.idPrefix}`)))].join("\n")}}const x=t=>null==t?"null":Array.isArray(t)?"array":typeof t;
*/const k=async(t,e,r)=>{const s=(t=>{if(t instanceof Function)return t;if(t.invoke)return t.invoke;throw new Error("Invalid handler")})(t);return new Promise((t=>{s(e,r).then(t).catch((e=>{t({$error:{error:e}})}))}))},S=t=>t.reduce(((t,e)=>({...e.handlers,...t})),{}),$=t=>t&&t.replace(/-/g,""),E=(t,e="")=>{if(!t)return"";const r=t.id,s=`${e?`${$(e)}_`:""}${$(r)}`,n=t.type,o=`"${n} <br> id='${r}'"`;switch(n){case"include":return`${s}[[${o}]]:::include`;case"slot":return`${s}((${o})):::slot`;case"passthrough":return`${s}((${o})):::passthrough`;case"input":return`${s}[/${o}/]:::input`;case"secrets":return`${s}(${o}):::secrets`;case"output":return`${s}{{${o}}}:::output`;default:return`${s}[${o}]`}};class O{nodeMap;edges;nodes;idPrefix;subgraphs;constructor(t,e=""){const{edges:r,nodes:s}=t;this.nodeMap=new Map(s.map((t=>[t.id,t]))),this.edges=r,this.nodes=s,this.idPrefix=e,this.subgraphs=t.graphs||{}}handleSlotted(t,e){const r=e?`${$(e)}_`:"";if("include"!==t.type)return"";const s=t.configuration?.slotted;if(!s)return"";return Object.entries(s).map((([e,s])=>this.describeSubgraph(s,e,"slotted",t,`${r}${t.id}`))).join("\n")}handleLambda(t,e){const r=e?`${$(e)}_`:"",s=t.configuration?.board;if(!s)return"";const n=s;if("board"!==n.kind)return"";const o=n.board;return this.describeSubgraph(o,t.id,"lamdba",t,`${r}${t.id}`)}describeSubgraphs(t,e=""){const r=this.nodeMap.get(t.from);if(!r)return"";const s=this.handleLambda(r,e);return`${this.handleSlotted(r,e)}${s}`}describeSubgraph(t,e,r,s,n){const o=new O(t,n).describeGraph(),i=this.idPrefix?`${$(this.idPrefix)}_`:"",a=r&&s?`sg_${$(e)}:::slotted -- "${r}->${r}" --o ${i}${$(s.id)}\n`:"";return`\nsubgraph sg_${$(e)} [${e}]\n${o}\nend\n${a}`}describeGraph(t=!1){return[...this.edges.map((e=>{const r=((t,e,r="")=>{const s=t.from,n=E(e.get(s),r),o=t.to,i=E(e.get(o),r),a=t.in,c=t.out,u=t.optional,p=t.constant;return"*"===c?`${n} -- all --\x3e ${i}`:c&&a?u?`${n} -. "${c}->${a}" .-> ${i}`:p?`${n} -- "${c}->${a}" --o ${i}`:`${n} -- "${c}->${a}" --\x3e ${i}`:`${n} --\x3e ${i}`})(e,this.nodeMap,this.idPrefix);return`${r}${t?"":this.describeSubgraphs(e,this.idPrefix)}`})),...t?"":Object.entries(this.subgraphs).map((([t,e])=>this.describeSubgraph(e,t,void 0,void 0,`${t}${this.idPrefix}`)))].join("\n")}}const x=t=>null==t?"null":Array.isArray(t)?"array":typeof t;
/**

@@ -68,3 +68,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/const N=(t,e={},r)=>{const s=e.title??e?.url;return`Missing ${r?"required ":""}input "${t}"${s?` for board "${s}".`:"."}`},j=async(t,e,r,s)=>{if(!e.requestInput)return;const n=await s.outputsPromise??{},o=new R(n,s.inputs);s.outputsPromise=o.read(I(t,e,r))},I=(t,e,r)=>async(s,n,o)=>{if(o)throw new Error(N(s,t,o));if(void 0!==n.default)return"string"!==n.type?JSON.parse(n.default):n.default;const i=await(e.requestInput?.(s,n,r));if(void 0===i)throw new Error(N(s,t,o));return i};class R{#p;#d;constructor(t,e){this.#p=t,this.#d=e}async read(t){if(!("schema"in this.#d))return this.#p;const e=this.#d.schema;if(!e.properties)return this.#p;const r=Object.entries(e.properties),s={};for(const[n,o]of r){if(n in this.#p){s[n]=this.#p[n];continue}const r=e.required?.includes(n)??!1,i=await t(n,o,r);s[n]=i}return{...this.#p,...s}}}class q{#h;#l=new Map;constructor(t){this.#h=t}createHandler(t,e){return async(r,s,n)=>{const o=this.#l.get(r);if(void 0!==o)return o;const i={id:n.id,type:n.type},a={...e,descriptor:i,inputs:{schema:{type:"object",properties:{[r]:s}}}};console.log("requestInputResult",a),await t(new d(a,void 0,-1));const c=await a.outputsPromise;let u=c&&c[r];return void 0===u&&(u=await(this.#h.requestInput?.(r,s,i))),this.#l.set(r,u),u}}}
*/const N=(t,e={},r)=>{const s=e.title??e?.url;return`Missing ${r?"required ":""}input "${t}"${s?` for board "${s}".`:"."}`},j=async(t,e,r,s)=>{if(!e.requestInput)return;const n=await s.outputsPromise??{},o=new R(n,s.inputs);s.outputsPromise=o.read(I(t,e,r))},I=(t,e,r)=>async(s,n,o)=>{if(o)throw new Error(N(s,t,o));if(void 0!==n.default)return"type"in n&&"string"!==n.type?JSON.parse(n.default):n.default;const i=await(e.requestInput?.(s,n,r));if(void 0===i)throw new Error(N(s,t,o));return i};class R{#p;#d;constructor(t,e){this.#p=t,this.#d=e}async read(t){if(!("schema"in this.#d))return this.#p;const e=this.#d.schema;if(!e.properties)return this.#p;const r=Object.entries(e.properties),s={};for(const[n,o]of r){if(n in this.#p){s[n]=this.#p[n];continue}const r=e.required?.includes(n)??!1,i=await t(n,o,r);s[n]=i}return{...this.#p,...s}}}class q{#h;#l=new Map;constructor(t){this.#h=t}createHandler(t,e){return async(r,s,n)=>{const o=this.#l.get(r);if(void 0!==o)return o;const i={id:n.id,type:n.type},a={...e,descriptor:i,inputs:{schema:{type:"object",properties:{[r]:s}}}};await t(new d(a,void 0,-1));const c=await a.outputsPromise;let u=c&&c[r];return void 0===u&&(u=await(this.#h.requestInput?.(r,s,i))),this.#l.set(r,u),u}}}
/**

@@ -74,3 +74,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/const C=()=>{};class A{#f=[];#w=C;#y;#m;abort=C;constructor(){this.#g()}#g(){this.#y=new Promise(((t,e)=>{this.#w=t,this.abort=e}))}#b(t){this.#f.push(t),1==this.#f.length&&(this.#w(),this.#g())}async write(t){return new Promise((e=>{this.#b({value:t,receipt:e})}))}async read(){this.#m&&this.#m(),0===this.#f.length&&await this.#y;const t=this.#f.shift();if(!t)throw new Error("asyncGen queue should never be empty.");return this.#m=t.receipt,t.value?{done:!1,value:t.value}:{done:!0,value:void 0}}close(){this.#b({value:void 0,receipt:C})}}class T{#v;#k=!0;#f=new A;constructor(t){this.#v=t}async#$(t){return this.#f.write(t)}async next(){return this.#k&&(this.#k=!1,this.#v(this.#$.bind(this)).then((()=>{this.#f.close()})).catch((t=>{this.#f.abort(t)}))),this.#f.read()}}const M=t=>({[Symbol.asyncIterator]:()=>new T(t)});
*/const C=()=>{};class A{#f=[];#w=C;#y;#m;abort=C;constructor(){this.#g()}#g(){this.#y=new Promise(((t,e)=>{this.#w=t,this.abort=e}))}#b(t){this.#f.push(t),1==this.#f.length&&(this.#w(),this.#g())}async write(t){return new Promise((e=>{this.#b({value:t,receipt:e})}))}async read(){this.#m&&this.#m(),0===this.#f.length&&await this.#y;const t=this.#f.shift();if(!t)throw new Error("asyncGen queue should never be empty.");return this.#m=t.receipt,t.value?{done:!1,value:t.value}:{done:!0,value:void 0}}close(){this.#b({value:void 0,receipt:C})}}class T{#v;#k=!0;#f=new A;constructor(t){this.#v=t}async#S(t){return this.#f.write(t)}async next(){return this.#k&&(this.#k=!1,this.#v(this.#S.bind(this)).then((()=>{this.#f.close()})).catch((t=>{this.#f.abort(t)}))),this.#f.read()}}const M=t=>({[Symbol.asyncIterator]:()=>new T(t)});
/**

@@ -80,3 +80,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/class F{#S;#E;constructor(t){this.#S=structuredClone(t)||[]}onGraphStart(){this.#S.push({graph:0,node:0})}onNodeStart(t){this.#S[this.#S.length-1].node++,this.#E=t}onNodeEnd(){}onGraphEnd(){}async state(){const t=structuredClone(this.#S);return this.#E&&(t[t.length-1].state=await c("nodestart",this.#E)),t}}
*/class F{#$;#E;constructor(t){this.#$=structuredClone(t)||[]}onGraphStart(){this.#$.push({graph:0,node:0})}onNodeStart(t){this.#$[this.#$.length-1].node++,this.#E=t}onNodeEnd(){}onGraphEnd(){}async state(){const t=structuredClone(this.#$);return this.#E&&(t[t.length-1].state=await c("nodestart",this.#E)),t}}
/**

@@ -86,3 +86,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/class W{url;title;description;version;edges=[];nodes=[];kits=[];graphs;args;#O={};#x=[];#P;constructor(t){const{url:e,title:r,description:s,version:n}=t||{};Object.assign(this,{url:e,title:r,description:s,version:n})}async*run(t={},e){const r=t.base||new URL(this.url||"",import.meta.url);yield*M((async s=>{const{probe:n}=t,i=await W.handlersFromBoard(this,t.kits),a={...this.#O,...t.slots};this.#x.forEach((t=>t.addGraph(this)));const c=new o(this,e?.state),p=new q(t),l=t.invocationPath||[],f=new F(t.state);await(n?.report?.({type:"graphstart",data:{metadata:this,path:l,timestamp:u()}}));let w=0;f.onGraphStart();const y=()=>[...l,w];for await(const e of c){w++;const{inputs:o,descriptor:c,missingInputs:l}=e;if(e.skip){await(n?.report?.({type:"skip",data:{node:c,inputs:o,missingInputs:l,path:y(),timestamp:u()}}));continue}let m;if(f.onNodeStart(e),await(n?.report?.({type:"nodestart",data:{node:c,inputs:o,path:y(),timestamp:u()},state:await f.state()})),"input"===c.type)await s(new d(e,await f.state(),w)),await j(this,t,c,e),m=e.outputsPromise;else if("output"===c.type)await s(new h(e,w)),m=e.outputsPromise;else{const n=i[c.type];if(!n)throw new Error(`No handler for node type "${c.type}"`);const u={...t,board:this,descriptor:c,outerGraph:this.#P||this,base:r,slots:a,kits:[...t.kits||[],...this.kits],requestInput:p.createHandler(s,e),invocationPath:y(),state:await f.state()};m=k(n,o,u)}f.onNodeEnd(),await(n?.report?.({type:"nodeend",data:{node:c,inputs:o,outputs:await m,validatorMetadata:this.#x.map((t=>t.getValidatorMetadata(c))),path:y(),timestamp:u()}})),e.outputsPromise=m}f.onGraphEnd(),await(n?.report?.({type:"graphend",data:{metadata:this,path:l,timestamp:u()}}))}))}get validators(){return this.#x}async runOnce(t,e={}){const r={...t,...this.args},{probe:s}=e;if(e.board&&e.descriptor)for(const t of e.board.validators)this.addValidator(t.getSubgraphValidator(e.descriptor,Object.keys(r)));try{let t={};const n=e.invocationPath||[];for await(const o of this.run(e))if("input"===o.type)o.inputs=r;else if("output"===o.type){t=o.outputs,await(s?.report?.({type:"nodeend",data:{node:o.node,inputs:o.inputs,outputs:t,path:[...n,o.invocationId],timestamp:u()}})),await(s?.report?.({type:"graphend",data:{metadata:this,path:n,timestamp:u()}}));break}return t}catch(t){if(t.cause)return{$error:t.cause};throw t}}addValidator(t){this.#x.push(t)}mermaid(t="TD",e=!1){return((t,e="TD",r=!1)=>{const s=new O(t).describeGraph();return r?((t,e)=>`graph ${e};\n${t}`)(s,e):((t,e)=>`%%{init: 'themeVariables': { 'fontFamily': 'Fira Code, monospace' }}%%\ngraph ${e};\n${t}\nclassDef default stroke:#ffab40,fill:#fff2ccff,color:#000\nclassDef input stroke:#3c78d8,fill:#c9daf8ff,color:#000\nclassDef output stroke:#38761d,fill:#b6d7a8ff,color:#000\nclassDef passthrough stroke:#a64d79,fill:#ead1dcff,color:#000\nclassDef slot stroke:#a64d79,fill:#ead1dcff,color:#000\nclassDef config stroke:#a64d79,fill:#ead1dcff,color:#000\nclassDef secrets stroke:#db4437,fill:#f4cccc,color:#000\nclassDef slotted stroke:#a64d79`)(s,e)})(this,t,e)}static async fromGraphDescriptor(t){const e=new W(t);return e.edges=t.edges,e.nodes=t.nodes,e.graphs=t.graphs,e.args=t.args,e}static async load(t,e){const{base:r,slotted:s,outerGraph:n}=e||{},o=new m({base:r,graphs:n?.graphs}),{isSubgraph:i,graph:a}=await o.load(t),c=await W.fromGraphDescriptor(a);return i&&(c.#P=n),c.#O=s||{},c}static async fromBreadboardCapability(t){if("board"!==t.kind||!t.board)throw new Error(`Expected a "board" Capability, but got ${t}`);const e=t.board;if(!(e.edges&&e.kits&&e.nodes))throw new Error('Supplied "board" Capability argument is not actually a board');let r=t.board;return r.runOnce||(r=await W.fromGraphDescriptor(e)),r}static async handlersFromBoard(t,e=[]){const r=[new B,...e,...t.kits];return $(r)}static runRemote=v}class B{handlers;constructor(){this.handlers={lambda:{describe:async t=>({inputSchema:(new P).setAdditionalProperties(!0).addInputs(t).addProperty("board",{title:"board",description:"The board to run.",type:"object"}).build(),outputSchema:(new P).addProperty("board",{title:"board",description:"The now-runnable board.",type:"object"}).build()}),invoke:async t=>{const{board:e,...r}=t;if(!e||"board"!==e.kind||!e.board)throw new Error('Lambda node requires a BoardCapability as "board" input');const s={...await W.fromBreadboardCapability(e),args:r};return{board:{...e,board:s}}}}}}}
*/class W{url;title;description;version;edges=[];nodes=[];kits=[];graphs;args;#O={};#x=[];#P;constructor(t){const{url:e,title:r,description:s,version:n}=t||{};Object.assign(this,{url:e,title:r,description:s,version:n})}async*run(t={},e){const r=t.base||new URL(this.url||"",import.meta.url);yield*M((async s=>{const{probe:n}=t,i=await W.handlersFromBoard(this,t.kits),a={...this.#O,...t.slots};this.#x.forEach((t=>t.addGraph(this)));const c=new o(this,e?.state),p=new q(t),l=t.invocationPath||[],f=new F(t.state);await(n?.report?.({type:"graphstart",data:{metadata:this,path:l,timestamp:u()}}));let w=0;f.onGraphStart();const y=()=>[...l,w];for await(const e of c){w++;const{inputs:o,descriptor:c,missingInputs:l}=e;if(e.skip){await(n?.report?.({type:"skip",data:{node:c,inputs:o,missingInputs:l,path:y(),timestamp:u()}}));continue}let m;if(f.onNodeStart(e),await(n?.report?.({type:"nodestart",data:{node:c,inputs:o,path:y(),timestamp:u()},state:await f.state()})),"input"===c.type)await s(new d(e,await f.state(),w)),await j(this,t,c,e),m=e.outputsPromise;else if("output"===c.type)await s(new h(e,w)),m=e.outputsPromise;else{const n=i[c.type];if(!n)throw new Error(`No handler for node type "${c.type}"`);const u={...t,board:this,descriptor:c,outerGraph:this.#P||this,base:r,slots:a,kits:[...t.kits||[],...this.kits],requestInput:p.createHandler(s,e),invocationPath:y(),state:await f.state()};m=k(n,o,u)}f.onNodeEnd(),await(n?.report?.({type:"nodeend",data:{node:c,inputs:o,outputs:await m,validatorMetadata:this.#x.map((t=>t.getValidatorMetadata(c))),path:y(),timestamp:u()}})),e.outputsPromise=m}f.onGraphEnd(),await(n?.report?.({type:"graphend",data:{metadata:this,path:l,timestamp:u()}}))}))}get validators(){return this.#x}async runOnce(t,e={}){const r={...t,...this.args},{probe:s}=e;if(e.board&&e.descriptor)for(const t of e.board.validators)this.addValidator(t.getSubgraphValidator(e.descriptor,Object.keys(r)));try{let t={};const n=e.invocationPath||[];for await(const o of this.run(e))if("input"===o.type)o.inputs=r;else if("output"===o.type){t=o.outputs,await(s?.report?.({type:"nodeend",data:{node:o.node,inputs:o.inputs,outputs:t,path:[...n,o.invocationId],timestamp:u()}})),await(s?.report?.({type:"graphend",data:{metadata:this,path:n,timestamp:u()}}));break}return t}catch(t){if(t.cause)return{$error:t.cause};throw t}}addValidator(t){this.#x.push(t)}mermaid(t="TD",e=!1,r=!1){return((t,e="TD",r=!1,s=!1)=>{const n=new O(t).describeGraph(s);return r?((t,e)=>`graph ${e};\n${t}`)(n,e):((t,e)=>`%%{init: 'themeVariables': { 'fontFamily': 'Fira Code, monospace' }}%%\ngraph ${e};\n${t}\nclassDef default stroke:#ffab40,fill:#fff2ccff,color:#000\nclassDef input stroke:#3c78d8,fill:#c9daf8ff,color:#000\nclassDef output stroke:#38761d,fill:#b6d7a8ff,color:#000\nclassDef passthrough stroke:#a64d79,fill:#ead1dcff,color:#000\nclassDef slot stroke:#a64d79,fill:#ead1dcff,color:#000\nclassDef config stroke:#a64d79,fill:#ead1dcff,color:#000\nclassDef secrets stroke:#db4437,fill:#f4cccc,color:#000\nclassDef slotted stroke:#a64d79`)(n,e)})(this,t,e,r)}static async fromGraphDescriptor(t){const e=new W(t);return e.edges=t.edges,e.nodes=t.nodes,e.graphs=t.graphs,e.args=t.args,e}static async load(t,e){const{base:r,slotted:s,outerGraph:n}=e||{},o=new m({base:r,graphs:n?.graphs}),{isSubgraph:i,graph:a}=await o.load(t),c=await W.fromGraphDescriptor(a);return i&&(c.#P=n),c.#O=s||{},c}static async fromBreadboardCapability(t){if("board"!==t.kind||!t.board)throw new Error(`Expected a "board" Capability, but got ${t}`);const e=t.board;if(!(e.edges&&e.kits&&e.nodes))throw new Error('Supplied "board" Capability argument is not actually a board');let r=t.board;return r.runOnce||(r=await W.fromGraphDescriptor(e)),r}static async handlersFromBoard(t,e=[]){const r=[new B,...e,...t.kits];return S(r)}static runRemote=v}class B{handlers;constructor(){this.handlers={lambda:{describe:async t=>({inputSchema:(new P).setAdditionalProperties(!0).addInputs(t).addProperty("board",{title:"board",description:"The board to run.",type:"object"}).build(),outputSchema:(new P).addProperty("board",{title:"board",description:"The now-runnable board.",type:"object"}).build()}),invoke:async t=>{const{board:e,...r}=t;if(!e||"board"!==e.kind||!e.board)throw new Error('Lambda node requires a BoardCapability as "board" input');const s={...await W.fromBreadboardCapability(e),args:r};return{board:{...e,board:s}}}}}}}
/**

@@ -108,3 +108,3 @@ * @license

*/
class G extends W{#R=[];#q;#C=[];input(t={}){const{$id:e,...r}=t;return new _(this,void 0,"input",{...r},e)}output(t={}){const{$id:e,...r}=t;return new _(this,void 0,"output",{...r},e)}lambda(t,e={}){const{$id:r,...s}=e;let n,o;if("function"==typeof t){n=new G,o=n.input();const e=n.output();n.#q=this.#q??this,n.#q.#R.push(n),t(n,o,e),n.#q.#R.pop()}else n=t;const i=new _(this,void 0,"lambda",{board:{kind:"board",board:n},...s},r);if(o&&n.#C.length>0){for(const{edge:t,from:e,to:r}of n.#C){if(r!==n||!t.constant)throw new Error("Across board wires: Must be constant and from parent to child");const s=`$l-${t.to}-${t.in}`;n.addEdge({...t,from:o.id,out:s});const a={...t,to:i.id,in:s};e===this?this.addEdge(a):this.addEdgeAcrossBoards(a,e,this)}n.#C=[]}return i}addEdge(t){this.edges.push(t)}addNode(t){this.nodes.push(t)}addKit(t){const e=(r=this,new t({create:(...t)=>new _(r,...t),getConfigWithLambda:t=>H(r,t)}));var r;return this.kits.push(e),e}currentBoardToAddTo(){const t=this.#q?this.#q.#R:this.#R;return 0===t.length?this:t[t.length-1]}addEdgeAcrossBoards(t,e,r){if("*"===t.out)throw new Error("Across board wires: * wires not supported");if(!t.constant)throw new Error("Across board wires: Must be constant for now");if(r!==this)throw new Error("Across board wires: Must be invoked on to board");const s=this.#q?this.#q.#R:this.#R;if(e!==this.#q&&!s.includes(e))throw new Error("Across board wires: From must be parent of to");this.#C.push({edge:t,from:e,to:r})}}
class J extends W{#R=[];#q;#C=[];input(t={}){const{$id:e,...r}=t;return new _(this,void 0,"input",{...r},e)}output(t={}){const{$id:e,...r}=t;return new _(this,void 0,"output",{...r},e)}lambda(t,e={}){const{$id:r,...s}=e;let n,o;if("function"==typeof t){n=new J,o=n.input();const e=n.output();n.#q=this.#q??this,n.#q.#R.push(n),t(n,o,e),n.#q.#R.pop()}else n=t;const i=new _(this,void 0,"lambda",{board:{kind:"board",board:n},...s},r);if(o&&n.#C.length>0){for(const{edge:t,from:e,to:r}of n.#C){if(r!==n||!t.constant)throw new Error("Across board wires: Must be constant and from parent to child");const s=`$l-${t.to}-${t.in}`;n.addEdge({...t,from:o.id,out:s});const a={...t,to:i.id,in:s};e===this?this.addEdge(a):this.addEdgeAcrossBoards(a,e,this)}n.#C=[]}return i}addEdge(t){this.edges.push(t)}addNode(t){this.nodes.push(t)}addKit(t){const e=(r=this,new t({create:(...t)=>new _(r,...t),getConfigWithLambda:t=>H(r,t)}));var r;return this.kits.push(e),e}currentBoardToAddTo(){const t=this.#q?this.#q.#R:this.#R;return 0===t.length?this:t[t.length-1]}addEdgeAcrossBoards(t,e,r){if("*"===t.out)throw new Error("Across board wires: * wires not supported");if(!t.constant)throw new Error("Across board wires: Must be constant for now");if(r!==this)throw new Error("Across board wires: Must be invoked on to board");const s=this.#q?this.#q.#R:this.#R;if(e!==this.#q&&!s.includes(e))throw new Error("Across board wires: From must be parent of to");this.#C.push({edge:t,from:e,to:r})}}
/**

@@ -114,3 +114,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/class J{#A;constructor(t){this.#A=t}async serve(){const t=this.#A.createServerStream().readableRequests.getReader(),e=await t.read();if(e.done)throw new Error("Client closed stream without sending a request.");return e.value.url}}class V{#A;constructor(t){this.#A=t}async load(t){const e=this.#A.createClientStream().writableRequests.getWriter();await e.write({url:t}),await e.close()}}
*/class G{#A;constructor(t){this.#A=t}async serve(){const t=this.#A.createServerStream().readableRequests.getReader(),e=await t.read();if(e.done)throw new Error("Client closed stream without sending a request.");return e.value.url}}class V{#A;constructor(t){this.#A=t}async load(t){const e=this.#A.createClientStream().writableRequests.getWriter();await e.write({url:t}),await e.close()}}
/**

@@ -125,3 +125,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/const Q="stream";class X{kind=Q;stream;constructor(t){this.stream=t}}const Y=t=>{const e=[];return{value:JSON.stringify(t,((t,r)=>(t=>{const e=t;return e&&e.kind&&e.kind===Q&&e.stream instanceof ReadableStream})(r)?(e.push(r.stream),{$type:"Stream",id:e.length-1}):r)),streams:e}},Z=(t,e)=>{const r=JSON.parse(t,((t,r)=>"object"==typeof r&&null!==r&&"Stream"===r.$type&&"number"==typeof r.id?new X(e(r.id)):r));return r},tt=t=>{const e=Y(t).value;return Z(e,(()=>new ReadableStream))},et=t=>({readable:new ReadableStream({start(e){t.onmessage=t=>{null!==t.data?e.enqueue(t.data):e.close()}},cancel(){t.onmessage=null}}),writable:new WritableStream({write(e){const r=Y(e);t.postMessage(e,r.streams)},close(){t.postMessage(null,[])}})});class rt{#T;data;constructor(t,e){this.#T=e,this.data=t}async reply(t){await this.#T.write(t)}}class st{#M;#T;constructor(t,e){this.#M=e.getReader(),this.#T=t.getWriter()}async next(){const{done:t,value:e}=await this.#M.read();return t?(this.#T.close(),{done:t,value:void 0}):{done:!1,value:new rt(e,this.#T)}}async return(){return this.#T.close(),{done:!0,value:void 0}}async throw(t){return this.#T.abort(t),{done:!0,value:void 0}}}const nt=(t,e)=>({async start(e){const r=t.getWriter();await r.write(e),r.releaseLock()},[Symbol.asyncIterator]:()=>new st(t,e)});class ot{#A;constructor(t){this.#A=t}async serve(t,e=!1,r={}){const s=this.#A.createServerStream(),n=s.readableRequests.getReader();let o=await n.read();if(o.done)return;const i=(t=>{const[e,,r]=t;if(console.log("resumeRun",e,r),!r)return;if(r.length>1)throw new Error("I don't yet know how to resume from nested subgraphs.");const s=p.load(r[0].state);if("input"===e){const[,e]=t;s.inputs=e.inputs}return s})(o.value),a=s.writableResponses.getWriter(),c={...r,probe:e?new K((async t=>{const{type:e,data:r}=t,s=[e,tt(r)];"nodestart"==e&&s.push(t.state),await a.write(s)})):void 0};try{for await(const e of t.run(c,i))if("input"===e.type){const t=e.runState,{node:r,inputArguments:s,timestamp:i}=e;if(await a.write(["input",{node:r,inputArguments:s,timestamp:i},t]),o=await n.read(),o.done)return void await a.close();{const[t,r]=o.value;"input"===t&&(e.inputs=r.inputs)}}else if("output"===e.type){const{node:t,outputs:r,timestamp:s}=e;await a.write(["output",{node:t,outputs:r,timestamp:s}])}await a.write(["end",{timestamp:u()}]),await a.close()}catch(t){let e=t,r="";for(;e?.cause;)e=e.cause.error,r+=`\n${e.message}`;console.error("Run Server error:",e.message),await a.write(["error",{error:r,timestamp:u()}]),await a.close()}}}const it=t=>{const[e,r,s]=t.data;return{type:e,data:r,state:s,reply:async r=>{if("input"!==e)throw new Error("For now, we cannot reply to messages other than 'input'.");await t.reply([e,r,s])}}};class at{#A;constructor(t){this.#A=t}async*run(t){const e=this.#A.createClientStream(),r=nt(e.writableRequests,e.readableResponses),s=["run",{}];t&&s.push(t),await r.start(s);for await(const t of r)yield it(t)}async runOnce(t){let e;for await(const r of this.run()){const{type:s,data:n}=r;if("input"===s)r.reply({inputs:t});else if("output"===s){e=n.outputs;break}}return e||{}}}
*/const Q="stream";class X{kind=Q;stream;constructor(t){this.stream=t}}const Y=t=>{const e=[];return{value:JSON.stringify(t,((t,r)=>(t=>{const e=t;return e&&e.kind&&e.kind===Q&&e.stream instanceof ReadableStream})(r)?(e.push(r.stream),{$type:"Stream",id:e.length-1}):r)),streams:e}},Z=(t,e)=>{const r=JSON.parse(t,((t,r)=>"object"==typeof r&&null!==r&&"Stream"===r.$type&&"number"==typeof r.id?new X(e(r.id)):r));return r},tt=t=>{const e=Y(t).value;return Z(e,(()=>new ReadableStream))},et=t=>({readable:new ReadableStream({start(e){t.onmessage=t=>{null!==t.data?e.enqueue(t.data):e.close()}},cancel(){t.onmessage=null}}),writable:new WritableStream({write(e){const r=Y(e);t.postMessage(e,r.streams)},close(){t.postMessage(null,[])}})});class rt{#T;data;constructor(t,e){this.#T=e,this.data=t}async reply(t){await this.#T.write(t)}}class st{#M;#T;constructor(t,e){this.#M=e.getReader(),this.#T=t.getWriter()}async next(){const{done:t,value:e}=await this.#M.read();return t?(this.#T.close(),{done:t,value:void 0}):{done:!1,value:new rt(e,this.#T)}}async return(){return this.#T.close(),{done:!0,value:void 0}}async throw(t){return this.#T.abort(t),{done:!0,value:void 0}}}const nt=(t,e)=>({async start(e){const r=t.getWriter();await r.write(e),r.releaseLock()},[Symbol.asyncIterator]:()=>new st(t,e)});class ot{#A;constructor(t){this.#A=t}async serve(t,e=!1,r={}){const s=this.#A.createServerStream(),n=s.readableRequests.getReader();let o=await n.read();if(o.done)return;const i=(t=>{const[e,,r]=t;if(console.log("resumeRun",e,r),!r)return;if(r.length>1)throw new Error("I don't yet know how to resume from nested subgraphs.");const s=p.load(r[0].state);if("input"===e){const[,e]=t;s.inputs=e.inputs}return s})(o.value),a=s.writableResponses.getWriter(),c={...r,probe:e?new K((async t=>{const{type:e,data:r}=t,s=[e,tt(r)];"nodestart"==e&&s.push(t.state),await a.write(s)})):void 0};try{for await(const e of t.run(c,i))if("input"===e.type){const t=e.runState,{node:r,inputArguments:s,timestamp:i}=e;if(await a.write(["input",{node:r,inputArguments:s,timestamp:i},t]),o=await n.read(),o.done)return void await a.close();{const[t,r]=o.value;"input"===t&&(e.inputs=r.inputs)}}else if("output"===e.type){const{node:t,outputs:r,timestamp:s}=e;await a.write(["output",{node:t,outputs:r,timestamp:s}])}await a.write(["end",{timestamp:u()}]),await a.close()}catch(t){const e=t;let r;if(e?.cause){const{cause:t}=e;r=t}else r=e.message;console.error("Run Server error:",r),await a.write(["error",{error:r,timestamp:u()}]),await a.close()}}}const it=t=>{const[e,r,s]=t.data;return{type:e,data:r,state:s,reply:async r=>{if("input"!==e)throw new Error("For now, we cannot reply to messages other than 'input'.");await t.reply([e,r,s])}}};class at{#A;constructor(t){this.#A=t}async*run(t){const e=this.#A.createClientStream(),r=nt(e.writableRequests,e.readableResponses),s=["run",{}];t&&s.push(t),await r.start(s);for await(const t of r)yield it(t)}async runOnce(t){let e;for await(const r of this.run()){const{type:s,data:n}=r;if("input"===s)r.reply({inputs:t});else if("output"===s){e=n.outputs;break}}return e||{}}}
/**

@@ -141,3 +141,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/const lt=globalThis.process?t=>Buffer.from(t,"base64").toString("binary"):globalThis.atob,ft=globalThis.process?t=>Buffer.from(t,"binary").toString("base64"):globalThis.btoa;class wt{outputName;from;to;when;constructor(t,e,r,s={}){this.outputName=t,this.from=e,this.to=r,this.when=s}getInputNames(){const t=Object.keys(this.when);return 0===t.length?[this.outputName]:t}matches(t){return Object.entries(this.when).every((([e,r])=>{const s=t[e];return"string"==typeof r?s===r:"string"==typeof s&&r.test(s)}))}}const yt=(t,e)=>Object.fromEntries(Object.entries(e).map((([e,r])=>"string"==typeof r?[e,[new wt(e,t,r)]]:Array.isArray(r)?[e,r.map((r=>"string"==typeof r?new wt(e,t,r):new wt(e,t,r.to,r.when)))]:[e,[new wt(e,t,r.to,r.when)]]))),mt=Math.round(Date.now()/6048e5).toString(36),gt=`T-${mt}-`,bt=`-${mt}-T`,vt=new RegExp(`(${gt}.*?${bt})`,"gm"),kt=new RegExp(`^${gt}(.+?)${bt}$`),$t=async(t,e,r)=>{const s=JSON.stringify(t),n=s.split(vt).filter(Boolean).map((t=>{const e=t.match(kt);if(e){const t=e[1].split("~"),[r,s,n]=t;return{nodeType:r,outputName:s,inputs:lt(n)}}return{value:t}}));const o=await Promise.all(n.map((async t=>{if("inputs"in t){const s=JSON.parse(t.inputs),{nodeType:n,outputName:o}=t,i=e?await r(n,s):{[o]:"VALUE_BLOCKED"};if(!i)return"";let a=JSON.stringify(i[o]);return a.startsWith('"')&&(a=a.slice(1,-1)),a=JSON.stringify(a),a.slice(1,-1)}return t.value})));return JSON.parse(o.join(""))},St=(t,e)=>{const r=Object.fromEntries(Object.entries(e).map((([e,r])=>{const s=t[e];return s?[e,async(t,n)=>((t,e,r)=>{if(t)return Object.fromEntries(Object.entries(t).map((([t,s])=>t in e?[t,r(t,s)]:[t,s])))})(await k(r,t,n),s,(r=>((t,e,r)=>{const s=ft(JSON.stringify(r)).replace("=","");return`${gt}${t}~${e}~${s}${bt}`})(e,r,t)))]:[e,r]}))),s=(t=>Object.entries(t).flatMap((([t,e])=>Object.entries(e).flatMap((([t,e])=>e.map((t=>[t.to,t])))))).reduce(((t,[e,r])=>(t[e]||(t[e]=[]),t[e].push(r),t)),{}))(t),n=Object.fromEntries(Object.entries(r).map((([t,r])=>{const n=s[t];return n?[t,async(t,s)=>k(r,await(async(t,e,r)=>{const s=e.some((e=>e.matches(t)));return Object.fromEntries(await Promise.all(Object.entries(t).map((async([t,e])=>[t,await r(e,s)]))))})(t,n,(async(t,r)=>$t(t,r,(async(t,r)=>k(e[t],r,s))))),s)]:[t,r]})));return{url:"tunnel-kit",handlers:n}},Et=(t,e=[])=>{const r=e.find((e=>"string"==typeof e?e===t:e.node===t));return"string"==typeof r?{node:r}:r};class Ot{#A;constructor(t){this.#A=t}async serve(t){const{kits:e}=t,r=this.#A.createServerStream(),s=St((t=>t.proxy?Object.fromEntries(t.proxy.map((t=>{if("string"!=typeof t&&t.tunnel)return[t.node,yt(t.node,t.tunnel)]})).filter(Boolean)):{})(t),$(e)),n=s.handlers;for await(const e of nt(r.writableResponses,r.readableRequests)){const[r]=e.data;if("end"===r)break;if("proxy"!==r){e.reply(["error",{error:"Expected proxy request.",timestamp:u()}]);continue}const[,{node:s,inputs:o}]=e.data,i=Et(s.type,t.proxy)?n[s.type]:void 0;if(i)try{const t=await k(i,o,{descriptor:s});if(!t){e.reply(["error",{error:"Handler returned nothing.",timestamp:u()}]);continue}e.reply(["proxy",{outputs:t}])}catch(t){e.reply(["error",{error:t.message,timestamp:u()}])}else e.reply(["error",{error:"Can't proxy a node of this node type.",timestamp:u()}])}}}class xt{#A;constructor(t){this.#A=t}shutdownServer(){const t=this.#A.createClientStream().writableRequests.getWriter();t.write(["end",{timestamp:u()}]),t.close()}async proxy(t,e){const r=this.#A.createClientStream(),s=r.writableRequests.getWriter(),n=r.readableResponses.getReader();s.write(["proxy",{node:t,inputs:e}]),s.close();const o=await n.read();if(o.done)throw new Error("Unexpected proxy failure: empty response.");const[i]=o.value;if("proxy"===i){const[,{outputs:t}]=o.value;return t}if("error"===i){const[,{error:t}]=o.value;throw new Error(t)}throw new Error(`Unexpected proxy failure: unknown response type "${i}".`)}createProxyKit(t=[]){const e=t.map((t=>"string"==typeof t?t:t.node)),r=Object.fromEntries(e.map((t=>[t,{invoke:async(t,e)=>{const r=e.descriptor;return await this.proxy(r,t)}}])));return z(new ht({url:"proxy"}).build(r))}}
*/const lt=globalThis.process?t=>Buffer.from(t,"base64").toString("binary"):globalThis.atob,ft=globalThis.process?t=>Buffer.from(t,"binary").toString("base64"):globalThis.btoa;class wt{outputName;from;to;when;constructor(t,e,r,s={}){this.outputName=t,this.from=e,this.to=r,this.when=s}getInputNames(){const t=Object.keys(this.when);return 0===t.length?[this.outputName]:t}matches(t){return Object.entries(this.when).every((([e,r])=>{const s=t[e];return"string"==typeof r?s===r:"string"==typeof s&&r.test(s)}))}}const yt=(t,e)=>Object.fromEntries(Object.entries(e).map((([e,r])=>"string"==typeof r?[e,[new wt(e,t,r)]]:Array.isArray(r)?[e,r.map((r=>"string"==typeof r?new wt(e,t,r):new wt(e,t,r.to,r.when)))]:[e,[new wt(e,t,r.to,r.when)]]))),mt=Math.round(Date.now()/6048e5).toString(36),gt=`T-${mt}-`,bt=`-${mt}-T`,vt=new RegExp(`(${gt}.*?${bt})`,"gm"),kt=new RegExp(`^${gt}(.+?)${bt}$`),St=async(t,e,r)=>{const s=JSON.stringify(t),n=s.split(vt).filter(Boolean).map((t=>{const e=t.match(kt);if(e){const t=e[1].split("~"),[r,s,n]=t;return{nodeType:r,outputName:s,inputs:lt(n)}}return{value:t}}));const o=await Promise.all(n.map((async t=>{if("inputs"in t){const s=JSON.parse(t.inputs),{nodeType:n,outputName:o}=t,i=e?await r(n,s):{[o]:"VALUE_BLOCKED"};if(!i)return"";let a=JSON.stringify(i[o]);return a.startsWith('"')&&(a=a.slice(1,-1)),a=JSON.stringify(a),a.slice(1,-1)}return t.value})));return JSON.parse(o.join(""))},$t=(t,e)=>{const r=Object.fromEntries(Object.entries(e).map((([e,r])=>{const s=t[e];return s?[e,async(t,n)=>((t,e,r)=>{if(t)return Object.fromEntries(Object.entries(t).map((([t,s])=>t in e?[t,r(t,s)]:[t,s])))})(await k(r,t,n),s,(r=>((t,e,r)=>{const s=ft(JSON.stringify(r)).replace("=","");return`${gt}${t}~${e}~${s}${bt}`})(e,r,t)))]:[e,r]}))),s=(t=>Object.entries(t).flatMap((([t,e])=>Object.entries(e).flatMap((([t,e])=>e.map((t=>[t.to,t])))))).reduce(((t,[e,r])=>(t[e]||(t[e]=[]),t[e].push(r),t)),{}))(t),n=Object.fromEntries(Object.entries(r).map((([t,r])=>{const n=s[t];return n?[t,async(t,s)=>k(r,await(async(t,e,r)=>{const s=e.some((e=>e.matches(t)));return Object.fromEntries(await Promise.all(Object.entries(t).map((async([t,e])=>[t,await r(e,s)]))))})(t,n,(async(t,r)=>St(t,r,(async(t,r)=>k(e[t],r,s))))),s)]:[t,r]})));return{url:"tunnel-kit",handlers:n}},Et=(t,e=[])=>{const r=e.find((e=>"string"==typeof e?e===t:e.node===t));return"string"==typeof r?{node:r}:r};class Ot{#A;constructor(t){this.#A=t}async serve(t){const{kits:e}=t,r=this.#A.createServerStream(),s=$t((t=>t.proxy?Object.fromEntries(t.proxy.map((t=>{if("string"!=typeof t&&t.tunnel)return[t.node,yt(t.node,t.tunnel)]})).filter(Boolean)):{})(t),S(e)),n=s.handlers;for await(const e of nt(r.writableResponses,r.readableRequests)){const[r]=e.data;if("end"===r)break;if("proxy"!==r){e.reply(["error",{error:"Expected proxy request.",timestamp:u()}]);continue}const[,{node:s,inputs:o}]=e.data,i=Et(s.type,t.proxy)?n[s.type]:void 0;if(i)try{const t=await k(i,o,{descriptor:s});if(!t){e.reply(["error",{error:"Handler returned nothing.",timestamp:u()}]);continue}e.reply(["proxy",{outputs:t}])}catch(t){e.reply(["error",{error:t.message,timestamp:u()}])}else e.reply(["error",{error:"Can't proxy a node of this node type.",timestamp:u()}])}}}class xt{#A;constructor(t){this.#A=t}shutdownServer(){const t=this.#A.createClientStream().writableRequests.getWriter();t.write(["end",{timestamp:u()}]),t.close()}async proxy(t,e){const r=this.#A.createClientStream(),s=r.writableRequests.getWriter(),n=r.readableResponses.getReader();s.write(["proxy",{node:t,inputs:e}]),s.close();const o=await n.read();if(o.done)throw new Error("Unexpected proxy failure: empty response.");const[i]=o.value;if("proxy"===i){const[,{outputs:t}]=o.value;return t}if("error"===i){const[,{error:t}]=o.value;throw new Error(JSON.stringify(t))}throw new Error(`Unexpected proxy failure: unknown response type "${i}".`)}createProxyKit(t=[]){const e=t.map((t=>"string"==typeof t?t:t.node)),r=Object.fromEntries(e.map((t=>[t,{invoke:async(t,e)=>{const r=e.descriptor;return await this.proxy(r,t)}}])));return z(new ht({url:"proxy"}).build(r))}}
/**

@@ -147,3 +147,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/const Pt=t=>t.base?t.base:"window"in self?new URL(self.location.href):new URL(import.meta.url);class Nt{#D;constructor(t){this.#D=t}client(t){return new pt(this.#D.send(t))}server(t){return new dt(this.#D.receive(t))}}const jt=async t=>{if("worker"!==t.transport)throw new Error("Only worker transport is supported at this time.");const e="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:(()=>{throw new Error("Not implemented")})(),r=new Nt(new ut(e)),s=((t,e)=>t.map((t=>"proxy"in t?new xt(e.client("proxy")).createProxyKit(t.proxy):t)))(t.kits,r),n=new ot(r.server("run")),o=await(async(t,e)=>{const r=t.url;if(r)return r;const s=new J(e.server("load"));return await s.serve()})(t,r),i=Pt(t),a=await G.load(o,{base:i});return n.serve(a,!!t.diagnostics,{kits:s})},It=t=>t;
*/const Pt=t=>t.base?t.base:"window"in self?new URL(self.location.href):new URL(import.meta.url);class Nt{#D;constructor(t){this.#D=t}client(t){return new pt(this.#D.send(t))}server(t){return new dt(this.#D.receive(t))}}const jt=async t=>{if("worker"!==t.transport)throw new Error("Only worker transport is supported at this time.");const e="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:(()=>{throw new Error("Not implemented")})(),r=new Nt(new ut(e)),s=((t,e)=>t.map((t=>"proxy"in t?new xt(e.client("proxy")).createProxyKit(t.proxy):t)))(t.kits,r),n=new ot(r.server("run")),o=await(async(t,e)=>{const r=t.url;if(r)return r;const s=new G(e.server("load"));return await s.serve()})(t,r),i=Pt(t),a=await J.load(o,{base:i});return n.serve(a,!!t.diagnostics,{kits:s})},It=t=>t;
/**

@@ -169,3 +169,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/class Tt{parentLexicalScope;parentDynamicScope;#G={};#J=[];#V=[];constructor(t={}){this.parentLexicalScope=t.lexicalScope,this.parentDynamicScope=t.dynamicScope}addHandlers(t){Object.entries(t).forEach((([t,e])=>this.#G[t]=e))}getHandler(t){return this.#G[t]||this.parentDynamicScope?.getHandler(t)||this.parentLexicalScope?.getHandler(t)}pin(t){this.#J.push(t)}compactPins(){const t=new Set,e=[];for(const r of this.#J){if(t.has(r))continue;e.push(r);this.#K(r).forEach((e=>t.add(e)))}this.#J=e}getPinnedNodes(){return this.#J}addCallbacks(t){this.#V.push(t)}#Q(){return[...this.#V,...this.parentDynamicScope?this.parentDynamicScope.#Q():[]]}async invoke(t,e=new At){try{!1!==t&&(t?t instanceof Array?t:[t]:this.#J).flatMap((t=>this.#K(t).filter((t=>!1===e?.missingInputs(t))))).forEach((t=>e?.queueUp(t)));const r=this.#Q();for(;!e.done();){for(const t of r)if(await(t.stop?.(this,e)))return;const t=e.next(),s=e.shiftInputs(t);let n;for(const e of r)n??=await(e.before?.(this,t,s));const o=n??await t.invoke(s,this).catch((t=>({$error:{type:"error",error:t}}))),i=e.processResult(t,o);for(const e of r)await(e.after?.(this,t,s,o,i));if(i.unused.includes("$error"))throw o.$error.error}}finally{for(const t of this.#V)await(t.done?.())}}invokeOneRound(t={},e=void 0,r){let s;"$state"in t&&(r=t.$state,delete t.$state);const n=new Promise((t=>{s=t})),o=new Tt({dynamicScope:this});let i;o.addHandlers({input:async()=>t,output:async t=>(s?.(await t),s=void 0,t)});const a=new Map;let c;o.addCallbacks({stop:(t,e)=>(s||(c=e),!s),after:(t,e,r,s,n)=>{i=e;for(const{node:t,missing:e}of n.nodes)e?a.set(t.id,e.join(", ")):a.delete(t.id)},done:()=>{s?.({$error:{type:"error",error:new Error(`Output node never reach. Last node was ${i?.id}.\n\nThese nodes had inputs missing:\n${Array.from(a,(([t,e])=>` ${t}: ${e}`)).join("\n")}`)}})}});const u=o.invoke(void 0!==e?e:this.#J,r);return Promise.all([n,u]).then((([t])=>({...t,...c?{$state:c}:{}})))}async serialize(t,e){const r=(e?[e]:this.#J).flatMap((t=>this.#K(t))),s={},n=await Promise.all(r.map((async t=>{const[e,r]=await t.serializeNode();if(r&&(s[e.id]=r),("input"===e.type||"output"===e.type)&&!e.configuration?.schema){const r=await this.#X(t);Object.entries(r.properties??{}).length>0&&(e.configuration={...e.configuration,schema:r})}return e}))),o=r.flatMap((t=>t.outgoing.map((t=>({from:t.from.id,to:t.to.id,out:t.out,in:t.in,...t.constant?{constant:!0}:{}})))));return{...t,edges:o,nodes:n,graphs:s}}#K(t){const e=new Set,r=[t];for(;r.length;){const t=r.shift();e.has(t)||(e.add(t),t.incoming.forEach((t=>r.push(t.from))),t.outgoing.forEach((t=>r.push(t.to))))}return[...e]}async#Y(t){const e=Object.fromEntries(t.incoming.filter((t=>""!==t.out&&"*"!==t.out)).map((t=>[t.out,t.schema??{}]))),r=Object.fromEntries(t.outgoing.filter((t=>""!==t.out&&"*"!==t.out)).map((t=>[t.out,t.schema??{}])));return await t.describe(this,t.configuration,{properties:e},{properties:r})}async#X(t){const e={},r=new Set;if("input"===t.type){const s=new Set;for(const n of t.outgoing)"*"!==n.out&&""!==n.out&&(s.add(n.to),r.add(n.out),n.schema&&(e[n.out]=n.schema));for(const r of s){const s=await this.#Y(r),n=s?.inputSchema?.properties;if(n)for(const s of r.incoming)s.from===t&&n[s.in]&&(e[s.out]={...n[s.in],...e[s.out]})}}else{if("output"!==t.type)throw new Error("Can't yet derive schema for non-input/output nodes");{const s=new Set;for(const n of t.incoming)"*"!==n.out&&""!==n.out&&(s.add(n.from),r.add(n.in),n.schema&&(e[n.in]=n.schema));for(const r of s){const s=await this.#Y(r),n=s?.outputSchema?.properties;if(n)for(const s of r.outgoing)s.to===t&&n[s.out]&&(e[s.in]={...n[s.out],...e[s.in]})}}}for(const t of r)e[t]?(e[t].type||="string",e[t].title||=t):e[t]={type:"string",title:t};const s=(t=>Object.entries(t).map((([t,e])=>{const r=e;if(!r.$optional)return t;delete r.$optional})).filter(Boolean))(e);return{type:"object",properties:e,required:s}}}
*/class Tt{parentLexicalScope;parentDynamicScope;#J={};#G=[];#V=[];constructor(t={}){this.parentLexicalScope=t.lexicalScope,this.parentDynamicScope=t.dynamicScope}addHandlers(t){Object.entries(t).forEach((([t,e])=>this.#J[t]=e))}getHandler(t){return this.#J[t]||this.parentDynamicScope?.getHandler(t)||this.parentLexicalScope?.getHandler(t)}pin(t){this.#G.push(t)}compactPins(){const t=new Set,e=[];for(const r of this.#G){if(t.has(r))continue;e.push(r);this.#K(r).forEach((e=>t.add(e)))}this.#G=e}getPinnedNodes(){return this.#G}addCallbacks(t){this.#V.push(t)}#Q(){return[...this.#V,...this.parentDynamicScope?this.parentDynamicScope.#Q():[]]}async invoke(t,e=new At){try{!1!==t&&(t?t instanceof Array?t:[t]:this.#G).flatMap((t=>this.#K(t).filter((t=>!1===e?.missingInputs(t))))).forEach((t=>e?.queueUp(t)));const r=this.#Q();for(;!e.done();){for(const t of r)if(await(t.stop?.(this,e)))return;const t=e.next(),s=e.shiftInputs(t);let n;for(const e of r)n??=await(e.before?.(this,t,s));const o=n??await t.invoke(s,this).catch((t=>({$error:{type:"error",error:t}}))),i=e.processResult(t,o);for(const e of r)await(e.after?.(this,t,s,o,i));if(i.unused.includes("$error"))throw o.$error.error}}finally{for(const t of this.#V)await(t.done?.())}}invokeOneRound(t={},e=void 0,r){let s;"$state"in t&&(r=t.$state,delete t.$state);const n=new Promise((t=>{s=t})),o=new Tt({dynamicScope:this});let i;o.addHandlers({input:async()=>t,output:async t=>(s?.(await t),s=void 0,t)});const a=new Map;let c;o.addCallbacks({stop:(t,e)=>(s||(c=e),!s),after:(t,e,r,s,n)=>{i=e;for(const{node:t,missing:e}of n.nodes)e?a.set(t.id,e.join(", ")):a.delete(t.id)},done:()=>{s?.({$error:{type:"error",error:new Error(`Output node never reach. Last node was ${i?.id}.\n\nThese nodes had inputs missing:\n${Array.from(a,(([t,e])=>` ${t}: ${e}`)).join("\n")}`)}})}});const u=o.invoke(void 0!==e?e:this.#G,r);return Promise.all([n,u]).then((([t])=>({...t,...c?{$state:c}:{}})))}async serialize(t,e){const r=(e?[e]:this.#G).flatMap((t=>this.#K(t))),s={},n=await Promise.all(r.map((async t=>{const[e,r]=await t.serializeNode();if(r&&(s[e.id]=r),("input"===e.type||"output"===e.type)&&!e.configuration?.schema){const r=await this.#X(t);Object.entries(r.properties??{}).length>0&&(e.configuration={...e.configuration,schema:r})}return e}))),o=r.flatMap((t=>t.outgoing.map((t=>({from:t.from.id,to:t.to.id,out:t.out,in:t.in,...t.constant?{constant:!0}:{}})))));return{...t,edges:o,nodes:n,graphs:s}}#K(t){const e=new Set,r=[t];for(;r.length;){const t=r.shift();e.has(t)||(e.add(t),t.incoming.forEach((t=>r.push(t.from))),t.outgoing.forEach((t=>r.push(t.to))))}return[...e]}async#Y(t){const e=Object.fromEntries(t.incoming.filter((t=>""!==t.out&&"*"!==t.out)).map((t=>[t.out,t.schema??{}]))),r=Object.fromEntries(t.outgoing.filter((t=>""!==t.out&&"*"!==t.out)).map((t=>[t.out,t.schema??{}])));return await t.describe(this,t.configuration,{properties:e},{properties:r})}async#X(t){const e={},r=new Set;if("input"===t.type){const s=new Set;for(const n of t.outgoing)"*"!==n.out&&""!==n.out&&(s.add(n.to),r.add(n.out),n.schema&&(e[n.out]=n.schema));for(const r of s){const s=await this.#Y(r),n=s?.inputSchema?.properties;if(n)for(const s of r.incoming)s.from===t&&n[s.in]&&(e[s.out]={...n[s.in],...e[s.out]})}}else{if("output"!==t.type)throw new Error("Can't yet derive schema for non-input/output nodes");{const s=new Set;for(const n of t.incoming)"*"!==n.out&&""!==n.out&&(s.add(n.from),r.add(n.in),n.schema&&(e[n.in]=n.schema));for(const r of s){const s=await this.#Y(r),n=s?.outputSchema?.properties;if(n)for(const s of r.outgoing)s.to===t&&n[s.out]&&(e[s.in]={...n[s.out],...e[s.in]})}}}for(const t of r)e[t]?(e[t].type||="string",e[t].title||=t):e[t]={type:"string",title:t};const s=(t=>Object.entries(t).map((([t,e])=>{const r=e;if(!r.$optional)return t;delete r.$optional})).filter(Boolean))(e);return{type:"object",properties:e,required:s}}}
/**

@@ -190,3 +190,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/const Ut=Symbol("IsValue");function Dt(t){return("object"==typeof t||"function"==typeof t)&&void 0!==t[Ut]}class _t extends Lt{#et;#z;#rt;#st;#nt;constructor(t,e,r,s=!1,n={}){super(),this.#et=t,this.#z=e,this.#rt="string"==typeof r?{[r]:r}:r,this[Ut]=this,this.#st=s,this.#nt=n}then(t,e){if(1!==Object.keys(this.#rt).length)throw Error("Can't `await` for multiple values");return this.#et.then((e=>e&&t&&this.#z.asScopeFor(t)(e[Object.keys(this.#rt)[0]])),e&&this.#z.asScopeFor(e))}asNodeInput(){return[this.#et.unProxy(),this.#rt,this.#st,this.#nt]}to(t,e){const r=Ht(t)?t.unProxy():new zt(t,this.#z,e);return r.addInputsFromNode(this.#et,this.#rt,this.#st,this.#nt),r.asProxy()}in(t){let e=Object.fromEntries(Object.entries(this.#rt).map((([t,e])=>[e,t])));Dt(t)?(e=t.#ot(e),this.#et.addInputsFromNode(t.#et,e,t.#st,t.#nt)):Ht(t)?this.#et.addInputsFromNode(t.unProxy(),e):this.#et.addInputsAsValues(t)}as(t){let e;if("string"==typeof t){if(1!==Object.keys(this.#rt).length)throw new Error("Can't rename multiple values with a single string");e={[Object.keys(this.#rt)[0]]:t}}else e=this.#ot(t);return new _t(this.#et,this.#z,e,this.#st,this.#nt)}memoize(){return new _t(this.#et,this.#z,this.#rt,!0,this.#nt)}invoke(t){return new zt("invoke",this.#z,{...t,$recipe:this}).asProxy()}isUnknown(){return delete this.#nt.type,this}isString(){return this.#nt.type="string",this}isNumber(){return this.#nt.type="number",this}isBoolean(){return this.#nt.type="boolean",this}isArray(){return this.#nt.type="array",this}isObject(){return this.#nt.type="object",this}title(t){return this.#nt.title=t,this}description(t){return this.#nt.description=t,this}format(t){return this.#nt.format=t,this}examples(...t){return this.#nt.examples=t,this}default(t){return this.#nt.default=t,this}optional(){return this.#nt.$optional=!0,this}#ot(t){const e={...this.#rt};return Object.entries(t).forEach((([t,r])=>{this.#rt[r]?(e[t]=this.#rt[r],delete this.#rt[r]):e[t]=r})),e}}
*/const Ut=Symbol("IsValue");function Dt(t){return("object"==typeof t||"function"==typeof t)&&void 0!==t[Ut]}class _t extends Lt{#et;#z;#rt;#st;#nt;constructor(t,e,r,s=!1,n={}){super(),this.#et=t,this.#z=e,this.#rt="string"==typeof r?{[r]:r}:r,this[Ut]=this,this.#st=s,this.#nt=n}then(t,e){if(1!==Object.keys(this.#rt).length)throw Error("Can't `await` for multiple values");return this.#et.then((e=>e&&t&&this.#z.asScopeFor(t)(e[Object.keys(this.#rt)[0]])),e&&this.#z.asScopeFor(e))}asNodeInput(){return[this.#et.unProxy(),this.#rt,this.#st,this.#nt]}to(t,e){const r=Ht(t)?t.unProxy():new zt(t,this.#z,e);return r.addInputsFromNode(this.#et,this.#rt,this.#st,this.#nt),r.asProxy()}in(t){let e=Object.fromEntries(Object.entries(this.#rt).map((([t,e])=>[e,t])));Dt(t)?(e=t.#ot(e),this.#et.addInputsFromNode(t.#et,e,t.#st,t.#nt)):Ht(t)?this.#et.addInputsFromNode(t.unProxy(),e):this.#et.addInputsAsValues(t)}as(t){let e;if("string"==typeof t){if(1!==Object.keys(this.#rt).length)throw new Error("Can't rename multiple values with a single string");e={[Object.keys(this.#rt)[0]]:t}}else e=this.#ot(t);return new _t(this.#et,this.#z,e,this.#st,this.#nt)}memoize(){return new _t(this.#et,this.#z,this.#rt,!0,this.#nt)}invoke(t){return new zt("invoke",this.#z,{...t,$board:this}).asProxy()}isUnknown(){return delete this.#nt.type,this}isString(){return this.#nt.type="string",this}isNumber(){return this.#nt.type="number",this}isBoolean(){return this.#nt.type="boolean",this}isArray(){return this.#nt.type="array",this}isObject(){return this.#nt.type="object",this}title(t){return this.#nt.title=t,this}description(t){return this.#nt.description=t,this}format(t){return this.#nt.format=t,this}examples(...t){return this.#nt.examples=t,this}default(t){return this.#nt.default=t,this}optional(){return this.#nt.$optional=!0,this}#ot(t){const e={...this.#rt};return Object.entries(t).forEach((([t,r])=>{this.#rt[r]?(e[t]=this.#rt[r],delete this.#rt[r]):e[t]=r})),e}}
/**

@@ -196,3 +196,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/class zt extends Ct{#it;#at;#ct;#z;#_;constructor(t,e,r={}){const s=!Ht(r)&&!(r instanceof Rt)&&!Jt(r)&&!Dt(r)&&r.$id;super(t,e,s?{$id:s}:{}),this.#z=e,"string"!=typeof t&&(this.#_=t),Ht(r)?this.addInputsFromNode(r.unProxy()):r instanceof Rt?this.addInputsFromNode(r):Jt(r)?this.addInputsAsValues({$recipe:r.getBoardCapabilityAsValue()}):Dt(r)?this.addInputsFromNode(...r.asNodeInput()):(void 0!==r.$id&&delete r.$id,this.addInputsAsValues(r)),this[this.#ut()]=this,this.#it=new Promise(((t,e)=>{this.#at=t,this.#ct=e}))}addInputsAsValues(t){const e={},r=[];Object.entries(t).forEach((([t,s])=>{Jt(s)&&(s=s.getBoardCapabilityAsValue()),Dt(s)?r.push(s.as(t).asNodeInput()):s instanceof Rt||Ht(s)?r.push([Ht(s)?s.unProxy():s,{[t]:t},!1,void 0]):e[t]=s})),this.configuration={...this.configuration,...e},r.forEach((t=>this.unProxy().addInputsFromNode(...t)))}addInputsFromNode(t,e={"*":""},r,s){const n=Object.entries(e);0===n.length?this.addIncomingEdge(t,"","",r):n.forEach((([e,n])=>{e.startsWith("*-")&&(e="*",n=""),this.unProxy().addIncomingEdge(Ht(t)?t.unProxy():t,e,n,r,s)}))}addIncomingEdge(t,e,r,s,n){const o=t.#z;if(o!==this.#z){for(let t=this.#z;t!==o;t=t.parentLexicalScope)if(!t)throw new Error("Only wires from parent scopes allowed");if("*"===e||""===e)throw new Error("Can't use * or empty wires from parent scopes");this.#z.addClosureEdge({scope:o,from:t,to:this,out:e,in:r})}else super.addIncomingEdge(t,e,r,s,n)}async invoke(t,e){const r=new Bt({dynamicScope:e,lexicalScope:this.#z});return r.asScopeFor((async()=>{try{const e=this.#_??r.getHandler(this.type);let s;const n="function"==typeof e?e:e?.invoke;if(n)s=await n(t,this);else{if(!e||"function"==typeof e||!e.graph)throw new Error(`Can't find handler for ${this.id}`);{const n=e.graph.getPinnedNodes();if(1!==n.length)throw new Error("Expected exactly one graph");s=await r.invokeOneRound(t,n[0])}}for(const[t,e]of Object.entries(s))e instanceof zt?s[t]=(await e)[t]:Dt(e)?s[t]=await e:Jt(e)&&(s[t]=await e.getBoardCapabilityAsValue());return this.#at&&(this.#at(s),this.#at=this.#ct=void 0),s}catch(t){throw this.#ct&&(this.#ct(t),this.#at=this.#ct=void 0),t}}))()}async serializeNode(){for(const[t,e]of Object.entries(this.configuration))e instanceof Promise&&(this.configuration[t]=await e);if("fn"!==this.type)return super.serializeNode();const t=new Bt({lexicalScope:this.#z,serialize:!0}),e=this.#_??t.getHandler(this.type);if(e&&"function"!=typeof e&&e.graph){const r={id:this.id,type:"invoke",configuration:{...this.configuration,path:"#"+this.id}},s=e.graph.getPinnedNodes();if(1!==s.length)throw new Error("Expected exactly one graph");return[r,await t.serialize({},s[0])]}const r="function"==typeof e?e:e?.invoke;if(!r)throw new Error(`Handler for ${this.type} in ${this.id} not found`);let s=r.toString(),n=this.id.replace(/-/g,"_");const o=/(?:async\s*)?(\w+|\([^)]*\))\s*=>\s*/,i=/(?:async\s+)?function\s+(\w+)\s*\(([^)]*)\)\s*\{/;if(o.test(s))s=s.replace(o,((t,e)=>{const r=s.trim().startsWith("async")?"async ":"",o=e.startsWith("(")?e:`(${e})`;return`${r}function ${n}${o} `}));else{const t=i.exec(s);if(null===t)throw new Error("Unexpected seralization: "+s);n=t[1]||n}const a=await this.describe(t),c={edges:[{from:`${this.id}-input`,to:`${this.id}-run`,out:"*"},{from:`${this.id}-run`,to:`${this.id}-output`,out:"*"}],nodes:[{id:`${this.id}-input`,type:"input",configuration:a?.inputSchema?{schema:a.inputSchema}:{}},{id:`${this.id}-run`,type:"runJavascript",configuration:{...this.configuration,code:s,name:n,raw:!0}},{id:`${this.id}-output`,type:"output",configuration:a?.outputSchema?{schema:a.outputSchema}:{}}]};return[{id:this.id,type:"invoke",configuration:{path:"#"+this.id}},c]}asProxy(){return new Proxy(this,{get(t,e,r){if("string"==typeof e){const r=new _t(t,t.#z,e);let s=t[e];return s=s&&"function"==typeof s?s.bind(t):(t=>r.invoke(t)).bind(r),new Proxy(s,{get(t,e,s){const n=Reflect.get(r,e,r);return"function"==typeof n?n.bind(r):n},ownKeys:t=>Reflect.ownKeys(r).filter((t=>"string"==typeof t))})}return Reflect.get(t,e,r)},ownKeys:t=>[t.#ut()]})}unProxy(){return this}then(t,e){if(this.#z.serializing())throw new Error(`Can't \`await\` on ${this.id} in recipe declaration. Did you mean to use \`code\` instead of \`recipe\`?`);try{return this.#z.invoke(this).catch((t=>{if(e)return Promise.reject(t).catch(this.#z.asScopeFor(e));throw t})),this.#it.then(t&&this.#z.asScopeFor(t),e&&this.#z.asScopeFor(e))}catch(t){if(e)return Promise.reject(t).catch(this.#z.asScopeFor(e));throw t}}to(t,e){const r=Ht(t)?t.unProxy():new zt(t,this.#z,e);return r.addInputsFromNode(this,{"*":""}),r.asProxy()}in(t){return t instanceof Ct?this.addInputsFromNode(t):Dt(t)?this.addInputsFromNode(...t.asNodeInput()):this.addInputsAsValues(t),this.asProxy()}as(t){return new _t(this,this.#z,t)}keys(){return[this.#ut()]}#ut(){return"*-"+this.id}}function Ht(t){return"function"==typeof t.unProxy}
*/class zt extends Ct{#it;#at;#ct;#z;#_;constructor(t,e,r={}){const s=!Ht(r)&&!(r instanceof Rt)&&!Gt(r)&&!Dt(r)&&r.$id;super(t,e,s?{$id:s}:{}),this.#z=e,"string"!=typeof t&&(this.#_=t),Ht(r)?this.addInputsFromNode(r.unProxy()):r instanceof Rt?this.addInputsFromNode(r):Gt(r)?this.addInputsAsValues({$board:r.getBoardCapabilityAsValue()}):Dt(r)?this.addInputsFromNode(...r.asNodeInput()):(void 0!==r.$id&&delete r.$id,this.addInputsAsValues(r)),this[this.#ut()]=this,this.#it=new Promise(((t,e)=>{this.#at=t,this.#ct=e}))}addInputsAsValues(t){const e={},r=[];Object.entries(t).forEach((([t,s])=>{Gt(s)&&(s=s.getBoardCapabilityAsValue()),Dt(s)?r.push(s.as(t).asNodeInput()):s instanceof Rt||Ht(s)?r.push([Ht(s)?s.unProxy():s,{[t]:t},!1,void 0]):e[t]=s})),this.configuration={...this.configuration,...e},r.forEach((t=>this.unProxy().addInputsFromNode(...t)))}addInputsFromNode(t,e={"*":""},r,s){const n=Object.entries(e);0===n.length?this.addIncomingEdge(t,"","",r):n.forEach((([e,n])=>{e.startsWith("*-")&&(e="*",n=""),this.unProxy().addIncomingEdge(Ht(t)?t.unProxy():t,e,n,r,s)}))}addIncomingEdge(t,e,r,s,n){const o=t.#z;if(o!==this.#z){for(let t=this.#z;t!==o;t=t.parentLexicalScope)if(!t)throw new Error("Only wires from parent scopes allowed");if("*"===e||""===e)throw new Error("Can't use * or empty wires from parent scopes");this.#z.addClosureEdge({scope:o,from:t,to:this,out:e,in:r})}else super.addIncomingEdge(t,e,r,s,n)}async invoke(t,e){const r=new Bt({dynamicScope:e,lexicalScope:this.#z});return r.asScopeFor((async()=>{try{const e=this.#_??r.getHandler(this.type);let s;const n="function"==typeof e?e:e?.invoke;if(n)s=await n(t,this);else{if(!e||"function"==typeof e||!e.graph)throw new Error(`Can't find handler for ${this.id}`);{const n=e.graph.getPinnedNodes();if(1!==n.length)throw new Error("Expected exactly one graph");s=await r.invokeOneRound(t,n[0])}}for(const[t,e]of Object.entries(s))e instanceof zt?s[t]=(await e)[t]:Dt(e)?s[t]=await e:Gt(e)&&(s[t]=await e.getBoardCapabilityAsValue());return this.#at&&(this.#at(s),this.#at=this.#ct=void 0),s}catch(t){throw this.#ct&&(this.#ct(t),this.#at=this.#ct=void 0),t}}))()}async serializeNode(){for(const[t,e]of Object.entries(this.configuration))e instanceof Promise&&(this.configuration[t]=await e);if("fn"!==this.type)return super.serializeNode();const t=new Bt({lexicalScope:this.#z,serialize:!0}),e=this.#_??t.getHandler(this.type);if(e&&"function"!=typeof e&&e.graph){const r={id:this.id,type:"invoke",configuration:{...this.configuration,path:"#"+this.id}},s=e.graph.getPinnedNodes();if(1!==s.length)throw new Error("Expected exactly one graph");return[r,await t.serialize({},s[0])]}const r="function"==typeof e?e:e?.invoke;if(!r)throw new Error(`Handler for ${this.type} in ${this.id} not found`);let s=r.toString(),n=this.id.replace(/-/g,"_");const o=/(?:async\s*)?(\w+|\([^)]*\))\s*=>\s*/,i=/(?:async\s+)?function\s+(\w+)\s*\(([^)]*)\)\s*\{/;if(o.test(s))s=s.replace(o,((t,e)=>{const r=s.trim().startsWith("async")?"async ":"",o=e.startsWith("(")?e:`(${e})`;return`${r}function ${n}${o} `}));else{const t=i.exec(s);if(null===t)throw new Error("Unexpected seralization: "+s);n=t[1]||n}const a=await this.describe(t),c={edges:[{from:`${this.id}-input`,to:`${this.id}-run`,out:"*"},{from:`${this.id}-run`,to:`${this.id}-output`,out:"*"}],nodes:[{id:`${this.id}-input`,type:"input",configuration:a?.inputSchema?{schema:a.inputSchema}:{}},{id:`${this.id}-run`,type:"runJavascript",configuration:{...this.configuration,code:s,name:n,raw:!0}},{id:`${this.id}-output`,type:"output",configuration:a?.outputSchema?{schema:a.outputSchema}:{}}]};return[{id:this.id,type:"invoke",configuration:{path:"#"+this.id}},c]}asProxy(){return new Proxy(this,{get(t,e,r){if("string"==typeof e){const r=new _t(t,t.#z,e);let s=t[e];return s=s&&"function"==typeof s?s.bind(t):(t=>r.invoke(t)).bind(r),new Proxy(s,{get(t,e,s){const n=Reflect.get(r,e,r);return"function"==typeof n?n.bind(r):n},ownKeys:t=>Reflect.ownKeys(r).filter((t=>"string"==typeof t))})}return Reflect.get(t,e,r)},ownKeys:t=>[t.#ut()]})}unProxy(){return this}then(t,e){if(this.#z.serializing())throw new Error(`Can't \`await\` on ${this.id} in board declaration. Did you mean to use \`code\` instead of \`board\`?`);try{return this.#z.invoke(this).catch((t=>{if(e)return Promise.reject(t).catch(this.#z.asScopeFor(e));throw t})),this.#it.then(t&&this.#z.asScopeFor(t),e&&this.#z.asScopeFor(e))}catch(t){if(e)return Promise.reject(t).catch(this.#z.asScopeFor(e));throw t}}to(t,e){const r=Ht(t)?t.unProxy():new zt(t,this.#z,e);return r.addInputsFromNode(this,{"*":""}),r.asProxy()}in(t){return t instanceof Ct?this.addInputsFromNode(t):Dt(t)?this.addInputsFromNode(...t.asNodeInput()):this.addInputsAsValues(t),this.asProxy()}as(t){return new _t(this,this.#z,t)}keys(){return[this.#ut()]}#ut(){return"*-"+this.id}}function Ht(t){return"function"==typeof t.unProxy}
/**

@@ -202,3 +202,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/function Gt(t,e){return t&&function(t,e){Ft().addHandlers({[t]:e})}
*/function Jt(t,e){return t&&function(t,e){Ft().addHandlers({[t]:e})}
/**

@@ -208,3 +208,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/(t,e),r=>new zt(t??e,Ft(),r).asProxy()}function Jt(t){return"function"==typeof t&&"function"==typeof t.getBoardCapabilityAsValue}
*/(t,e),r=>new zt(t??e,Ft(),r).asProxy()}function Gt(t){return"function"==typeof t&&"function"==typeof t.getBoardCapabilityAsValue}
/**

@@ -214,3 +214,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/const Vt=async()=>{throw new Error("Reserved word handler should never be invoked")};Gt("input",Vt),Gt("output",Vt);class Kt{#pt;#dt;#ht;constructor(t,e){this.#pt=t,this.#dt={...e,method:"POST",headers:{"Content-Type":"application/json"}},this.#ht=this.#dt.fetch??globalThis.fetch.bind(globalThis)}createClientStream(){let t;const e=new Promise((e=>{t=e})),r=this;return{readableResponses:new ReadableStream({async pull(t){const r=(await e).getReader();for(;;){const e=await r.read();if(e.done)break;console.log("%cServer-Sent Event Chunk","background: #009; color: #FFF",e.value),t.enqueue(e.value)}t.close()}}),writableRequests:new WritableStream({async write(e,s){if(!t)throw new Error("HTTPClientTransport supports only one write per stream instance.");const n=await r.#ht(r.#pt,{...r.#dt,body:JSON.stringify(e)});n.ok||s.error(new Error(`HTTP error: ${n.status}`)),t(n.body?.pipeThrough(new TextDecoderStream).pipeThrough((()=>{let t=[];return new TransformStream({transform(e,r){const s=!e.endsWith("\n"),n=e.split("\n").filter(Boolean);for(t.length&&!s&&(r.enqueue(`${t.join("")}${n.shift()}`),t=[]);n.length>1;)r.enqueue(n.shift());const o=n.shift();o&&(s?t.push(o):r.enqueue(o))},flush(){if(t.length)throw new Error("Unexpected end of stream.")}})})()).pipeThrough(new TransformStream({transform(t,e){t.startsWith("data: ")&&e.enqueue(t.slice(6))}})).pipeThrough((()=>{const t=new TransformStream,e=t.writable.getWriter();return new TransformStream({transform(r,s){const n=Z(r,(e=>{if(0!==e)throw new Error("HTTPClientTransport does not support multiple streams at the moment.");return t.readable})),[o]=Array.isArray(n)?n:[];"http-stream-chunk"===o?e.write(n[1].chunk):"http-stream-end"===o?e.close():s.enqueue(n)}})})())),t=void 0}})}}}
*/const Vt=async()=>{throw new Error("Reserved word handler should never be invoked")};Jt("input",Vt),Jt("output",Vt);class Kt{#pt;#dt;#ht;constructor(t,e){this.#pt=t,this.#dt={...e,method:"POST",headers:{"Content-Type":"application/json"}},this.#ht=this.#dt.fetch??globalThis.fetch.bind(globalThis)}createClientStream(){let t;const e=new Promise((e=>{t=e})),r=this;return{readableResponses:new ReadableStream({async pull(t){const r=(await e).getReader();for(;;){const e=await r.read();if(e.done)break;console.log("%cServer-Sent Event Chunk","background: #009; color: #FFF",e.value),t.enqueue(e.value)}t.close()}}),writableRequests:new WritableStream({async write(e,s){if(!t)throw new Error("HTTPClientTransport supports only one write per stream instance.");const n=await r.#ht(r.#pt,{...r.#dt,body:JSON.stringify(e)});n.ok||s.error(new Error(`HTTP error: ${n.status}`)),t(n.body?.pipeThrough(new TextDecoderStream).pipeThrough((()=>{let t=[];return new TransformStream({transform(e,r){const s=!e.endsWith("\n"),n=e.split("\n").filter(Boolean);for(t.length&&!s&&(r.enqueue(`${t.join("")}${n.shift()}`),t=[]);n.length>1;)r.enqueue(n.shift());const o=n.shift();o&&(s?t.push(o):r.enqueue(o))},flush(){if(t.length)throw new Error("Unexpected end of stream.")}})})()).pipeThrough(new TransformStream({transform(t,e){t.startsWith("data: ")&&e.enqueue(t.slice(6))}})).pipeThrough((()=>{const t=new TransformStream,e=t.writable.getWriter();return new TransformStream({transform(r,s){const n=Z(r,(e=>{if(0!==e)throw new Error("HTTPClientTransport does not support multiple streams at the moment.");return t.readable})),[o]=Array.isArray(n)?n:[];"http-stream-chunk"===o?e.write(n[1].chunk):"http-stream-end"===o?e.close():s.enqueue(n)}})})())),t=void 0}})}}}
/**

@@ -237,3 +237,3 @@ * @license

*/
const re=t=>{const e=t.proxy?.[0];if(!e)return t.kits;if("http"!==e.location)throw new Error("Only HTTP node proxy server is supported at this time.");if(!e.url)throw new Error("No node proxy server URL provided.");return[new xt(new Kt(e.url)).createProxyKit(e.nodes),...t.kits]};async function*se(t){if(t.remote){if("worker"!==t.remote.type)throw new Error(`Unsupported harness configuration: ${JSON.stringify(t,null,2)}`);{const e=t.remote&&t.remote.url;if(!e)throw new Error("Worker harness requires a worker URL");yield*async function*(t,e,r){const s=ee(t),n=new ut(s),o=new V(new pt(n.send("load"))),i=new Ot(new dt(n.receive("proxy"))),a=new at(new pt(n.send("run")));await o.load(e.url),yield*M((async t=>{const s=[te(t),...e.kits],n=e.proxy?.[0]?.nodes;i.serve({kits:s,proxy:n});for await(const e of a.run(r))await t(e)}))}(e,t)}}else yield*M((async e=>{const r=[te(e),...re(t)];for await(const s of async function*(t,e){yield*M((async r=>{const s=Pt(t),n=await G.load(t.url,{base:s});try{const s=t.diagnostics?new K((async t=>{await r(Qt(t))})):void 0;for await(const t of n.run({probe:s,kits:e}))await r(Xt(t));await r(Yt())}catch(t){let e=t,s="";for(;e?.cause;)e=e.cause.error??{name:"Unexpected Error",message:JSON.stringify(e.cause,null,2)},e&&"message"in e&&(s+=`\n${e.message}`);console.error(s,e),await r(Zt(s))}}))}(t,r))await e(s)}))}export{te as createSecretAskingKit,ee as createWorker,It as defineServeConfig,se as run,jt as serve};
const re=t=>{const e=t.proxy?.[0];if(!e)return t.kits;if("http"!==e.location)throw new Error("Only HTTP node proxy server is supported at this time.");if(!e.url)throw new Error("No node proxy server URL provided.");return[new xt(new Kt(e.url)).createProxyKit(e.nodes),...t.kits]};async function*se(t){if(t.remote){if("worker"!==t.remote.type)throw new Error(`Unsupported harness configuration: ${JSON.stringify(t,null,2)}`);{const e=t.remote&&t.remote.url;if(!e)throw new Error("Worker harness requires a worker URL");yield*async function*(t,e,r){const s=ee(t),n=new ut(s),o=new V(new pt(n.send("load"))),i=new Ot(new dt(n.receive("proxy"))),a=new at(new pt(n.send("run")));await o.load(e.url),yield*M((async t=>{const s=[te(t),...e.kits],n=e.proxy?.[0]?.nodes;i.serve({kits:s,proxy:n});for await(const e of a.run(r))await t(e)}))}(e,t)}}else yield*M((async e=>{const r=[te(e),...re(t)];for await(const s of async function*(t,e){yield*M((async r=>{const s=Pt(t),n=await J.load(t.url,{base:s});try{const s=t.diagnostics?new K((async t=>{await r(Qt(t))})):void 0;for await(const t of n.run({probe:s,kits:e}))await r(Xt(t));await r(Yt())}catch(t){let e=t,s="";for(;e?.cause;)e=e.cause.error??{name:"Unexpected Error",message:JSON.stringify(e.cause,null,2)},e&&"message"in e&&(s+=`\n${e.message}`);console.error(s,e),await r(Zt(s))}}))}(t,r))await e(s)}))}export{te as createSecretAskingKit,ee as createWorker,It as defineServeConfig,se as run,jt as serve};
//# sourceMappingURL=harness.min.js.map

@@ -11,3 +11,3 @@ /**

* SPDX-License-Identifier: Apache-2.0
*/const r=async(t,e,r)=>t instanceof Function?t(e,r):t.invoke?t.invoke(e,r):void 0;
*/const r=async(t,e,r)=>{const s=(t=>{if(t instanceof Function)return t;if(t.invoke)return t.invoke;throw new Error("Invalid handler")})(t);return new Promise((t=>{s(e,r).then(t).catch((e=>{t({$error:{error:e}})}))}))};
/**

@@ -33,3 +33,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/class o{graph;#e;#r;constructor(t,e,r=!0){this.graph=t,this.#e=e,this.#r=r}static#s(t,e){const{promiseId:r,outputs:s,newOpportunities:i}=e;t.pendingOutputs.delete(r);const n=s.$error?i.filter((t=>"$error"===t.out)):i;if(t.opportunities.push(...n),t.state.wireOutputs(n,s),s.$error){if(0===n.length)throw new Error("Uncaught exception in node handler. Catch by wiring up the $error output.",{cause:s.$error});globalThis.console.warn("Error in node handler, passinng to the wired $error output.",s.$error,n)}}static async processAllPendingNodes(t){return(await Promise.all(t.pendingOutputs.values())).forEach((e=>{o.#s(t,e)})),t}async next(){if(!this.#e.skip){const{inputs:t,outputsPromise:e,newOpportunities:r,descriptor:s}=this.#e;this.#e.state.useInputs(s.id,this.#e.inputs);const i=Symbol(),n=new Promise((n=>{(e||Promise.resolve({})).then((e=>{if(e.$error){const r=e.$error;e.$error={descriptor:s,...r,inputs:{...t,...r.inputs}}}n({promiseId:i,outputs:e,newOpportunities:r})})).catch((e=>{n({promiseId:i,outputs:{$error:{kind:"error",error:e,inputs:t,descriptor:s}},newOpportunities:r.filter((t=>"$error"===t.out))})}))}));this.#e.pendingOutputs.set(i,n)}for(;(0===this.#e.opportunities.length||this.#r)&&this.#e.pendingOutputs.size>0;)o.#s(this.#e,await Promise.race(this.#e.pendingOutputs.values()));if(0===this.#e.opportunities.length)return{done:!0,value:null};const t=this.#e.opportunities.shift(),{heads:e,nodes:r,tails:i}=this.graph,a=t.to,u=r.get(a);if(!u)throw new Error(`No node found for id "${a}"`);const c=e.get(a)||[],p=this.#e.state.getAvailableInputs(a),h=s.computeMissingInputs(c,p,u),d=i.get(a)||[],l={...u.configuration,...p};return this.#e=new n(u,l,h,this.#e.opportunities,d,this.#e.state,this.#e.pendingOutputs),{done:!1,value:this.#e}}}
*/class o{graph;#e;#r;constructor(t,e,r=!0){this.graph=t,this.#e=e,this.#r=r}static#s(t,e){const{promiseId:r,outputs:s,newOpportunities:i}=e;t.pendingOutputs.delete(r);const n=s.$error?i.filter((t=>"$error"===t.out)):i;if(t.opportunities.push(...n),t.state.wireOutputs(n,s),s.$error){if(0===n.length)throw new Error("Uncaught exception in node handler. Catch by wiring up the $error output.",{cause:s.$error});globalThis.console.warn("Error in node handler, passing to the wired $error output.",s.$error,n)}}static async processAllPendingNodes(t){return(await Promise.all(t.pendingOutputs.values())).forEach((e=>{o.#s(t,e)})),t}async next(){if(!this.#e.skip){const{inputs:t,outputsPromise:e,newOpportunities:r,descriptor:s}=this.#e;this.#e.state.useInputs(s.id,this.#e.inputs);const i=Symbol(),n=new Promise((n=>{(e||Promise.resolve({})).then((e=>{if(e.$error){const r=e.$error;e.$error={descriptor:s,...r,inputs:{...t,...r.inputs}}}n({promiseId:i,outputs:e,newOpportunities:r})})).catch((e=>{n({promiseId:i,outputs:{$error:{kind:"error",error:e,inputs:t,descriptor:s}},newOpportunities:r.filter((t=>"$error"===t.out))})}))}));this.#e.pendingOutputs.set(i,n)}for(;(0===this.#e.opportunities.length||this.#r)&&this.#e.pendingOutputs.size>0;)o.#s(this.#e,await Promise.race(this.#e.pendingOutputs.values()));if(0===this.#e.opportunities.length)return{done:!0,value:null};const t=this.#e.opportunities.shift(),{heads:e,nodes:r,tails:i}=this.graph,a=t.to,u=r.get(a);if(!u)throw new Error(`No node found for id "${a}"`);const c=e.get(a)||[],p=this.#e.state.getAvailableInputs(a),h=s.computeMissingInputs(c,p,u),d=i.get(a)||[],l={...u.configuration,...p};return this.#e=new n(u,l,h,this.#e.opportunities,d,this.#e.state,this.#e.pendingOutputs),{done:!1,value:this.#e}}}
/**

@@ -64,3 +64,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=async function*(){const t=this.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)return;yield r}}finally{t.releaseLock()}});class v{writable;readable;controller=null;constructor(){this.writable=new WritableStream({write:t=>this.write(t)}),this.readable=new ReadableStream({start:t=>{this.controller=t}})}write(t){(new TextDecoder).decode(t).split("\n").map((t=>t.trim())).filter((t=>t.length>0)).forEach((t=>{try{if("stop"===t)return void this.controller?.close();const e=JSON.parse(t);this.controller?.enqueue(e)}catch(t){console.error(t)}}))}}const O=async(t,e,r)=>{const s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({inputs:e,state:r})});return s.body?.pipeThrough(new v)};async function*P(t){let e,r;for(;;){const s=await O(t,e,r);if(!s)break;for await(const t of s)r=JSON.stringify(t.state),yield t,e=t.inputs;if(!r)break}}
*/ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=async function*(){const t=this.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)return;yield r}}finally{t.releaseLock()}});class v{writable;readable;controller=null;constructor(){this.writable=new WritableStream({write:t=>this.write(t)}),this.readable=new ReadableStream({start:t=>{this.controller=t}})}write(t){(new TextDecoder).decode(t).split("\n").map((t=>t.trim())).filter((t=>t.length>0)).forEach((t=>{try{if("stop"===t)return void this.controller?.close();const e=JSON.parse(t);this.controller?.enqueue(e)}catch(t){console.error(t)}}))}}const P=async(t,e,r)=>{const s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({inputs:e,state:r})});return s.body?.pipeThrough(new v)};async function*O(t){let e,r;for(;;){const s=await P(t,e,r);if(!s)break;for await(const t of s)r=JSON.stringify(t.state),yield t,e=t.inputs;if(!r)break}}
/**

@@ -70,3 +70,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/const k=t=>t&&t.replace(/-/g,""),S=(t,e="")=>{if(!t)return"";const r=t.id,s=`${e?`${k(e)}_`:""}${k(r)}`,i=t.type,n=`"${i} <br> id='${r}'"`;switch(i){case"include":return`${s}[[${n}]]:::include`;case"slot":return`${s}((${n})):::slot`;case"passthrough":return`${s}((${n})):::passthrough`;case"input":return`${s}[/${n}/]:::input`;case"secrets":return`${s}(${n}):::secrets`;case"output":return`${s}{{${n}}}:::output`;default:return`${s}[${n}]`}};class E{nodeMap;edges;nodes;idPrefix;subgraphs;constructor(t,e=""){const{edges:r,nodes:s}=t;this.nodeMap=new Map(s.map((t=>[t.id,t]))),this.edges=r,this.nodes=s,this.idPrefix=e,this.subgraphs=t.graphs||{}}handleSlotted(t,e){const r=e?`${k(e)}_`:"";if("include"!==t.type)return"";const s=t.configuration?.slotted;if(!s)return"";return Object.entries(s).map((([e,s])=>this.describeSubgraph(s,e,"slotted",t,`${r}${t.id}`))).join("\n")}handleLambda(t,e){const r=e?`${k(e)}_`:"",s=t.configuration?.board;if(!s)return"";const i=s;if("board"!==i.kind)return"";const n=i.board;return this.describeSubgraph(n,t.id,"lamdba",t,`${r}${t.id}`)}describeSubgraphs(t,e=""){const r=this.nodeMap.get(t.from);if(!r)return"";const s=this.handleLambda(r,e);return`${this.handleSlotted(r,e)}${s}`}describeSubgraph(t,e,r,s,i){const n=new E(t,i).describeGraph(),o=this.idPrefix?`${k(this.idPrefix)}_`:"",a=r&&s?`sg_${k(e)}:::slotted -- "${r}->${r}" --o ${o}${k(s.id)}\n`:"";return`\nsubgraph sg_${k(e)} [${e}]\n${n}\nend\n${a}`}describeGraph(){return[...this.edges.map((t=>{const e=((t,e,r="")=>{const s=t.from,i=S(e.get(s),r),n=t.to,o=S(e.get(n),r),a=t.in,u=t.out,c=t.optional,p=t.constant;return"*"===u?`${i} -- all --\x3e ${o}`:u&&a?c?`${i} -. "${u}->${a}" .-> ${o}`:p?`${i} -- "${u}->${a}" --o ${o}`:`${i} -- "${u}->${a}" --\x3e ${o}`:`${i} --\x3e ${o}`})(t,this.nodeMap,this.idPrefix);return`${e}${this.describeSubgraphs(t,this.idPrefix)}`})),...Object.entries(this.subgraphs).map((([t,e])=>this.describeSubgraph(e,t,void 0,void 0,`${t}${this.idPrefix}`)))].join("\n")}}const I=(t,e={},r)=>{const s=e.title??e?.url;return`Missing ${r?"required ":""}input "${t}"${s?` for board "${s}".`:"."}`},x=async(t,e,r,s)=>{if(!e.requestInput)return;const i=await s.outputsPromise??{},n=new M(i,s.inputs);s.outputsPromise=n.read(q(t,e,r))},q=(t,e,r)=>async(s,i,n)=>{if(n)throw new Error(I(s,t,n));if(void 0!==i.default)return"string"!==i.type?JSON.parse(i.default):i.default;const o=await(e.requestInput?.(s,i,r));if(void 0===o)throw new Error(I(s,t,n));return o};
*/const k=t=>t&&t.replace(/-/g,""),S=(t,e="")=>{if(!t)return"";const r=t.id,s=`${e?`${k(e)}_`:""}${k(r)}`,i=t.type,n=`"${i} <br> id='${r}'"`;switch(i){case"include":return`${s}[[${n}]]:::include`;case"slot":return`${s}((${n})):::slot`;case"passthrough":return`${s}((${n})):::passthrough`;case"input":return`${s}[/${n}/]:::input`;case"secrets":return`${s}(${n}):::secrets`;case"output":return`${s}{{${n}}}:::output`;default:return`${s}[${n}]`}};class E{nodeMap;edges;nodes;idPrefix;subgraphs;constructor(t,e=""){const{edges:r,nodes:s}=t;this.nodeMap=new Map(s.map((t=>[t.id,t]))),this.edges=r,this.nodes=s,this.idPrefix=e,this.subgraphs=t.graphs||{}}handleSlotted(t,e){const r=e?`${k(e)}_`:"";if("include"!==t.type)return"";const s=t.configuration?.slotted;if(!s)return"";return Object.entries(s).map((([e,s])=>this.describeSubgraph(s,e,"slotted",t,`${r}${t.id}`))).join("\n")}handleLambda(t,e){const r=e?`${k(e)}_`:"",s=t.configuration?.board;if(!s)return"";const i=s;if("board"!==i.kind)return"";const n=i.board;return this.describeSubgraph(n,t.id,"lamdba",t,`${r}${t.id}`)}describeSubgraphs(t,e=""){const r=this.nodeMap.get(t.from);if(!r)return"";const s=this.handleLambda(r,e);return`${this.handleSlotted(r,e)}${s}`}describeSubgraph(t,e,r,s,i){const n=new E(t,i).describeGraph(),o=this.idPrefix?`${k(this.idPrefix)}_`:"",a=r&&s?`sg_${k(e)}:::slotted -- "${r}->${r}" --o ${o}${k(s.id)}\n`:"";return`\nsubgraph sg_${k(e)} [${e}]\n${n}\nend\n${a}`}describeGraph(t=!1){return[...this.edges.map((e=>{const r=((t,e,r="")=>{const s=t.from,i=S(e.get(s),r),n=t.to,o=S(e.get(n),r),a=t.in,u=t.out,c=t.optional,p=t.constant;return"*"===u?`${i} -- all --\x3e ${o}`:u&&a?c?`${i} -. "${u}->${a}" .-> ${o}`:p?`${i} -- "${u}->${a}" --o ${o}`:`${i} -- "${u}->${a}" --\x3e ${o}`:`${i} --\x3e ${o}`})(e,this.nodeMap,this.idPrefix);return`${r}${t?"":this.describeSubgraphs(e,this.idPrefix)}`})),...t?"":Object.entries(this.subgraphs).map((([t,e])=>this.describeSubgraph(e,t,void 0,void 0,`${t}${this.idPrefix}`)))].join("\n")}}const I=(t,e={},r)=>{const s=e.title??e?.url;return`Missing ${r?"required ":""}input "${t}"${s?` for board "${s}".`:"."}`},x=async(t,e,r,s)=>{if(!e.requestInput)return;const i=await s.outputsPromise??{},n=new M(i,s.inputs);s.outputsPromise=n.read(q(t,e,r))},q=(t,e,r)=>async(s,i,n)=>{if(n)throw new Error(I(s,t,n));if(void 0!==i.default)return"type"in i&&"string"!==i.type?JSON.parse(i.default):i.default;const o=await(e.requestInput?.(s,i,r));if(void 0===o)throw new Error(I(s,t,n));return o};
/**

@@ -76,3 +76,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/class M{#p;#h;constructor(t,e){this.#p=t,this.#h=e}async read(t){if(!("schema"in this.#h))return this.#p;const e=this.#h.schema;if(!e.properties)return this.#p;const r=Object.entries(e.properties),s={};for(const[i,n]of r){if(i in this.#p){s[i]=this.#p[i];continue}const r=e.required?.includes(i)??!1,o=await t(i,n,r);s[i]=o}return{...this.#p,...s}}}class j{#d;#l=new Map;constructor(t){this.#d=t}createHandler(t,e){return async(r,s,i)=>{const n=this.#l.get(r);if(void 0!==n)return n;const o={id:i.id,type:i.type},a={...e,descriptor:o,inputs:{schema:{type:"object",properties:{[r]:s}}}};console.log("requestInputResult",a),await t(new f(a,void 0,-1));const u=await a.outputsPromise;let c=u&&u[r];return void 0===c&&(c=await(this.#d.requestInput?.(r,s,o))),this.#l.set(r,c),c}}}
*/class M{#p;#h;constructor(t,e){this.#p=t,this.#h=e}async read(t){if(!("schema"in this.#h))return this.#p;const e=this.#h.schema;if(!e.properties)return this.#p;const r=Object.entries(e.properties),s={};for(const[i,n]of r){if(i in this.#p){s[i]=this.#p[i];continue}const r=e.required?.includes(i)??!1,o=await t(i,n,r);s[i]=o}return{...this.#p,...s}}}class j{#d;#l=new Map;constructor(t){this.#d=t}createHandler(t,e){return async(r,s,i)=>{const n=this.#l.get(r);if(void 0!==n)return n;const o={id:i.id,type:i.type},a={...e,descriptor:o,inputs:{schema:{type:"object",properties:{[r]:s}}}};await t(new f(a,void 0,-1));const u=await a.outputsPromise;let c=u&&u[r];return void 0===c&&(c=await(this.#d.requestInput?.(r,s,o))),this.#l.set(r,c),c}}}
/**

@@ -82,3 +82,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/const N=()=>{};class A{#f=[];#g=N;#w;#y;abort=N;constructor(){this.#b()}#b(){this.#w=new Promise(((t,e)=>{this.#g=t,this.abort=e}))}#m(t){this.#f.push(t),1==this.#f.length&&(this.#g(),this.#b())}async write(t){return new Promise((e=>{this.#m({value:t,receipt:e})}))}async read(){this.#y&&this.#y(),0===this.#f.length&&await this.#w;const t=this.#f.shift();if(!t)throw new Error("asyncGen queue should never be empty.");return this.#y=t.receipt,t.value?{done:!1,value:t.value}:{done:!0,value:void 0}}close(){this.#m({value:void 0,receipt:N})}}class R{#$;#v=!0;#f=new A;constructor(t){this.#$=t}async#O(t){return this.#f.write(t)}async next(){return this.#v&&(this.#v=!1,this.#$(this.#O.bind(this)).then((()=>{this.#f.close()})).catch((t=>{this.#f.abort(t)}))),this.#f.read()}}
*/const N=()=>{};class A{#f=[];#g=N;#w;#y;abort=N;constructor(){this.#b()}#b(){this.#w=new Promise(((t,e)=>{this.#g=t,this.abort=e}))}#m(t){this.#f.push(t),1==this.#f.length&&(this.#g(),this.#b())}async write(t){return new Promise((e=>{this.#m({value:t,receipt:e})}))}async read(){this.#y&&this.#y(),0===this.#f.length&&await this.#w;const t=this.#f.shift();if(!t)throw new Error("asyncGen queue should never be empty.");return this.#y=t.receipt,t.value?{done:!1,value:t.value}:{done:!0,value:void 0}}close(){this.#m({value:void 0,receipt:N})}}class _{#$;#v=!0;#f=new A;constructor(t){this.#$=t}async#P(t){return this.#f.write(t)}async next(){return this.#v&&(this.#v=!1,this.#$(this.#P.bind(this)).then((()=>{this.#f.close()})).catch((t=>{this.#f.abort(t)}))),this.#f.read()}}
/**

@@ -89,3 +89,3 @@ * @license

*/
class _{#P;#k;constructor(t){this.#P=structuredClone(t)||[]}onGraphStart(){this.#P.push({graph:0,node:0})}onNodeStart(t){this.#P[this.#P.length-1].node++,this.#k=t}onNodeEnd(){}onGraphEnd(){}async state(){const t=structuredClone(this.#P);return this.#k&&(t[t.length-1].state=await h("nodestart",this.#k)),t}}
class R{#O;#k;constructor(t){this.#O=structuredClone(t)||[]}onGraphStart(){this.#O.push({graph:0,node:0})}onNodeStart(t){this.#O[this.#O.length-1].node++,this.#k=t}onNodeEnd(){}onGraphEnd(){}async state(){const t=structuredClone(this.#O);return this.#k&&(t[t.length-1].state=await h("nodestart",this.#k)),t}}
/**

@@ -95,3 +95,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/class T{url;title;description;version;edges=[];nodes=[];kits=[];graphs;args;#S={};#E=[];#I;constructor(t){const{url:e,title:r,description:s,version:i}=t||{};Object.assign(this,{url:e,title:r,description:s,version:i})}async*run(t={},e){const s=t.base||new URL(this.url||"",import.meta.url);var i;yield*(i=async i=>{const{probe:n}=t,o=await T.handlersFromBoard(this,t.kits),a={...this.#S,...t.slots};this.#E.forEach((t=>t.addGraph(this)));const c=new u(this,e?.state),p=new j(t),h=t.invocationPath||[],l=new _(t.state);await(n?.report?.({type:"graphstart",data:{metadata:this,path:h,timestamp:d()}}));let w=0;l.onGraphStart();const y=()=>[...h,w];for await(const e of c){w++;const{inputs:u,descriptor:c,missingInputs:h}=e;if(e.skip){await(n?.report?.({type:"skip",data:{node:c,inputs:u,missingInputs:h,path:y(),timestamp:d()}}));continue}let b;if(l.onNodeStart(e),await(n?.report?.({type:"nodestart",data:{node:c,inputs:u,path:y(),timestamp:d()},state:await l.state()})),"input"===c.type)await i(new f(e,await l.state(),w)),await x(this,t,c,e),b=e.outputsPromise;else if("output"===c.type)await i(new g(e,w)),b=e.outputsPromise;else{const n=o[c.type];if(!n)throw new Error(`No handler for node type "${c.type}"`);const h={...t,board:this,descriptor:c,outerGraph:this.#I||this,base:s,slots:a,kits:[...t.kits||[],...this.kits],requestInput:p.createHandler(i,e),invocationPath:y(),state:await l.state()};b=r(n,u,h)}l.onNodeEnd(),await(n?.report?.({type:"nodeend",data:{node:c,inputs:u,outputs:await b,validatorMetadata:this.#E.map((t=>t.getValidatorMetadata(c))),path:y(),timestamp:d()}})),e.outputsPromise=b}l.onGraphEnd(),await(n?.report?.({type:"graphend",data:{metadata:this,path:h,timestamp:d()}}))},{[Symbol.asyncIterator]:()=>new R(i)})}get validators(){return this.#E}async runOnce(t,e={}){const r={...t,...this.args},{probe:s}=e;if(e.board&&e.descriptor)for(const t of e.board.validators)this.addValidator(t.getSubgraphValidator(e.descriptor,Object.keys(r)));try{let t={};const i=e.invocationPath||[];for await(const n of this.run(e))if("input"===n.type)n.inputs=r;else if("output"===n.type){t=n.outputs,await(s?.report?.({type:"nodeend",data:{node:n.node,inputs:n.inputs,outputs:t,path:[...i,n.invocationId],timestamp:d()}})),await(s?.report?.({type:"graphend",data:{metadata:this,path:i,timestamp:d()}}));break}return t}catch(t){if(t.cause)return{$error:t.cause};throw t}}addValidator(t){this.#E.push(t)}mermaid(t="TD",e=!1){return((t,e="TD",r=!1)=>{const s=new E(t).describeGraph();return r?((t,e)=>`graph ${e};\n${t}`)(s,e):((t,e)=>`%%{init: 'themeVariables': { 'fontFamily': 'Fira Code, monospace' }}%%\ngraph ${e};\n${t}\nclassDef default stroke:#ffab40,fill:#fff2ccff,color:#000\nclassDef input stroke:#3c78d8,fill:#c9daf8ff,color:#000\nclassDef output stroke:#38761d,fill:#b6d7a8ff,color:#000\nclassDef passthrough stroke:#a64d79,fill:#ead1dcff,color:#000\nclassDef slot stroke:#a64d79,fill:#ead1dcff,color:#000\nclassDef config stroke:#a64d79,fill:#ead1dcff,color:#000\nclassDef secrets stroke:#db4437,fill:#f4cccc,color:#000\nclassDef slotted stroke:#a64d79`)(s,e)})(this,t,e)}static async fromGraphDescriptor(t){const e=new T(t);return e.edges=t.edges,e.nodes=t.nodes,e.graphs=t.graphs,e.args=t.args,e}static async load(t,e){const{base:r,slotted:s,outerGraph:i}=e||{},n=new $({base:r,graphs:i?.graphs}),{isSubgraph:o,graph:a}=await n.load(t),u=await T.fromGraphDescriptor(a);return o&&(u.#I=i),u.#S=s||{},u}static async fromBreadboardCapability(t){if("board"!==t.kind||!t.board)throw new Error(`Expected a "board" Capability, but got ${t}`);const e=t.board;if(!(e.edges&&e.kits&&e.nodes))throw new Error('Supplied "board" Capability argument is not actually a board');let r=t.board;return r.runOnce||(r=await T.fromGraphDescriptor(e)),r}static async handlersFromBoard(t,e=[]){return(t=>t.reduce(((t,e)=>({...e.handlers,...t})),{}))([new G,...e,...t.kits])}static runRemote=P}class G{handlers;constructor(){this.handlers={lambda:{describe:async t=>({inputSchema:(new e).setAdditionalProperties(!0).addInputs(t).addProperty("board",{title:"board",description:"The board to run.",type:"object"}).build(),outputSchema:(new e).addProperty("board",{title:"board",description:"The now-runnable board.",type:"object"}).build()}),invoke:async t=>{const{board:e,...r}=t;if(!e||"board"!==e.kind||!e.board)throw new Error('Lambda node requires a BoardCapability as "board" input');const s={...await T.fromBreadboardCapability(e),args:r};return{board:{...e,board:s}}}}}}}
*/class T{url;title;description;version;edges=[];nodes=[];kits=[];graphs;args;#S={};#E=[];#I;constructor(t){const{url:e,title:r,description:s,version:i}=t||{};Object.assign(this,{url:e,title:r,description:s,version:i})}async*run(t={},e){const s=t.base||new URL(this.url||"",import.meta.url);var i;yield*(i=async i=>{const{probe:n}=t,o=await T.handlersFromBoard(this,t.kits),a={...this.#S,...t.slots};this.#E.forEach((t=>t.addGraph(this)));const c=new u(this,e?.state),p=new j(t),h=t.invocationPath||[],l=new R(t.state);await(n?.report?.({type:"graphstart",data:{metadata:this,path:h,timestamp:d()}}));let w=0;l.onGraphStart();const y=()=>[...h,w];for await(const e of c){w++;const{inputs:u,descriptor:c,missingInputs:h}=e;if(e.skip){await(n?.report?.({type:"skip",data:{node:c,inputs:u,missingInputs:h,path:y(),timestamp:d()}}));continue}let b;if(l.onNodeStart(e),await(n?.report?.({type:"nodestart",data:{node:c,inputs:u,path:y(),timestamp:d()},state:await l.state()})),"input"===c.type)await i(new f(e,await l.state(),w)),await x(this,t,c,e),b=e.outputsPromise;else if("output"===c.type)await i(new g(e,w)),b=e.outputsPromise;else{const n=o[c.type];if(!n)throw new Error(`No handler for node type "${c.type}"`);const h={...t,board:this,descriptor:c,outerGraph:this.#I||this,base:s,slots:a,kits:[...t.kits||[],...this.kits],requestInput:p.createHandler(i,e),invocationPath:y(),state:await l.state()};b=r(n,u,h)}l.onNodeEnd(),await(n?.report?.({type:"nodeend",data:{node:c,inputs:u,outputs:await b,validatorMetadata:this.#E.map((t=>t.getValidatorMetadata(c))),path:y(),timestamp:d()}})),e.outputsPromise=b}l.onGraphEnd(),await(n?.report?.({type:"graphend",data:{metadata:this,path:h,timestamp:d()}}))},{[Symbol.asyncIterator]:()=>new _(i)})}get validators(){return this.#E}async runOnce(t,e={}){const r={...t,...this.args},{probe:s}=e;if(e.board&&e.descriptor)for(const t of e.board.validators)this.addValidator(t.getSubgraphValidator(e.descriptor,Object.keys(r)));try{let t={};const i=e.invocationPath||[];for await(const n of this.run(e))if("input"===n.type)n.inputs=r;else if("output"===n.type){t=n.outputs,await(s?.report?.({type:"nodeend",data:{node:n.node,inputs:n.inputs,outputs:t,path:[...i,n.invocationId],timestamp:d()}})),await(s?.report?.({type:"graphend",data:{metadata:this,path:i,timestamp:d()}}));break}return t}catch(t){if(t.cause)return{$error:t.cause};throw t}}addValidator(t){this.#E.push(t)}mermaid(t="TD",e=!1,r=!1){return((t,e="TD",r=!1,s=!1)=>{const i=new E(t).describeGraph(s);return r?((t,e)=>`graph ${e};\n${t}`)(i,e):((t,e)=>`%%{init: 'themeVariables': { 'fontFamily': 'Fira Code, monospace' }}%%\ngraph ${e};\n${t}\nclassDef default stroke:#ffab40,fill:#fff2ccff,color:#000\nclassDef input stroke:#3c78d8,fill:#c9daf8ff,color:#000\nclassDef output stroke:#38761d,fill:#b6d7a8ff,color:#000\nclassDef passthrough stroke:#a64d79,fill:#ead1dcff,color:#000\nclassDef slot stroke:#a64d79,fill:#ead1dcff,color:#000\nclassDef config stroke:#a64d79,fill:#ead1dcff,color:#000\nclassDef secrets stroke:#db4437,fill:#f4cccc,color:#000\nclassDef slotted stroke:#a64d79`)(i,e)})(this,t,e,r)}static async fromGraphDescriptor(t){const e=new T(t);return e.edges=t.edges,e.nodes=t.nodes,e.graphs=t.graphs,e.args=t.args,e}static async load(t,e){const{base:r,slotted:s,outerGraph:i}=e||{},n=new $({base:r,graphs:i?.graphs}),{isSubgraph:o,graph:a}=await n.load(t),u=await T.fromGraphDescriptor(a);return o&&(u.#I=i),u.#S=s||{},u}static async fromBreadboardCapability(t){if("board"!==t.kind||!t.board)throw new Error(`Expected a "board" Capability, but got ${t}`);const e=t.board;if(!(e.edges&&e.kits&&e.nodes))throw new Error('Supplied "board" Capability argument is not actually a board');let r=t.board;return r.runOnce||(r=await T.fromGraphDescriptor(e)),r}static async handlersFromBoard(t,e=[]){return(t=>t.reduce(((t,e)=>({...e.handlers,...t})),{}))([new G,...e,...t.kits])}static runRemote=O}class G{handlers;constructor(){this.handlers={lambda:{describe:async t=>({inputSchema:(new e).setAdditionalProperties(!0).addInputs(t).addProperty("board",{title:"board",description:"The board to run.",type:"object"}).build(),outputSchema:(new e).addProperty("board",{title:"board",description:"The now-runnable board.",type:"object"}).build()}),invoke:async t=>{const{board:e,...r}=t;if(!e||"board"!==e.kind||!e.board)throw new Error('Lambda node requires a BoardCapability as "board" input');const s={...await T.fromBreadboardCapability(e),args:r};return{board:{...e,board:s}}}}}}}
/**

@@ -98,0 +98,0 @@ * @license

@@ -16,3 +16,3 @@ /**

* SPDX-License-Identifier: Apache-2.0
*/const f=async(t,e,r)=>t instanceof Function?t(e,r):t.invoke?t.invoke(e,r):void 0;
*/const f=async(t,e,r)=>{const s=(t=>{if(t instanceof Function)return t;if(t.invoke)return t.invoke;throw new Error("Invalid handler")})(t);return new Promise((t=>{s(e,r).then(t).catch((e=>{t({$error:{error:e}})}))}))};
/**

@@ -28,3 +28,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/const g=globalThis.process?t=>Buffer.from(t,"base64").toString("binary"):globalThis.atob,b=globalThis.process?t=>Buffer.from(t,"binary").toString("base64"):globalThis.btoa;class S{outputName;from;to;when;constructor(t,e,r,s={}){this.outputName=t,this.from=e,this.to=r,this.when=s}getInputNames(){const t=Object.keys(this.when);return 0===t.length?[this.outputName]:t}matches(t){return Object.entries(this.when).every((([e,r])=>{const s=t[e];return"string"==typeof r?s===r:"string"==typeof s&&r.test(s)}))}}const v=(t,e)=>Object.fromEntries(Object.entries(e).map((([e,r])=>"string"==typeof r?[e,[new S(e,t,r)]]:Array.isArray(r)?[e,r.map((r=>"string"==typeof r?new S(e,t,r):new S(e,t,r.to,r.when)))]:[e,[new S(e,t,r.to,r.when)]]))),O=Math.round(Date.now()/6048e5).toString(36),$=`T-${O}-`,k=`-${O}-T`,E=new RegExp(`(${$}.*?${k})`,"gm"),R=new RegExp(`^${$}(.+?)${k}$`),T=async(t,e,r)=>{const s=JSON.stringify(t),n=s.split(E).filter(Boolean).map((t=>{const e=t.match(R);if(e){const t=e[1].split("~"),[r,s,n]=t;return{nodeType:r,outputName:s,inputs:g(n)}}return{value:t}}));const a=await Promise.all(n.map((async t=>{if("inputs"in t){const s=JSON.parse(t.inputs),{nodeType:n,outputName:a}=t,o=e?await r(n,s):{[a]:"VALUE_BLOCKED"};if(!o)return"";let i=JSON.stringify(o[a]);return i.startsWith('"')&&(i=i.slice(1,-1)),i=JSON.stringify(i),i.slice(1,-1)}return t.value})));return JSON.parse(a.join(""))},x=(t,e)=>{const r=Object.fromEntries(Object.entries(e).map((([e,r])=>{const s=t[e];return s?[e,async(t,n)=>((t,e,r)=>{if(t)return Object.fromEntries(Object.entries(t).map((([t,s])=>t in e?[t,r(t,s)]:[t,s])))})(await f(r,t,n),s,(r=>((t,e,r)=>{const s=b(JSON.stringify(r)).replace("=","");return`${$}${t}~${e}~${s}${k}`})(e,r,t)))]:[e,r]}))),s=(t=>Object.entries(t).flatMap((([t,e])=>Object.entries(e).flatMap((([t,e])=>e.map((t=>[t.to,t])))))).reduce(((t,[e,r])=>(t[e]||(t[e]=[]),t[e].push(r),t)),{}))(t),n=Object.fromEntries(Object.entries(r).map((([t,r])=>{const n=s[t];return n?[t,async(t,s)=>f(r,await(async(t,e,r)=>{const s=e.some((e=>e.matches(t)));return Object.fromEntries(await Promise.all(Object.entries(t).map((async([t,e])=>[t,await r(e,s)]))))})(t,n,(async(t,r)=>T(t,r,(async(t,r)=>f(e[t],r,s))))),s)]:[t,r]})));return{url:"tunnel-kit",handlers:n}},P=()=>globalThis.performance.now()
*/const g=globalThis.process?t=>Buffer.from(t,"base64").toString("binary"):globalThis.atob,b=globalThis.process?t=>Buffer.from(t,"binary").toString("base64"):globalThis.btoa;class S{outputName;from;to;when;constructor(t,e,r,s={}){this.outputName=t,this.from=e,this.to=r,this.when=s}getInputNames(){const t=Object.keys(this.when);return 0===t.length?[this.outputName]:t}matches(t){return Object.entries(this.when).every((([e,r])=>{const s=t[e];return"string"==typeof r?s===r:"string"==typeof s&&r.test(s)}))}}const v=(t,e)=>Object.fromEntries(Object.entries(e).map((([e,r])=>"string"==typeof r?[e,[new S(e,t,r)]]:Array.isArray(r)?[e,r.map((r=>"string"==typeof r?new S(e,t,r):new S(e,t,r.to,r.when)))]:[e,[new S(e,t,r.to,r.when)]]))),O=Math.round(Date.now()/6048e5).toString(36),$=`T-${O}-`,E=`-${O}-T`,k=new RegExp(`(${$}.*?${E})`,"gm"),R=new RegExp(`^${$}(.+?)${E}$`),T=async(t,e,r)=>{const s=JSON.stringify(t),n=s.split(k).filter(Boolean).map((t=>{const e=t.match(R);if(e){const t=e[1].split("~"),[r,s,n]=t;return{nodeType:r,outputName:s,inputs:g(n)}}return{value:t}}));const a=await Promise.all(n.map((async t=>{if("inputs"in t){const s=JSON.parse(t.inputs),{nodeType:n,outputName:a}=t,o=e?await r(n,s):{[a]:"VALUE_BLOCKED"};if(!o)return"";let i=JSON.stringify(o[a]);return i.startsWith('"')&&(i=i.slice(1,-1)),i=JSON.stringify(i),i.slice(1,-1)}return t.value})));return JSON.parse(a.join(""))},x=(t,e)=>{const r=Object.fromEntries(Object.entries(e).map((([e,r])=>{const s=t[e];return s?[e,async(t,n)=>((t,e,r)=>{if(t)return Object.fromEntries(Object.entries(t).map((([t,s])=>t in e?[t,r(t,s)]:[t,s])))})(await f(r,t,n),s,(r=>((t,e,r)=>{const s=b(JSON.stringify(r)).replace("=","");return`${$}${t}~${e}~${s}${E}`})(e,r,t)))]:[e,r]}))),s=(t=>Object.entries(t).flatMap((([t,e])=>Object.entries(e).flatMap((([t,e])=>e.map((t=>[t.to,t])))))).reduce(((t,[e,r])=>(t[e]||(t[e]=[]),t[e].push(r),t)),{}))(t),n=Object.fromEntries(Object.entries(r).map((([t,r])=>{const n=s[t];return n?[t,async(t,s)=>f(r,await(async(t,e,r)=>{const s=e.some((e=>e.matches(t)));return Object.fromEntries(await Promise.all(Object.entries(t).map((async([t,e])=>[t,await r(e,s)]))))})(t,n,(async(t,r)=>T(t,r,(async(t,r)=>f(e[t],r,s))))),s)]:[t,r]})));return{url:"tunnel-kit",handlers:n}},P=()=>globalThis.performance.now()
/**

@@ -34,3 +34,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/,j=(t,e=[])=>{const r=e.find((e=>"string"==typeof e?e===t:e.node===t));return"string"==typeof r?{node:r}:r};class q{#h;constructor(t){this.#h=t}async serve(t){const{kits:e}=t,r=this.#h.createServerStream(),s=x((t=>t.proxy?Object.fromEntries(t.proxy.map((t=>{if("string"!=typeof t&&t.tunnel)return[t.node,v(t.node,t.tunnel)]})).filter(Boolean)):{})(t),(t=>t.reduce(((t,e)=>({...e.handlers,...t})),{}))(e)),n=s.handlers;for await(const e of u(r.writableResponses,r.readableRequests)){const[r]=e.data;if("end"===r)break;if("proxy"!==r){e.reply(["error",{error:"Expected proxy request.",timestamp:P()}]);continue}const[,{node:s,inputs:a}]=e.data,o=j(s.type,t.proxy)?n[s.type]:void 0;if(o)try{const t=await f(o,a,{descriptor:s});if(!t){e.reply(["error",{error:"Handler returned nothing.",timestamp:P()}]);continue}e.reply(["proxy",{outputs:t}])}catch(t){e.reply(["error",{error:t.message,timestamp:P()}])}else e.reply(["error",{error:"Can't proxy a node of this node type.",timestamp:P()}])}}}class M{#h;constructor(t){this.#h=t}shutdownServer(){const t=this.#h.createClientStream().writableRequests.getWriter();t.write(["end",{timestamp:P()}]),t.close()}async proxy(t,e){const r=this.#h.createClientStream(),s=r.writableRequests.getWriter(),n=r.readableResponses.getReader();s.write(["proxy",{node:t,inputs:e}]),s.close();const a=await n.read();if(a.done)throw new Error("Unexpected proxy failure: empty response.");const[o]=a.value;if("proxy"===o){const[,{outputs:t}]=a.value;return t}if("error"===o){const[,{error:t}]=a.value;throw new Error(t)}throw new Error(`Unexpected proxy failure: unknown response type "${o}".`)}createProxyKit(t=[]){const e=t.map((t=>"string"==typeof t?t:t.node)),r=Object.fromEntries(e.map((t=>[t,{invoke:async(t,e)=>{const r=e.descriptor;return await this.proxy(r,t)}}])));return new(new y({url:"proxy"}).build(r))({create:()=>{throw Error("Node instantiation can't (yet) happen during runtime")}})}}
*/,j=(t,e=[])=>{const r=e.find((e=>"string"==typeof e?e===t:e.node===t));return"string"==typeof r?{node:r}:r};class q{#h;constructor(t){this.#h=t}async serve(t){const{kits:e}=t,r=this.#h.createServerStream(),s=x((t=>t.proxy?Object.fromEntries(t.proxy.map((t=>{if("string"!=typeof t&&t.tunnel)return[t.node,v(t.node,t.tunnel)]})).filter(Boolean)):{})(t),(t=>t.reduce(((t,e)=>({...e.handlers,...t})),{}))(e)),n=s.handlers;for await(const e of u(r.writableResponses,r.readableRequests)){const[r]=e.data;if("end"===r)break;if("proxy"!==r){e.reply(["error",{error:"Expected proxy request.",timestamp:P()}]);continue}const[,{node:s,inputs:a}]=e.data,o=j(s.type,t.proxy)?n[s.type]:void 0;if(o)try{const t=await f(o,a,{descriptor:s});if(!t){e.reply(["error",{error:"Handler returned nothing.",timestamp:P()}]);continue}e.reply(["proxy",{outputs:t}])}catch(t){e.reply(["error",{error:t.message,timestamp:P()}])}else e.reply(["error",{error:"Can't proxy a node of this node type.",timestamp:P()}])}}}class N{#h;constructor(t){this.#h=t}shutdownServer(){const t=this.#h.createClientStream().writableRequests.getWriter();t.write(["end",{timestamp:P()}]),t.close()}async proxy(t,e){const r=this.#h.createClientStream(),s=r.writableRequests.getWriter(),n=r.readableResponses.getReader();s.write(["proxy",{node:t,inputs:e}]),s.close();const a=await n.read();if(a.done)throw new Error("Unexpected proxy failure: empty response.");const[o]=a.value;if("proxy"===o){const[,{outputs:t}]=a.value;return t}if("error"===o){const[,{error:t}]=a.value;throw new Error(JSON.stringify(t))}throw new Error(`Unexpected proxy failure: unknown response type "${o}".`)}createProxyKit(t=[]){const e=t.map((t=>"string"==typeof t?t:t.node)),r=Object.fromEntries(e.map((t=>[t,{invoke:async(t,e)=>{const r=e.descriptor;return await this.proxy(r,t)}}])));return new(new y({url:"proxy"}).build(r))({create:()=>{throw Error("Node instantiation can't (yet) happen during runtime")}})}}
/**

@@ -40,3 +40,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/class N extends EventTarget{#d;constructor(t){super(),this.#d=t}async report(t){return this.#d(t)}}
*/class M extends EventTarget{#d;constructor(t){super(),this.#d=t}async report(t){return this.#d(t)}}
/**

@@ -46,3 +46,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/class W{static computeMissingInputs(t,e,r){const s=[...new Set(t.filter((t=>!!t.in&&!t.optional)).map((t=>t.in||"")))],n=new Set;return Object.keys(e).forEach((t=>n.add(t))),r.configuration&&Object.keys(r.configuration).forEach((t=>n.add(t))),s.filter((t=>!n.has(t)))}}
*/class I{static computeMissingInputs(t,e,r){const s=[...new Set(t.filter((t=>!!t.in&&!t.optional)).map((t=>t.in||"")))],n=new Set;return Object.keys(e).forEach((t=>n.add(t))),r.configuration&&Object.keys(r.configuration).forEach((t=>n.add(t))),s.filter((t=>!n.has(t)))}}
/**

@@ -52,3 +52,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/class I{state=new Map;constants=new Map;#w(t,e,r,s){let n=t.get(e);n||(n=new Map,t.set(e,n));let a=n.get(r);a||(a=[],n.set(r,a)),a.push(s)}wireOutputs(t,e){if(0!==t.filter((e=>e.from!=t[0].from)).length)throw new Error("All opportunities must be from the same node");t.forEach((t=>{const r=t.to,s=t.out,n=t.constant?this.constants:this.state;if(s)if("*"===s)for(const t in e){const s=e[t];null!=s&&null!=s&&this.#w(n,r,t,s)}else if(t.in){const a=e[s];null!=a&&null!=a&&this.#w(n,r,t.in,a)}}))}getAvailableInputs(t){const e={};for(const r of[this.constants.get(t),this.state.get(t)])if(r)for(const[t,s]of r.entries())0!==s.length&&(e[t]=s[0]);return e}useInputs(t,e){const r=this.state.get(t);if(r)for(const t in e){const e=r.get(t);e&&e.shift()}}}
*/class W{state=new Map;constants=new Map;#w(t,e,r,s){let n=t.get(e);n||(n=new Map,t.set(e,n));let a=n.get(r);a||(a=[],n.set(r,a)),a.push(s)}wireOutputs(t,e){if(0!==t.filter((e=>e.from!=t[0].from)).length)throw new Error("All opportunities must be from the same node");t.forEach((t=>{const r=t.to,s=t.out,n=t.constant?this.constants:this.state;if(s)if("*"===s)for(const t in e){const s=e[t];null!=s&&null!=s&&this.#w(n,r,t,s)}else if(t.in){const a=e[s];null!=a&&null!=a&&this.#w(n,r,t.in,a)}}))}getAvailableInputs(t){const e={};for(const r of[this.constants.get(t),this.state.get(t)])if(r)for(const[t,s]of r.entries())0!==s.length&&(e[t]=s[0]);return e}useInputs(t,e){const r=this.state.get(t);if(r)for(const t in e){const e=r.get(t);e&&e.shift()}}}
/**

@@ -58,3 +58,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/class A{descriptor;inputs;missingInputs;opportunities;newOpportunities;state;outputsPromise;pendingOutputs;constructor(t,e,r,s,n,a,o){this.descriptor=t,this.inputs=e,this.missingInputs=r,this.opportunities=s,this.newOpportunities=n,this.state=a,this.pendingOutputs=o}get skip(){return this.missingInputs.length>0}static fromObject(t){const e=new I;return e.constants=t.state.constants,e.state=t.state.state,new A(t.descriptor,t.inputs,t.missingInputs,t.opportunities,t.newOpportunities,e,t.pendingOutputs)}}
*/class A{descriptor;inputs;missingInputs;opportunities;newOpportunities;state;outputsPromise;pendingOutputs;constructor(t,e,r,s,n,a,o){this.descriptor=t,this.inputs=e,this.missingInputs=r,this.opportunities=s,this.newOpportunities=n,this.state=a,this.pendingOutputs=o}get skip(){return this.missingInputs.length>0}static fromObject(t){const e=new W;return e.constants=t.state.constants,e.state=t.state.state,new A(t.descriptor,t.inputs,t.missingInputs,t.opportunities,t.newOpportunities,e,t.pendingOutputs)}}
/**

@@ -64,3 +64,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/class C{graph;#m;#f;constructor(t,e,r=!0){this.graph=t,this.#m=e,this.#f=r}static#y(t,e){const{promiseId:r,outputs:s,newOpportunities:n}=e;t.pendingOutputs.delete(r);const a=s.$error?n.filter((t=>"$error"===t.out)):n;if(t.opportunities.push(...a),t.state.wireOutputs(a,s),s.$error){if(0===a.length)throw new Error("Uncaught exception in node handler. Catch by wiring up the $error output.",{cause:s.$error});globalThis.console.warn("Error in node handler, passinng to the wired $error output.",s.$error,a)}}static async processAllPendingNodes(t){return(await Promise.all(t.pendingOutputs.values())).forEach((e=>{C.#y(t,e)})),t}async next(){if(!this.#m.skip){const{inputs:t,outputsPromise:e,newOpportunities:r,descriptor:s}=this.#m;this.#m.state.useInputs(s.id,this.#m.inputs);const n=Symbol(),a=new Promise((a=>{(e||Promise.resolve({})).then((e=>{if(e.$error){const r=e.$error;e.$error={descriptor:s,...r,inputs:{...t,...r.inputs}}}a({promiseId:n,outputs:e,newOpportunities:r})})).catch((e=>{a({promiseId:n,outputs:{$error:{kind:"error",error:e,inputs:t,descriptor:s}},newOpportunities:r.filter((t=>"$error"===t.out))})}))}));this.#m.pendingOutputs.set(n,a)}for(;(0===this.#m.opportunities.length||this.#f)&&this.#m.pendingOutputs.size>0;)C.#y(this.#m,await Promise.race(this.#m.pendingOutputs.values()));if(0===this.#m.opportunities.length)return{done:!0,value:null};const t=this.#m.opportunities.shift(),{heads:e,nodes:r,tails:s}=this.graph,n=t.to,a=r.get(n);if(!a)throw new Error(`No node found for id "${n}"`);const o=e.get(n)||[],i=this.#m.state.getAvailableInputs(n),u=W.computeMissingInputs(o,i,a),c=s.get(n)||[],p={...a.configuration,...i};return this.#m=new A(a,p,u,this.#m.opportunities,c,this.#m.state,this.#m.pendingOutputs),{done:!1,value:this.#m}}}
*/class C{graph;#m;#f;constructor(t,e,r=!0){this.graph=t,this.#m=e,this.#f=r}static#y(t,e){const{promiseId:r,outputs:s,newOpportunities:n}=e;t.pendingOutputs.delete(r);const a=s.$error?n.filter((t=>"$error"===t.out)):n;if(t.opportunities.push(...a),t.state.wireOutputs(a,s),s.$error){if(0===a.length)throw new Error("Uncaught exception in node handler. Catch by wiring up the $error output.",{cause:s.$error});globalThis.console.warn("Error in node handler, passing to the wired $error output.",s.$error,a)}}static async processAllPendingNodes(t){return(await Promise.all(t.pendingOutputs.values())).forEach((e=>{C.#y(t,e)})),t}async next(){if(!this.#m.skip){const{inputs:t,outputsPromise:e,newOpportunities:r,descriptor:s}=this.#m;this.#m.state.useInputs(s.id,this.#m.inputs);const n=Symbol(),a=new Promise((a=>{(e||Promise.resolve({})).then((e=>{if(e.$error){const r=e.$error;e.$error={descriptor:s,...r,inputs:{...t,...r.inputs}}}a({promiseId:n,outputs:e,newOpportunities:r})})).catch((e=>{a({promiseId:n,outputs:{$error:{kind:"error",error:e,inputs:t,descriptor:s}},newOpportunities:r.filter((t=>"$error"===t.out))})}))}));this.#m.pendingOutputs.set(n,a)}for(;(0===this.#m.opportunities.length||this.#f)&&this.#m.pendingOutputs.size>0;)C.#y(this.#m,await Promise.race(this.#m.pendingOutputs.values()));if(0===this.#m.opportunities.length)return{done:!0,value:null};const t=this.#m.opportunities.shift(),{heads:e,nodes:r,tails:s}=this.graph,n=t.to,a=r.get(n);if(!a)throw new Error(`No node found for id "${n}"`);const o=e.get(n)||[],i=this.#m.state.getAvailableInputs(n),u=I.computeMissingInputs(o,i,a),c=s.get(n)||[],p={...a.configuration,...i};return this.#m=new A(a,p,u,this.#m.opportunities,c,this.#m.state,this.#m.pendingOutputs),{done:!1,value:this.#m}}}
/**

@@ -75,3 +75,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/class J{graph;previousResult;constructor(t,e){this.graph=new _(t),this.previousResult=e}[Symbol.asyncIterator](){return this.start()}start(){if(this.previousResult)return new C(this.graph,this.previousResult);const{entries:t}=this.graph;if(0===t.length)throw new Error("No entry node found in graph.");const e=t.map((t=>({from:"$entry",to:t}))),r=new A({id:"$empty",type:"$empty"},{},[],e,[],new I,new Map);return new C(this.graph,r)}static async prepareToSave(t){return await C.processAllPendingNodes(t)}}
*/class J{graph;previousResult;constructor(t,e){this.graph=new _(t),this.previousResult=e}[Symbol.asyncIterator](){return this.start()}start(){if(this.previousResult)return new C(this.graph,this.previousResult);const{entries:t}=this.graph;if(0===t.length)throw new Error("No entry node found in graph.");const e=t.map((t=>({from:"$entry",to:t}))),r=new A({id:"$empty",type:"$empty"},{},[],e,[],new W,new Map);return new C(this.graph,r)}static async prepareToSave(t){return await C.processAllPendingNodes(t)}}
/**

@@ -92,3 +92,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/class U{#h;constructor(t){this.#h=t}async serve(t,e=!1,r={}){const s=this.#h.createServerStream(),a=s.readableRequests.getReader();let o=await a.read();if(o.done)return;const i=(t=>{const[e,,r]=t;if(console.log("resumeRun",e,r),!r)return;if(r.length>1)throw new Error("I don't yet know how to resume from nested subgraphs.");const s=B.load(r[0].state);if("input"===e){const[,e]=t;s.inputs=e.inputs}return s})(o.value),u=s.writableResponses.getWriter(),c={...r,probe:e?new N((async t=>{const{type:e,data:r}=t,s=[e,n(r)];"nodestart"==e&&s.push(t.state),await u.write(s)})):void 0};try{for await(const e of t.run(c,i))if("input"===e.type){const t=e.runState,{node:r,inputArguments:s,timestamp:n}=e;if(await u.write(["input",{node:r,inputArguments:s,timestamp:n},t]),o=await a.read(),o.done)return void await u.close();{const[t,r]=o.value;"input"===t&&(e.inputs=r.inputs)}}else if("output"===e.type){const{node:t,outputs:r,timestamp:s}=e;await u.write(["output",{node:t,outputs:r,timestamp:s}])}await u.write(["end",{timestamp:P()}]),await u.close()}catch(t){let e=t,r="";for(;e?.cause;)e=e.cause.error,r+=`\n${e.message}`;console.error("Run Server error:",e.message),await u.write(["error",{error:r,timestamp:P()}]),await u.close()}}}const H=t=>{const[e,r,s]=t.data;return{type:e,data:r,state:s,reply:async r=>{if("input"!==e)throw new Error("For now, we cannot reply to messages other than 'input'.");await t.reply([e,r,s])}}};class z{#h;constructor(t){this.#h=t}async*run(t){const e=this.#h.createClientStream(),r=u(e.writableRequests,e.readableResponses),s=["run",{}];t&&s.push(t),await r.start(s);for await(const t of r)yield H(t)}async runOnce(t){let e;for await(const r of this.run()){const{type:s,data:n}=r;if("input"===s)r.reply({inputs:t});else if("output"===s){e=n.outputs;break}}return e||{}}}
*/class U{#h;constructor(t){this.#h=t}async serve(t,e=!1,r={}){const s=this.#h.createServerStream(),a=s.readableRequests.getReader();let o=await a.read();if(o.done)return;const i=(t=>{const[e,,r]=t;if(console.log("resumeRun",e,r),!r)return;if(r.length>1)throw new Error("I don't yet know how to resume from nested subgraphs.");const s=B.load(r[0].state);if("input"===e){const[,e]=t;s.inputs=e.inputs}return s})(o.value),u=s.writableResponses.getWriter(),c={...r,probe:e?new M((async t=>{const{type:e,data:r}=t,s=[e,n(r)];"nodestart"==e&&s.push(t.state),await u.write(s)})):void 0};try{for await(const e of t.run(c,i))if("input"===e.type){const t=e.runState,{node:r,inputArguments:s,timestamp:n}=e;if(await u.write(["input",{node:r,inputArguments:s,timestamp:n},t]),o=await a.read(),o.done)return void await u.close();{const[t,r]=o.value;"input"===t&&(e.inputs=r.inputs)}}else if("output"===e.type){const{node:t,outputs:r,timestamp:s}=e;await u.write(["output",{node:t,outputs:r,timestamp:s}])}await u.write(["end",{timestamp:P()}]),await u.close()}catch(t){const e=t;let r;if(e?.cause){const{cause:t}=e;r=t}else r=e.message;console.error("Run Server error:",r),await u.write(["error",{error:r,timestamp:P()}]),await u.close()}}}const H=t=>{const[e,r,s]=t.data;return{type:e,data:r,state:s,reply:async r=>{if("input"!==e)throw new Error("For now, we cannot reply to messages other than 'input'.");await t.reply([e,r,s])}}};class z{#h;constructor(t){this.#h=t}async*run(t){const e=this.#h.createClientStream(),r=u(e.writableRequests,e.readableResponses),s=["run",{}];t&&s.push(t),await r.start(s);for await(const t of r)yield H(t)}async runOnce(t){let e;for await(const r of this.run()){const{type:s,data:n}=r;if("input"===s)r.reply({inputs:t});else if("output"===s){e=n.outputs;break}}return e||{}}}
/**

@@ -103,3 +103,3 @@ * @license

* SPDX-License-Identifier: Apache-2.0
*/const V=t=>t,G=t=>({test:e=>new URL(e).origin===t});export{l as HTTPClientTransport,p as HTTPServerTransport,K as InitClient,D as InitServer,d as PortDispatcher,M as ProxyClient,q as ProxyServer,z as RunClient,U as RunServer,w as WorkerClientTransport,m as WorkerServerTransport,V as defineConfig,G as hasOrigin};
*/const V=t=>t,G=t=>({test:e=>new URL(e).origin===t});export{l as HTTPClientTransport,p as HTTPServerTransport,K as InitClient,D as InitServer,d as PortDispatcher,N as ProxyClient,q as ProxyServer,z as RunClient,U as RunServer,w as WorkerClientTransport,m as WorkerServerTransport,V as defineConfig,G as hasOrigin};
//# sourceMappingURL=remote.min.js.map

@@ -27,3 +27,3 @@ /**

if (schema.default !== undefined) {
if (schema.type !== "string") {
if ("type" in schema && schema.type !== "string") {
return JSON.parse(schema.default);

@@ -89,3 +89,3 @@ }

};
console.log("requestInputResult", requestInputResult);
//console.log("requestInputResult", requestInputResult);
await next(new InputStageResult(requestInputResult, undefined, -1));

@@ -92,0 +92,0 @@ const outputs = await requestInputResult.outputsPromise;

@@ -6,5 +6,5 @@ /**

*/
import type { InputValues, Kit, NodeHandler, NodeHandlerContext, NodeHandlers } from "./types.js";
export declare const callHandler: (handler: NodeHandler, inputs: InputValues, context: NodeHandlerContext) => Promise<void | Partial<Record<string, import("./types.js").NodeValue>>>;
import type { InputValues, Kit, NodeHandler, NodeHandlerContext, NodeHandlers, OutputValues } from "./types.js";
export declare const callHandler: (handler: NodeHandler, inputs: InputValues, context: NodeHandlerContext) => Promise<OutputValues | void>;
export declare const handlersFromKits: (kits: Kit[]) => NodeHandlers;
//# sourceMappingURL=handler.d.ts.map

@@ -6,8 +6,21 @@ /**

*/
export const callHandler = async (handler, inputs, context) => {
const getHandlerFunction = (handler) => {
if (handler instanceof Function)
return handler(inputs, context);
return handler;
if (handler.invoke)
return handler.invoke(inputs, context);
return handler.invoke;
throw new Error("Invalid handler");
};
export const callHandler = async (handler, inputs, context) => {
// if (handler instanceof Function) return handler(inputs, context);
// if (handler.invoke) return handler.invoke(inputs, context);
const handlerFunction = getHandlerFunction(handler);
return new Promise((resolve) => {
handlerFunction(inputs, context)
.then(resolve)
.catch((error) => {
resolve({ $error: { error } });
});
});
};
export const handlersFromKits = (kits) => {

@@ -14,0 +27,0 @@ return kits.reduce((handlers, kit) => {

@@ -20,8 +20,8 @@ /**

export { Runner } from "./new/runner/runner.js";
export { recipe, code } from "./new/recipe-grammar/recipe.js";
export { addKit } from "./new/recipe-grammar/kits.js";
export { base } from "./new/recipe-grammar/base.js";
export { board, board as recipe, code, } from "./new/grammar/board.js";
export { addKit } from "./new/grammar/kits.js";
export { base } from "./new/grammar/base.js";
export type { NodeValue as NewNodeValue, InputValues as NewInputValues, OutputValues as NewOutputValues, Serializeable, AbstractNode, } from "./new/runner/types.js";
export type { Lambda, InputsForHandler, InputsForGraphDeclaration, OutputsForGraphDeclaration, NodeFactory as NewNodeFactory, NodeProxy as __NodeProxy, InputsMaybeAsValues, OutputsMaybeAsValues, OutputValuesOrUnknown, ProjectBackToOutputValues as __ProjectBackToOutputValues, InputValues as NewInputValuesWithNodeFactory, AbstractValue as V, } from "./new/recipe-grammar/types.js";
export type { Lambda, InputsForHandler, InputsForGraphDeclaration, OutputsForGraphDeclaration, NodeFactory as NewNodeFactory, NodeProxy as __NodeProxy, InputsMaybeAsValues, OutputsMaybeAsValues, OutputValuesOrUnknown, ProjectBackToOutputValues as __ProjectBackToOutputValues, InputValues as NewInputValuesWithNodeFactory, AbstractValue as V, } from "./new/grammar/types.js";
export { asyncGen } from "./utils/async-gen.js";
//# sourceMappingURL=index.d.ts.map

@@ -20,6 +20,8 @@ /**

export { Runner } from "./new/runner/runner.js";
export { recipe, code } from "./new/recipe-grammar/recipe.js";
export { addKit } from "./new/recipe-grammar/kits.js";
export { base } from "./new/recipe-grammar/base.js";
export { board,
// TODO Alias for easier migration to the new name. Remove in a future breaking change.
board as recipe, code, } from "./new/grammar/board.js";
export { addKit } from "./new/grammar/kits.js";
export { base } from "./new/grammar/base.js";
export { asyncGen } from "./utils/async-gen.js";
//# sourceMappingURL=index.js.map

@@ -10,3 +10,3 @@ /**

import type { GraphDescriptor } from "./types.js";
export declare const toMermaid: (graph: GraphDescriptor, direction?: string, unstyled?: boolean) => string;
export declare const toMermaid: (graph: GraphDescriptor, direction?: string, unstyled?: boolean, ignoreSubgraphs?: boolean) => string;
//# sourceMappingURL=mermaid.d.ts.map

@@ -128,15 +128,19 @@ /**

}
describeGraph() {
describeGraph(ignoreSubgraphs = false) {
const result = this.edges.map((edge) => {
const mermEdge = describeEdge(edge, this.nodeMap, this.idPrefix);
const mermSubgraphs = this.describeSubgraphs(edge, this.idPrefix);
const mermSubgraphs = ignoreSubgraphs
? ""
: this.describeSubgraphs(edge, this.idPrefix);
return `${mermEdge}${mermSubgraphs}`;
});
const subgraphs = Object.entries(this.subgraphs).map(([name, subgraph]) => this.describeSubgraph(subgraph, name, undefined, undefined, `${name}${this.idPrefix}`));
const subgraphs = ignoreSubgraphs
? ""
: Object.entries(this.subgraphs).map(([name, subgraph]) => this.describeSubgraph(subgraph, name, undefined, undefined, `${name}${this.idPrefix}`));
return [...result, ...subgraphs].join("\n");
}
}
export const toMermaid = (graph, direction = "TD", unstyled = false) => {
export const toMermaid = (graph, direction = "TD", unstyled = false, ignoreSubgraphs = false) => {
const generator = new MermaidGenerator(graph);
const edges = generator.describeGraph();
const edges = generator.describeGraph(ignoreSubgraphs);
return unstyled

@@ -143,0 +147,0 @@ ? unstyledTemplate(edges, direction)

@@ -110,3 +110,3 @@ /**

const [, { error }] = result.value;
throw new Error(error);
throw new Error(JSON.stringify(error));
}

@@ -113,0 +113,0 @@ else {

@@ -83,9 +83,12 @@ /**

catch (e) {
let error = e;
let message = "";
while (error?.cause) {
error = error.cause.error;
message += `\n${error.message}`;
const error = e;
let message;
if (error?.cause) {
const { cause } = error;
message = cause;
}
console.error("Run Server error:", error.message);
else {
message = error.message;
}
console.error("Run Server error:", message);
await responses.write([

@@ -92,0 +95,0 @@ "error",

@@ -101,3 +101,3 @@ /**

*/
mermaid(direction?: string, unstyled?: boolean): string;
mermaid(direction?: string, unstyled?: boolean, ignoreSubgraphs?: boolean): string;
/**

@@ -104,0 +104,0 @@ * Creates a new board from JSON. If you have a serialized board, you can

@@ -263,4 +263,4 @@ /**

*/
mermaid(direction = "TD", unstyled = false) {
return toMermaid(this, direction, unstyled);
mermaid(direction = "TD", unstyled = false, ignoreSubgraphs = false) {
return toMermaid(this, direction, unstyled, ignoreSubgraphs);
}

@@ -267,0 +267,0 @@ /**

@@ -11,12 +11,6 @@ /**

$type?: string | undefined;
value: Iterable<readonly [
string,
unknown
]>;
value: Iterable<readonly [string, unknown]>;
}) => {
$type?: string | undefined;
value: Iterable<readonly [
string,
unknown
]>;
value: Iterable<readonly [string, unknown]>;
} | Map<string, unknown>;

@@ -23,0 +17,0 @@ export declare const saveRunnerState: (type: string, result: TraversalResult) => Promise<string>;

@@ -36,3 +36,3 @@ /**

else {
globalThis.console.warn("Error in node handler, passinng to the wired $error output.", outputs.$error, opportunities);
globalThis.console.warn("Error in node handler, passing to the wired $error output.", outputs.$error, opportunities);
}

@@ -39,0 +39,0 @@ }

@@ -503,2 +503,17 @@ /**

};
export type ErrorObject = {
/**
* The error message. Can be a string or a more detailed object. For
* example, fetch errors may return a JSON response from the server.
*/
error: string | object;
/**
* The node that threw the error.
*/
descriptor: NodeDescriptor;
/**
* The inputs that were passed to the node that threw the error.
*/
inputs: InputValues;
};
/**

@@ -510,5 +525,5 @@ * Sent by the runner when an error occurs.

/**
* The error message.
* The error message string or a more detailed error object
*/
error: string;
error: string | ErrorObject;
timestamp: number;

@@ -515,0 +530,0 @@ };

{
"name": "@google-labs/breadboard",
"version": "0.8.0",
"publishConfig": {
"registry": "https://wombat-dressing-room.appspot.com"
},
"version": "0.9.0",
"description": "A library for rapid generative AI application prototyping",

@@ -118,4 +121,3 @@ "main": "./dist/src/index.js",

"dist/*.js",
"dist/*.js.map",
"breadboard.schema.json"
"dist/*.js.map"
],

@@ -122,0 +124,0 @@ "ava": {

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet