blink 0.1.13 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -48,7 +48,7 @@ Your platform (`+process.platform+`-`+process.arch+`) might not be supported.`:t
48
48
  `);return t.from(n)},exports.decodePax=function(e){let n={};for(;e.length;){let r=0;for(;r<e.length&&e[r]!==32;)r++;let i=parseInt(t.toString(e.subarray(0,r)),10);if(!i)return n;let a=t.toString(e.subarray(r+1,i-1)),o=a.indexOf(`=`);if(o===-1)return n;n[a.slice(0,o)]=a.slice(o+1),e=e.subarray(i)}return n},exports.encode=function(e){let i=t.alloc(512),a=e.name,o=``;if(e.typeflag===5&&a[a.length-1]!==`/`&&(a+=`/`),t.byteLength(a)!==a.length)return null;for(;t.byteLength(a)>100;){let e=a.indexOf(`/`);if(e===-1)return null;o+=o?`/`+a.slice(0,e):a.slice(0,e),a=a.slice(e+1)}return t.byteLength(a)>100||t.byteLength(o)>155||e.linkname&&t.byteLength(e.linkname)>100?null:(t.write(i,a),t.write(i,p(e.mode&4095,6),100),t.write(i,p(e.uid,6),108),t.write(i,p(e.gid,6),116),h(e.size,i,124),t.write(i,p(e.mtime.getTime()/1e3|0,11),136),i[156]=48+u(e.type),e.linkname&&t.write(i,e.linkname,157),t.copy(n,i,257),t.copy(r,i,263),e.uname&&t.write(i,e.uname,265),e.gname&&t.write(i,e.gname,297),t.write(i,p(e.devmajor||0,6),329),t.write(i,p(e.devminor||0,6),337),o&&t.write(i,o,345),t.write(i,p(f(i),6),148),i)},exports.decode=function(e,t,n){let r=e[156]===0?0:e[156]-48,i=v(e,0,100,t),a=_(e,100,8),c=_(e,108,8),u=_(e,116,8),d=_(e,124,12),p=_(e,136,12),m=l(r),h=e[157]===0?null:v(e,157,100,t),g=v(e,265,32),y=v(e,297,32),b=_(e,329,8),x=_(e,337,8),S=f(e);if(S===256)return null;if(S!==_(e,148,8))throw Error(`Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?`);if(o(e))e[345]&&(i=v(e,345,155,t)+`/`+i);else if(!s(e)&&!n)throw Error(`Invalid tar header: unknown format.`);return r===0&&i&&i[i.length-1]===`/`&&(r=5),{name:i,mode:a,uid:c,gid:u,size:d,mtime:new Date(1e3*p),type:m,linkname:h,uname:g,gname:y,devmajor:b,devminor:x,pax:null}};function o(e){return t.equals(n,e.subarray(257,263))}function s(e){return t.equals(i,e.subarray(257,263))&&t.equals(a,e.subarray(263,265))}function c(e,t,n){return typeof e==`number`?(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0):n}function l(e){switch(e){case 0:return`file`;case 1:return`link`;case 2:return`symlink`;case 3:return`character-device`;case 4:return`block-device`;case 5:return`directory`;case 6:return`fifo`;case 7:return`contiguous-file`;case 72:return`pax-header`;case 55:return`pax-global-header`;case 27:return`gnu-long-link-path`;case 28:case 30:return`gnu-long-path`}return null}function u(e){switch(e){case`file`:return 0;case`link`:return 1;case`symlink`:return 2;case`character-device`:return 3;case`block-device`:return 4;case`directory`:return 5;case`fifo`:return 6;case`contiguous-file`:return 7;case`pax-header`:return 72}return 0}function d(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function f(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function p(e,t){return e=e.toString(8),e.length>t?`7777777777777777777`.slice(0,t)+` `:`0000000000000000000`.slice(0,t-e.length)+e+` `}function m(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function h(e,n,r){e.toString(8).length>11?m(e,n,r):t.write(n,p(e,11),r)}function g(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let i=e[r];t?n.push(i):n.push(255-i)}let i=0,a=n.length;for(r=0;r<a;r++)i+=n[r]*256**r;return t?i:-1*i}function _(e,n,r){if(e=e.subarray(n,n+r),n=0,e[n]&128)return g(e);{for(;n<e.length&&e[n]===32;)n++;let r=c(d(e,32,n,e.length),e.length,e.length);for(;n<r&&e[n]===0;)n++;return r===n?0:parseInt(t.toString(e.subarray(n,r)),8)}}function v(e,n,r,i){return t.toString(e.subarray(n,d(e,0,n,n+r)),i)}function y(e){let n=t.byteLength(e),r=Math.floor(Math.log(n)/Math.log(10))+1;return n+r>=10**r&&r++,n+r+e}})),Cr=e(((exports,t)=>{let{Writable:n,Readable:r,getStreamError:i}=xr(),a=gr(),o=_r(),s=Sr(),c=o.alloc(0);var l=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new a,this._offset=0}push(e){this.buffered+=e.byteLength,this.queue.push(e)}shiftFirst(e){return this._buffered===0?null:this._next(e)}shift(e){if(e>this.buffered)return null;if(e===0)return c;let t=this._next(e);if(e===t.byteLength)return t;let n=[t];for(;(e-=t.byteLength)>0;)t=this._next(e),n.push(t);return o.concat(n)}_next(e){let t=this.queue.peek(),n=t.byteLength-this._offset;if(e>=n){let e=this._offset?t.subarray(this._offset,t.byteLength):t;return this.queue.shift(),this._offset=0,this.buffered-=n,this.shifted+=n,e}return this.buffered-=e,this.shifted+=e,t.subarray(this._offset,this._offset+=e)}},u=class extends r{constructor(e,t,n){super(),this.header=t,this.offset=n,this._parent=e}_read(e){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),e(null)}_predestroy(){this._parent.destroy(i(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=p(this.header.size),this._parent._update())}_destroy(e){this._detach(),e(null)}},d=class extends n{constructor(e){super(e),e||={},this._buffer=new l,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=f,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=e.filenameEncoding||`utf-8`,this._allowUnknownFormat=!!e.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(e){if(this._locked=!1,e){this.destroy(e),this._continueWrite(e);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=s.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(e){return this._continueWrite(e),!1}if(!this._header)return!0;switch(this._header.type){case`gnu-long-path`:case`gnu-long-link-path`:case`pax-global-header`:case`pax-header`:return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type===`directory`?(this.emit(`entry`,this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit(`entry`,this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&=(this._header.name=this._gnuLongPath,null),this._gnuLongLinkPath&&=(this._header.linkname=this._gnuLongLinkPath,null),this._pax&&=(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,null)}_decodeLongHeader(e){switch(this._header.type){case`gnu-long-path`:this._gnuLongPath=s.decodeLongPath(e,this._filenameEncoding);break;case`gnu-long-link-path`:this._gnuLongLinkPath=s.decodeLongPath(e,this._filenameEncoding);break;case`pax-global-header`:this._paxGlobal=s.decodePax(e);break;case`pax-header`:this._pax=this._paxGlobal===null?s.decodePax(e):Object.assign({},this._paxGlobal,s.decodePax(e));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=p(this._header.size);let e=this._buffer.shift(this._header.size);try{this._decodeLongHeader(e)}catch(e){return this._continueWrite(e),!1}return!0}_consumeStream(){let e=this._buffer.shiftFirst(this._missing);if(e===null)return!1;this._missing-=e.byteLength;let t=this._stream.push(e);return this._missing===0?(this._stream.push(null),t&&this._stream._detach(),t&&this._locked===!1):t}_createStream(){return new u(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let e=this._buffer.shiftFirst(this._missing);e!==null&&(this._missing-=e.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(e){let t=this._callback;this._callback=f,t(e)}_write(e,t){this._callback=t,this._buffer.push(e),this._update()}_final(e){this._finished=this._missing===0&&this._buffer.buffered===0,e(this._finished?null:Error(`Unexpected end of data`))}_predestroy(){this._continueWrite(null)}_destroy(e){this._stream&&this._stream.destroy(i(this)),e(null)}[Symbol.asyncIterator](){let e=null,t=null,n=null,r=null,i=null,a=this;return this.on(`entry`,c),this.on(`error`,t=>{e=t}),this.on(`close`,l),{[Symbol.asyncIterator](){return this},next(){return new Promise(s)},return(){return u(null)},throw(e){return u(e)}};function o(e){if(!i)return;let t=i;i=null,t(e)}function s(i,s){if(e)return s(e);if(r){i({value:r,done:!1}),r=null;return}t=i,n=s,o(null),a._finished&&t&&(t({value:void 0,done:!0}),t=n=null)}function c(e,a,o){i=o,a.on(`error`,f),t?(t({value:a,done:!1}),t=n=null):r=a}function l(){o(e),t&&=(e?n(e):t({value:void 0,done:!0}),n=null)}function u(e){return a.destroy(e),o(e),new Promise((t,n)=>{if(a.destroyed)return t({value:void 0,done:!0});a.once(`close`,function(){e?n(e):t({value:void 0,done:!0})})})}}};t.exports=function(e){return new d(e)};function f(){}function p(e){return e&=511,e&&512-e}})),wr=e(((exports,t)=>{let r={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{t.exports=n(`fs`).constants||r}catch{t.exports=r}})),Tr=e(((exports,t)=>{let{Readable:n,Writable:r,getStreamError:i}=xr(),a=_r(),o=wr(),s=Sr(),c=a.alloc(1024);var l=class extends r{constructor(e,t,n){super({mapWritable:m,eagerOpen:!0}),this.written=0,this.header=t,this._callback=n,this._linkname=null,this._isLinkname=t.type===`symlink`&&!t.linkname,this._isVoid=t.type!==`file`&&t.type!==`contiguous-file`,this._finished=!1,this._pack=e,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(e){this._openCallback=e,this._pack._stream===this&&this._continueOpen()}_continuePack(e){if(this._callback===null)return;let t=this._callback;this._callback=null,t(e)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let e=this._openCallback;if(this._openCallback=null,e!==null){if(this._pack.destroying)return e(Error(`pack stream destroyed`));if(this._pack._finalized)return e(Error(`pack stream is already finalized`));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),e(null)}}_write(e,t){if(this._isLinkname)return this._linkname=this._linkname?a.concat([this._linkname,e]):e,t(null);if(this._isVoid)return e.byteLength>0?t(Error(`No body allowed for this entry`)):t();if(this.written+=e.byteLength,this._pack.push(e))return t();this._pack._drain=t}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?a.toString(this._linkname,`utf-8`):``,this._pack._encode(this.header)),p(this._pack,this.header.size),this._pack._done(this))}_final(e){if(this.written!==this.header.size)return e(Error(`Size mismatch`));this._finish(),e(null)}_getError(){return i(this)||Error(`tar entry destroyed`)}_predestroy(){this._pack.destroy(this._getError())}_destroy(e){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),e()}},u=class extends n{constructor(e){super(e),this._drain=f,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(e,t,n){if(this._finalized||this.destroying)throw Error(`already finalized or destroyed`);typeof t==`function`&&(n=t,t=null),n||=f,(!e.size||e.type===`symlink`)&&(e.size=0),e.type||=d(e.mode),e.mode||=e.type===`directory`?493:420,e.uid||=0,e.gid||=0,e.mtime||=new Date,typeof t==`string`&&(t=a.from(t));let r=new l(this,e,n);return a.isBuffer(t)?(e.size=t.byteLength,r.write(t),r.end(),r):(r._isVoid,r)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(c),this.push(null))}_done(e){e===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(e){if(!e.pax){let t=s.encode(e);if(t){this.push(t);return}}this._encodePax(e)}_encodePax(e){let t=s.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),n={name:`PaxHeader`,mode:e.mode,uid:e.uid,gid:e.gid,size:t.byteLength,mtime:e.mtime,type:`pax-header`,linkname:e.linkname&&`PaxHeader`,uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(s.encode(n)),this.push(t),p(this,t.byteLength),n.size=e.size,n.type=e.type,this.push(s.encode(n))}_doDrain(){let e=this._drain;this._drain=f,e()}_predestroy(){let e=i(this);for(this._stream&&this._stream.destroy(e);this._pending.length;){let t=this._pending.shift();t.destroy(e),t._continueOpen()}this._doDrain()}_read(e){this._doDrain(),e()}};t.exports=function(e){return new u(e)};function d(e){switch(e&o.S_IFMT){case o.S_IFBLK:return`block-device`;case o.S_IFCHR:return`character-device`;case o.S_IFDIR:return`directory`;case o.S_IFIFO:return`fifo`;case o.S_IFLNK:return`symlink`}return`file`}function f(){}function p(e,t){t&=511,t&&e.push(c.subarray(0,512-t))}function m(e){return a.isBuffer(e)?e:a.from(e)}})),Er=e((exports=>{exports.extract=Cr(),exports.pack=Tr()}));mr();var Dr=r(Er());const Or=async(e,t)=>{let{maxBytes:n=50*1024*1024}=t??{},r=await N.stat(e);if(!r.isDirectory())throw Error(`Path is not a directory: ${e}`);let i=Dr.pack(),a=async(e,t=``)=>{let n=await N.readdir(e,{withFileTypes:!0});for(let r of n){let n=`${e}/${r.name}`,o=t?`${t}/${r.name}`:r.name;if(r.isDirectory()){i.entry({name:`${o}/`,type:`directory`}),await a(n,o);continue}if(r.isSymbolicLink?.()){let e=await N.readlink(n);i.entry({name:o,type:`symlink`,linkname:e});continue}if(r.isFile()){let e=await N.stat(n);await new Promise((t,r)=>{let a=S(n),s=i.entry({name:o,size:e.size,mode:e.mode,mtime:e.mtime},e=>{e&&r(e)});a.on(`error`,r),a.on(`data`,e=>s.write(e)),a.on(`end`,()=>{s.end(),t()})});continue}}};(async()=>{try{await a(e),i.finalize()}catch(e){i.destroy(e)}})();let o=i,s=0,c=!1;return new ReadableStream({start(e){let t=t=>{if(!c){if(s+=t.length,s>n){c=!0,e.error(Error(`Archive exceeds size limit (${n} bytes). Emitted=${s} bytes.`));try{o.destroy()}catch{}return}e.enqueue(new Uint8Array(t))}},r=t=>{c||(c=!0,e.error(t instanceof Error?t:Error(String(t))))},i=()=>{c||(c=!0,e.close())};o.on(`data`,t),o.once(`error`,r),o.once(`end`,i)},cancel(){try{o.destroy()}catch{}}})},kr=(e,t)=>e.length<=t?e:e.slice(e.length-t),Ar=(e,t)=>{if(e.length===0)return{lines:[],truncated:!1};let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){let a=e[i].length;if(n+a>t&&r!==e.length)break;n+=a,r=i}return r===0?{lines:e,truncated:!1}:{lines:e.slice(r),truncated:!0}};var jr=class{multiplexer;notificationStream;decoder=new TextDecoder;encoder=new TextEncoder;processManager;createDeploymentFromTar;constructor(e){this.createDeploymentFromTar=e.createDeploymentFromTar,this.multiplexer=new Me({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new qn(e.env),this.processManager.onSpawn(e=>{let t=()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})};t(),e.terminal.onTitleChange(()=>{t()}),e.onExit(()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})}),e.onOutput(t=>{let n=ke.getMaxPayloadSize()-1;for(let r=0;r<t.length;r+=n){let i=t.slice(r,r+n);this.sendNotification({type:`process_output`,payload:{pid:e.pid,output:i}})}})})}handleMessage(e){this.multiplexer.handleMessage(e)}handleStream(e){let t=new AbortController;e.onClose(()=>{t.abort()}),e.onData(n=>{let r=n[0],i=n.subarray(1);switch(r){case Fe.REQUEST:{let n=JSON.parse(this.decoder.decode(i));this.handleRequest(e,n,t.signal).catch(t=>{this.sendResponse(e,{id:n.id,error:t instanceof Error?t.message:String(t)})});break}case Fe.PROXY_INIT:{let t=Le[Fe.PROXY_INIT].safeParse(JSON.parse(this.decoder.decode(i)));if(!t.success)throw Error(`Invalid proxy init message`);let n;n=t.data.headers.upgrade===`websocket`?this.handleProxyWebSocket(e,t.data):this.handleProxyRequest(e,t.data),n.catch(t=>{e.error(t.message)});break}}})}async handleProxyWebSocket(e,t){let n=new URL(t.url);n.protocol===`http:`?n.protocol=`ws:`:n.protocol===`https:`&&(n.protocol=`wss:`);let r=new dr.default(n.toString(),t.headers[`sec-websocket-protocol`]?t.headers[`sec-websocket-protocol`]:void 0,{headers:t.headers,perMessageDeflate:!1});r.addEventListener(`open`,()=>{let t={status_code:101,status_message:`Switching Protocols`,headers:{}};e.writeTyped(Ie.PROXY_INIT,this.encoder.encode(JSON.stringify(t)))}),r.addEventListener(`message`,t=>{e.disposed||e.writeTyped(Ie.PROXY_WEBSOCKET_MESSAGE,Ne(t.data,this.encoder))}),r.addEventListener(`close`,t=>{if(e.disposed)return;let n={code:t.code,reason:t.reason};e.writeTyped(Ie.PROXY_WEBSOCKET_CLOSE,this.encoder.encode(JSON.stringify(n))),e.close()}),r.addEventListener(`error`,e=>{console.log(`err`,e)}),e.onClose(()=>{r.close()}),e.onError(e=>{r.close(1011,e)}),e.onData(t=>{let n=t.subarray(1);switch(t[0]){case Fe.PROXY_WEBSOCKET_MESSAGE:{let e=Pe(n,this.decoder);r.send(e);break}case Fe.PROXY_WEBSOCKET_CLOSE:{let e=Le[Fe.PROXY_WEBSOCKET_CLOSE].safeParse(JSON.parse(this.decoder.decode(n)));if(!e.success)throw Error(`Invalid proxy websocket close message`);try{r.close(e.data.code,e.data.reason)}catch(t){console.error(`Error closing websocket`,t,e.data)}break}default:e.error(`Unexpected message type: ${t[0]}`)}})}async handleProxyRequest(e,t){let n,r;if(t.method!==`GET`&&t.method!==`HEAD`&&t.method!==`OPTIONS`){let e=new TransformStream;n=e.writable.getWriter(),r=e.readable}e.onData(t=>{switch(t[0]){case Fe.PROXY_BODY:if(n){let e=t.subarray(1);e.length===0?n.close():n.write(e)}break;default:e.error(`Unexpected message type: ${t[0]}`)}});let i=await fetch(t.url,{headers:t.headers,method:t.method,body:r}),a={};i.headers.forEach((e,t)=>{a[t]=e});let o={headers:a,status_code:i.status,status_message:i.statusText};e.writeTyped(Ie.PROXY_INIT,this.encoder.encode(JSON.stringify(o)));let s=i.headers.get(`content-length`),c=s?parseInt(s):0,l=ke.getMaxPayloadSize()-1;if(c>=l){if(!i.body){e.close();return}let t=i.body.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;if(r){let t=0;for(;t<r.length;){let n=Math.min(l,r.length-t),i=r.subarray(t,t+n);e.writeTyped(Ie.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else i.body&&await i.body.pipeTo(new WritableStream({write:t=>{e.writeTyped(Ie.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=Re[t.type],i=r.safeParse(t.payload);if(!i.success)throw Error(`Invalid request payload: ${i.error.message}`);switch(t.type){case`process_execute`:{let n=this.processManager.execute(t.payload.command,t.payload.args,{cwd:t.payload.cwd,env:t.payload.env});this.sendResponse(e,{id:t.id,payload:{pid:n.pid}});break}case`process_wait`:this.handleProcessWait(e,t,n);break;case`process_kill`:{let n=this.mustGetProcess(t.payload.pid);n.kill(t.payload.signal),this.sendResponse(e,{id:t.id,payload:{}});break}case`process_list`:this.sendResponse(e,{id:t.id,payload:{processes:this.processManager.list(t.payload.include_dead??!1)}});break;case`process_read_plain_output`:{let n=this.mustGetProcess(t.payload.pid),r=this.processManager.readPlainOutput(t.payload.pid,t.payload.start_line,t.payload.end_line),i=Ar(r.lines,256e3);this.sendResponse(e,{id:t.id,payload:{lines:i.lines,total_lines:r.totalLines,duration_ms:Date.now()-n.startTimeMS,exit_code:n.exitCode,exit_signal:n.exitSignal}});break}case`process_send_input`:{let n=this.mustGetProcess(t.payload.pid);n.sendInput(t.payload.data),this.sendResponse(e,{id:t.id,payload:{}});break}case`set_env`:this.processManager.setEnv(t.payload.env),this.sendResponse(e,{id:t.id,payload:{}});break;case`deploy_static_files`:{if(!this.createDeploymentFromTar)throw Error(`This server does not support static file deployments!`);let n=await Or(t.payload.path),r=await this.createDeploymentFromTar(n);this.sendResponse(e,{id:t.id,payload:{deployment_id:r}});break}case`read_file`:{let n=await l.readFile(t.payload.path),r=await On(n),i=!r||r?.mime===`text/plain`;if(!i){this.sendResponse(e,{id:t.id,payload:{content:n.toString(`base64`),mime_type:r?.mime,total_lines:0,lines_read:0,start_line:0}});break}let a=n.toString(`utf-8`),o=a.split(`
49
49
  `),s=(t.payload.line_start??1)-1,c=t.payload.line_end??o.length,u=o.slice(s,c);this.sendResponse(e,{id:t.id,payload:{content:u.join(`
50
50
  `),mime_type:`text/plain`,total_lines:o.length,lines_read:u.length,start_line:s}});break}case`write_file`:t.payload.base64?await l.writeFile(t.payload.path,Buffer.from(t.payload.content,`base64`)):await l.writeFile(t.payload.path,t.payload.content),typeof t.payload.mode==`number`&&await l.chmod(t.payload.path,t.payload.mode),this.sendResponse(e,{id:t.id,payload:{}});break;case`read_directory`:{let n=await l.readdir(t.payload.path,{withFileTypes:!0});this.sendResponse(e,{id:t.id,payload:{entries:n.map(e=>({name:e.name,type:e.isDirectory()?`directory`:e.isSymbolicLink()?`symlink`:`file`}))}});break}default:throw Error(`Unknown request type: ${t.type}`)}}sendResponse(e,t){e.writeTyped(Ie.RESPONSE,this.encoder.encode(JSON.stringify(t)))}sendNotification(e){this.notificationStream.write(new Uint8Array([Ie.NOTIFICATION,...this.encoder.encode(JSON.stringify(e))]))}handleProcessWait(e,t,n){let r=t.payload,i=this.mustGetProcess(r.pid),a,o,s=!1,c,l;typeof r.timeout_ms==`number`&&(l=setTimeout(()=>{u()},r.timeout_ms));let u=()=>{if(s||(s=!0,a&&a.dispose(),o&&o.dispose(),l&&clearTimeout(l),c&&clearTimeout(c),n?.aborted))return;let i=this.processManager.status(r.pid),u=this.processManager.readPlainOutput(i.pid),d=kr(this.processManager.readANSIOutput(i.pid),64e3),f=Ar(u.lines,256e3);this.sendResponse(e,{id:t.id,payload:{...i,ansi_output:d,plain_output:{lines:f.lines,total_lines:u.totalLines}}})};if(typeof i.exitCode==`number`||typeof i.exitSignal==`number`){u();return}a=i.onOutput(()=>{c&&clearTimeout(c),typeof r.output_idle_timeout_ms==`number`&&(c=setTimeout(()=>{u()},r.output_idle_timeout_ms))}),o=i.onExit(()=>{setTimeout(()=>{u()},10)}),n.addEventListener(`abort`,()=>{u()})}mustGetProcess(e){let t=this.processManager.getProcess(e);if(!t)throw Error(`Process ${e} not found`);return t}};function Mr(){let e=new TextEncoder,t=new TextDecoder,n=new jr({send:e=>{r.handleMessage(e)}}),r=new Me({send:e=>{n.handleMessage(e)},isClient:!0}),i=r.createStream(),a=new qe({send:t=>{i.writeTyped(0,e.encode(t),!0)}});return i.onData(e=>{let n=e.subarray(1);a.handleMessage(t.decode(n))}),r.onStream(e=>{e.onData(e=>{let n=e.subarray(1);a.handleMessage(t.decode(n))})}),{client:a,server:n}}function Nr(e){let{client:t}=Mr();return o({...e,internal:{computeExecute:async e=>{let n=await t.request(`process_execute`,{command:e.command,args:e.args||[],cwd:e.cwd,env:e.env},{signal:e.abortSignal});return{pid:n.pid}},computeSetenv:async e=>{await t.request(`set_env`,{env:e.env},{signal:e.abortSignal})},computeReadFile:async e=>{let n=await t.request(`read_file`,{path:e.path,line_start:e.lineStart,line_end:e.lineEnd},{signal:e.abortSignal});return n},computeWriteFile:async e=>{await t.request(`write_file`,{path:e.path,content:e.content},{signal:e.abortSignal})},computeReadDirectory:async e=>{let n=await t.request(`read_directory`,{path:e.path},{signal:e.abortSignal});return n.entries},writeProcessInput:async e=>{await t.request(`process_send_input`,{pid:e.pid,data:e.input},{signal:e.abortSignal})},waitProcess:async e=>{let n=t.onNotification(`process_output`,t=>{t.pid===e.pid&&e.onOutput&&e.onOutput(t.output)});try{let n=await t.request(`process_wait`,{pid:e.pid,output_idle_timeout_ms:e.idleOutputTimeoutMs,timeout_ms:e.timeoutMs},{signal:e.abortSignal});return{pid:n.pid,title:n.title,command:n.command,args:n.args,cwd:n.cwd,env:n.env,ansiOutput:n.ansi_output,plainOutput:{totalLines:n.plain_output.total_lines,lines:n.plain_output.lines},durationMs:n.duration_ms,exitCode:n.exit_code,exitSignal:n.exit_signal}}finally{n.dispose()}},readProcessOutput:async e=>{let n=await t.request(`process_read_plain_output`,{pid:e.pid,start_line:e.lineStart,end_line:e.lineEnd},{signal:e.abortSignal});return n.lines.join(`
51
- `)},killProcess:async e=>{await t.request(`process_kill`,{pid:e.pid,signal:e.signal},{signal:e.abortSignal})}}})}async function Pr(e){e||=process.cwd();let t=await s(e),n=await a();await c(t,(e,t)=>{console.log(`compiled in ${t}ms`,n),Nr({code:e,console,wasm:n,process:{env:process.env}}).then(async e=>{let t=[{role:`user`,content:`tell me about recent pto and who takes the most in 2025. if you get an error, please tell me the error verbatim`}],n=async()=>{let r=await e.streamText({messages:t,stream:void 0});r.toUIMessageStream().pipeTo(new WritableStream({write(e){switch(e.type){case`text-delta`:process.stdout.write(e.delta);break;case`text-end`:process.stdout.write(`
51
+ `)},killProcess:async e=>{await t.request(`process_kill`,{pid:e.pid,signal:e.signal},{signal:e.abortSignal})}}})}async function Pr(e){e||=process.cwd();let t=await s(e),n=await a();await c(t,(e,t)=>{console.log(`compiled in ${t}ms`,n),Nr({code:e,console,wasm:n,process:{env:process.env}}).then(async e=>{let t=[{role:`user`,content:`listen to the prompt`}],n=async()=>{let r=await e.streamText({messages:t,stream:void 0});r.toUIMessageStream().pipeTo(new WritableStream({write(e){switch(e.type){case`text-delta`:process.stdout.write(e.delta);break;case`text-end`:process.stdout.write(`
52
52
  `);break;default:break}}}));let i=await r.response,a=await r.finishReason;if(t.push(...i.messages),a===`tool-calls`)return console.log(`looping`),n()};await n()}).catch(e=>{console.error(e)})})}var Fr=e((exports=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.iterator;function p(e){return typeof e!=`object`||!e?null:(e=f&&e[f]||e[`@@iterator`],typeof e==`function`?e:null)}var m={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},h=Object.assign,g={};function _(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||m}_.prototype.isReactComponent={},_.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},_.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function v(){}v.prototype=_.prototype;function y(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||m}var b=y.prototype=new v;b.constructor=y,h(b,_.prototype),b.isPureReactComponent=!0;var x=Array.isArray,S={H:null,A:null,T:null,S:null,V:null},C=Object.prototype.hasOwnProperty;function w(e,n,r,i,a,o){return r=o.ref,{$$typeof:t,type:e,key:n,ref:r===void 0?null:r,props:o}}function T(e,t){return w(e.type,t,void 0,void 0,void 0,e.props)}function E(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function D(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var O=/\/+/g;function k(e,t){return typeof e==`object`&&e&&e.key!=null?D(``+e.key):t.toString(36)}function A(){}function j(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(A,A):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function M(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,M(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+k(e,0):a,x(o)?(i=``,c!=null&&(i=c.replace(O,`$&/`)+`/`),M(o,r,i,``,function(e){return e})):o!=null&&(E(o)&&(o=T(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(O,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(x(e))for(var u=0;u<e.length;u++)a=e[u],s=l+k(a,u),c+=M(a,r,i,s,o);else if(u=p(e),typeof u==`function`)for(e=u.call(e),u=0;!(a=e.next()).done;)a=a.value,s=l+k(a,u++),c+=M(a,r,i,s,o);else if(s===`object`){if(typeof e.then==`function`)return M(j(e),r,i,a,o);throw r=String(e),Error(`Objects are not valid as a React child (found: `+(r===`[object Object]`?`object with keys {`+Object.keys(e).join(`, `)+`}`:r)+`). If you meant to render a collection of children, use an array instead.`)}return c}function N(e,t,n){if(e==null)return e;var r=[],i=0;return M(e,r,``,``,function(e){return t.call(n,e,i++)}),r}function P(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(t){(e._status===0||e._status===-1)&&(e._status=1,e._result=t)},function(t){(e._status===0||e._status===-1)&&(e._status=2,e._result=t)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var ee=typeof reportError==`function`?reportError:function(e){if(typeof window==`object`&&typeof window.ErrorEvent==`function`){var t=new window.ErrorEvent(`error`,{bubbles:!0,cancelable:!0,message:typeof e==`object`&&e&&typeof e.message==`string`?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process==`object`&&typeof process.emit==`function`){process.emit(`uncaughtException`,e);return}console.error(e)};function te(){}exports.Children={map:N,forEach:function(e,t,n){N(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return N(e,function(){t++}),t},toArray:function(e){return N(e,function(e){return e})||[]},only:function(e){if(!E(e))throw Error(`React.Children.only expected to receive a single React element child.`);return e}},exports.Component=_,exports.Fragment=r,exports.Profiler=a,exports.PureComponent=y,exports.StrictMode=i,exports.Suspense=l,exports.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=S,exports.__COMPILER_RUNTIME={__proto__:null,c:function(e){return S.H.useMemoCache(e)}},exports.cache=function(e){return function(){return e.apply(null,arguments)}},exports.cloneElement=function(e,t,n){if(e==null)throw Error(`The argument must be a React element, but you passed `+e+`.`);var r=h({},e.props),i=e.key,a=void 0;if(t!=null)for(o in t.ref!==void 0&&(a=void 0),t.key!==void 0&&(i=``+t.key),t)!C.call(t,o)||o===`key`||o===`__self`||o===`__source`||o===`ref`&&t.ref===void 0||(r[o]=t[o]);var o=arguments.length-2;if(o===1)r.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];r.children=s}return w(e.type,i,void 0,void 0,a,r)},exports.createContext=function(e){return e={$$typeof:s,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:o,_context:e},e},exports.createElement=function(e,t,n){var r,i={},a=null;if(t!=null)for(r in t.key!==void 0&&(a=``+t.key),t)C.call(t,r)&&r!==`key`&&r!==`__self`&&r!==`__source`&&(i[r]=t[r]);var o=arguments.length-2;if(o===1)i.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];i.children=s}if(e&&e.defaultProps)for(r in o=e.defaultProps,o)i[r]===void 0&&(i[r]=o[r]);return w(e,a,void 0,void 0,null,i)},exports.createRef=function(){return{current:null}},exports.forwardRef=function(e){return{$$typeof:c,render:e}},exports.isValidElement=E,exports.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:P}},exports.memo=function(e,t){return{$$typeof:u,type:e,compare:t===void 0?null:t}},exports.startTransition=function(e){var t=S.T,n={};S.T=n;try{var r=e(),i=S.S;i!==null&&i(n,r),typeof r==`object`&&r&&typeof r.then==`function`&&r.then(te,ee)}catch(e){ee(e)}finally{S.T=t}},exports.unstable_useCacheRefresh=function(){return S.H.useCacheRefresh()},exports.use=function(e){return S.H.use(e)},exports.useActionState=function(e,t,n){return S.H.useActionState(e,t,n)},exports.useCallback=function(e,t){return S.H.useCallback(e,t)},exports.useContext=function(e){return S.H.useContext(e)},exports.useDebugValue=function(){},exports.useDeferredValue=function(e,t){return S.H.useDeferredValue(e,t)},exports.useEffect=function(e,t,n){var r=S.H;if(typeof n==`function`)throw Error(`useEffect CRUD overload is not enabled in this build of React.`);return r.useEffect(e,t)},exports.useId=function(){return S.H.useId()},exports.useImperativeHandle=function(e,t,n){return S.H.useImperativeHandle(e,t,n)},exports.useInsertionEffect=function(e,t){return S.H.useInsertionEffect(e,t)},exports.useLayoutEffect=function(e,t){return S.H.useLayoutEffect(e,t)},exports.useMemo=function(e,t){return S.H.useMemo(e,t)},exports.useOptimistic=function(e,t){return S.H.useOptimistic(e,t)},exports.useReducer=function(e,t,n){return S.H.useReducer(e,t,n)},exports.useRef=function(e){return S.H.useRef(e)},exports.useState=function(e){return S.H.useState(e)},exports.useSyncExternalStore=function(e,t,n){return S.H.useSyncExternalStore(e,t,n)},exports.useTransition=function(){return S.H.useTransition()},exports.version=`19.1.1`})),Ir=e(((exports,t)=>{process.env.NODE_ENV!==`production`&&(function(){function n(e,t){Object.defineProperty(a.prototype,e,{get:function(){console.warn(`%s(...) is deprecated in plain JavaScript React classes. %s`,t[0],t[1])}})}function r(e){return typeof e!=`object`||!e?null:(e=le&&e[le]||e[`@@iterator`],typeof e==`function`?e:null)}function i(e,t){e=(e=e.constructor)&&(e.displayName||e.name)||`ReactClass`;var n=e+`.`+t;ue[n]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",t,e),ue[n]=!0)}function a(e,t,n){this.props=e,this.context=t,this.refs=pe,this.updater=n||de}function o(){}function s(e,t,n){this.props=e,this.context=t,this.refs=pe,this.updater=n||de}function c(e){return``+e}function l(e){try{c(e);var t=!1}catch{t=!0}if(t){t=console;var n=t.error,r=typeof Symbol==`function`&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||`Object`;return n.call(t,`The provided key is an unsupported type %s. This value must be coerced to a string before using it here.`,r),c(e)}}function u(e){if(e==null)return null;if(typeof e==`function`)return e.$$typeof===_e?null:e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case te:return`Fragment`;case ne:return`Profiler`;case F:return`StrictMode`;case ae:return`Suspense`;case oe:return`SuspenseList`;case ce:return`Activity`}if(typeof e==`object`)switch(typeof e.tag==`number`&&console.error(`Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.`),e.$$typeof){case ee:return`Portal`;case I:return(e.displayName||`Context`)+`.Provider`;case re:return(e._context.displayName||`Context`)+`.Consumer`;case ie:var t=e.render;return e=e.displayName,e||=(e=t.displayName||t.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case L:return t=e.displayName||null,t===null?u(e.type)||`Memo`:t;case se:t=e._payload,e=e._init;try{return u(e(t))}catch{}}return null}function d(e){if(e===te)return`<>`;if(typeof e==`object`&&e&&e.$$typeof===se)return`<...>`;try{var t=u(e);return t?`<`+t+`>`:`<...>`}catch{return`<...>`}}function f(){var e=R.A;return e===null?null:e.getOwner()}function p(){return Error(`react-stack-top-frame`)}function m(e){if(ve.call(e,`key`)){var t=Object.getOwnPropertyDescriptor(e,`key`).get;if(t&&t.isReactWarning)return!1}return e.key!==void 0}function h(e,t){function n(){be||(be=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",t))}n.isReactWarning=!0,Object.defineProperty(e,`key`,{get:n,configurable:!0})}function g(){var e=u(this.type);return Se[e]||(Se[e]=!0,console.error(`Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.`)),e=this.props.ref,e===void 0?null:e}function _(e,t,n,r,i,a,o,s){return n=a.ref,e={$$typeof:P,type:e,key:t,props:a,_owner:i},(n===void 0?null:n)===null?Object.defineProperty(e,`ref`,{enumerable:!1,value:null}):Object.defineProperty(e,`ref`,{enumerable:!1,get:g}),e._store={},Object.defineProperty(e._store,`validated`,{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,`_debugInfo`,{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,`_debugStack`,{configurable:!1,enumerable:!1,writable:!0,value:o}),Object.defineProperty(e,`_debugTask`,{configurable:!1,enumerable:!1,writable:!0,value:s}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function v(e,t){return t=_(e.type,t,void 0,void 0,e._owner,e.props,e._debugStack,e._debugTask),e._store&&(t._store.validated=e._store.validated),t}function y(e){return typeof e==`object`&&!!e&&e.$$typeof===P}function b(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}function x(e,t){return typeof e==`object`&&e&&e.key!=null?(l(e.key),b(``+e.key)):t.toString(36)}function S(){}function C(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(S,S):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function w(e,t,n,i,a){var o=typeof e;(o===`undefined`||o===`boolean`)&&(e=null);var s=!1;if(e===null)s=!0;else switch(o){case`bigint`:case`string`:case`number`:s=!0;break;case`object`:switch(e.$$typeof){case P:case ee:s=!0;break;case se:return s=e._init,w(s(e._payload),t,n,i,a)}}if(s){s=e,a=a(s);var c=i===``?`.`+x(s,0):i;return ge(a)?(n=``,c!=null&&(n=c.replace(Ee,`$&/`)+`/`),w(a,t,n,``,function(e){return e})):a!=null&&(y(a)&&(a.key!=null&&(s&&s.key===a.key||l(a.key)),n=v(a,n+(a.key==null||s&&s.key===a.key?``:(``+a.key).replace(Ee,`$&/`)+`/`)+c),i!==``&&s!=null&&y(s)&&s.key==null&&s._store&&!s._store.validated&&(n._store.validated=2),a=n),t.push(a)),1}if(s=0,c=i===``?`.`:i+`:`,ge(e))for(var u=0;u<e.length;u++)i=e[u],o=c+x(i,u),s+=w(i,t,n,o,a);else if(u=r(e),typeof u==`function`)for(u===e.entries&&(Te||console.warn(`Using Maps as children is not supported. Use an array of keyed ReactElements instead.`),Te=!0),e=u.call(e),u=0;!(i=e.next()).done;)i=i.value,o=c+x(i,u++),s+=w(i,t,n,o,a);else if(o===`object`){if(typeof e.then==`function`)return w(C(e),t,n,i,a);throw t=String(e),Error(`Objects are not valid as a React child (found: `+(t===`[object Object]`?`object with keys {`+Object.keys(e).join(`, `)+`}`:t)+`). If you meant to render a collection of children, use an array instead.`)}return s}function T(e,t,n){if(e==null)return e;var r=[],i=0;return w(e,r,``,``,function(e){return t.call(n,e,i++)}),r}function E(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(t){(e._status===0||e._status===-1)&&(e._status=1,e._result=t)},function(t){(e._status===0||e._status===-1)&&(e._status=2,e._result=t)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return t=e._result,t===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
53
53
 
54
54
  Your code should look like:
@@ -436,7 +436,6 @@ ${Bu}`),t.includes(`
436
436
  ${Bu}${t.trimStart()}`),n=3+ie(t.trimStart()).length)}process.stdout.write(`
437
437
  `)},info:e=>Vu.message(e,{symbol:_u.default.blue(Au)}),success:e=>Vu.message(e,{symbol:_u.default.green(ju)}),step:e=>Vu.message(e,{symbol:_u.default.green(wu)}),warn:e=>Vu.message(e,{symbol:_u.default.yellow(Mu)}),warning:e=>Vu.warn(e),error:e=>Vu.message(e,{symbol:_u.default.red(Q)})};async function Hu(e){e||=process.cwd(),Lu(`Initializing a new Blink Agent`),(await u(e)).length>0&&(Iu("You must be in an empty directory to run `blink init`."),process.exit(1));let t=f(e).replace(/[^a-zA-Z0-9]/g,`-`),n;if(process.env.npm_config_user_agent?.includes(`bun/`)?n=`bun`:process.env.npm_config_user_agent?.includes(`pnpm/`)?n=`pnpm`:process.env.npm_config_user_agent?.includes(`yarn/`)?n=`yarn`:process.env.npm_config_user_agent?.includes(`npm/`)&&(n=`npm`),!n){let e=await Fu({options:[{label:`Bun`,value:`bun`},{label:`NPM`,value:`npm`},{label:`PNPM`,value:`pnpm`},{label:`Yarn`,value:`yarn`}],message:`What package manager do you want to use?`});ou(e)&&process.exit(0),n=e}zu.info(`Using ${n} as the package manager.`);let r={"package.json":JSON.stringify({name:t,main:`agent.ts`,type:`module`,private:!0}),"agent.ts":`import { streamText, tool } from "ai";
438
438
  import * as blink from "blink";
439
- import * as compute from "@blink-sdk/compute";
440
439
  import { z } from "zod";
441
440
 
442
441
  export default blink.agent({
@@ -444,21 +443,14 @@ export default blink.agent({
444
443
 
445
444
  async streamText({ messages }) {
446
445
  return streamText({
447
- model: "openai/gpt-5",
448
- system: "You are a coding agent.",
446
+ model: "anthropic/claude-sonnet-4",
447
+ system: "You return the IP address of the computer.",
449
448
  messages,
450
- tools: {
451
- // Allows Blink run processes and modify files.
452
- // There are many SDKs available: https://github.com/coder/blink
453
- ...compute.tools(),
454
-
449
+ tools: {
455
450
  get_ip_info: tool({
456
451
  description: "Get IP address information of the computer.",
457
- inputSchema: z.object({
458
- location: z.string(),
459
- }),
460
- execute: async ({ location }) => {
461
- const response = await fetch("ipinfo.io/json");
452
+ execute: async () => {
453
+ const response = await fetch("https://ipinfo.io/json");
462
454
  return response.json();
463
455
  },
464
456
  })
package/dist/wasm.js CHANGED
@@ -1,4 +1,4 @@
1
- import{createRequire as e}from"node:module";import{readFile as t,stat as n}from"fs/promises";import{dirname as r,join as i,relative as a}from"path";var o=Object.create,s=Object.defineProperty,c=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,u=Object.getPrototypeOf,d=Object.prototype.hasOwnProperty,f=(e,t)=>()=>(e&&(t=e(e=0)),t),ee=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),p=(e,t)=>{for(var n in t)s(e,n,{get:t[n],enumerable:!0})},m=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=l(t),a=0,o=i.length,u;a<o;a++)u=i[a],!d.call(e,u)&&u!==n&&s(e,u,{get:(e=>t[e]).bind(null,u),enumerable:!(r=c(t,u))||r.enumerable});return e},te=(e,t,n)=>(n=e==null?{}:o(u(e)),m(t||!e||!e.__esModule?s(n,`default`,{value:e,enumerable:!0}):n,e)),h=e(import.meta.url);async function ne(e){let t=v(),n=await t.build({..._,entryPoints:[e]});return n.outputFiles[0].text}async function re(e,t){let n=v(),r=await n.context({..._,entryPoints:[e],plugins:[{name:`blink-dev-server`,setup(e){let n=0;e.onStart(()=>{n=Date.now()}),e.onEnd(e=>{let r=e.outputFiles[0].text,i=Date.now()-n;t(r,i)})}}]});await r.watch()}async function ie(e){let o=await g(e,`package.json`);if(!o)throw Error(`No package.json found in ${e}`);let s=JSON.parse(await t(o,`utf-8`)),c=s.main;if(!c)throw Error(`"main" is not set in ${a(process.cwd(),o)}. It should be set to the entrypoint of your agent.`);let l=i(r(o),c),u=await n(l);if(!u.isFile())throw Error(`${l} is not a file.`);return l}async function g(e,t){let a=e;for(;a!==r(a);){let e=i(a,t);try{return await n(e),e}catch{}a=r(a)}}const _={bundle:!0,format:`esm`,target:`chrome58`,sourcemap:`inline`,write:!1},v=()=>{try{return h(`esbuild`)}catch{throw Error("esbuild is not installed. Please install it with `bun add esbuild`.")}};var y,b,x,S,C,w=f((()=>{y={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},b={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},x={Pending:0,Fulfilled:1,Rejected:2},S={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},C={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}}));function T(...e){M&&console.log(`quickjs-emscripten:`,...e)}function*ae(e){return yield e}function oe(e){return ae(E(e))}function se(e,t){return(...n)=>{let r=t.call(e,B,...n);return E(r)}}function ce(e,t){let n=t.call(e,B);return E(n)}function E(e){function t(n){return n.done?n.value:n.value instanceof Promise?n.value.then(n=>t(e.next(n)),n=>t(e.throw(n))):t(e.next(n.value))}return t(e.next())}function D(e,t){let n;try{e.dispose()}catch(e){n=e}if(t&&n)throw Object.assign(t,{message:`${t.message}
1
+ import{createRequire as e}from"node:module";import{readFile as t,stat as n}from"fs/promises";import{dirname as r,join as i,relative as a}from"path";var o=Object.create,s=Object.defineProperty,c=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,u=Object.getPrototypeOf,d=Object.prototype.hasOwnProperty,f=(e,t)=>()=>(e&&(t=e(e=0)),t),ee=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),p=(e,t)=>{for(var n in t)s(e,n,{get:t[n],enumerable:!0})},m=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=l(t),a=0,o=i.length,u;a<o;a++)u=i[a],!d.call(e,u)&&u!==n&&s(e,u,{get:(e=>t[e]).bind(null,u),enumerable:!(r=c(t,u))||r.enumerable});return e},te=(e,t,n)=>(n=e==null?{}:o(u(e)),m(t||!e||!e.__esModule?s(n,`default`,{value:e,enumerable:!0}):n,e)),h=e(import.meta.url);async function ne(e){let t=v(),n=await t.build({..._,entryPoints:[e]});return n.outputFiles[0].text}async function re(e,t){let n=v(),r=await n.context({..._,entryPoints:[e],plugins:[{name:`blink-dev-server`,setup(e){let n=0;e.onStart(()=>{n=Date.now()}),e.onEnd(e=>{if(!e.outputFiles||!e.outputFiles[0])return;let r=e.outputFiles[0].text,i=Date.now()-n;t(r,i)})}}]});await r.watch()}async function ie(e){let o=await g(e,`package.json`);if(!o)throw Error(`No package.json found in ${e}`);let s=JSON.parse(await t(o,`utf-8`)),c=s.main;if(!c)throw Error(`"main" is not set in ${a(process.cwd(),o)}. It should be set to the entrypoint of your agent.`);let l=i(r(o),c),u=await n(l);if(!u.isFile())throw Error(`${l} is not a file.`);return l}async function g(e,t){let a=e;for(;a!==r(a);){let e=i(a,t);try{return await n(e),e}catch{}a=r(a)}}const _={bundle:!0,format:`esm`,target:`chrome58`,sourcemap:`inline`,write:!1},v=()=>{try{return h(`esbuild`)}catch{throw Error("esbuild is not installed. Please install it with `bun add esbuild`.")}};var y,b,x,S,C,w=f((()=>{y={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},b={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},x={Pending:0,Fulfilled:1,Rejected:2},S={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},C={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}}));function T(...e){M&&console.log(`quickjs-emscripten:`,...e)}function*ae(e){return yield e}function oe(e){return ae(E(e))}function se(e,t){return(...n)=>{let r=t.call(e,B,...n);return E(r)}}function ce(e,t){let n=t.call(e,B);return E(n)}function E(e){function t(n){return n.done?n.value:n.value instanceof Promise?n.value.then(n=>t(e.next(n)),n=>t(e.throw(n))):t(e.next(n.value))}return t(e.next())}function D(e,t){let n;try{e.dispose()}catch(e){n=e}if(t&&n)throw Object.assign(t,{message:`${t.message}
2
2
  Then, failed to dispose scope: ${n.message}`,disposeError:n}),t;if(t||n)throw t||n}function O(e){let t=e?Array.from(e):[];function n(){return t.forEach(e=>e.alive?e.dispose():void 0)}function r(){return t.some(e=>e.alive)}return Object.defineProperty(t,H,{configurable:!0,enumerable:!1,value:n}),Object.defineProperty(t,`dispose`,{configurable:!0,enumerable:!1,value:n}),Object.defineProperty(t,`alive`,{configurable:!0,enumerable:!1,get:r}),t}function k(e){return!!(e&&(typeof e==`object`||typeof e==`function`)&&`alive`in e&&typeof e.alive==`boolean`&&`dispose`in e&&typeof e.dispose==`function`)}function le(e){if(!e)return 0;let t=0;for(let[n,r]of Object.entries(e)){if(!(n in b))throw new ye(n);r&&(t|=b[n])}return t}function A(e){if(typeof e==`number`)return e;if(e===void 0)return 0;let{type:t,strict:n,strip:r,compileOnly:i,backtraceBarrier:a}=e,o=0;return t===`global`&&(o|=y.JS_EVAL_TYPE_GLOBAL),t===`module`&&(o|=y.JS_EVAL_TYPE_MODULE),n&&(o|=y.JS_EVAL_FLAG_STRICT),r&&(o|=y.JS_EVAL_FLAG_STRIP),i&&(o|=y.JS_EVAL_FLAG_COMPILE_ONLY),a&&(o|=y.JS_EVAL_FLAG_BACKTRACE_BARRIER),o}function ue(e){if(typeof e==`number`)return e;if(e===void 0)return 0;let{strings:t,symbols:n,quickjsPrivate:r,onlyEnumerable:i,numbers:a,numbersAsStrings:o}=e,s=0;return t&&(s|=S.JS_GPN_STRING_MASK),n&&(s|=S.JS_GPN_SYMBOL_MASK),r&&(s|=S.JS_GPN_PRIVATE_MASK),i&&(s|=S.JS_GPN_ENUM_ONLY),a&&(s|=S.QTS_GPN_NUMBER_MASK),o&&(s|=S.QTS_STANDARD_COMPLIANT_NUMBER),s}function de(...e){let t=[];for(let n of e)n!==void 0&&(t=t.concat(n));return t}function fe(e,t){t.interruptHandler&&e.setInterruptHandler(t.interruptHandler),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes)}function pe(e,t){t.moduleLoader&&e.setModuleLoader(t.moduleLoader),t.shouldInterrupt&&e.setInterruptHandler(t.shouldInterrupt),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes)}var me,j,M,he,N,P,F,ge,I,L,_e,ve,ye,R,z,B,V,H,be,U,W,G,K,q,xe,Se,J,Ce,we,Te,Ee,De,Oe,ke,Ae,je,Me,Ne=f((()=>{w(),me=Object.defineProperty,j=(e,t)=>{for(var n in t)me(e,n,{get:t[n],enumerable:!0})},M=!1,he={},j(he,{QuickJSAsyncifyError:()=>I,QuickJSAsyncifySuspended:()=>L,QuickJSEmptyGetOwnPropertyNames:()=>z,QuickJSEmscriptenModuleError:()=>ve,QuickJSMemoryLeakDetected:()=>_e,QuickJSNotImplemented:()=>ge,QuickJSPromisePending:()=>R,QuickJSUnknownIntrinsic:()=>ye,QuickJSUnwrapError:()=>N,QuickJSUseAfterFree:()=>F,QuickJSWrongOwner:()=>P}),N=class extends Error{constructor(e,t){let n=typeof e==`object`&&e&&`message`in e?String(e.message):String(e);super(n),this.cause=e,this.context=t,this.name=`QuickJSUnwrapError`}},P=class extends Error{constructor(){super(...arguments),this.name=`QuickJSWrongOwner`}},F=class extends Error{constructor(){super(...arguments),this.name=`QuickJSUseAfterFree`}},ge=class extends Error{constructor(){super(...arguments),this.name=`QuickJSNotImplemented`}},I=class extends Error{constructor(){super(...arguments),this.name=`QuickJSAsyncifyError`}},L=class extends Error{constructor(){super(...arguments),this.name=`QuickJSAsyncifySuspended`}},_e=class extends Error{constructor(){super(...arguments),this.name=`QuickJSMemoryLeakDetected`}},ve=class extends Error{constructor(){super(...arguments),this.name=`QuickJSEmscriptenModuleError`}},ye=class extends TypeError{constructor(){super(...arguments),this.name=`QuickJSUnknownIntrinsic`}},R=class extends Error{constructor(){super(...arguments),this.name=`QuickJSPromisePending`}},z=class extends Error{constructor(){super(...arguments),this.name=`QuickJSEmptyGetOwnPropertyNames`}},B=ae,B.of=oe,V=class{[Symbol.dispose](){return this.dispose()}},H=Symbol.dispose??Symbol.for(`Symbol.dispose`),be=V.prototype,be[H]||(be[H]=function(){return this.dispose()}),U=class e extends V{constructor(e,t,n,r){super(),this._value=e,this.copier=t,this.disposer=n,this._owner=r,this._alive=!0,this._constructorStack=M?Error(`Lifetime constructed`).stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw Error(`Non-dupable lifetime`);return new e(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(e){this.assertAlive();let t=e(this);return this.dispose(),t}map(e){return this.assertAlive(),e(this)}tap(e){return e(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new F(`Lifetime not alive
3
3
  ${this._constructorStack}
4
4
  Lifetime used`):new F(`Lifetime not alive`)}},W=class extends U{constructor(e,t){super(e,void 0,void 0,t)}get dupable(){return!0}dup(){return this}dispose(){}},G=class extends U{constructor(e,t,n,r){super(e,t,n,r)}dispose(){this._alive=!1}},K=class e extends V{constructor(){super(...arguments),this._disposables=new U(new Set),this.manage=e=>(this._disposables.value.add(e),e)}static withScope(t){let n=new e,r;try{return t(n)}catch(e){throw r=e,e}finally{D(n,r)}}static withScopeMaybeAsync(t,n){return ce(void 0,function*(r){let i=new e,a;try{return yield*r.of(n.call(t,r,i))}catch(e){throw a=e,e}finally{D(i,a)}})}static async withScopeAsync(t){let n=new e,r;try{return await t(n)}catch(e){throw r=e,e}finally{D(n,r)}}get alive(){return this._disposables.alive}dispose(){let e=Array.from(this._disposables.value.values()).reverse();for(let t of e)t.alive&&t.dispose();this._disposables.dispose()}},q=class e extends V{static success(e){return new xe(e)}static fail(e,t){return new Se(e,t)}static is(t){return t instanceof e}},xe=class extends q{constructor(e){super(),this.value=e}get alive(){return k(this.value)?this.value.alive:!0}dispose(){k(this.value)&&this.value.dispose()}unwrap(){return this.value}unwrapOr(e){return this.value}},Se=class extends q{constructor(e,t){super(),this.error=e,this.onUnwrap=t}get alive(){return k(this.error)?this.error.alive:!0}dispose(){k(this.error)&&this.error.dispose()}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(e){return e}},J=q,Ce=class extends V{constructor(e){super(),this.resolve=e=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,e||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.reject=e=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,e||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers()},this.context=e.context,this.owner=e.context.runtime,this.handle=e.promiseHandle,this.settled=new Promise(e=>{this.onSettled=e}),this.resolveHandle=e.resolveHandle,this.rejectHandle=e.rejectHandle}get alive(){return this.handle.alive||this.resolveHandle.alive||this.rejectHandle.alive}disposeResolvers(){this.resolveHandle.alive&&this.resolveHandle.dispose(),this.rejectHandle.alive&&this.rejectHandle.dispose()}},we=class{constructor(e){this.module=e}toPointerArray(e){let t=new Int32Array(e.map(e=>e.value)),n=t.length*t.BYTES_PER_ELEMENT,r=this.module._malloc(n);return new Uint8Array(this.module.HEAPU8.buffer,r,n).set(new Uint8Array(t.buffer)),new U(r,void 0,e=>this.module._free(e))}newTypedArray(e,t){let n=new e(Array(t).fill(0)),r=n.length*n.BYTES_PER_ELEMENT,i=this.module._malloc(r),a=new e(this.module.HEAPU8.buffer,i,t);return a.set(n),new U({typedArray:a,ptr:i},void 0,e=>this.module._free(e.ptr))}newMutablePointerArray(e){return this.newTypedArray(Int32Array,e)}newHeapCharPointer(e){let t=this.module.lengthBytesUTF8(e),n=t+1,r=this.module._malloc(n);return this.module.stringToUTF8(e,r,n),new U({ptr:r,strlen:t},void 0,e=>this.module._free(e.ptr))}newHeapBufferPointer(e){let t=e.byteLength,n=this.module._malloc(t);return this.module.HEAPU8.set(e,n),new U({pointer:n,numBytes:t},void 0,e=>this.module._free(e.pointer))}consumeHeapCharPointer(e){let t=this.module.UTF8ToString(e);return this.module._free(e),t}},Te=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0}),Ee=class extends V{constructor(e,t){super(),this.handle=e,this.context=t,this._isDone=!1,this.owner=t.runtime}[Symbol.iterator](){return this}next(e){if(!this.alive||this._isDone)return{done:!0,value:void 0};let t=this._next??=this.context.getProp(this.handle,`next`);return this.callIteratorMethod(t,e)}return(e){if(!this.alive)return{done:!0,value:void 0};let t=this.context.getProp(this.handle,`return`);if(t===this.context.undefined&&e===void 0)return this.dispose(),{done:!0,value:void 0};let n=this.callIteratorMethod(t,e);return t.dispose(),this.dispose(),n}throw(e){if(!this.alive)return{done:!0,value:void 0};let t=e instanceof U?e:this.context.newError(e),n=this.context.getProp(this.handle,`throw`),r=this.callIteratorMethod(n,e);return t.alive&&t.dispose(),n.dispose(),this.dispose(),r}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(e,t){let n=t?this.context.callFunction(e,this.handle,t):this.context.callFunction(e,this.handle);if(n.error)return this.dispose(),{value:n};let r=this.context.getProp(n.value,`done`).consume(e=>this.context.dump(e));if(r)return n.value.dispose(),this.dispose(),{done:r,value:void 0};let i=this.context.getProp(n.value,`value`);return n.value.dispose(),{value:J.success(i),done:r}}},De=class extends we{constructor(e){super(e.module),this.scope=new K,this.copyJSValue=e=>this.ffi.QTS_DupValuePointer(this.ctx.value,e),this.freeJSValue=e=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,e)},e.ownedLifetimes?.forEach(e=>this.scope.manage(e)),this.owner=e.owner,this.module=e.module,this.ffi=e.ffi,this.rt=e.rt,this.ctx=this.scope.manage(e.ctx)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(e){return this.scope.manage(e)}consumeJSCharPointer(e){let t=this.module.UTF8ToString(e);return this.ffi.QTS_FreeCString(this.ctx.value,e),t}heapValueHandle(e){return new U(e,this.copyJSValue,this.freeJSValue,this.owner)}staticHeapValueHandle(e){return this.manage(this.heapValueHandle(e)),new W(e,this.owner)}},Oe=class extends V{constructor(e){super(),this._undefined=void 0,this._null=void 0,this._false=void 0,this._true=void 0,this._global=void 0,this._BigInt=void 0,this._Symbol=void 0,this._SymbolIterator=void 0,this._SymbolAsyncIterator=void 0,this.fnNextId=-32768,this.fnMaps=new Map,this.cToHostCallbacks={callFunction:(e,t,n,r,i)=>{if(e!==this.ctx.value)throw Error(`QuickJSContext instance received C -> JS call with mismatched ctx`);let a=this.getFunction(i);if(!a)throw Error(`QuickJSContext had no callback with id ${i}`);return K.withScopeMaybeAsync(this,function*(e,i){let o=i.manage(new G(t,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),s=Array(n);for(let e=0;e<n;e++){let t=this.ffi.QTS_ArgvGetJSValueConstPointer(r,e);s[e]=i.manage(new G(t,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let t=yield*e(a.apply(o,s));if(t){if(`error`in t&&t.error)throw this.runtime.debugLog(`throw error`,t.error),t.error;let e=i.manage(t instanceof U?t:t.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,e.value)}return 0}catch(e){return this.errorToHandle(e).consume(e=>this.ffi.QTS_Throw(this.ctx.value,e.value))}})}},this.runtime=e.runtime,this.module=e.module,this.ffi=e.ffi,this.rt=e.rt,this.ctx=e.ctx,this.memory=new De({...e,owner:this.runtime}),e.callbacks.setContextCallbacks(this.ctx.value,this.cToHostCallbacks),this.dump=this.dump.bind(this),this.getString=this.getString.bind(this),this.getNumber=this.getNumber.bind(this),this.resolvePromise=this.resolvePromise.bind(this),this.uint32Out=this.memory.manage(this.memory.newTypedArray(Uint32Array,1))}get alive(){return this.memory.alive}dispose(){this.memory.dispose()}get undefined(){if(this._undefined)return this._undefined;let e=this.ffi.QTS_GetUndefined();return this._undefined=new W(e)}get null(){if(this._null)return this._null;let e=this.ffi.QTS_GetNull();return this._null=new W(e)}get true(){if(this._true)return this._true;let e=this.ffi.QTS_GetTrue();return this._true=new W(e)}get false(){if(this._false)return this._false;let e=this.ffi.QTS_GetFalse();return this._false=new W(e)}get global(){if(this._global)return this._global;let e=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(e),this._global}newNumber(e){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,e))}newString(e){let t=this.memory.newHeapCharPointer(e).consume(e=>this.ffi.QTS_NewString(this.ctx.value,e.value.ptr));return this.memory.heapValueHandle(t)}newUniqueSymbol(e){let t=(typeof e==`symbol`?e.description:e)??``,n=this.memory.newHeapCharPointer(t).consume(e=>this.ffi.QTS_NewSymbol(this.ctx.value,e.value.ptr,0));return this.memory.heapValueHandle(n)}newSymbolFor(e){let t=(typeof e==`symbol`?e.description:e)??``,n=this.memory.newHeapCharPointer(t).consume(e=>this.ffi.QTS_NewSymbol(this.ctx.value,e.value.ptr,1));return this.memory.heapValueHandle(n)}getWellKnownSymbol(e){return this._Symbol??=this.memory.manage(this.getProp(this.global,`Symbol`)),this.getProp(this._Symbol,e)}newBigInt(e){if(!this._BigInt){let e=this.getProp(this.global,`BigInt`);this.memory.manage(e),this._BigInt=new W(e.value,this.runtime)}let t=this._BigInt,n=String(e);return this.newString(n).consume(e=>this.unwrapResult(this.callFunction(t,this.undefined,e)))}newObject(e){e&&this.runtime.assertOwned(e);let t=e?this.ffi.QTS_NewObjectProto(this.ctx.value,e.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle(t)}newArray(){let e=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(e)}newArrayBuffer(e){let t=new Uint8Array(e),n=this.memory.newHeapBufferPointer(t),r=this.ffi.QTS_NewArrayBuffer(this.ctx.value,n.value.pointer,t.length);return this.memory.heapValueHandle(r)}newPromise(e){let t=K.withScope(e=>{let t=e.manage(this.memory.newMutablePointerArray(2)),n=this.ffi.QTS_NewPromiseCapability(this.ctx.value,t.value.ptr),r=this.memory.heapValueHandle(n),[i,a]=Array.from(t.value.typedArray).map(e=>this.memory.heapValueHandle(e));return new Ce({context:this,promiseHandle:r,resolveHandle:i,rejectHandle:a})});return e&&typeof e==`function`&&(e=new Promise(e)),e&&Promise.resolve(e).then(t.resolve,e=>e instanceof U?t.reject(e):this.newError(e).consume(t.reject)),t}newFunction(e,t){let n=++this.fnNextId;return this.setFunction(n,t),this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,n,e))}newError(e){let t=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));return e&&typeof e==`object`?(e.name!==void 0&&this.newString(e.name).consume(e=>this.setProp(t,`name`,e)),e.message!==void 0&&this.newString(e.message).consume(e=>this.setProp(t,`message`,e))):typeof e==`string`?this.newString(e).consume(e=>this.setProp(t,`message`,e)):e!==void 0&&this.newString(String(e)).consume(e=>this.setProp(t,`message`,e)),t}typeof(e){return this.runtime.assertOwned(e),this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value,e.value))}getNumber(e){return this.runtime.assertOwned(e),this.ffi.QTS_GetFloat64(this.ctx.value,e.value)}getString(e){return this.runtime.assertOwned(e),this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value,e.value))}getSymbol(e){this.runtime.assertOwned(e);let t=this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value,e.value));return this.ffi.QTS_IsGlobalSymbol(this.ctx.value,e.value)?Symbol.for(t):Symbol(t)}getBigInt(e){this.runtime.assertOwned(e);let t=this.getString(e);return BigInt(t)}getArrayBuffer(e){this.runtime.assertOwned(e);let t=this.ffi.QTS_GetArrayBufferLength(this.ctx.value,e.value),n=this.ffi.QTS_GetArrayBuffer(this.ctx.value,e.value);if(!n)throw Error(`Couldn't allocate memory to get ArrayBuffer`);return new U(this.module.HEAPU8.subarray(n,n+t),void 0,()=>this.module._free(n))}getPromiseState(e){this.runtime.assertOwned(e);let t=this.ffi.QTS_PromiseState(this.ctx.value,e.value);if(t<0)return{type:`fulfilled`,value:e,notAPromise:!0};if(t===x.Pending)return{type:`pending`,get error(){return new R(`Cannot unwrap a pending promise`)}};let n=this.ffi.QTS_PromiseResult(this.ctx.value,e.value),r=this.memory.heapValueHandle(n);if(t===x.Fulfilled)return{type:`fulfilled`,value:r};if(t===x.Rejected)return{type:`rejected`,error:r};throw r.dispose(),Error(`Unknown JSPromiseStateEnum: ${t}`)}resolvePromise(e){this.runtime.assertOwned(e);let t=K.withScope(t=>{let n=t.manage(this.getProp(this.global,`Promise`)),r=t.manage(this.getProp(n,`resolve`));return this.callFunction(r,n,e)});return t.error?Promise.resolve(t):new Promise(e=>{K.withScope(n=>{let r=n.manage(this.newFunction(`resolve`,t=>{e(this.success(t&&t.dup()))})),i=n.manage(this.newFunction(`reject`,t=>{e(this.fail(t&&t.dup()))})),a=n.manage(t.value),o=n.manage(this.getProp(a,`then`));this.callFunction(o,a,r,i).unwrap().dispose()})})}isEqual(e,t,n=C.IsStrictlyEqual){if(e===t)return!0;this.runtime.assertOwned(e),this.runtime.assertOwned(t);let r=this.ffi.QTS_IsEqual(this.ctx.value,e.value,t.value,n);if(r===-1)throw new ge(`WASM variant does not expose equality`);return!!r}eq(e,t){return this.isEqual(e,t,C.IsStrictlyEqual)}sameValue(e,t){return this.isEqual(e,t,C.IsSameValue)}sameValueZero(e,t){return this.isEqual(e,t,C.IsSameValueZero)}getProp(e,t){this.runtime.assertOwned(e);let n;return n=typeof t==`number`&&t>=0?this.ffi.QTS_GetPropNumber(this.ctx.value,e.value,t):this.borrowPropertyKey(t).consume(t=>this.ffi.QTS_GetProp(this.ctx.value,e.value,t.value)),this.memory.heapValueHandle(n)}getLength(e){if(this.runtime.assertOwned(e),!(this.ffi.QTS_GetLength(this.ctx.value,this.uint32Out.value.ptr,e.value)<0))return this.uint32Out.value.typedArray[0]}getOwnPropertyNames(e,t={strings:!0,numbersAsStrings:!0}){this.runtime.assertOwned(e),e.value;let n=ue(t);if(n===0)throw new z(`No options set, will return an empty array`);return K.withScope(t=>{let r=t.manage(this.memory.newMutablePointerArray(1)),i=this.ffi.QTS_GetOwnPropertyNames(this.ctx.value,r.value.ptr,this.uint32Out.value.ptr,e.value,n);if(i)return this.fail(this.memory.heapValueHandle(i));let a=this.uint32Out.value.typedArray[0],o=r.value.typedArray[0],s=new Uint32Array(this.module.HEAP8.buffer,o,a),c=Array.from(s).map(e=>this.memory.heapValueHandle(e));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,o),this.success(O(c))})}getIterator(e){let t=this._SymbolIterator??=this.memory.manage(this.getWellKnownSymbol(`iterator`));return K.withScope(n=>{let r=n.manage(this.getProp(e,t)),i=this.callFunction(r,e);return i.error?i:this.success(new Ee(i.value,this))})}setProp(e,t,n){this.runtime.assertOwned(e),this.borrowPropertyKey(t).consume(t=>this.ffi.QTS_SetProp(this.ctx.value,e.value,t.value,n.value))}defineProp(e,t,n){this.runtime.assertOwned(e),K.withScope(r=>{let i=r.manage(this.borrowPropertyKey(t)),a=n.value||this.undefined,o=!!n.configurable,s=!!n.enumerable,c=!!n.value,l=n.get?r.manage(this.newFunction(n.get.name,n.get)):this.undefined,u=n.set?r.manage(this.newFunction(n.set.name,n.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,e.value,i.value,a.value,l.value,u.value,o,s,c)})}callFunction(e,t,...n){this.runtime.assertOwned(e);let r,i=n[0];r=i===void 0||Array.isArray(i)?i??[]:n;let a=this.memory.toPointerArray(r).consume(n=>this.ffi.QTS_Call(this.ctx.value,e.value,t.value,r.length,n.value)),o=this.ffi.QTS_ResolveException(this.ctx.value,a);return o?(this.ffi.QTS_FreeValuePointer(this.ctx.value,a),this.fail(this.memory.heapValueHandle(o))):this.success(this.memory.heapValueHandle(a))}callMethod(e,t,n=[]){return this.getProp(e,t).consume(t=>this.callFunction(t,e,n))}evalCode(e,t=`eval.js`,n){let r=n===void 0?1:0,i=A(n),a=this.memory.newHeapCharPointer(e).consume(e=>this.ffi.QTS_Eval(this.ctx.value,e.value.ptr,e.value.strlen,t,r,i)),o=this.ffi.QTS_ResolveException(this.ctx.value,a);return o?(this.ffi.QTS_FreeValuePointer(this.ctx.value,a),this.fail(this.memory.heapValueHandle(o))):this.success(this.memory.heapValueHandle(a))}throw(e){return this.errorToHandle(e).consume(e=>this.ffi.QTS_Throw(this.ctx.value,e.value))}borrowPropertyKey(e){return typeof e==`number`?this.newNumber(e):typeof e==`string`?this.newString(e):new W(e.value,this.runtime)}getMemory(e){if(e===this.rt.value)return this.memory;throw Error(`Private API. Cannot get memory from a different runtime`)}dump(e){this.runtime.assertOwned(e);let t=this.typeof(e);if(t===`string`)return this.getString(e);if(t===`number`)return this.getNumber(e);if(t===`bigint`)return this.getBigInt(e);if(t===`undefined`)return;if(t===`symbol`)return this.getSymbol(e);let n=this.getPromiseState(e);if(n.type===`fulfilled`&&!n.notAPromise)return e.dispose(),{type:n.type,value:n.value.consume(this.dump)};if(n.type===`pending`)return e.dispose(),{type:n.type};if(n.type===`rejected`)return e.dispose(),{type:n.type,error:n.error.consume(this.dump)};let r=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,e.value));try{return JSON.parse(r)}catch{return r}}unwrapResult(e){if(e.error){let t=`context`in e.error?e.error.context:this,n=e.error.consume(e=>this.dump(e));if(n&&typeof n==`object`&&typeof n.message==`string`){let{message:e,name:r,stack:i,...a}=n,o=new N(n,t);typeof r==`string`&&(o.name=n.name),o.message=e;let s=o.stack;throw typeof i==`string`&&(o.stack=`${r}: ${e}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blink",
3
- "version": "0.1.13",
3
+ "version": "0.1.14",
4
4
  "description": "Blink is a JavaScript runtime for building and deploying AI agents.",
5
5
  "type": "module",
6
6
  "bin": {