blink 0.1.57 → 0.1.59
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/api/index.cjs +2 -2
- package/dist/api/index.d.ts +1 -1
- package/dist/api/index.js +9 -9
- package/dist/cli/{auth-Dw-wJ1IM.js → auth-BUNIOupD.js} +1 -1
- package/dist/cli/{chat-CvTLq5E0.js → chat-L0VBV1Zr.js} +1 -1
- package/dist/cli/{dev-AdCRPYXi.js → dev-_R5nfhjp.js} +204 -236
- package/dist/cli/esm-DmR1E1ox.js +1 -0
- package/dist/cli/{getMachineId-bsd-C-mIkoX1.js → getMachineId-bsd-BZVr5tA4.js} +1 -1
- package/dist/cli/{getMachineId-darwin-BndlBc-C.js → getMachineId-darwin-CovNSxTh.js} +1 -1
- package/dist/cli/{getMachineId-linux-DYz-C3hh.js → getMachineId-linux-UJ7XEIYa.js} +1 -1
- package/dist/cli/{getMachineId-unsupported-CcuIl2b-.js → getMachineId-unsupported-DfUiEY7G.js} +1 -1
- package/dist/cli/{getMachineId-win-KRlx7d-Q.js → getMachineId-win-DYgilU22.js} +1 -1
- package/dist/cli/index.js +3 -3
- package/dist/cli/{init-x07jlFqm.js → init-B61NlodJ.js} +1 -1
- package/dist/cli/login-DKW_KVCA.js +1 -0
- package/dist/http/api.cjs +1 -1
- package/dist/http/api.d.cts +9 -1
- package/dist/http/api.d.ts +9 -1
- package/dist/http/api.js +1 -1
- package/dist/http/index.cjs +1 -1
- package/dist/http/index.d.ts +2 -2
- package/dist/http/index.js +1 -1
- package/dist/http-B_3J2CH3.js +21 -0
- package/dist/http-C-hX8Pv2.cjs +21 -0
- package/dist/{index-tvf1rglX.d.ts → index-CIUoZVwP.d.ts} +1 -1
- package/dist/{index-auvvMWNH.d.ts → index-DPvs3m4c.d.ts} +1 -1
- package/dist/test.d.ts +2 -2
- package/package.json +4 -4
- package/dist/cli/esm-CeJfCMPI.js +0 -1
- package/dist/cli/login-KHDcJ0iZ.js +0 -1
- package/dist/http-BAfeJhFm.js +0 -53
- package/dist/http-DS8vmbQx.cjs +0 -53
- /package/dist/cli/{dist-CN69Y-yA.js → dist-NqrnQGst.js} +0 -0
- /package/dist/cli/{open-Cr8lEmcs.js → open-CSMQaj0E.js} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{__esmMin as e,__export as t}from"./chunk-ByIbJXPc.js";var n,r=e((()=>{n=typeof globalThis==`object`?globalThis:global})),i=e((()=>{r()})),a=e((()=>{i()})),o,s=e((()=>{o=`1.9.0`}));function c(e){var t=new Set([e]),n=new Set,r=e.match(l);if(!r)return function(){return!1};var i={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(i.prerelease!=null)return function(t){return t===e};function a(e){return n.add(e),!1}function o(e){return t.add(e),!0}return function(e){if(t.has(e))return!0;if(n.has(e))return!1;var r=e.match(l);if(!r)return a(e);var s={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};return s.prerelease!=null||i.major!==s.major?a(e):i.major===0?i.minor===s.minor&&i.patch<=s.patch?o(e):a(e):i.minor<=s.minor?o(e):a(e)}}var l,ee,te=e((()=>{s(),l=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/,ee=c(o)}));function u(e,t,n,r){var i;r===void 0&&(r=!1);var a=m[p]=(i=m[p])==null?{version:o}:i;if(!r&&a[e]){var s=Error(`@opentelemetry/api: Attempted duplicate registration of API: `+e);return n.error(s.stack||s.message),!1}if(a.version!==o){var s=Error(`@opentelemetry/api: Registration of version v`+a.version+` for `+e+` does not match previously registered API v`+o);return n.error(s.stack||s.message),!1}return a[e]=t,n.debug(`@opentelemetry/api: Registered a global for `+e+` v`+o+`.`),!0}function d(e){var t,n,r=(t=m[p])==null?void 0:t.version;if(!(!r||!ee(r)))return(n=m[p])==null?void 0:n[e]}function f(e,t){t.debug(`@opentelemetry/api: Unregistering a global for `+e+` v`+o+`.`);var n=m[p];n&&delete n[e]}var ne,p,m,h=e((()=>{a(),s(),te(),ne=o.split(`.`)[0],p=Symbol.for(`opentelemetry.js.api.`+ne),m=n}));function g(e,t,n){var r=d(`diag`);if(r)return n.unshift(t),r[e].apply(r,ie([],re(n),!1))}var re,ie,ae,oe=e((()=>{h(),re=function(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a},ie=function(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||(a=Array.prototype.slice.call(t,0,r)),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))},ae=function(){function e(e){this._namespace=e.namespace||`DiagComponentLogger`}return e.prototype.debug=function(){var e=[...arguments];return g(`debug`,this._namespace,e)},e.prototype.error=function(){var e=[...arguments];return g(`error`,this._namespace,e)},e.prototype.info=function(){var e=[...arguments];return g(`info`,this._namespace,e)},e.prototype.warn=function(){var e=[...arguments];return g(`warn`,this._namespace,e)},e.prototype.verbose=function(){var e=[...arguments];return g(`verbose`,this._namespace,e)},e}()})),_,v=e((()=>{(function(e){e[e.NONE=0]=`NONE`,e[e.ERROR=30]=`ERROR`,e[e.WARN=50]=`WARN`,e[e.INFO=60]=`INFO`,e[e.DEBUG=70]=`DEBUG`,e[e.VERBOSE=80]=`VERBOSE`,e[e.ALL=9999]=`ALL`})(_||(_={}))}));function se(e,t){e<_.NONE?e=_.NONE:e>_.ALL&&(e=_.ALL),t=t||{};function n(n,r){var i=t[n];return typeof i==`function`&&e>=r?i.bind(t):function(){}}return{error:n(`error`,_.ERROR),warn:n(`warn`,_.WARN),info:n(`info`,_.INFO),debug:n(`debug`,_.DEBUG),verbose:n(`verbose`,_.VERBOSE)}}var ce=e((()=>{v()})),le,ue,de,y,b=e((()=>{oe(),ce(),v(),h(),le=function(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a},ue=function(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||(a=Array.prototype.slice.call(t,0,r)),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))},de=`diag`,y=function(){function e(){function e(e){return function(){var t=[...arguments],n=d(`diag`);if(n)return n[e].apply(n,ue([],le(t),!1))}}var t=this,n=function(e,n){var r,i,a;if(n===void 0&&(n={logLevel:_.INFO}),e===t){var o=Error(`Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation`);return t.error((r=o.stack)==null?o.message:r),!1}typeof n==`number`&&(n={logLevel:n});var s=d(`diag`),c=se((i=n.logLevel)==null?_.INFO:i,e);if(s&&!n.suppressOverrideMessage){var l=(a=Error().stack)==null?`<failed to generate stacktrace>`:a;s.warn(`Current logger will be overwritten from `+l),c.warn(`Current logger will overwrite one already registered from `+l)}return u(`diag`,c,t,!0)};t.setLogger=n,t.disable=function(){f(de,t)},t.createComponentLogger=function(e){return new ae(e)},t.verbose=e(`verbose`),t.debug=e(`debug`),t.info=e(`info`),t.warn=e(`warn`),t.error=e(`error`)}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e}()})),fe,pe,me,he=e((()=>{fe=function(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a},pe=function(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)},me=function(){function e(e){this._entries=e?new Map(e):new Map}return e.prototype.getEntry=function(e){var t=this._entries.get(e);if(t)return Object.assign({},t)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var t=fe(e,2),n=t[0],r=t[1];return[n,r]})},e.prototype.setEntry=function(t,n){var r=new e(this._entries);return r._entries.set(t,n),r},e.prototype.removeEntry=function(t){var n=new e(this._entries);return n._entries.delete(t),n},e.prototype.removeEntries=function(){for(var t,n,r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];var a=new e(this._entries);try{for(var o=pe(r),s=o.next();!s.done;s=o.next()){var c=s.value;a._entries.delete(c)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return a},e.prototype.clear=function(){return new e},e}()})),ge,_e=e((()=>{ge=Symbol(`BaggageEntryMetadata`)}));function ve(e){return e===void 0&&(e={}),new me(new Map(Object.entries(e)))}function ye(e){return typeof e!=`string`&&(be.error(`Cannot create baggage metadata from unknown type: `+typeof e),e=``),{__TYPE__:ge,toString:function(){return e}}}var be,xe=e((()=>{b(),he(),_e(),be=y.instance()}));function x(e){return Symbol.for(e)}var Se,S,C=e((()=>{Se=function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(e){return n._currentContext.get(e)},n.setValue=function(t,r){var i=new e(n._currentContext);return i._currentContext.set(t,r),i},n.deleteValue=function(t){var r=new e(n._currentContext);return r._currentContext.delete(t),r}}return e}(),S=new Se})),w,T,Ce=e((()=>{w=[{n:`error`,c:`error`},{n:`warn`,c:`warn`},{n:`info`,c:`info`},{n:`debug`,c:`debug`},{n:`verbose`,c:`trace`}],T=function(){function e(){function e(e){return function(){var t=[...arguments];if(console){var n=console[e];if(typeof n!=`function`&&(n=console.log),typeof n==`function`)return n.apply(console,t)}}}for(var t=0;t<w.length;t++)this[w[t].n]=e(w[t].c)}return e}()}));function we(){return k}var E,Te,D,Ee,De,Oe,ke,O,Ae,je,Me,k,Ne,Pe,Fe,Ie,Le,Re,ze,Be=e((()=>{E=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};return function(t,n){if(typeof n!=`function`&&n!==null)throw TypeError(`Class extends value `+String(n)+` is not a constructor or null`);e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Te=function(){function e(){}return e.prototype.createGauge=function(e,t){return Pe},e.prototype.createHistogram=function(e,t){return Fe},e.prototype.createCounter=function(e,t){return Ne},e.prototype.createUpDownCounter=function(e,t){return Ie},e.prototype.createObservableGauge=function(e,t){return Re},e.prototype.createObservableCounter=function(e,t){return Le},e.prototype.createObservableUpDownCounter=function(e,t){return ze},e.prototype.addBatchObservableCallback=function(e,t){},e.prototype.removeBatchObservableCallback=function(e){},e}(),D=function(){function e(){}return e}(),Ee=function(e){E(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(e,t){},t}(D),De=function(e){E(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(e,t){},t}(D),Oe=function(e){E(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(e,t){},t}(D),ke=function(e){E(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(e,t){},t}(D),O=function(){function e(){}return e.prototype.addCallback=function(e){},e.prototype.removeCallback=function(e){},e}(),Ae=function(e){E(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(O),je=function(e){E(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(O),Me=function(e){E(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(O),k=new Te,Ne=new Ee,Pe=new Oe,Fe=new ke,Ie=new De,Le=new Ae,Re=new je,ze=new Me})),A,Ve=e((()=>{(function(e){e[e.INT=0]=`INT`,e[e.DOUBLE=1]=`DOUBLE`})(A||(A={}))})),He,Ue,We=e((()=>{He={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},Ue={set:function(e,t,n){e!=null&&(e[t]=n)}}})),Ge,Ke,qe,Je=e((()=>{C(),Ge=function(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a},Ke=function(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||(a=Array.prototype.slice.call(t,0,r)),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))},qe=function(){function e(){}return e.prototype.active=function(){return S},e.prototype.with=function(e,t,n){var r=[...arguments].slice(3);return t.call.apply(t,Ke([n],Ge(r),!1))},e.prototype.bind=function(e,t){return t},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}()})),Ye,Xe,j,Ze,M,N=e((()=>{Je(),h(),b(),Ye=function(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a},Xe=function(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||(a=Array.prototype.slice.call(t,0,r)),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))},j=`context`,Ze=new qe,M=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(e){return u(j,e,y.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(e,t,n){for(var r,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(r=this._getContextManager()).with.apply(r,Xe([e,t,n],Ye(i),!1))},e.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},e.prototype._getContextManager=function(){return d(j)||Ze},e.prototype.disable=function(){this._getContextManager().disable(),f(j,y.instance())},e}()})),P,Qe=e((()=>{(function(e){e[e.NONE=0]=`NONE`,e[e.SAMPLED=1]=`SAMPLED`})(P||(P={}))})),F,I,$e,et=e((()=>{Qe(),F=`0000000000000000`,I=`00000000000000000000000000000000`,$e={traceId:I,spanId:F,traceFlags:P.NONE}})),L,tt=e((()=>{et(),L=function(){function e(e){e===void 0&&(e=$e),this._spanContext=e}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(e,t){return this},e.prototype.setAttributes=function(e){return this},e.prototype.addEvent=function(e,t){return this},e.prototype.addLink=function(e){return this},e.prototype.addLinks=function(e){return this},e.prototype.setStatus=function(e){return this},e.prototype.updateName=function(e){return this},e.prototype.end=function(e){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(e,t){},e}()}));function nt(e){return e.getValue(z)||void 0}function rt(){return nt(M.getInstance().active())}function R(e,t){return e.setValue(z,t)}function it(e){return e.deleteValue(z)}function at(e,t){return R(e,new L(t))}function ot(e){var t;return(t=nt(e))==null?void 0:t.spanContext()}var z,st=e((()=>{C(),tt(),N(),z=x(`OpenTelemetry Context Key SPAN`)}));function ct(e){return dt.test(e)&&e!==I}function lt(e){return ft.test(e)&&e!==F}function B(e){return ct(e.traceId)&<(e.spanId)}function ut(e){return new L(e)}var dt,ft,V=e((()=>{et(),tt(),dt=/^([0-9a-f]{32})$/i,ft=/^[0-9a-f]{16}$/i}));function pt(e){return typeof e==`object`&&typeof e.spanId==`string`&&typeof e.traceId==`string`&&typeof e.traceFlags==`number`}var H,U,mt=e((()=>{N(),st(),tt(),V(),H=M.getInstance(),U=function(){function e(){}return e.prototype.startSpan=function(e,t,n){n===void 0&&(n=H.active());var r=!!(t!=null&&t.root);if(r)return new L;var i=n&&ot(n);return pt(i)&&B(i)?new L(i):new L},e.prototype.startActiveSpan=function(e,t,n,r){var i,a,o;if(!(arguments.length<2)){arguments.length===2?o=t:arguments.length===3?(i=t,o=n):(i=t,a=n,o=r);var s=a==null?H.active():a,c=this.startSpan(e,i,s),l=R(s,c);return H.with(l,o,void 0,c)}},e}()})),ht,W,gt=e((()=>{mt(),ht=new U,W=function(){function e(e,t,n,r){this._provider=e,this.name=t,this.version=n,this.options=r}return e.prototype.startSpan=function(e,t,n){return this._getTracer().startSpan(e,t,n)},e.prototype.startActiveSpan=function(e,t,n,r){var i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):ht},e}()})),_t,vt=e((()=>{mt(),_t=function(){function e(){}return e.prototype.getTracer=function(e,t,n){return new U},e}()})),yt,G,bt=e((()=>{gt(),vt(),yt=new _t,G=function(){function e(){}return e.prototype.getTracer=function(e,t,n){var r;return(r=this.getDelegateTracer(e,t,n))==null?new W(this,e,t,n):r},e.prototype.getDelegate=function(){var e;return(e=this._delegate)==null?yt:e},e.prototype.setDelegate=function(e){this._delegate=e},e.prototype.getDelegateTracer=function(e,t,n){var r;return(r=this._delegate)==null?void 0:r.getTracer(e,t,n)},e}()})),xt,St=e((()=>{(function(e){e[e.NOT_RECORD=0]=`NOT_RECORD`,e[e.RECORD=1]=`RECORD`,e[e.RECORD_AND_SAMPLED=2]=`RECORD_AND_SAMPLED`})(xt||(xt={}))})),Ct,wt=e((()=>{(function(e){e[e.INTERNAL=0]=`INTERNAL`,e[e.SERVER=1]=`SERVER`,e[e.CLIENT=2]=`CLIENT`,e[e.PRODUCER=3]=`PRODUCER`,e[e.CONSUMER=4]=`CONSUMER`})(Ct||(Ct={}))})),Tt,Et=e((()=>{(function(e){e[e.UNSET=0]=`UNSET`,e[e.OK=1]=`OK`,e[e.ERROR=2]=`ERROR`})(Tt||(Tt={}))}));function Dt(e){return jt.test(e)}function Ot(e){return Mt.test(e)&&!Nt.test(e)}var K,kt,At,jt,Mt,Nt,Pt=e((()=>{K=`[_0-9a-z-*/]`,kt=`[a-z]`+K+`{0,255}`,At=`[a-z0-9]`+K+`{0,240}@[a-z]`+K+`{0,13}`,jt=RegExp(`^(?:`+kt+`|`+At+`)$`),Mt=/^[ -~]{0,255}[!-~]$/,Nt=/,|=/})),Ft,It,Lt,Rt,zt,Bt=e((()=>{Pt(),Ft=32,It=512,Lt=`,`,Rt=`=`,zt=function(){function e(e){this._internalState=new Map,e&&this._parse(e)}return e.prototype.set=function(e,t){var n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,t),n},e.prototype.unset=function(e){var t=this._clone();return t._internalState.delete(e),t},e.prototype.get=function(e){return this._internalState.get(e)},e.prototype.serialize=function(){var e=this;return this._keys().reduce(function(t,n){return t.push(n+Rt+e.get(n)),t},[]).join(Lt)},e.prototype._parse=function(e){e.length>It||(this._internalState=e.split(Lt).reverse().reduce(function(e,t){var n=t.trim(),r=n.indexOf(Rt);if(r!==-1){var i=n.slice(0,r),a=n.slice(r+1,t.length);Dt(i)&&Ot(a)&&e.set(i,a)}return e},new Map),this._internalState.size>Ft&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,Ft))))},e.prototype._keys=function(){return Array.from(this._internalState.keys()).reverse()},e.prototype._clone=function(){var t=new e;return t._internalState=new Map(this._internalState),t},e}()}));function Vt(e){return new zt(e)}var Ht=e((()=>{Bt()})),Ut,Wt=e((()=>{N(),Ut=M.getInstance()})),q,Gt=e((()=>{b(),q=y.instance()})),Kt,qt,Jt=e((()=>{Be(),Kt=function(){function e(){}return e.prototype.getMeter=function(e,t,n){return k},e}(),qt=new Kt})),J,Yt,Xt=e((()=>{Jt(),h(),b(),J=`metrics`,Yt=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(e){return u(J,e,y.instance())},e.prototype.getMeterProvider=function(){return d(J)||qt},e.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},e.prototype.disable=function(){f(J,y.instance())},e}()})),Y,Zt=e((()=>{Xt(),Y=Yt.getInstance()})),Qt,$t=e((()=>{Qt=function(){function e(){}return e.prototype.inject=function(e,t){},e.prototype.extract=function(e,t){return e},e.prototype.fields=function(){return[]},e}()}));function en(e){return e.getValue(X)||void 0}function tn(){return en(M.getInstance().active())}function nn(e,t){return e.setValue(X,t)}function rn(e){return e.deleteValue(X)}var X,an=e((()=>{N(),C(),X=x(`OpenTelemetry Baggage Key`)})),Z,on,sn,cn=e((()=>{h(),$t(),We(),an(),xe(),b(),Z=`propagation`,on=new Qt,sn=function(){function e(){this.createBaggage=ve,this.getBaggage=en,this.getActiveBaggage=tn,this.setBaggage=nn,this.deleteBaggage=rn}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(e){return u(Z,e,y.instance())},e.prototype.inject=function(e,t,n){return n===void 0&&(n=Ue),this._getGlobalPropagator().inject(e,t,n)},e.prototype.extract=function(e,t,n){return n===void 0&&(n=He),this._getGlobalPropagator().extract(e,t,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){f(Z,y.instance())},e.prototype._getGlobalPropagator=function(){return d(Z)||on},e}()})),ln,un=e((()=>{cn(),ln=sn.getInstance()})),Q,dn,fn=e((()=>{h(),bt(),V(),st(),b(),Q=`trace`,dn=function(){function e(){this._proxyTracerProvider=new G,this.wrapSpanContext=ut,this.isSpanContextValid=B,this.deleteSpan=it,this.getSpan=nt,this.getActiveSpan=rt,this.getSpanContext=ot,this.setSpan=R,this.setSpanContext=at}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(e){var t=u(Q,this._proxyTracerProvider,y.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},e.prototype.getTracerProvider=function(){return d(Q)||this._proxyTracerProvider},e.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},e.prototype.disable=function(){f(Q,y.instance()),this._proxyTracerProvider=new G},e}()})),$,pn=e((()=>{fn(),$=dn.getInstance()})),mn={};t(mn,{DiagConsoleLogger:()=>T,DiagLogLevel:()=>_,INVALID_SPANID:()=>F,INVALID_SPAN_CONTEXT:()=>$e,INVALID_TRACEID:()=>I,ProxyTracer:()=>W,ProxyTracerProvider:()=>G,ROOT_CONTEXT:()=>S,SamplingDecision:()=>xt,SpanKind:()=>Ct,SpanStatusCode:()=>Tt,TraceFlags:()=>P,ValueType:()=>A,baggageEntryMetadataFromString:()=>ye,context:()=>Ut,createContextKey:()=>x,createNoopMeter:()=>we,createTraceState:()=>Vt,default:()=>hn,defaultTextMapGetter:()=>He,defaultTextMapSetter:()=>Ue,diag:()=>q,isSpanContextValid:()=>B,isValidSpanId:()=>lt,isValidTraceId:()=>ct,metrics:()=>Y,propagation:()=>ln,trace:()=>$});var hn,gn=e((()=>{xe(),C(),Ce(),v(),Be(),Ve(),We(),gt(),bt(),St(),wt(),Et(),Qe(),Ht(),V(),et(),Wt(),Gt(),Zt(),un(),pn(),hn={context:Ut,diag:q,metrics:Y,propagation:ln,trace:$}}));export{T as DiagConsoleLogger,_ as DiagLogLevel,A as ValueType,q as diag,mn as esm_exports,gn as init_esm,Y as metrics};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__commonJSMin as e,__require as t,__toCommonJS as n}from"./chunk-ByIbJXPc.js";import{require_execAsync as r}from"./execAsync-q2CSWc1b.js";import{esm_exports as i,init_esm as a}from"./esm-
|
|
1
|
+
import{__commonJSMin as e,__require as t,__toCommonJS as n}from"./chunk-ByIbJXPc.js";import{require_execAsync as r}from"./execAsync-q2CSWc1b.js";import{esm_exports as i,init_esm as a}from"./esm-DmR1E1ox.js";var o=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.getMachineId=void 0;let o=t(`fs`),s=r(),c=(a(),n(i));async function l(){try{let e=await o.promises.readFile(`/etc/hostid`,{encoding:`utf8`});return e.trim()}catch(e){c.diag.debug(`error reading machine id: ${e}`)}try{let e=await(0,s.execAsync)(`kenv -q smbios.system.uuid`);return e.stdout.trim()}catch(e){c.diag.debug(`error reading machine id: ${e}`)}}exports.getMachineId=l}));export default o();export{};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__commonJSMin as e,__toCommonJS as t}from"./chunk-ByIbJXPc.js";import{require_execAsync as n}from"./execAsync-q2CSWc1b.js";import{esm_exports as r,init_esm as i}from"./esm-
|
|
1
|
+
import{__commonJSMin as e,__toCommonJS as t}from"./chunk-ByIbJXPc.js";import{require_execAsync as n}from"./execAsync-q2CSWc1b.js";import{esm_exports as r,init_esm as i}from"./esm-DmR1E1ox.js";var a=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.getMachineId=void 0;let a=n(),o=(i(),t(r));async function s(){try{let e=await(0,a.execAsync)(`ioreg -rd1 -c "IOPlatformExpertDevice"`),t=e.stdout.split(`
|
|
2
2
|
`).find(e=>e.includes(`IOPlatformUUID`));if(!t)return;let n=t.split(`" = "`);if(n.length===2)return n[1].slice(0,-1)}catch(e){o.diag.debug(`error reading machine id: ${e}`)}}exports.getMachineId=s}));export default a();export{};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__commonJSMin as e,__require as t,__toCommonJS as n}from"./chunk-ByIbJXPc.js";import{esm_exports as r,init_esm as i}from"./esm-
|
|
1
|
+
import{__commonJSMin as e,__require as t,__toCommonJS as n}from"./chunk-ByIbJXPc.js";import{esm_exports as r,init_esm as i}from"./esm-DmR1E1ox.js";var a=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.getMachineId=void 0;let a=t(`fs`),o=(i(),n(r));async function s(){let e=[`/etc/machine-id`,`/var/lib/dbus/machine-id`];for(let t of e)try{let e=await a.promises.readFile(t,{encoding:`utf8`});return e.trim()}catch(e){o.diag.debug(`error reading machine id: ${e}`)}}exports.getMachineId=s}));export default a();export{};
|
package/dist/cli/{getMachineId-unsupported-CcuIl2b-.js → getMachineId-unsupported-DfUiEY7G.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__commonJSMin as e,__toCommonJS as t}from"./chunk-ByIbJXPc.js";import{esm_exports as n,init_esm as r}from"./esm-
|
|
1
|
+
import{__commonJSMin as e,__toCommonJS as t}from"./chunk-ByIbJXPc.js";import{esm_exports as n,init_esm as r}from"./esm-DmR1E1ox.js";var i=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.getMachineId=void 0;let i=(r(),t(n));async function a(){i.diag.debug(`could not read machine-id: unsupported platform`)}exports.getMachineId=a}));export default i();export{};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__commonJSMin as e,__require as t,__toCommonJS as n}from"./chunk-ByIbJXPc.js";import{require_execAsync as r}from"./execAsync-q2CSWc1b.js";import{esm_exports as i,init_esm as a}from"./esm-
|
|
1
|
+
import{__commonJSMin as e,__require as t,__toCommonJS as n}from"./chunk-ByIbJXPc.js";import{require_execAsync as r}from"./execAsync-q2CSWc1b.js";import{esm_exports as i,init_esm as a}from"./esm-DmR1E1ox.js";var o=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.getMachineId=void 0;let o=t(`process`),s=r(),c=(a(),n(i));async function l(){let e=`%windir%\\System32\\REG.exe`;o.arch===`ia32`&&`PROCESSOR_ARCHITEW6432`in o.env&&(e=`%windir%\\sysnative\\cmd.exe /c `+e);try{let t=await(0,s.execAsync)(`${e} QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid`),n=t.stdout.split(`REG_SZ`);if(n.length===2)return n[1].trim()}catch(e){c.diag.debug(`error reading machine id: ${e}`)}}exports.getMachineId=l}));export default o();export{};
|
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{__commonJSMin as e,__require as t,__toESM as n}from"./chunk-ByIbJXPc.js";import{import_websocket as r}from"./wrapper-B4vDwpOq.js";import{findNearestEntry as i,require_main as a,resolveConfig as o}from"./util-cVEGIV3r.js";import{Client as s,loginIfNeeded as c,source_default as l}from"./auth-
|
|
2
|
+
import{__commonJSMin as e,__require as t,__toESM as n}from"./chunk-ByIbJXPc.js";import{import_websocket as r}from"./wrapper-B4vDwpOq.js";import{findNearestEntry as i,require_main as a,resolveConfig as o}from"./util-cVEGIV3r.js";import{Client as s,loginIfNeeded as c,source_default as l}from"./auth-BUNIOupD.js";import{Y as u,pD as d,ve as f,ye as p}from"./dist-NqrnQGst.js";import"./open-CSMQaj0E.js";import{randomUUID as m}from"crypto";import{basename as h,dirname as g,join as _}from"node:path";import{existsSync as v}from"node:fs";import{mkdir as y,readdir as b,writeFile as x}from"fs/promises";import{readFile as S,stat as C}from"node:fs/promises";var w=e((exports=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};exports.CommanderError=t,exports.InvalidArgumentError=n})),T=e((exports=>{let{InvalidArgumentError:t}=w();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)===`...`&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._concatValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}exports.Argument=n,exports.humanReadableArgName=r})),E=e((exports=>{let{humanReadableArgName:t}=T();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0){let n=e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`;n&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));a=a.concat(this.formatItemList(`Arguments:`,s,t));let c=this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`);if(c.forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}let l=this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`);return l.forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
|
|
3
3
|
`)}displayWidth(e){return r(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=this.helpWidth??80,s=o-t-2-2,c;if(s<this.minWidthToWrap||r.preformatted(n))c=n;else{let e=r.boxWrap(n,s);c=e.replace(/\n/g,`
|
|
4
4
|
`+` `.repeat(t+2))}return i+a+` `.repeat(2)+c.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
|
|
5
5
|
`)}};function r(e){let t=/\x1b\[\d*(;\d*)*m/g;return e.replace(t,``)}exports.Help=n,exports.stripColor=r})),D=e((exports=>{let{InvalidArgumentError:t}=w();var n=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=a(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._concatValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?i(this.name().replace(/^no-/,``)):i(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r===void 0?!1:r;return t.negate===(i===e)}};function i(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function a(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
|
|
@@ -17,6 +17,6 @@ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._life
|
|
|
17
17
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
18
18
|
- ${r}`;throw Error(i)}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function c(e,t){let n=i.resolve(e,t);if(a.existsSync(n))return n;if(s.includes(i.extname(t)))return;let r=s.find(e=>a.existsSync(`${n}${e}`));if(r)return`${n}${r}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let u=e._executableFile||`${this._name}-${e._name}`,d=this._executableDir||``;if(this._scriptPath){let e;try{e=a.realpathSync(this._scriptPath)}catch{e=this._scriptPath}d=i.resolve(i.dirname(e),d)}if(d){let t=c(d,u);if(!t&&!e._executableFile&&this._scriptPath){let n=i.basename(this._scriptPath,i.extname(this._scriptPath));n!==this._name&&(t=c(d,`${n}-${e._name}`))}u=t||u}n=s.includes(i.extname(u));let f;if(o.platform===`win32`?(this._checkForMissingExecutable(u,d,e._name),t.unshift(u),t=g(o.execArgv).concat(t),f=r.spawn(o.execPath,t,{stdio:`inherit`})):n?(t.unshift(u),t=g(o.execArgv).concat(t),f=r.spawn(o.argv[0],t,{stdio:`inherit`})):f=r.spawn(u,t,{stdio:`inherit`}),!f.killed){let e=[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`];e.forEach(e=>{o.on(e,()=>{f.killed===!1&&f.exitCode===null&&f.kill(e)})})}let p=this._exitCallback;f.on(`close`,e=>{e=e??1,p?p(new l(e,`commander.executeSubCommandAsync`,`(close)`)):o.exit(e)}),f.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(u,d,e._name);else if(t.code===`EACCES`)throw Error(`'${u}' not executable`);if(!p)o.exit(1);else{let e=new l(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,p(e)}}),this.runningCommand=f}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent&&this.parent.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)===void 0?!1:this.getOptionValueSource(t)!==`default`}),t=e.filter(e=>e.conflictsWith.length>0);t.forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t,i=e.slice();function a(e){return e.length>1&&e[0]===`-`}let o=e=>/^-\d*\.?\d+(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,s=null;for(;i.length;){let e=i.shift();if(e===`--`){r===n&&r.push(e),r.push(...i);break}if(s&&(!a(e)||o(e))){this.emit(`option:${s.name()}`,e);continue}if(s=null,a(e)){let t=this._findOption(e);if(t){if(t.required){let e=i.shift();e===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,e)}else if(t.optional){let e=null;i.length>0&&(!a(i[0])||o(i[0]))&&(e=i.shift()),this.emit(`option:${t.name()}`,e)}else this.emit(`option:${t.name()}`);s=t.variadic?t:null;continue}}if(e.length>2&&e[0]===`-`&&e[1]!==`-`){let t=this._findOption(`-${e[1]}`);if(t){t.required||t.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${t.name()}`,e.slice(2)):(this.emit(`option:${t.name()}`),i.unshift(`-${e.slice(2)}`));continue}}if(/^--[^=]+=/.test(e)){let t=e.indexOf(`=`),n=this._findOption(e.slice(0,t));if(n&&(n.required||n.optional)){this.emit(`option:${n.name()}`,e.slice(t+1));continue}}if(r===t&&a(e)&&!(this.commands.length===0&&o(e))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(e)){t.push(e),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&e===this._getHelpCommand().name()){t.push(e),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){n.push(e),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){r.push(e),i.length>0&&r.push(...i);break}r.push(e)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
19
19
|
`),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in o.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,o.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new p(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName(),i=this.getOptionValueSource(r);return i===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=m(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=this.parent?` for '${this.name()}'`:``,i=`error: too many arguments${r}. Expected ${t} argument${n} but got ${e.length}.`;this.error(i,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=m(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||`-V, --version`,n=n||`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>c(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=i.basename(e,i.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e=e||{};let t=!!e.error,n,r,i;t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth());let a=e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e));return{error:t,write:a,hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(o.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
20
|
-
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption(),n=t&&e.find(e=>t.is(e));n&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function g(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _(){if(o.env.NO_COLOR||o.env.FORCE_COLOR===`0`||o.env.FORCE_COLOR===`false`)return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}exports.Command=h,exports.useColor=_})),A=e((exports=>{let{Argument:t}=T(),{Command:n}=k(),{CommanderError:r,InvalidArgumentError:i}=w(),{Help:a}=E(),{Option:o}=D();exports.program=new n,exports.createCommand=e=>new n(e),exports.createOption=(e,t)=>new o(e,t),exports.createArgument=(e,n)=>new t(e,n),exports.Command=n,exports.Option=o,exports.Argument=t,exports.Help=a,exports.CommanderError=r,exports.InvalidArgumentError=i,exports.InvalidOptionArgumentError=i})),j=n(A(),1);const{program:M,createCommand:N,createArgument:P,createOption:F,CommanderError:I,InvalidArgumentError:L,InvalidOptionArgumentError:R,Command:z,Argument:B,Option:V,Help:H}=j.default;var U=`0.1.
|
|
20
|
+
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption(),n=t&&e.find(e=>t.is(e));n&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function g(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _(){if(o.env.NO_COLOR||o.env.FORCE_COLOR===`0`||o.env.FORCE_COLOR===`false`)return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}exports.Command=h,exports.useColor=_})),A=e((exports=>{let{Argument:t}=T(),{Command:n}=k(),{CommanderError:r,InvalidArgumentError:i}=w(),{Help:a}=E(),{Option:o}=D();exports.program=new n,exports.createCommand=e=>new n(e),exports.createOption=(e,t)=>new o(e,t),exports.createArgument=(e,n)=>new t(e,n),exports.Command=n,exports.Option=o,exports.Argument=t,exports.Help=a,exports.CommanderError=r,exports.InvalidArgumentError=i,exports.InvalidOptionArgumentError=i})),j=n(A(),1);const{program:M,createCommand:N,createArgument:P,createOption:F,CommanderError:I,InvalidArgumentError:L,InvalidOptionArgumentError:R,Command:z,Argument:B,Option:V,Help:H}=j.default;var U=`0.1.59`;async function W(e){e||(e=process.cwd());let t=o(e);await t.build({cwd:e,entry:t.entry,outdir:t.outdir,watch:!1,onStart:()=>{console.log(`Building agent...`)},onResult:e=>{`error`in e&&(console.error(e.error),process.exit(1));for(let t of e.warnings)console.warn(t.message);console.log(`Built agent to ${e.entry}`)}})}var G=n(a(),1);async function K(e,t){e||(e=process.cwd());let n=await c(),r=new s({authToken:n}),a=await i(e,`package.json`);if(!a)throw Error(`package.json not found`);let m=await S(a,`utf-8`),w=JSON.parse(m),T=g(a),E=_(T,`.blink`,`config.json`),D={};if(v(E)){let e=await S(E,`utf-8`);D=JSON.parse(e)}let O;if(D?.organizationId)try{let e=await r.organizations.get(D.organizationId);O=e.name}catch(e){D.organizationId=void 0}if(!D?.organizationId){let e=await r.organizations.list();if(e.length===1){let t=e[0];D.organizationId=t.id,O=t.name}else{let t=await f({message:`Which organization should contain this agent?`,options:e.map(e=>({value:e.id,label:e.name}))});if(d(t))return;D.organizationId=t,O=e.find(e=>e.id===t).name}}if(!D.organizationId)throw Error(`Developer error: No organization ID found.`);let k;if(D?.agentId)try{let e=await r.agents.get(D.agentId);k=e.name}catch(e){D.agentId=void 0}if(!D?.agentId)try{let e=await r.organizations.agents.get({organization_id:D.organizationId,agent_name:w.name});D.agentId=e.id,k=e.name}catch(e){let t=await r.agents.create({name:w.name,organization_id:D.organizationId});D.agentId=t.id,k=t.name}if(!D.agentId)throw Error(`Developer error: No agent ID found.`);await y(g(E),{recursive:!0}),await x(E,JSON.stringify({_:`This file can be source controlled. It contains no secrets.`,...D},null,2),`utf-8`);let A=o(T),j=await new Promise((e,t)=>{A.build({cwd:T,entry:A.entry,outdir:A.outdir,watch:!1,onStart:()=>{},onResult:t=>{e(t)}}).catch(t)});if(!j)throw Error(`Failed to build agent`);if(`error`in j)throw Error(j.error.message);let M={},N=await b(j.outdir);for(let e of N)M[_(j.outdir,e)]=e;let P=_(e,`README.md`);await q(P)&&(M[P]=`README.md`);let F=[],I=Object.keys(M).length,L=0,R=0;for(let[e,t]of Object.entries(M)){let n=await C(e),i=n.size;Y(`${l.dim(`[${L+1}/${I}]`)} Uploading ${t} (${J(i)})...`);let a=await S(e),o=await r.files.upload(new File([a],t));F.push({path:t,id:o.id}),L+=1,R+=i}Y(`${l.dim(`[${L}/${I}]`)} Uploaded files (${J(R)}).`),process.stdout.write(`
|
|
21
21
|
`);let z=_(e,`.env.local`),B=[];if(await q(z)){let e=(0,G.parse)(await S(z,`utf-8`));B=Object.keys(e)}let V=[],H=await r.agents.env.list({agent_id:D.agentId});V=H.map(e=>e.key);let U=_(e,`.env.production`);if(await q(U)){let e=(0,G.parse)(await S(U,`utf-8`)),t=Object.entries(e),n=t.length,i=0;for(let[e,a]of t){let t=await r.agents.env.create({agent_id:D.agentId,key:e,value:a,target:[`production`,`preview`],secret:!0,upsert:!0});V.push(t.key),i+=1,Y(`${l.dim(`[${i}/${n}]`)} Updating environment variable: ${e} ${l.dim(`(.env.production)`)}`)}Y(`${l.dim(`[${i}/${n}]`)} Updated environment variables! ${l.dim(`(.env.production)`)}`),process.stdout.write(`
|
|
22
|
-
`)}let W=B.filter(e=>!V.includes(e));if(W.length>0){console.log(`Warning: The following environment variables are set in .env.local but not in .env.production:`);for(let e of W)console.log(`- ${e}`);let e=await p({message:`Do you want to deploy anyway?`});if(e===!1||d(e))return}let K=await r.agents.deployments.create({agent_id:D.agentId,target:`production`,entrypoint:h(j.entry),files:F,message:t?.message}),X=`https://blink.so/${O}/${k}/deployments/${K.number}`;console.log(`Deployed:`,X);let Z=u();Z.start(`Waiting for deployment to be live...`);try{for(;;){let e=await r.agents.deployments.get({agent_id:D.agentId,deployment_id:K.id});if(e.status===`success`){let t=`Deployment successful.`;e.target===`production`&&(t+=` All chats will use this deployment!`),Z.stop(t);break}if(e.status===`failed`){let t=`Deployment failed.`;e.error_message&&(t+=` ${e.error_message}`),Z.stop(t),console.log(`Read logs for details:`,X);return}await new Promise(e=>setTimeout(e,500))}}catch(e){Z.stop(`Failed to poll for deployment status.`),console.log(`Read logs for details:`,X);return}}const q=async e=>{try{return await C(e),!0}catch(e){return!1}};function J(e){if(e===0)return`0B`;let t=1024,n=[`B`,`KB`,`MB`,`GB`,`TB`],r=Math.floor(Math.log(e)/Math.log(t)),i=e/Math.pow(t,r);return`${i.toFixed(i>=100?0:i>=10?1:2)}${n[r]}`}function Y(e){if(process.stdout.isTTY)try{process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(e);return}catch{}console.log(e)}globalThis.WebSocket||(globalThis.WebSocket=r.default),globalThis.crypto||(globalThis.crypto={}),globalThis.crypto.randomUUID||(globalThis.crypto.randomUUID=()=>m()),M.name(`blink`).description(`Blink is a runtime for building and deploying AI agents.`).version(U).action(()=>{M.outputHelp()});const X=e=>async(...t)=>{let{default:n}=await e();return n(...t)};M.command(`init [directory]`).description(`Initialize a new Blink agent.`).action(X(()=>import(`./init-
|
|
22
|
+
`)}let W=B.filter(e=>!V.includes(e));if(W.length>0){console.log(`Warning: The following environment variables are set in .env.local but not in .env.production:`);for(let e of W)console.log(`- ${e}`);let e=await p({message:`Do you want to deploy anyway?`});if(e===!1||d(e))return}let K=await r.agents.deployments.create({agent_id:D.agentId,target:`production`,entrypoint:h(j.entry),files:F,message:t?.message}),X=`https://blink.so/${O}/${k}/deployments/${K.number}`;console.log(`Deployed:`,X);let Z=u();Z.start(`Waiting for deployment to be live...`);try{for(;;){let e=await r.agents.deployments.get({agent_id:D.agentId,deployment_id:K.id});if(e.status===`success`){let t=`Deployment successful.`;e.target===`production`&&(t+=` All chats will use this deployment!`),Z.stop(t);break}if(e.status===`failed`){let t=`Deployment failed.`;e.error_message&&(t+=` ${e.error_message}`),Z.stop(t),console.log(`Read logs for details:`,X);return}await new Promise(e=>setTimeout(e,500))}}catch(e){Z.stop(`Failed to poll for deployment status.`),console.log(`Read logs for details:`,X);return}}const q=async e=>{try{return await C(e),!0}catch(e){return!1}};function J(e){if(e===0)return`0B`;let t=1024,n=[`B`,`KB`,`MB`,`GB`,`TB`],r=Math.floor(Math.log(e)/Math.log(t)),i=e/Math.pow(t,r);return`${i.toFixed(i>=100?0:i>=10?1:2)}${n[r]}`}function Y(e){if(process.stdout.isTTY)try{process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(e);return}catch{}console.log(e)}globalThis.WebSocket||(globalThis.WebSocket=r.default),globalThis.crypto||(globalThis.crypto={}),globalThis.crypto.randomUUID||(globalThis.crypto.randomUUID=()=>m()),M.name(`blink`).description(`Blink is a runtime for building and deploying AI agents.`).version(U).action(()=>{M.outputHelp()});const X=e=>async(...t)=>{let{default:n}=await e();return n(...t)};M.command(`init [directory]`).description(`Initialize a new Blink agent.`).action(X(()=>import(`./init-B61NlodJ.js`))),M.command(`dev [directory] [options]`).description(`Start a development server for your agent.`).action(X(()=>import(`./dev-_R5nfhjp.js`))),M.command(`deploy [directory]`).description(`Deploy your agent to the Blink Cloud.`).option(`-m, --message <message>`,`Message for this deployment`).action(K),M.command(`build [directory]`).description(`Build your agent for production.`).action(W),M.command(`telemetry [boolean]`).description(`Enable or disable telemetry.`),M.command(`start [directory]`).description("Starts the Blink runtime in production mode. The agent must be compiled with `blink build` first."),M.command(`connect`,{hidden:!0}).description(`Connect compute to the Blink Cloud.`).action(X(()=>import(`./connect-BHyGYU8L.js`))),M.command(`chat`,{hidden:!0}).description(`Start a Blink chat connected to your machine.`).action(X(()=>import(`./chat-L0VBV1Zr.js`))),M.command(`login`,{hidden:!0}).description(`Log in to the Blink Cloud.`).action(X(()=>import(`./login-DKW_KVCA.js`))),M.parse(process.argv);export{};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ie as e,M as t,Se as n,pD as r,ve as i,xe as a}from"./dist-
|
|
1
|
+
import{Ie as e,M as t,Se as n,pD as r,ve as i,xe as a}from"./dist-NqrnQGst.js";import{basename as o,dirname as s,join as c}from"path";import{readdir as l,writeFile as u}from"fs/promises";import{spawn as d}from"child_process";async function f(s){s||(s=process.cwd()),e(`Initializing a new Blink Agent`),(await l(s)).length>0&&(a("You must be in an empty directory to run `blink init`."),process.exit(1));let f=o(s).replace(/[^a-zA-Z0-9]/g,`-`),p;if(process.env.npm_config_user_agent?.includes(`bun/`)?p=`bun`:process.env.npm_config_user_agent?.includes(`pnpm/`)?p=`pnpm`:process.env.npm_config_user_agent?.includes(`yarn/`)?p=`yarn`:process.env.npm_config_user_agent?.includes(`npm/`)&&(p=`npm`),!p){let e=await i({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?`});r(e)&&process.exit(0),p=e}t.info(`Using ${p} as the package manager.`);let m={"package.json":JSON.stringify({name:f,main:`agent.ts`,type:`module`,private:!0}),"agent.ts":`import { convertToModelMessages, streamText, tool } from "ai";
|
|
2
2
|
import * as blink from "blink";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{login as e}from"./auth-BUNIOupD.js";import"./dist-NqrnQGst.js";import"./open-CSMQaj0E.js";async function t(){await e()}export{t as default};
|
package/dist/http/api.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},t=Symbol(),n=async(e,t=Object.create(null))=>{let{all:n=!1,dot:i=!1}=t,a=e instanceof C?e.raw.headers:e.headers,o=a.get(`Content-Type`);return o?.startsWith(`multipart/form-data`)||o?.startsWith(`application/x-www-form-urlencoded`)?r(e,{all:n,dot:i}):{}};async function r(e,t){let n=await e.formData();return n?i(n,t):{}}function i(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?a(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(o(n,e,t),delete n[e])}),n}var a=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},o=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},s=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},c=e=>{let{groups:t,path:n}=l(e),r=s(n);return u(r,t)},l=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},u=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},d={},f=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return d[r]||(n[2]?d[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:d[r]=[e,n[1],!0]),d[r]}return null},p=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},m=e=>p(e,decodeURI),h=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.slice(n,e===-1?void 0:e);return m(i.includes(`%25`)?i.replace(/%25/g,`%2525`):i)}else if(e===63)break}return t.slice(n,r)},g=e=>{let t=h(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},_=(e,t,...n)=>(n.length&&(t=_(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),v=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e))if(/\?/.test(e)){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.replace(`?`,``);r+=`/`+t,n.push(r)}else r+=`/`+e}),n.filter((e,t,n)=>n.indexOf(e)===t)},y=e=>/[%+]/.test(e)?(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),e.indexOf(`%`)===-1?e:p(e,x)):e,b=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let n=e.indexOf(`?${t}`,8);for(n===-1&&(n=e.indexOf(`&${t}`,8));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return y(e.slice(r,i===-1?void 0:i))}else if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(r=/[%+]/.test(e),!r)return}let i={};r??=/[%+]/.test(e);let a=e.indexOf(`?`,8);for(;a!==-1;){let t=e.indexOf(`&`,a+1),o=e.indexOf(`=`,a);o>t&&t!==-1&&(o=-1);let s=e.slice(a+1,o===-1?t===-1?void 0:t:o);if(r&&(s=y(s)),a=t,s===``)continue;let c;o===-1?c=``:(c=e.slice(o+1,t===-1?void 0:t),r&&(c=y(c))),n?(i[s]&&Array.isArray(i[s])||(i[s]=[]),i[s].push(c)):i[s]??=c}return t?i[t]:i},ee=b,te=(e,t)=>b(e,t,!0),x=decodeURIComponent,S=e=>p(e,x),C=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?S(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?S(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return ee(this.url,e)}queries(e){return te(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await n(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[t](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},ne={Stringify:1,BeforeStream:2,Stream:3},re=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},w=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>w(e,t,!1,r,i))).then(()=>i[0]));return n?re(await o,a):o},ie=`text/plain; charset=UTF-8`,T=(e,t)=>({"Content-Type":e,...t}),E=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new C(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,T(ie,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,T(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,T(`text/html; charset=UTF-8`,n));return typeof e==`object`?w(e,ne.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},D=`ALL`,O=`all`,ae=[`get`,`post`,`put`,`delete`,`options`,`patch`],k=`Can not add a route since the matcher is already built.`,A=class extends Error{},oe=`__COMPOSED_HANDLER`,se=e=>e.text(`404 Not Found`,404),j=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},M=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...ae,O];t.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(D,this.#path,e)}),this);let{strict:n,...r}=e;Object.assign(this,r),this.getPath=n??!0?e.getPath??h:g}#clone(){let e=new M({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=se;errorHandler=j;route(t,n){let r=this.basePath(t);return n.routes.map(t=>{let i;n.errorHandler===j?i=t.handler:(i=async(r,i)=>(await e([],n.errorHandler)(r,()=>t.handler(r,i))).res,i[oe]=t.handler),r.#addRoute(t.method,t.path,i)}),this}basePath(e){let t=this.#clone();return t._basePath=_(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};r||=(()=>{let t=_(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(n)||`/`,new Request(t,e)}})();let o=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#addRoute(D,_(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=_(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(t,n,r,i){if(i===`HEAD`)return(async()=>new Response(null,await this.#dispatch(t,n,r,`GET`)))();let a=this.getPath(t,{env:r}),o=this.router.match(i,a),s=new E(t,{path:a,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#notFoundHandler});if(o[0].length===1){let e;try{e=o[0][0][0][0](s,async()=>{s.res=await this.#notFoundHandler(s)})}catch(e){return this.#handleError(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#notFoundHandler(s))).catch(e=>this.#handleError(e,s)):e??this.#notFoundHandler(s)}let c=e(o[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await c(s);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,s)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${_(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},N=`[^/]+`,P=`.*`,F=`(?:|/.*)`,I=Symbol(),ce=new Set(`.\\+*[^]$()`);function le(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===P||e===F?1:t===P||t===F?-1:e===N?1:t===N?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var L=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw I;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,P]:[``,``,N]:a===`/*`?[``,``,F]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||N;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw I;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==P&&e!==F))throw I;if(i)return;c=this.#children[t]=new L,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==P&&e!==F))throw I;if(i)return;c=this.#children[a]=new L}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(le),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:ce.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},ue=class{#context={varIndex:0};#root=new L;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},R=[],de=[/^$/,[],Object.create(null)],z=Object.create(null);function B(e){return z[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function V(){z=Object.create(null)}function H(e){let t=new ue,n=[];if(e.length===0)return de;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),R]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===I?new A(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function U(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(B(n).test(t))return[...e[n]]}}var fe=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[D]:Object.create(null)},this.#routes={[D]:Object.create(null)}}add(e,t,n){let r=this.#middleware,i=this.#routes;if(!r||!i)throw Error(k);r[e]||[r,i].forEach(t=>{t[e]=Object.create(null),Object.keys(t[D]).forEach(n=>{t[e][n]=[...t[D][n]]})}),t===`/*`&&(t=`*`);let a=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let o=B(t);e===D?Object.keys(r).forEach(e=>{r[e][t]||=U(r[e],t)||U(r[D],t)||[]}):r[e][t]||=U(r[e],t)||U(r[D],t)||[],Object.keys(r).forEach(t=>{(e===D||e===t)&&Object.keys(r[t]).forEach(e=>{o.test(e)&&r[t][e].push([n,a])})}),Object.keys(i).forEach(t=>{(e===D||e===t)&&Object.keys(i[t]).forEach(e=>o.test(e)&&i[t][e].push([n,a]))});return}let o=v(t)||[t];for(let t=0,s=o.length;t<s;t++){let c=o[t];Object.keys(i).forEach(o=>{(e===D||e===o)&&(i[o][c]||=[...U(r[o],c)||U(r[D],c)||[]],i[o][c].push([n,a-s+t+1]))})}}match(e,t){V();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[D],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],R];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===D;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==D&&t.push(...Object.keys(r[D]).map(e=>[e,r[D][e]])):(n||=!0,t.push(...i))}),n?H(t):null}},pe=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(k);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof A)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},W=Object.create(null),G=class{#methods;#children;#patterns;#order=0;#params=W;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(e,t,n){this.#order=++this.#order;let r=this,i=c(t),a=[];for(let e=0,t=i.length;e<t;e++){let t=i[e],n=i[e+1],o=f(t,n),s=Array.isArray(o)?o[0]:t;if(s in r.#children){r=r.#children[s],o&&a.push(o[1]);continue}r.#children[s]=new G,o&&(r.#patterns.push(o),a.push(o[1])),r=r.#children[s]}return r.#methods.push({[e]:{handler:n,possibleKeys:a.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),r}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[D],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==W||r&&r!==W))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(e,t){let n=[];this.#params=W;let r=this,i=[r],a=s(t),o=[];for(let t=0,r=a.length;t<r;t++){let s=a[t],c=t===r-1,l=[];for(let r=0,u=i.length;r<u;r++){let u=i[r],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&n.push(...this.#getHandlerSets(d.#children[`*`],e,u.#params)),n.push(...this.#getHandlerSets(d,e,u.#params))):l.push(d));for(let r=0,i=u.#patterns.length;r<i;r++){let i=u.#patterns[r],d=u.#params===W?{}:{...u.#params};if(i===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.slice(t).join(`/`);if(m instanceof RegExp){let t=m.exec(g);if(t){if(d[p]=t[0],n.push(...this.#getHandlerSets(h,e,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let e=t[0].match(/\//)?.length??0,n=o[e]||=[];n.push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(n.push(...this.#getHandlerSets(h,e,d,u.#params)),h.#children[`*`]&&n.push(...this.#getHandlerSets(h.#children[`*`],e,d,u.#params))):(h.#params=d,l.push(h)))}}i=l.concat(o.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},me=class{name=`TrieRouter`;#node;constructor(){this.#node=new G}add(e,t,n){let r=v(t);if(r){for(let t=0,i=r.length;t<i;t++)this.#node.insert(e,r[t],n);return}this.#node.insert(e,t,n)}match(e,t){return this.#node.search(e,t)}},K=class extends M{constructor(e={}){super(e),this.router=e.router??new pe({routers:[new fe,new me]})}},he=/^[\w!#$%&'*.^`|~+-]+$/,ge=/^[ !#-:<-[\]-~]*$/,q=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.trim().split(`;`),r={};for(let e of n){e=e.trim();let n=e.indexOf(`=`);if(n===-1)continue;let i=e.substring(0,n).trim();if(t&&t!==i||!he.test(i))continue;let a=e.substring(n+1).trim();if(a.startsWith(`"`)&&a.endsWith(`"`)&&(a=a.slice(1,-1)),ge.test(a)&&(r[i]=a.indexOf(`%`)===-1?a:p(a,x),t))break}return r},_e=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t);let i=q(r,e);return i[e]}if(!r)return{};let i=q(r);return i},J=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},ve=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},ye=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,be=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,xe=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Y=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!ye.test(a))break;try{i=await n.req.json()}catch{throw new J(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(be.test(a)||xe.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await ve(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new J(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=_e(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const X=(e,t)=>e.json({error:t},400),Z=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Q=()=>new K,Se=Q().get(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.storage.kv.get(t);return e.json({value:r},200)}).post(`/kv/:key`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?X(t,`Value is too long. Max length is 1024 characters.`):{value:n}:X(t,`Value must be a string`):X(t,`Value is required`)}),async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.kv.set(t,r),e.body(null,204)}).delete(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);return n?X(e,n):(await e.env.storage.kv.del(t),e.body(null,204))}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},Ce=Q().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Y(`json`,(e,t)=>{let n=e.messages;if(!n)return X(t,`Messages are required`);if(!Array.isArray(n))return X(t,`Messages must be an array`);if(n.length===0)return X(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?X(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);try{await e.env.chat.sendMessages(t,{messages:r,behavior:i})}catch(t){return X(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),we=new K().route(`/storage`,Se).route(`/chat`,Ce);var Te=we;module.exports=Te;
|
|
1
|
+
Object.defineProperty(exports,`__esModule`,{value:!0});var e=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},t=Symbol(),n=async(e,t=Object.create(null))=>{let{all:n=!1,dot:i=!1}=t,a=e instanceof S?e.raw.headers:e.headers,o=a.get(`Content-Type`);return o?.startsWith(`multipart/form-data`)||o?.startsWith(`application/x-www-form-urlencoded`)?r(e,{all:n,dot:i}):{}};async function r(e,t){let n=await e.formData();return n?i(n,t):{}}function i(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?a(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(o(n,e,t),delete n[e])}),n}var a=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},o=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},s=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},c=e=>{let{groups:t,path:n}=l(e),r=s(n);return u(r,t)},l=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},u=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},d={},f=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return d[r]||(n[2]?d[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:d[r]=[e,n[1],!0]),d[r]}return null},p=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},m=e=>p(e,decodeURI),h=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.slice(n,e===-1?void 0:e);return m(i.includes(`%25`)?i.replace(/%25/g,`%2525`):i)}else if(e===63)break}return t.slice(n,r)},g=e=>{let t=h(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},_=(e,t,...n)=>(n.length&&(t=_(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),ee=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e))if(/\?/.test(e)){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.replace(`?`,``);r+=`/`+t,n.push(r)}else r+=`/`+e}),n.filter((e,t,n)=>n.indexOf(e)===t)},v=e=>/[%+]/.test(e)?(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),e.indexOf(`%`)===-1?e:p(e,b)):e,y=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let n=e.indexOf(`?${t}`,8);for(n===-1&&(n=e.indexOf(`&${t}`,8));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return v(e.slice(r,i===-1?void 0:i))}else if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(r=/[%+]/.test(e),!r)return}let i={};r??=/[%+]/.test(e);let a=e.indexOf(`?`,8);for(;a!==-1;){let t=e.indexOf(`&`,a+1),o=e.indexOf(`=`,a);o>t&&t!==-1&&(o=-1);let s=e.slice(a+1,o===-1?t===-1?void 0:t:o);if(r&&(s=v(s)),a=t,s===``)continue;let c;o===-1?c=``:(c=e.slice(o+1,t===-1?void 0:t),r&&(c=v(c))),n?(i[s]&&Array.isArray(i[s])||(i[s]=[]),i[s].push(c)):i[s]??=c}return t?i[t]:i},te=y,ne=(e,t)=>y(e,t,!0),b=decodeURIComponent,x=e=>p(e,b),S=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?x(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?x(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return te(this.url,e)}queries(e){return ne(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await n(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[t](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},re={Stringify:1,BeforeStream:2,Stream:3},ie=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},C=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>C(e,t,!1,r,i))).then(()=>i[0]));return n?ie(await o,a):o},ae=`text/plain; charset=UTF-8`,w=(e,t)=>({"Content-Type":e,...t}),oe=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new S(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,w(ae,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,w(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,w(`text/html; charset=UTF-8`,n));return typeof e==`object`?C(e,re.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},T=`ALL`,se=`all`,ce=[`get`,`post`,`put`,`delete`,`options`,`patch`],E=`Can not add a route since the matcher is already built.`,D=class extends Error{},le=`__COMPOSED_HANDLER`,ue=e=>e.text(`404 Not Found`,404),O=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},k=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...ce,se];t.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(T,this.#path,e)}),this);let{strict:n,...r}=e;Object.assign(this,r),this.getPath=n??!0?e.getPath??h:g}#clone(){let e=new k({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=ue;errorHandler=O;route(t,n){let r=this.basePath(t);return n.routes.map(t=>{let i;n.errorHandler===O?i=t.handler:(i=async(r,i)=>(await e([],n.errorHandler)(r,()=>t.handler(r,i))).res,i[le]=t.handler),r.#addRoute(t.method,t.path,i)}),this}basePath(e){let t=this.#clone();return t._basePath=_(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};r||=(()=>{let t=_(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(n)||`/`,new Request(t,e)}})();let o=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#addRoute(T,_(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=_(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(t,n,r,i){if(i===`HEAD`)return(async()=>new Response(null,await this.#dispatch(t,n,r,`GET`)))();let a=this.getPath(t,{env:r}),o=this.router.match(i,a),s=new oe(t,{path:a,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#notFoundHandler});if(o[0].length===1){let e;try{e=o[0][0][0][0](s,async()=>{s.res=await this.#notFoundHandler(s)})}catch(e){return this.#handleError(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#notFoundHandler(s))).catch(e=>this.#handleError(e,s)):e??this.#notFoundHandler(s)}let c=e(o[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await c(s);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,s)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${_(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},A=`[^/]+`,j=`.*`,M=`(?:|/.*)`,N=Symbol(),de=new Set(`.\\+*[^]$()`);function fe(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===j||e===M?1:t===j||t===M?-1:e===A?1:t===A?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var P=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw N;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,j]:[``,``,A]:a===`/*`?[``,``,M]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||A;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw N;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==j&&e!==M))throw N;if(i)return;c=this.#children[t]=new P,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==j&&e!==M))throw N;if(i)return;c=this.#children[a]=new P}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(fe),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:de.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},pe=class{#context={varIndex:0};#root=new P;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},F=[],me=[/^$/,[],Object.create(null)],I=Object.create(null);function L(e){return I[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function he(){I=Object.create(null)}function ge(e){let t=new pe,n=[];if(e.length===0)return me;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),F]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===N?new D(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function R(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(L(n).test(t))return[...e[n]]}}var _e=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[T]:Object.create(null)},this.#routes={[T]:Object.create(null)}}add(e,t,n){let r=this.#middleware,i=this.#routes;if(!r||!i)throw Error(E);r[e]||[r,i].forEach(t=>{t[e]=Object.create(null),Object.keys(t[T]).forEach(n=>{t[e][n]=[...t[T][n]]})}),t===`/*`&&(t=`*`);let a=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let o=L(t);e===T?Object.keys(r).forEach(e=>{r[e][t]||=R(r[e],t)||R(r[T],t)||[]}):r[e][t]||=R(r[e],t)||R(r[T],t)||[],Object.keys(r).forEach(t=>{(e===T||e===t)&&Object.keys(r[t]).forEach(e=>{o.test(e)&&r[t][e].push([n,a])})}),Object.keys(i).forEach(t=>{(e===T||e===t)&&Object.keys(i[t]).forEach(e=>o.test(e)&&i[t][e].push([n,a]))});return}let o=ee(t)||[t];for(let t=0,s=o.length;t<s;t++){let c=o[t];Object.keys(i).forEach(o=>{(e===T||e===o)&&(i[o][c]||=[...R(r[o],c)||R(r[T],c)||[]],i[o][c].push([n,a-s+t+1]))})}}match(e,t){he();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[T],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],F];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===T;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==T&&t.push(...Object.keys(r[T]).map(e=>[e,r[T][e]])):(n||=!0,t.push(...i))}),n?ge(t):null}},ve=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(E);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof D)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},z=Object.create(null),B=class{#methods;#children;#patterns;#order=0;#params=z;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(e,t,n){this.#order=++this.#order;let r=this,i=c(t),a=[];for(let e=0,t=i.length;e<t;e++){let t=i[e],n=i[e+1],o=f(t,n),s=Array.isArray(o)?o[0]:t;if(s in r.#children){r=r.#children[s],o&&a.push(o[1]);continue}r.#children[s]=new B,o&&(r.#patterns.push(o),a.push(o[1])),r=r.#children[s]}return r.#methods.push({[e]:{handler:n,possibleKeys:a.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),r}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[T],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==z||r&&r!==z))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(e,t){let n=[];this.#params=z;let r=this,i=[r],a=s(t),o=[];for(let t=0,r=a.length;t<r;t++){let s=a[t],c=t===r-1,l=[];for(let r=0,u=i.length;r<u;r++){let u=i[r],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&n.push(...this.#getHandlerSets(d.#children[`*`],e,u.#params)),n.push(...this.#getHandlerSets(d,e,u.#params))):l.push(d));for(let r=0,i=u.#patterns.length;r<i;r++){let i=u.#patterns[r],d=u.#params===z?{}:{...u.#params};if(i===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.slice(t).join(`/`);if(m instanceof RegExp){let t=m.exec(g);if(t){if(d[p]=t[0],n.push(...this.#getHandlerSets(h,e,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let e=t[0].match(/\//)?.length??0,n=o[e]||=[];n.push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(n.push(...this.#getHandlerSets(h,e,d,u.#params)),h.#children[`*`]&&n.push(...this.#getHandlerSets(h.#children[`*`],e,d,u.#params))):(h.#params=d,l.push(h)))}}i=l.concat(o.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},ye=class{name=`TrieRouter`;#node;constructor(){this.#node=new B}add(e,t,n){let r=ee(t);if(r){for(let t=0,i=r.length;t<i;t++)this.#node.insert(e,r[t],n);return}this.#node.insert(e,t,n)}match(e,t){return this.#node.search(e,t)}},V=class extends k{constructor(e={}){super(e),this.router=e.router??new ve({routers:[new _e,new ye]})}},be=/^[\w!#$%&'*.^`|~+-]+$/,xe=/^[ !#-:<-[\]-~]*$/,H=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.trim().split(`;`),r={};for(let e of n){e=e.trim();let n=e.indexOf(`=`);if(n===-1)continue;let i=e.substring(0,n).trim();if(t&&t!==i||!be.test(i))continue;let a=e.substring(n+1).trim();if(a.startsWith(`"`)&&a.endsWith(`"`)&&(a=a.slice(1,-1)),xe.test(a)&&(r[i]=a.indexOf(`%`)===-1?a:p(a,b),t))break}return r},Se=(e,t,n={})=>{let r=`${e}=${t}`;if(e.startsWith(`__Secure-`)&&!n.secure)throw Error(`__Secure- Cookie must have Secure attributes`);if(e.startsWith(`__Host-`)){if(!n.secure)throw Error(`__Host- Cookie must have Secure attributes`);if(n.path!==`/`)throw Error(`__Host- Cookie must have Path attributes with "/"`);if(n.domain)throw Error(`__Host- Cookie must not have Domain attributes`)}if(n&&typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!==`host`&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(r+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw Error(`Partitioned Cookie must have Secure attributes`);r+=`; Partitioned`}return r},Ce=(e,t,n)=>(t=encodeURIComponent(t),Se(e,t,n)),we=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t);let i=H(r,e);return i[e]}if(!r)return{};let i=H(r);return i},U=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},Te=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},Ee=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,De=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,Oe=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,W=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!Ee.test(a))break;try{i=await n.req.json()}catch{throw new U(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(De.test(a)||Oe.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await Te(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new U(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=we(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()},ke=(e,t)=>(e=e.replace(/\/+$/,``),e+=`/`,t=t.replace(/^\/+/,``),e+t),G=(e,t)=>{for(let[n,r]of Object.entries(t)){let t=RegExp(`/:`+n+`(?:{[^/]+})?\\??`);e=e.replace(t,r?`/${r}`:``)}return e},K=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e)){if(r===void 0)continue;if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r)}return t},Ae=(e,t)=>{switch(t){case`ws`:return e.replace(/^http/,`ws`);case`http`:return e.replace(/^ws/,`http`)}},q=e=>/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test(e)?e.replace(/\/index(?=\?|$)/,`/`):e.replace(/\/index(?=\?|$)/,``);function J(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Y(e,t){if(!J(e)&&!J(t))return t;let n={...e};for(let e in t){let r=t[e];J(n[e])&&J(r)?n[e]=Y(n[e],r):n[e]=r}return n}var X=(e,t)=>{let n=new Proxy(()=>{},{get(n,r){if(!(typeof r!=`string`||r===`then`))return X(e,[...t,r])},apply(n,r,i){return e({path:t,args:i})}});return n},je=class{url;method;queryParams=void 0;pathParams={};rBody;cType=void 0;constructor(e,t){this.url=e,this.method=t}fetch=async(e,t)=>{if(e){if(e.query&&(this.queryParams=K(e.query)),e.form){let t=new FormData;for(let[n,r]of Object.entries(e.form))if(Array.isArray(r))for(let e of r)t.append(n,e);else t.append(n,r);this.rBody=t}e.json&&(this.rBody=JSON.stringify(e.json),this.cType=`application/json`),e.param&&(this.pathParams=e.param)}let n=this.method.toUpperCase(),r={...e?.header,...typeof t?.headers==`function`?await t.headers():t?.headers};if(e?.cookie){let t=[];for(let[n,r]of Object.entries(e.cookie))t.push(Ce(n,r,{path:`/`}));r.Cookie=t.join(`,`)}this.cType&&(r[`Content-Type`]=this.cType);let i=new Headers(r??void 0),a=this.url;a=q(a),a=G(a,this.pathParams),this.queryParams&&(a=a+`?`+this.queryParams.toString()),n=this.method.toUpperCase();let o=!(n===`GET`||n===`HEAD`);return(t?.fetch||fetch)(a,{body:o?this.rBody:void 0,method:n,headers:i,...t?.init})}},Me=(e,t)=>X(function n(r){let i=[...r.path],a=i.slice(-3).reverse();if(a[0]===`toString`)return a[1]===`name`?a[2]||``:n.toString();if(a[0]===`valueOf`)return a[1]===`name`?a[2]||``:n;let o=``;if(/^\$/.test(a[0])){let e=i.pop();e&&(o=e.replace(/^\$/,``))}let s=i.join(`/`),c=ke(e,s);if(o===`url`){let e=c;return r.args[0]&&(r.args[0].param&&(e=G(c,r.args[0].param)),r.args[0].query&&(e=e+`?`+K(r.args[0].query).toString())),e=q(e),new URL(e)}if(o===`ws`){let e=Ae(r.args[0]&&r.args[0].param?G(c,r.args[0].param):c,`ws`),n=new URL(e),i=r.args[0]?.query;i&&Object.entries(i).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>n.searchParams.append(e,t)):n.searchParams.set(e,t)});let a=(...e)=>t?.webSocket!==void 0&&typeof t.webSocket==`function`?t.webSocket(...e):new WebSocket(...e);return a(n.toString())}let l=new je(c,o);if(o){t??={};let e=Y(t,{...r.args[1]});return l.fetch(r.args[0],e)}return l},[]);const Ne=`BLINK_API_SERVER_URL`,Pe=process.env[Ne],Fe=Me(Pe??``,{fetch:Pe?void 0:async()=>{throw console.warn(`Your code is attempting to use the Blink API server, but no API server is configured for this Blink agent.`),Error(`No API server is configured for this Blink agent. External APIs are not available.`)}}),Z=(e,t)=>e.json({error:t},400),Q=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Ie=()=>new V,Le=Ie().get(`/kv/:key`,async e=>{let{key:t,err:n}=Q(e);if(n)return Z(e,n);let r=await e.env.storage.kv.get(t);return e.json({value:r},200)}).post(`/kv/:key`,W(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?Z(t,`Value is too long. Max length is 1024 characters.`):{value:n}:Z(t,`Value must be a string`):Z(t,`Value is required`)}),async e=>{let{key:t,err:n}=Q(e);if(n)return Z(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.kv.set(t,r),e.body(null,204)}).delete(`/kv/:key`,async e=>{let{key:t,err:n}=Q(e);return n?Z(e,n):(await e.env.storage.kv.del(t),e.body(null,204))}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},Re=Ie().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return Z(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,W(`json`,(e,t)=>{let n=e.messages;if(!n)return Z(t,`Messages are required`);if(!Array.isArray(n))return Z(t,`Messages must be an array`);if(n.length===0)return Z(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?Z(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return Z(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);try{await e.env.chat.sendMessages(t,{messages:r,behavior:i})}catch(t){return Z(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),ze=new V().route(`/storage`,Le).route(`/chat`,Re);var Be=ze;exports.APIServerURLEnvironmentVariable=Ne,exports.default=Be;
|
package/dist/http/api.d.cts
CHANGED
|
@@ -13,6 +13,14 @@ interface Message<METADATA = unknown, DATA_TYPES extends UIDataTypes = UIDataTyp
|
|
|
13
13
|
readonly metadata?: METADATA;
|
|
14
14
|
}
|
|
15
15
|
//#endregion
|
|
16
|
+
//#region src/api/internal/client.d.ts
|
|
17
|
+
/**
|
|
18
|
+
* APIServerURLEnvironmentVariable is the environment variable that
|
|
19
|
+
* the Blink agent uses for executions to the `blink.*` API.
|
|
20
|
+
* (e.g. blink.chat.upsert).
|
|
21
|
+
*/
|
|
22
|
+
declare const APIServerURLEnvironmentVariable = "BLINK_API_SERVER_URL";
|
|
23
|
+
//#endregion
|
|
16
24
|
//#region src/http/api.d.ts
|
|
17
25
|
/**
|
|
18
26
|
* APIBindings are functions that will be invoked by the agent.
|
|
@@ -193,4 +201,4 @@ declare const api: hono_hono_base0.HonoBase<{
|
|
|
193
201
|
};
|
|
194
202
|
}, "/chat">, "/">;
|
|
195
203
|
//#endregion
|
|
196
|
-
export { APIBindings, api as default };
|
|
204
|
+
export { APIBindings, APIServerURLEnvironmentVariable, api as default };
|
package/dist/http/api.d.ts
CHANGED
|
@@ -13,6 +13,14 @@ interface Message<METADATA = unknown, DATA_TYPES extends UIDataTypes = UIDataTyp
|
|
|
13
13
|
readonly metadata?: METADATA;
|
|
14
14
|
}
|
|
15
15
|
//#endregion
|
|
16
|
+
//#region src/api/internal/client.d.ts
|
|
17
|
+
/**
|
|
18
|
+
* APIServerURLEnvironmentVariable is the environment variable that
|
|
19
|
+
* the Blink agent uses for executions to the `blink.*` API.
|
|
20
|
+
* (e.g. blink.chat.upsert).
|
|
21
|
+
*/
|
|
22
|
+
declare const APIServerURLEnvironmentVariable = "BLINK_API_SERVER_URL";
|
|
23
|
+
//#endregion
|
|
16
24
|
//#region src/http/api.d.ts
|
|
17
25
|
/**
|
|
18
26
|
* APIBindings are functions that will be invoked by the agent.
|
|
@@ -193,4 +201,4 @@ declare const api: hono_hono_base0.HonoBase<{
|
|
|
193
201
|
};
|
|
194
202
|
}, "/chat">, "/">;
|
|
195
203
|
//#endregion
|
|
196
|
-
export { APIBindings, api as default };
|
|
204
|
+
export { APIBindings, APIServerURLEnvironmentVariable, api as default };
|
package/dist/http/api.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},t=Symbol(),n=async(e,t=Object.create(null))=>{let{all:n=!1,dot:i=!1}=t,a=e instanceof C?e.raw.headers:e.headers,o=a.get(`Content-Type`);return o?.startsWith(`multipart/form-data`)||o?.startsWith(`application/x-www-form-urlencoded`)?r(e,{all:n,dot:i}):{}};async function r(e,t){let n=await e.formData();return n?i(n,t):{}}function i(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?a(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(o(n,e,t),delete n[e])}),n}var a=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},o=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},s=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},c=e=>{let{groups:t,path:n}=l(e),r=s(n);return u(r,t)},l=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},u=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},d={},f=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return d[r]||(n[2]?d[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:d[r]=[e,n[1],!0]),d[r]}return null},p=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},m=e=>p(e,decodeURI),h=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.slice(n,e===-1?void 0:e);return m(i.includes(`%25`)?i.replace(/%25/g,`%2525`):i)}else if(e===63)break}return t.slice(n,r)},g=e=>{let t=h(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},_=(e,t,...n)=>(n.length&&(t=_(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),v=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e))if(/\?/.test(e)){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.replace(`?`,``);r+=`/`+t,n.push(r)}else r+=`/`+e}),n.filter((e,t,n)=>n.indexOf(e)===t)},y=e=>/[%+]/.test(e)?(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),e.indexOf(`%`)===-1?e:p(e,x)):e,b=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let n=e.indexOf(`?${t}`,8);for(n===-1&&(n=e.indexOf(`&${t}`,8));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return y(e.slice(r,i===-1?void 0:i))}else if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(r=/[%+]/.test(e),!r)return}let i={};r??=/[%+]/.test(e);let a=e.indexOf(`?`,8);for(;a!==-1;){let t=e.indexOf(`&`,a+1),o=e.indexOf(`=`,a);o>t&&t!==-1&&(o=-1);let s=e.slice(a+1,o===-1?t===-1?void 0:t:o);if(r&&(s=y(s)),a=t,s===``)continue;let c;o===-1?c=``:(c=e.slice(o+1,t===-1?void 0:t),r&&(c=y(c))),n?(i[s]&&Array.isArray(i[s])||(i[s]=[]),i[s].push(c)):i[s]??=c}return t?i[t]:i},ee=b,te=(e,t)=>b(e,t,!0),x=decodeURIComponent,S=e=>p(e,x),C=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?S(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?S(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return ee(this.url,e)}queries(e){return te(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await n(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[t](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},ne={Stringify:1,BeforeStream:2,Stream:3},re=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},w=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>w(e,t,!1,r,i))).then(()=>i[0]));return n?re(await o,a):o},ie=`text/plain; charset=UTF-8`,T=(e,t)=>({"Content-Type":e,...t}),E=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new C(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,T(ie,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,T(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,T(`text/html; charset=UTF-8`,n));return typeof e==`object`?w(e,ne.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},D=`ALL`,O=`all`,ae=[`get`,`post`,`put`,`delete`,`options`,`patch`],k=`Can not add a route since the matcher is already built.`,A=class extends Error{},oe=`__COMPOSED_HANDLER`,se=e=>e.text(`404 Not Found`,404),j=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},M=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...ae,O];t.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(D,this.#path,e)}),this);let{strict:n,...r}=e;Object.assign(this,r),this.getPath=n??!0?e.getPath??h:g}#clone(){let e=new M({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=se;errorHandler=j;route(t,n){let r=this.basePath(t);return n.routes.map(t=>{let i;n.errorHandler===j?i=t.handler:(i=async(r,i)=>(await e([],n.errorHandler)(r,()=>t.handler(r,i))).res,i[oe]=t.handler),r.#addRoute(t.method,t.path,i)}),this}basePath(e){let t=this.#clone();return t._basePath=_(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};r||=(()=>{let t=_(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(n)||`/`,new Request(t,e)}})();let o=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#addRoute(D,_(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=_(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(t,n,r,i){if(i===`HEAD`)return(async()=>new Response(null,await this.#dispatch(t,n,r,`GET`)))();let a=this.getPath(t,{env:r}),o=this.router.match(i,a),s=new E(t,{path:a,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#notFoundHandler});if(o[0].length===1){let e;try{e=o[0][0][0][0](s,async()=>{s.res=await this.#notFoundHandler(s)})}catch(e){return this.#handleError(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#notFoundHandler(s))).catch(e=>this.#handleError(e,s)):e??this.#notFoundHandler(s)}let c=e(o[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await c(s);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,s)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${_(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},N=`[^/]+`,P=`.*`,F=`(?:|/.*)`,I=Symbol(),ce=new Set(`.\\+*[^]$()`);function le(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===P||e===F?1:t===P||t===F?-1:e===N?1:t===N?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var L=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw I;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,P]:[``,``,N]:a===`/*`?[``,``,F]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||N;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw I;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==P&&e!==F))throw I;if(i)return;c=this.#children[t]=new L,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==P&&e!==F))throw I;if(i)return;c=this.#children[a]=new L}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(le),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:ce.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},ue=class{#context={varIndex:0};#root=new L;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},R=[],de=[/^$/,[],Object.create(null)],z=Object.create(null);function B(e){return z[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function V(){z=Object.create(null)}function H(e){let t=new ue,n=[];if(e.length===0)return de;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),R]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===I?new A(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function U(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(B(n).test(t))return[...e[n]]}}var fe=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[D]:Object.create(null)},this.#routes={[D]:Object.create(null)}}add(e,t,n){let r=this.#middleware,i=this.#routes;if(!r||!i)throw Error(k);r[e]||[r,i].forEach(t=>{t[e]=Object.create(null),Object.keys(t[D]).forEach(n=>{t[e][n]=[...t[D][n]]})}),t===`/*`&&(t=`*`);let a=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let o=B(t);e===D?Object.keys(r).forEach(e=>{r[e][t]||=U(r[e],t)||U(r[D],t)||[]}):r[e][t]||=U(r[e],t)||U(r[D],t)||[],Object.keys(r).forEach(t=>{(e===D||e===t)&&Object.keys(r[t]).forEach(e=>{o.test(e)&&r[t][e].push([n,a])})}),Object.keys(i).forEach(t=>{(e===D||e===t)&&Object.keys(i[t]).forEach(e=>o.test(e)&&i[t][e].push([n,a]))});return}let o=v(t)||[t];for(let t=0,s=o.length;t<s;t++){let c=o[t];Object.keys(i).forEach(o=>{(e===D||e===o)&&(i[o][c]||=[...U(r[o],c)||U(r[D],c)||[]],i[o][c].push([n,a-s+t+1]))})}}match(e,t){V();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[D],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],R];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===D;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==D&&t.push(...Object.keys(r[D]).map(e=>[e,r[D][e]])):(n||=!0,t.push(...i))}),n?H(t):null}},pe=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(k);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof A)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},W=Object.create(null),G=class{#methods;#children;#patterns;#order=0;#params=W;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(e,t,n){this.#order=++this.#order;let r=this,i=c(t),a=[];for(let e=0,t=i.length;e<t;e++){let t=i[e],n=i[e+1],o=f(t,n),s=Array.isArray(o)?o[0]:t;if(s in r.#children){r=r.#children[s],o&&a.push(o[1]);continue}r.#children[s]=new G,o&&(r.#patterns.push(o),a.push(o[1])),r=r.#children[s]}return r.#methods.push({[e]:{handler:n,possibleKeys:a.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),r}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[D],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==W||r&&r!==W))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(e,t){let n=[];this.#params=W;let r=this,i=[r],a=s(t),o=[];for(let t=0,r=a.length;t<r;t++){let s=a[t],c=t===r-1,l=[];for(let r=0,u=i.length;r<u;r++){let u=i[r],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&n.push(...this.#getHandlerSets(d.#children[`*`],e,u.#params)),n.push(...this.#getHandlerSets(d,e,u.#params))):l.push(d));for(let r=0,i=u.#patterns.length;r<i;r++){let i=u.#patterns[r],d=u.#params===W?{}:{...u.#params};if(i===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.slice(t).join(`/`);if(m instanceof RegExp){let t=m.exec(g);if(t){if(d[p]=t[0],n.push(...this.#getHandlerSets(h,e,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let e=t[0].match(/\//)?.length??0,n=o[e]||=[];n.push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(n.push(...this.#getHandlerSets(h,e,d,u.#params)),h.#children[`*`]&&n.push(...this.#getHandlerSets(h.#children[`*`],e,d,u.#params))):(h.#params=d,l.push(h)))}}i=l.concat(o.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},me=class{name=`TrieRouter`;#node;constructor(){this.#node=new G}add(e,t,n){let r=v(t);if(r){for(let t=0,i=r.length;t<i;t++)this.#node.insert(e,r[t],n);return}this.#node.insert(e,t,n)}match(e,t){return this.#node.search(e,t)}},K=class extends M{constructor(e={}){super(e),this.router=e.router??new pe({routers:[new fe,new me]})}},he=/^[\w!#$%&'*.^`|~+-]+$/,ge=/^[ !#-:<-[\]-~]*$/,q=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.trim().split(`;`),r={};for(let e of n){e=e.trim();let n=e.indexOf(`=`);if(n===-1)continue;let i=e.substring(0,n).trim();if(t&&t!==i||!he.test(i))continue;let a=e.substring(n+1).trim();if(a.startsWith(`"`)&&a.endsWith(`"`)&&(a=a.slice(1,-1)),ge.test(a)&&(r[i]=a.indexOf(`%`)===-1?a:p(a,x),t))break}return r},_e=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t);let i=q(r,e);return i[e]}if(!r)return{};let i=q(r);return i},J=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},ve=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},ye=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,be=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,xe=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Y=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!ye.test(a))break;try{i=await n.req.json()}catch{throw new J(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(be.test(a)||xe.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await ve(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new J(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=_e(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const X=(e,t)=>e.json({error:t},400),Z=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Q=()=>new K,Se=Q().get(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.storage.kv.get(t);return e.json({value:r},200)}).post(`/kv/:key`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?X(t,`Value is too long. Max length is 1024 characters.`):{value:n}:X(t,`Value must be a string`):X(t,`Value is required`)}),async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.kv.set(t,r),e.body(null,204)}).delete(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);return n?X(e,n):(await e.env.storage.kv.del(t),e.body(null,204))}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},Ce=Q().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Y(`json`,(e,t)=>{let n=e.messages;if(!n)return X(t,`Messages are required`);if(!Array.isArray(n))return X(t,`Messages must be an array`);if(n.length===0)return X(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?X(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);try{await e.env.chat.sendMessages(t,{messages:r,behavior:i})}catch(t){return X(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),we=new K().route(`/storage`,Se).route(`/chat`,Ce);var Te=we;export{Te as default};
|
|
1
|
+
var e=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},t=Symbol(),n=async(e,t=Object.create(null))=>{let{all:n=!1,dot:i=!1}=t,a=e instanceof S?e.raw.headers:e.headers,o=a.get(`Content-Type`);return o?.startsWith(`multipart/form-data`)||o?.startsWith(`application/x-www-form-urlencoded`)?r(e,{all:n,dot:i}):{}};async function r(e,t){let n=await e.formData();return n?i(n,t):{}}function i(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?a(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(o(n,e,t),delete n[e])}),n}var a=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},o=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},s=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},c=e=>{let{groups:t,path:n}=l(e),r=s(n);return u(r,t)},l=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},u=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},d={},f=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return d[r]||(n[2]?d[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:d[r]=[e,n[1],!0]),d[r]}return null},p=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},m=e=>p(e,decodeURI),h=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.slice(n,e===-1?void 0:e);return m(i.includes(`%25`)?i.replace(/%25/g,`%2525`):i)}else if(e===63)break}return t.slice(n,r)},g=e=>{let t=h(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},_=(e,t,...n)=>(n.length&&(t=_(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),ee=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e))if(/\?/.test(e)){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.replace(`?`,``);r+=`/`+t,n.push(r)}else r+=`/`+e}),n.filter((e,t,n)=>n.indexOf(e)===t)},v=e=>/[%+]/.test(e)?(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),e.indexOf(`%`)===-1?e:p(e,b)):e,y=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let n=e.indexOf(`?${t}`,8);for(n===-1&&(n=e.indexOf(`&${t}`,8));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return v(e.slice(r,i===-1?void 0:i))}else if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(r=/[%+]/.test(e),!r)return}let i={};r??=/[%+]/.test(e);let a=e.indexOf(`?`,8);for(;a!==-1;){let t=e.indexOf(`&`,a+1),o=e.indexOf(`=`,a);o>t&&t!==-1&&(o=-1);let s=e.slice(a+1,o===-1?t===-1?void 0:t:o);if(r&&(s=v(s)),a=t,s===``)continue;let c;o===-1?c=``:(c=e.slice(o+1,t===-1?void 0:t),r&&(c=v(c))),n?(i[s]&&Array.isArray(i[s])||(i[s]=[]),i[s].push(c)):i[s]??=c}return t?i[t]:i},te=y,ne=(e,t)=>y(e,t,!0),b=decodeURIComponent,x=e=>p(e,b),S=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?x(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?x(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return te(this.url,e)}queries(e){return ne(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await n(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[t](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},re={Stringify:1,BeforeStream:2,Stream:3},ie=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},C=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>C(e,t,!1,r,i))).then(()=>i[0]));return n?ie(await o,a):o},ae=`text/plain; charset=UTF-8`,w=(e,t)=>({"Content-Type":e,...t}),oe=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new S(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,w(ae,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,w(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,w(`text/html; charset=UTF-8`,n));return typeof e==`object`?C(e,re.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},T=`ALL`,se=`all`,ce=[`get`,`post`,`put`,`delete`,`options`,`patch`],E=`Can not add a route since the matcher is already built.`,D=class extends Error{},le=`__COMPOSED_HANDLER`,ue=e=>e.text(`404 Not Found`,404),O=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},k=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...ce,se];t.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(T,this.#path,e)}),this);let{strict:n,...r}=e;Object.assign(this,r),this.getPath=n??!0?e.getPath??h:g}#clone(){let e=new k({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=ue;errorHandler=O;route(t,n){let r=this.basePath(t);return n.routes.map(t=>{let i;n.errorHandler===O?i=t.handler:(i=async(r,i)=>(await e([],n.errorHandler)(r,()=>t.handler(r,i))).res,i[le]=t.handler),r.#addRoute(t.method,t.path,i)}),this}basePath(e){let t=this.#clone();return t._basePath=_(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};r||=(()=>{let t=_(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(n)||`/`,new Request(t,e)}})();let o=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#addRoute(T,_(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=_(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(t,n,r,i){if(i===`HEAD`)return(async()=>new Response(null,await this.#dispatch(t,n,r,`GET`)))();let a=this.getPath(t,{env:r}),o=this.router.match(i,a),s=new oe(t,{path:a,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#notFoundHandler});if(o[0].length===1){let e;try{e=o[0][0][0][0](s,async()=>{s.res=await this.#notFoundHandler(s)})}catch(e){return this.#handleError(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#notFoundHandler(s))).catch(e=>this.#handleError(e,s)):e??this.#notFoundHandler(s)}let c=e(o[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await c(s);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,s)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${_(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},A=`[^/]+`,j=`.*`,M=`(?:|/.*)`,N=Symbol(),de=new Set(`.\\+*[^]$()`);function fe(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===j||e===M?1:t===j||t===M?-1:e===A?1:t===A?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var P=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw N;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,j]:[``,``,A]:a===`/*`?[``,``,M]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||A;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw N;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==j&&e!==M))throw N;if(i)return;c=this.#children[t]=new P,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==j&&e!==M))throw N;if(i)return;c=this.#children[a]=new P}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(fe),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:de.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},pe=class{#context={varIndex:0};#root=new P;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},F=[],me=[/^$/,[],Object.create(null)],I=Object.create(null);function L(e){return I[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function he(){I=Object.create(null)}function ge(e){let t=new pe,n=[];if(e.length===0)return me;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),F]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===N?new D(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function R(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(L(n).test(t))return[...e[n]]}}var _e=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[T]:Object.create(null)},this.#routes={[T]:Object.create(null)}}add(e,t,n){let r=this.#middleware,i=this.#routes;if(!r||!i)throw Error(E);r[e]||[r,i].forEach(t=>{t[e]=Object.create(null),Object.keys(t[T]).forEach(n=>{t[e][n]=[...t[T][n]]})}),t===`/*`&&(t=`*`);let a=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let o=L(t);e===T?Object.keys(r).forEach(e=>{r[e][t]||=R(r[e],t)||R(r[T],t)||[]}):r[e][t]||=R(r[e],t)||R(r[T],t)||[],Object.keys(r).forEach(t=>{(e===T||e===t)&&Object.keys(r[t]).forEach(e=>{o.test(e)&&r[t][e].push([n,a])})}),Object.keys(i).forEach(t=>{(e===T||e===t)&&Object.keys(i[t]).forEach(e=>o.test(e)&&i[t][e].push([n,a]))});return}let o=ee(t)||[t];for(let t=0,s=o.length;t<s;t++){let c=o[t];Object.keys(i).forEach(o=>{(e===T||e===o)&&(i[o][c]||=[...R(r[o],c)||R(r[T],c)||[]],i[o][c].push([n,a-s+t+1]))})}}match(e,t){he();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[T],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],F];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===T;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==T&&t.push(...Object.keys(r[T]).map(e=>[e,r[T][e]])):(n||=!0,t.push(...i))}),n?ge(t):null}},ve=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(E);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof D)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},z=Object.create(null),B=class{#methods;#children;#patterns;#order=0;#params=z;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(e,t,n){this.#order=++this.#order;let r=this,i=c(t),a=[];for(let e=0,t=i.length;e<t;e++){let t=i[e],n=i[e+1],o=f(t,n),s=Array.isArray(o)?o[0]:t;if(s in r.#children){r=r.#children[s],o&&a.push(o[1]);continue}r.#children[s]=new B,o&&(r.#patterns.push(o),a.push(o[1])),r=r.#children[s]}return r.#methods.push({[e]:{handler:n,possibleKeys:a.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),r}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[T],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==z||r&&r!==z))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(e,t){let n=[];this.#params=z;let r=this,i=[r],a=s(t),o=[];for(let t=0,r=a.length;t<r;t++){let s=a[t],c=t===r-1,l=[];for(let r=0,u=i.length;r<u;r++){let u=i[r],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&n.push(...this.#getHandlerSets(d.#children[`*`],e,u.#params)),n.push(...this.#getHandlerSets(d,e,u.#params))):l.push(d));for(let r=0,i=u.#patterns.length;r<i;r++){let i=u.#patterns[r],d=u.#params===z?{}:{...u.#params};if(i===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.slice(t).join(`/`);if(m instanceof RegExp){let t=m.exec(g);if(t){if(d[p]=t[0],n.push(...this.#getHandlerSets(h,e,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let e=t[0].match(/\//)?.length??0,n=o[e]||=[];n.push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(n.push(...this.#getHandlerSets(h,e,d,u.#params)),h.#children[`*`]&&n.push(...this.#getHandlerSets(h.#children[`*`],e,d,u.#params))):(h.#params=d,l.push(h)))}}i=l.concat(o.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},ye=class{name=`TrieRouter`;#node;constructor(){this.#node=new B}add(e,t,n){let r=ee(t);if(r){for(let t=0,i=r.length;t<i;t++)this.#node.insert(e,r[t],n);return}this.#node.insert(e,t,n)}match(e,t){return this.#node.search(e,t)}},V=class extends k{constructor(e={}){super(e),this.router=e.router??new ve({routers:[new _e,new ye]})}},be=/^[\w!#$%&'*.^`|~+-]+$/,xe=/^[ !#-:<-[\]-~]*$/,H=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.trim().split(`;`),r={};for(let e of n){e=e.trim();let n=e.indexOf(`=`);if(n===-1)continue;let i=e.substring(0,n).trim();if(t&&t!==i||!be.test(i))continue;let a=e.substring(n+1).trim();if(a.startsWith(`"`)&&a.endsWith(`"`)&&(a=a.slice(1,-1)),xe.test(a)&&(r[i]=a.indexOf(`%`)===-1?a:p(a,b),t))break}return r},Se=(e,t,n={})=>{let r=`${e}=${t}`;if(e.startsWith(`__Secure-`)&&!n.secure)throw Error(`__Secure- Cookie must have Secure attributes`);if(e.startsWith(`__Host-`)){if(!n.secure)throw Error(`__Host- Cookie must have Secure attributes`);if(n.path!==`/`)throw Error(`__Host- Cookie must have Path attributes with "/"`);if(n.domain)throw Error(`__Host- Cookie must not have Domain attributes`)}if(n&&typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!==`host`&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(r+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw Error(`Partitioned Cookie must have Secure attributes`);r+=`; Partitioned`}return r},Ce=(e,t,n)=>(t=encodeURIComponent(t),Se(e,t,n)),we=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t);let i=H(r,e);return i[e]}if(!r)return{};let i=H(r);return i},U=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},Te=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},Ee=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,De=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,Oe=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,W=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!Ee.test(a))break;try{i=await n.req.json()}catch{throw new U(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(De.test(a)||Oe.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await Te(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new U(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=we(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()},ke=(e,t)=>(e=e.replace(/\/+$/,``),e+=`/`,t=t.replace(/^\/+/,``),e+t),G=(e,t)=>{for(let[n,r]of Object.entries(t)){let t=RegExp(`/:`+n+`(?:{[^/]+})?\\??`);e=e.replace(t,r?`/${r}`:``)}return e},K=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e)){if(r===void 0)continue;if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r)}return t},Ae=(e,t)=>{switch(t){case`ws`:return e.replace(/^http/,`ws`);case`http`:return e.replace(/^ws/,`http`)}},q=e=>/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test(e)?e.replace(/\/index(?=\?|$)/,`/`):e.replace(/\/index(?=\?|$)/,``);function J(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Y(e,t){if(!J(e)&&!J(t))return t;let n={...e};for(let e in t){let r=t[e];J(n[e])&&J(r)?n[e]=Y(n[e],r):n[e]=r}return n}var X=(e,t)=>{let n=new Proxy(()=>{},{get(n,r){if(!(typeof r!=`string`||r===`then`))return X(e,[...t,r])},apply(n,r,i){return e({path:t,args:i})}});return n},je=class{url;method;queryParams=void 0;pathParams={};rBody;cType=void 0;constructor(e,t){this.url=e,this.method=t}fetch=async(e,t)=>{if(e){if(e.query&&(this.queryParams=K(e.query)),e.form){let t=new FormData;for(let[n,r]of Object.entries(e.form))if(Array.isArray(r))for(let e of r)t.append(n,e);else t.append(n,r);this.rBody=t}e.json&&(this.rBody=JSON.stringify(e.json),this.cType=`application/json`),e.param&&(this.pathParams=e.param)}let n=this.method.toUpperCase(),r={...e?.header,...typeof t?.headers==`function`?await t.headers():t?.headers};if(e?.cookie){let t=[];for(let[n,r]of Object.entries(e.cookie))t.push(Ce(n,r,{path:`/`}));r.Cookie=t.join(`,`)}this.cType&&(r[`Content-Type`]=this.cType);let i=new Headers(r??void 0),a=this.url;a=q(a),a=G(a,this.pathParams),this.queryParams&&(a=a+`?`+this.queryParams.toString()),n=this.method.toUpperCase();let o=!(n===`GET`||n===`HEAD`);return(t?.fetch||fetch)(a,{body:o?this.rBody:void 0,method:n,headers:i,...t?.init})}},Me=(e,t)=>X(function n(r){let i=[...r.path],a=i.slice(-3).reverse();if(a[0]===`toString`)return a[1]===`name`?a[2]||``:n.toString();if(a[0]===`valueOf`)return a[1]===`name`?a[2]||``:n;let o=``;if(/^\$/.test(a[0])){let e=i.pop();e&&(o=e.replace(/^\$/,``))}let s=i.join(`/`),c=ke(e,s);if(o===`url`){let e=c;return r.args[0]&&(r.args[0].param&&(e=G(c,r.args[0].param)),r.args[0].query&&(e=e+`?`+K(r.args[0].query).toString())),e=q(e),new URL(e)}if(o===`ws`){let e=Ae(r.args[0]&&r.args[0].param?G(c,r.args[0].param):c,`ws`),n=new URL(e),i=r.args[0]?.query;i&&Object.entries(i).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>n.searchParams.append(e,t)):n.searchParams.set(e,t)});let a=(...e)=>t?.webSocket!==void 0&&typeof t.webSocket==`function`?t.webSocket(...e):new WebSocket(...e);return a(n.toString())}let l=new je(c,o);if(o){t??={};let e=Y(t,{...r.args[1]});return l.fetch(r.args[0],e)}return l},[]);const Ne=`BLINK_API_SERVER_URL`,Pe=process.env[Ne];Me(Pe??``,{fetch:Pe?void 0:async()=>{throw console.warn(`Your code is attempting to use the Blink API server, but no API server is configured for this Blink agent.`),Error(`No API server is configured for this Blink agent. External APIs are not available.`)}});const Z=(e,t)=>e.json({error:t},400),Q=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Fe=()=>new V,Ie=Fe().get(`/kv/:key`,async e=>{let{key:t,err:n}=Q(e);if(n)return Z(e,n);let r=await e.env.storage.kv.get(t);return e.json({value:r},200)}).post(`/kv/:key`,W(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?Z(t,`Value is too long. Max length is 1024 characters.`):{value:n}:Z(t,`Value must be a string`):Z(t,`Value is required`)}),async e=>{let{key:t,err:n}=Q(e);if(n)return Z(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.kv.set(t,r),e.body(null,204)}).delete(`/kv/:key`,async e=>{let{key:t,err:n}=Q(e);return n?Z(e,n):(await e.env.storage.kv.del(t),e.body(null,204))}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},Le=Fe().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return Z(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,W(`json`,(e,t)=>{let n=e.messages;if(!n)return Z(t,`Messages are required`);if(!Array.isArray(n))return Z(t,`Messages must be an array`);if(n.length===0)return Z(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?Z(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return Z(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);try{await e.env.chat.sendMessages(t,{messages:r,behavior:i})}catch(t){return Z(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),Re=new V().route(`/storage`,Ie).route(`/chat`,Le);var ze=Re;export{Ne as APIServerURLEnvironmentVariable,ze as default};
|
package/dist/http/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=require(`../chunk-hhQzssFb.cjs`),t=require(`../http-
|
|
1
|
+
const e=require(`../chunk-hhQzssFb.cjs`),t=require(`../http-C-hX8Pv2.cjs`);exports.APIServerURLEnvironmentVariable=t.APIServerURLEnvironmentVariable,exports.Client=t.Client,exports.StreamResponseFormatHeader=t.StreamResponseFormatHeader,exports.createAsyncIterableStream=t.createAsyncIterableStream,exports.streamSSE=t.streamSSE;
|
package/dist/http/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import "../index-
|
|
2
|
-
import { APIServerURLEnvironmentVariable, AsyncIterableStream, CapabilitiesResponse, Client, ClientOptions, ExperimentalProvideCompletionsRequest, SendMessagesRequest, StreamResponseFormatHeader, createAsyncIterableStream, streamSSE } from "../index-
|
|
1
|
+
import "../index-CIUoZVwP.js";
|
|
2
|
+
import { APIServerURLEnvironmentVariable, AsyncIterableStream, CapabilitiesResponse, Client, ClientOptions, ExperimentalProvideCompletionsRequest, SendMessagesRequest, StreamResponseFormatHeader, createAsyncIterableStream, streamSSE } from "../index-DPvs3m4c.js";
|
|
3
3
|
export { APIServerURLEnvironmentVariable, AsyncIterableStream, CapabilitiesResponse, Client, ClientOptions, ExperimentalProvideCompletionsRequest, SendMessagesRequest, StreamResponseFormatHeader, createAsyncIterableStream, streamSSE };
|
package/dist/http/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{APIServerURLEnvironmentVariable as e,Client as t,StreamResponseFormatHeader as n,createAsyncIterableStream as r,streamSSE as i}from"../http-
|
|
1
|
+
import{APIServerURLEnvironmentVariable as e,Client as t,StreamResponseFormatHeader as n,createAsyncIterableStream as r,streamSSE as i}from"../http-B_3J2CH3.js";export{e as APIServerURLEnvironmentVariable,t as Client,n as StreamResponseFormatHeader,r as createAsyncIterableStream,i as streamSSE};
|