gemi 0.246.0 → 0.246.2
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/ai/index.js +1 -1
- package/dist/ai/providers/http.d.ts.map +1 -1
- package/dist/ai/providers/stream.d.ts +5 -1
- package/dist/ai/providers/stream.d.ts.map +1 -1
- package/dist/ai/testing/index.js +1 -1
- package/dist/{chunk-p8ypq16v.js → chunk-8adt2k7j.js} +1 -1
- package/dist/{chunk-t56z2zec.js → chunk-gv7eh0wd.js} +1 -1
- package/dist/{chunk-bcpxyv8m.js → chunk-hn2mm9r6.js} +4 -4
- package/dist/{chunk-bcpxyv8m.js.map → chunk-hn2mm9r6.js.map} +4 -4
- package/dist/{chunk-q0k1j5a4.js → chunk-n626761s.js} +1 -1
- package/dist/{chunk-dxtxvxcz.js → chunk-p9trv4kn.js} +2 -2
- package/dist/{chunk-dxtxvxcz.js.map → chunk-p9trv4kn.js.map} +1 -1
- package/dist/chunk-pvs5qjs7.js +5 -0
- package/dist/{chunk-dapd4vkd.js.map → chunk-pvs5qjs7.js.map} +3 -3
- package/dist/{chunk-ggh1hzdb.js → chunk-qqh6h36y.js} +1 -1
- package/dist/{chunk-11fc5nve.js → chunk-tm4kfnqh.js} +1 -1
- package/dist/client/describeCaughtError.d.ts +11 -0
- package/dist/client/describeCaughtError.d.ts.map +1 -0
- package/dist/client/index.js +1 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/init.d.ts.map +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/http/index.js +1 -1
- package/dist/i18n/index.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/file-storage/drivers/FileSystemDriver.d.ts +2 -3
- package/dist/services/file-storage/drivers/FileSystemDriver.d.ts.map +1 -1
- package/dist/services/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-dapd4vkd.js +0 -5
- /package/dist/{chunk-p8ypq16v.js.map → chunk-8adt2k7j.js.map} +0 -0
- /package/dist/{chunk-t56z2zec.js.map → chunk-gv7eh0wd.js.map} +0 -0
- /package/dist/{chunk-q0k1j5a4.js.map → chunk-n626761s.js.map} +0 -0
- /package/dist/{chunk-ggh1hzdb.js.map → chunk-qqh6h36y.js.map} +0 -0
- /package/dist/{chunk-11fc5nve.js.map → chunk-tm4kfnqh.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../client/init.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAa,KAAK,aAAa,EAAE,MAAM,OAAO,CAAC;AAItD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../client/init.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAa,KAAK,aAAa,EAAE,MAAM,OAAO,CAAC;AAItD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAKzD,OAAO,EAGL,KAAK,wBAAwB,EAC9B,MAAM,qBAAqB,CAAC;AAG7B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAEL,KAAK,qBAAqB,EAC3B,MAAM,wBAAwB,CAAC;AAEhC,MAAM,WAAW,WAAW;IAC1B;;;;OAIG;IACH,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B;;;;;;OAMG;IACH,iBAAiB,CAAC,EAAE,wBAAwB,GAAG,KAAK,CAAC;IACrD;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,eAAe,CAAC;IAC3B;;;;;;;;;;;;OAYG;IACH,qBAAqB,CAAC,EAAE,qBAAqB,CAAC;CAC/C;AAmCD,wBAAgB,IAAI,CAClB,UAAU,EAAE,aAAa,CAAC,GAAG,CAAC,EAC9B,OAAO,GAAE,WAAgB,QAgC1B;AAwCD,wBAAgB,MAAM,CACpB,UAAU,EAAE,aAAa,CAAC,GAAG,CAAC,EAC9B,EACE,aAAa,EACb,OAAO,EACP,aAAa,EACb,MAAM,EACN,IAAI,EACJ,IAAI,EACJ,cAAc,EACd,aAAa,GACd,EAAE,GAAG,QAsBP"}
|
package/dist/facades/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$f as i,Cg as q,Ng as r,Og as s,Pg as t,Qg as u,Uf as a,Xf as c,Yf as e,Zf as f,_f as h,ag as j,hg as k,ig as l,jg as m,kg as n,lg as o,mg as p,zh as v}from"../chunk-
|
|
2
|
+
import{$f as i,Cg as q,Ng as r,Og as s,Pg as t,Qg as u,Uf as a,Xf as c,Yf as e,Zf as f,_f as h,ag as j,hg as k,ig as l,jg as m,kg as n,lg as o,mg as p,zh as v}from"../chunk-gv7eh0wd.js";import"../chunk-kjzvrx2p.js";import"../chunk-gmkzq212.js";import{Sj as d}from"../chunk-pvs5qjs7.js";import"../chunk-2kt5kgaq.js";import{bk as b,fk as g}from"../chunk-gx5yhz2m.js";import"../chunk-vq0gcvcy.js";import"../chunk-cyxsmd4q.js";import"../chunk-qbm49b1t.js";import"../chunk-k5vt2kz6.js";import"../chunk-8vzxnjp4.js";import"../chunk-z5wwhgsg.js";import"../chunk-mbfjxyq0.js";import"../chunk-kss2kkmm.js";import"../chunk-n26d4z3t.js";import"../chunk-5npzvdh9.js";import"../chunk-zez3fjnf.js";import"../chunk-xac2vwtq.js";import"../chunk-se0tnb9x.js";import"../chunk-dx4h7rap.js";import"../chunk-w31afsrx.js";import"../chunk-ket76475.js";import"../chunk-jzg9zdtj.js";import"../chunk-748evey0.js";export{f as Url,d as Storage,r as Runs,j as Redis,a as Redirect,l as RateLimiter,e as Query,h as Meta,g as Log,m as Lock,c as Lang,s as Features,b as Facade,u as DB,n as Crypt,i as Cookie,o as Connections,t as ConnectionQueries,p as ChangeFeed,k as Cache,q as Broadcast,v as Auth};
|
|
3
3
|
|
|
4
4
|
//# debugId=EC14808321212D3A64756E2164756E21
|
package/dist/http/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$e as u,$h as na,Ah as ba,Bh as ca,Ch as da,Fh as ea,Gh as fa,Hh as ga,Ih as ha,Sf as K,Tf as L,Vf as M,Wf as N,Wh as ia,Xh as ja,Yg as aa,Yh as ka,Zh as la,_e as t,_h as ma,af as v,ai as oa,bf as w,bi as pa,cf as x,ci as qa,df as E,di as ra,ei as sa,fi as ta,gi as ua,hi as va,if as F,ii as wa,ji as xa,ki as ya,mf as G,nf as H,of as I,pf as J}from"../chunk-
|
|
2
|
+
import{$e as u,$h as na,Ah as ba,Bh as ca,Ch as da,Fh as ea,Gh as fa,Hh as ga,Ih as ha,Sf as K,Tf as L,Vf as M,Wf as N,Wh as ia,Xh as ja,Yg as aa,Yh as ka,Zh as la,_e as t,_h as ma,af as v,ai as oa,bf as w,bi as pa,cf as x,ci as qa,df as E,di as ra,ei as sa,fi as ta,gi as ua,hi as va,if as F,ii as wa,ji as xa,ki as ya,mf as G,nf as H,of as I,pf as J}from"../chunk-gv7eh0wd.js";import"../chunk-kjzvrx2p.js";import"../chunk-gmkzq212.js";import{Bj as O,Cj as P,Dj as Q,Ej as R,Fj as S,Gj as T,Hj as U,Ij as V,Jj as W,Ki as a,Kj as X,Li as b,Lj as Y,Mi as d,Nj as Z,Oj as _,Pj as $,Ri as e,Si as f,Ti as g,Ui as h,Vi as i,Wi as j,Zi as n,cj as o,dj as p,ej as q,fj as r,kj as s,mj as y,nj as z,oj as A,pj as B,qj as C,rj as D}from"../chunk-pvs5qjs7.js";import{Wj as c}from"../chunk-2kt5kgaq.js";import"../chunk-gx5yhz2m.js";import{ik as k,jk as l,kk as m}from"../chunk-vq0gcvcy.js";import"../chunk-cyxsmd4q.js";import"../chunk-qbm49b1t.js";import"../chunk-k5vt2kz6.js";import"../chunk-8vzxnjp4.js";import"../chunk-z5wwhgsg.js";import"../chunk-mbfjxyq0.js";import"../chunk-kss2kkmm.js";import"../chunk-n26d4z3t.js";import"../chunk-5npzvdh9.js";import"../chunk-zez3fjnf.js";import"../chunk-xac2vwtq.js";import"../chunk-se0tnb9x.js";import"../chunk-dx4h7rap.js";import"../chunk-w31afsrx.js";import"../chunk-ket76475.js";import"../chunk-jzg9zdtj.js";import"../chunk-748evey0.js";export{g as toRangeHeaderValue,v as toMiddlewareList,k as stateKey,$ as safeFetch,f as resolveRange,e as parseRangeHeader,h as parseContentRange,r as parseByteSize,ma as middlewareConfigDefaults,u as httpError,d as getCookies,j as formatUnsatisfiedContentRange,i as formatContentRange,ua as defineResourcePolicy,la as defineMiddlewareConfig,n as cspNonce,w as createUnsatisfiableResponse,x as createStreamResponse,M as createFileResponse,I as clientIp,J as clientAddress,Z as classifyAddress,da as authorizeChannel,N as ViewRouter,o as ValidationError,W as TooManyRedirectsError,U as TooLargeError,T as TimeoutError,va as SitemapError,wa as Sitemap,L as SameSiteBounceMiddleware,_ as SafeResponse,O as SafeFetchError,K as SAME_SITE_BOUNCE_PARAM,xa as RobotsTxt,ya as Robots,ta as ResourcePolicy,b as ResourceController,m as RequestState,c as RequestBreakerError,H as RateLimitMiddleware,F as RateLimitExceededError,A as RangeNotSatisfiableError,ra as PoliciesServiceProvider,sa as Policies,q as PayloadTooLargeError,B as NotFoundError,X as NetworkError,l as MissingRequestStateError,G as Middleware,ga as McpToolDeclaration,ha as McpRouter,fa as McpRouteDeclaration,ea as McpModelParam,ka as McpEndpointRoute,ia as McpEndpointError,ja as McpEndpoint,p as InvalidValidationRuleError,P as InvalidUrlError,z as InsufficientPermissionsError,Y as HttpStatusError,t as HttpResponse,s as HttpRequest,C as FileNotFoundError,S as DnsError,pa as CorsMiddleware,a as Controller,V as ContentTypeError,ca as ChannelRouter,ba as ChannelDeclaration,oa as CacheMiddleware,qa as CSRFMiddleware,aa as BodyLimitMiddleware,Q as BlockedHostError,R as BlockedAddressError,y as AuthorizationError,na as AuthenticationMiddleware,D as AuthenticationError,E as ApiRouter};
|
|
3
3
|
|
|
4
4
|
//# debugId=1A8133343F1854B164756E2164756E21
|
package/dist/i18n/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ra as T}from"../chunk-vg0yj29r.js";import"../chunk-hke4hzfm.js";import{pb as D}from"../chunk-8fb7gey2.js";import{Xe as b,Ye as w}from"../chunk-fgmd1hn7.js";import"../chunk-ptm1d4vp.js";import{Xf as j}from"../chunk-
|
|
2
|
+
import{ra as T}from"../chunk-vg0yj29r.js";import"../chunk-hke4hzfm.js";import{pb as D}from"../chunk-8fb7gey2.js";import{Xe as b,Ye as w}from"../chunk-fgmd1hn7.js";import"../chunk-ptm1d4vp.js";import{Xf as j}from"../chunk-gv7eh0wd.js";import"../chunk-kjzvrx2p.js";import"../chunk-gmkzq212.js";import"../chunk-pvs5qjs7.js";import"../chunk-2kt5kgaq.js";import"../chunk-gx5yhz2m.js";import"../chunk-vq0gcvcy.js";import"../chunk-cyxsmd4q.js";import"../chunk-qbm49b1t.js";import"../chunk-k5vt2kz6.js";import"../chunk-8vzxnjp4.js";import"../chunk-z5wwhgsg.js";import"../chunk-mbfjxyq0.js";import"../chunk-kss2kkmm.js";import"../chunk-n26d4z3t.js";import"../chunk-5npzvdh9.js";import{Em as V,Fm as X,Gm as E,Hm as L,Im as R,Jm as S}from"../chunk-zez3fjnf.js";import"../chunk-xac2vwtq.js";import"../chunk-se0tnb9x.js";import"../chunk-dx4h7rap.js";import"../chunk-w31afsrx.js";import"../chunk-ket76475.js";import"../chunk-jzg9zdtj.js";import"../chunk-748evey0.js";import{createElement as J,Fragment as M,isValidElement as U}from"react";function $(q,B){let G=Object.values(B).some((z)=>typeof z==="function"&&U(z(""))),Q=/{{([^{}]+?)(?::([^{}\[\]]+?))?(?:\[(.*?)\])?}}/g;if(!G)return q.replace(Q,(W,O,_,Z)=>{let C=O.includes(":")?O.split(":")[0]:O,H=B[C];if(H===void 0)return W;if(typeof H==="function"){let K=H(Z!==void 0?Z:"");if(U(K))throw Error("JSX returned in string context");return String(K)}if(_)switch(_.toLowerCase()){case"number":return Number(H).toString();case"string":return String(H);case"boolean":return Boolean(H).toString();default:return String(H)}return String(H)});else{let z=[],W=0,O=null;while((O=Q.exec(q))!==null){let[_,Z,C,H]=O,F=O.index,K=Z.includes(":")?Z.split(":")[0]:Z;if(F>W)z.push(q.substring(W,F));let Y=B[K];if(Y===void 0)z.push(_);else if(typeof Y==="function"){let A=Y(H!==void 0?H:"");z.push(A)}else if(C)switch(C.toLowerCase()){case"number":z.push(Number(Y).toString());break;case"string":z.push(String(Y));break;case"boolean":z.push(Boolean(Y).toString());break;default:z.push(String(Y))}else z.push(String(Y));W=F+_.length}if(W<q.length)z.push(q.substring(W));return J(M,{},...z)}}class P{name;dictionary;constructor(q,B){this.name=q;this.dictionary=B}reference(q){if(typeof window<"u")throw Error("Cannot use reference in the browser");if(!this.dictionary?.[q])throw Error(`Translation not found for ${String(q)}`);return this.dictionary[q]}render(q,...B){let{locale:G=j.locale(),params:Q}={params:{},...B[0]};if(typeof window<"u")throw Error("Cannot use render in the browser");if(!this.dictionary?.[q]?.[G])throw Error(`Translation not found for ${String(q)} in ${String(G)}`);return $(this.dictionary[q][G],Q??{})}static create(q,B){return new P(q,B)}static text(q,...B){let{locale:G=j.locale(),params:Q}={params:{},...B?.[0]};if(!q?.[G])throw Error(`Translation not found for ${String(G)}`);return $(q[G],Q??{})}}async function N(q,B,...G){let{locale:Q=j.locale(),params:z}={params:{},...G[0]},O=(await q.load(String(Q)))[B];if(typeof O!=="string")throw Error(`Translation not found for "${B}" in "${String(Q)}" (dictionary ${q.id})`);return $(O,z??{})}export{w as translationConfigDefaults,N as translate,V as resolveLocale,X as negotiateLocale,L as isValidTimeZone,b as defineTranslationConfig,T as defineDictionary,R as createFormatter,S as Translator,D as TranslationServiceProvider,P as Dictionary,E as DEFAULT_TIME_ZONE};
|
|
3
3
|
|
|
4
4
|
//# debugId=73920FEDA851BDF564756E2164756E21
|
package/dist/kernel/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ta as E}from"../chunk-1v7qcmr7.js";import{ob as l}from"../chunk-31fgprsv.js";import{pb as H}from"../chunk-8fb7gey2.js";import{Bb as g,Cb as W,Db as _,Eb as p,Fb as P,Gb as u,Hb as $,Ib as V,Jb as q,Kb as B,Lb as K,Pb as L,Qb as Q,Rb as T,Vb as U,Wb as y,Xb as F,Yb as C,Zb as D,_b as I,cc as b,fc as f,gc as k,hc as m}from"../chunk-
|
|
2
|
+
import{Ta as E}from"../chunk-1v7qcmr7.js";import{ob as l}from"../chunk-31fgprsv.js";import{pb as H}from"../chunk-8fb7gey2.js";import{Bb as g,Cb as W,Db as _,Eb as p,Fb as P,Gb as u,Hb as $,Ib as V,Jb as q,Kb as B,Lb as K,Pb as L,Qb as Q,Rb as T,Vb as U,Wb as y,Xb as F,Yb as C,Zb as D,_b as I,cc as b,fc as f,gc as k,hc as m}from"../chunk-n626761s.js";import"../chunk-tm4kfnqh.js";import"../chunk-hhka8j31.js";import"../chunk-wr7xq82n.js";import"../chunk-mc7p37d0.js";import{Re as h}from"../chunk-nbdjbde4.js";import"../chunk-fgmd1hn7.js";import"../chunk-ptm1d4vp.js";import{Qf as n,Rf as v,ph as w,th as A,uf as d,vf as s,xh as R}from"../chunk-gv7eh0wd.js";import"../chunk-kjzvrx2p.js";import"../chunk-gmkzq212.js";import"../chunk-pvs5qjs7.js";import"../chunk-2kt5kgaq.js";import"../chunk-gx5yhz2m.js";import"../chunk-vq0gcvcy.js";import"../chunk-cyxsmd4q.js";import{yk as M}from"../chunk-qbm49b1t.js";import"../chunk-k5vt2kz6.js";import"../chunk-8vzxnjp4.js";import"../chunk-z5wwhgsg.js";import"../chunk-mbfjxyq0.js";import"../chunk-kss2kkmm.js";import"../chunk-n26d4z3t.js";import"../chunk-5npzvdh9.js";import"../chunk-gm14dthh.js";import"../chunk-zez3fjnf.js";import{Km as O,Mm as J}from"../chunk-xac2vwtq.js";import"../chunk-se0tnb9x.js";import"../chunk-dx4h7rap.js";import"../chunk-w31afsrx.js";import"../chunk-ket76475.js";import"../chunk-jzg9zdtj.js";import"../chunk-748evey0.js";var N=[C,I,E,T,L,k,B,Q,D,y,_,U,f,V,F,H,b,K,q,m,$];class S{config={};providers=[];services=[];serviceInstances=[];serviceTokens=new Set;servicesBooted=!1;models=[];app=new J;boot(){if(this.models.length>0)l(...this.models);else a();this.app.config.merge(this.config),J.setInstance(this.app),this.app.registerMany([...N,...this.providers]),this.registerServices()}registerServices(){let j=this.serviceTokens;this.serviceInstances=[],this.serviceTokens=new Set,this.servicesBooted=!1;let X=new Map;for(let z of this.services){let G=typeof z==="function"?new z:z,x=G.constructor;if(!x.token)throw Error(`Service [${x.name}] is listed in \`services\` but does not declare a \`static token\`.`);let Y=X.get(x.token);if(Y)throw Error(`Services [${Y}] and [${x.name}] both declare the token "${x.token}". Tokens are the container's keys, so they must be unique.`);X.set(x.token,x.name);let Z=x;if(!j.has(x.token)&&this.app.bound(Z))throw Error(`Service [${x.name}] declares the token "${x.token}", which is already bound in the container by the framework or a provider. Binding it would replace that service everywhere, so pick a token nothing else owns.`);this.app.instance(Z,G),this.serviceInstances.push(G),this.serviceTokens.add(x.token)}this.app.setShutdownHooks(this.serviceInstances.map((z)=>({name:`${z.constructor.name}.onShutdown`,shutdown:(G)=>z.onShutdown(G)})))}async waitForBoot(){await this.app.boot(),await this.bootServices(),p(this.app)}async bootServices(){if(this.servicesBooted)return;for(let j of this.serviceInstances)await j.boot();this.servicesBooted=!0}shutdown(j){return this.run(()=>this.app.shutdown(j))}run(j){return O.run(this.app,j)}resolve(j){return this.app.make(j)}apiRoutes(){return this.app.make(A)}viewRoutes(){return this.app.make(w)}domains(){return this.app.make(R)}queue(){return this.app.make(h)}mcpHttp(){return this.app.config.get("route.mcp.remote.enabled")===!0?this.app.make(g):null}sockets(){return this.app.config.get("route.channels")?this.app.make(u):null}globalMiddleware(j){return P(j)}destroy(){if(this.app.resolved(W))this.app.make(W).stop();if(this.app.flush(),J.getInstance()===this.app)J.setInstance(void 0);O.disable()}}function a(){if(Bun.env.NODE_ENV==="production")return;let j=M();if(j.length===0)return;console.warn(`[gemi] ${j.length} model${j.length===1?" is":"s are"} registered, but Kernel.models is empty.
|
|
3
3
|
Nested relation reads resolve a model by name, so a policy on a subclass that does not own its
|
|
4
4
|
`+" name is skipped inside every include \u2014 scoped at the root, "+`unscoped in an include, with nothing
|
|
5
5
|
to notice it. Declaring the modules registers each class under its own name and audits the set:
|
package/dist/server/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ra as f}from"../chunk-ba1h9pm6.js";import{Sa as A}from"../chunk-d8ekdvsw.js";import{Wm as Q,Ym as q,Zm as w,an as Z,bn as P,cn as y,dn as S,en as U}from"../chunk-w31afsrx.js";import{in as H}from"../chunk-ket76475.js";import"../chunk-jzg9zdtj.js";import{qn as F}from"../chunk-748evey0.js";var x="/__gemi__/health",$=Symbol.for("gemi.server.health");function V(){let z=globalThis;return z[$]??={lagMs:0,consecutiveBreaches:0,degraded:!1,timer:void 0},z[$]}function W(){let z=V(),B=Q();return{healthy:!B&&!z.degraded,shuttingDown:B,lagMs:z.lagMs,consecutiveBreaches:z.consecutiveBreaches}}function E(z,B){let I=V();I.lagMs=z,I.consecutiveBreaches=z>B.maxLagMs?I.consecutiveBreaches+1:0;let J=I.consecutiveBreaches>=B.breaches;if(J&&!I.degraded)console.warn(`[gemi] Health: degraded (event-loop lag ${Math.round(z)}ms, ${I.consecutiveBreaches} samples in a row over ${B.maxLagMs}ms).`);else if(!J&&I.degraded)console.log(`[gemi] Health: recovered (event-loop lag ${Math.round(z)}ms).`);I.degraded=J}function G(z){let B=V();if(B.timer)return;let I=performance.now()+z.intervalMs;B.timer=setInterval(()=>{let J=performance.now();E(Math.max(0,J-I),z),I=J+z.intervalMs},z.intervalMs),B.timer.unref?.()}function _(z=process.env){return{paths:D(z.GEMI_HEALTH_PATH),intervalMs:O("GEMI_HEALTH_INTERVAL_MS",z.GEMI_HEALTH_INTERVAL_MS,500),maxLagMs:O("GEMI_HEALTH_MAX_LAG_MS",z.GEMI_HEALTH_MAX_LAG_MS,1000),breaches:Math.ceil(O("GEMI_HEALTH_BREACHES",z.GEMI_HEALTH_BREACHES,3))}}function D(z){if(z===void 0||z.trim()==="")return[x];if(z.trim().toLowerCase()==="off")return[];let B=z.split(",").map((J)=>J.trim()).filter(Boolean);if(B.filter((J)=>!J.startsWith("/")).length>0)throw Error(`GEMI_HEALTH_PATH: expected comma-separated paths starting with "/", or "off"; got ${JSON.stringify(z)}.`);return B}function O(z,B,I){if(B===void 0||B.trim()==="")return I;let J=Number(B);if(Number.isFinite(J)&&J>0)return J;return console.warn(`[gemi] Ignoring ${z}="${B}": expected a positive number.`),I}function j(z,B){if(B.length===0)return z;let I=new Set(B);return async(J,K)=>{if(!B.some((b)=>J.url.includes(b))||!I.has(new URL(J.url).pathname))return z(J,K);return y(R(J.method))}}function R(z){let B={"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"};if(z!=="GET"&&z!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{...B,Allow:"GET, HEAD"}});let{healthy:I,shuttingDown:J}=W();return new Response(z==="HEAD"?null:I?"ok":J?"shutting down":"degraded",{status:I?200:503,headers:B})}var L=Symbol.for("gemi.server.devGeneration"),X={graceMs:1e4,providerTimeoutMs:5000};class Y{app;inFlight=0;waiters=new Set;constructor(z){this.app=z}track(z){return async(B,I)=>{this.inFlight++;try{return await z(B,I)}finally{if(this.inFlight--,this.inFlight===0)this.wake()}}}get pending(){return this.inFlight}async retire({graceMs:z,providerTimeoutMs:B}){try{await this.idle(z),await Promise.resolve().then(()=>this.app.shutdown({timeoutMs:B}))}catch(I){C(I)}}idle(z){if(this.inFlight===0)return Promise.resolve();return new Promise((B)=>{let I=()=>{clearTimeout(J),this.waiters.delete(I),B()},J=setTimeout(I,z);this.waiters.add(I)})}wake(){for(let z of this.waiters)z()}}function N(z,B=X){let I=globalThis,J=I[L];if(I[L]=z,!J||J===z||typeof J.retire!=="function")return Promise.resolve();let K=J.retire.bind(J);return Promise.resolve().then(()=>K(B)).catch(C)}function C(z){console.error("[gemi] Shutting down the application a reload replaced failed:",z)}class k{app;instrumentation;handleSignals;server;stopping;settings;constructor(z){this.app=new A({kernel:z.kernel}),this.handleSignals=z.handleSignals??!0,this.instrumentation=S(z.instrumentation??((B,I)=>I(B)))}async start(){process.env.ROOT_DIR=H();let z=Bun.env.NODE_ENV==="production",B=_();if(z)G(B);let I=j(this.instrumentation,B.paths);if(z){if(this.handleSignals)U(()=>this.stop());this.settings=Z()}try{await this.app.waitForBoot()}catch(J){if(!z)this.app.shutdown({timeoutMs:X.providerTimeoutMs});throw J}if(z){let{httpProd:J}=await import("../chunk-
|
|
2
|
+
import{Ra as f}from"../chunk-ba1h9pm6.js";import{Sa as A}from"../chunk-d8ekdvsw.js";import{Wm as Q,Ym as q,Zm as w,an as Z,bn as P,cn as y,dn as S,en as U}from"../chunk-w31afsrx.js";import{in as H}from"../chunk-ket76475.js";import"../chunk-jzg9zdtj.js";import{qn as F}from"../chunk-748evey0.js";var x="/__gemi__/health",$=Symbol.for("gemi.server.health");function V(){let z=globalThis;return z[$]??={lagMs:0,consecutiveBreaches:0,degraded:!1,timer:void 0},z[$]}function W(){let z=V(),B=Q();return{healthy:!B&&!z.degraded,shuttingDown:B,lagMs:z.lagMs,consecutiveBreaches:z.consecutiveBreaches}}function E(z,B){let I=V();I.lagMs=z,I.consecutiveBreaches=z>B.maxLagMs?I.consecutiveBreaches+1:0;let J=I.consecutiveBreaches>=B.breaches;if(J&&!I.degraded)console.warn(`[gemi] Health: degraded (event-loop lag ${Math.round(z)}ms, ${I.consecutiveBreaches} samples in a row over ${B.maxLagMs}ms).`);else if(!J&&I.degraded)console.log(`[gemi] Health: recovered (event-loop lag ${Math.round(z)}ms).`);I.degraded=J}function G(z){let B=V();if(B.timer)return;let I=performance.now()+z.intervalMs;B.timer=setInterval(()=>{let J=performance.now();E(Math.max(0,J-I),z),I=J+z.intervalMs},z.intervalMs),B.timer.unref?.()}function _(z=process.env){return{paths:D(z.GEMI_HEALTH_PATH),intervalMs:O("GEMI_HEALTH_INTERVAL_MS",z.GEMI_HEALTH_INTERVAL_MS,500),maxLagMs:O("GEMI_HEALTH_MAX_LAG_MS",z.GEMI_HEALTH_MAX_LAG_MS,1000),breaches:Math.ceil(O("GEMI_HEALTH_BREACHES",z.GEMI_HEALTH_BREACHES,3))}}function D(z){if(z===void 0||z.trim()==="")return[x];if(z.trim().toLowerCase()==="off")return[];let B=z.split(",").map((J)=>J.trim()).filter(Boolean);if(B.filter((J)=>!J.startsWith("/")).length>0)throw Error(`GEMI_HEALTH_PATH: expected comma-separated paths starting with "/", or "off"; got ${JSON.stringify(z)}.`);return B}function O(z,B,I){if(B===void 0||B.trim()==="")return I;let J=Number(B);if(Number.isFinite(J)&&J>0)return J;return console.warn(`[gemi] Ignoring ${z}="${B}": expected a positive number.`),I}function j(z,B){if(B.length===0)return z;let I=new Set(B);return async(J,K)=>{if(!B.some((b)=>J.url.includes(b))||!I.has(new URL(J.url).pathname))return z(J,K);return y(R(J.method))}}function R(z){let B={"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"};if(z!=="GET"&&z!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{...B,Allow:"GET, HEAD"}});let{healthy:I,shuttingDown:J}=W();return new Response(z==="HEAD"?null:I?"ok":J?"shutting down":"degraded",{status:I?200:503,headers:B})}var L=Symbol.for("gemi.server.devGeneration"),X={graceMs:1e4,providerTimeoutMs:5000};class Y{app;inFlight=0;waiters=new Set;constructor(z){this.app=z}track(z){return async(B,I)=>{this.inFlight++;try{return await z(B,I)}finally{if(this.inFlight--,this.inFlight===0)this.wake()}}}get pending(){return this.inFlight}async retire({graceMs:z,providerTimeoutMs:B}){try{await this.idle(z),await Promise.resolve().then(()=>this.app.shutdown({timeoutMs:B}))}catch(I){C(I)}}idle(z){if(this.inFlight===0)return Promise.resolve();return new Promise((B)=>{let I=()=>{clearTimeout(J),this.waiters.delete(I),B()},J=setTimeout(I,z);this.waiters.add(I)})}wake(){for(let z of this.waiters)z()}}function N(z,B=X){let I=globalThis,J=I[L];if(I[L]=z,!J||J===z||typeof J.retire!=="function")return Promise.resolve();let K=J.retire.bind(J);return Promise.resolve().then(()=>K(B)).catch(C)}function C(z){console.error("[gemi] Shutting down the application a reload replaced failed:",z)}class k{app;instrumentation;handleSignals;server;stopping;settings;constructor(z){this.app=new A({kernel:z.kernel}),this.handleSignals=z.handleSignals??!0,this.instrumentation=S(z.instrumentation??((B,I)=>I(B)))}async start(){process.env.ROOT_DIR=H();let z=Bun.env.NODE_ENV==="production",B=_();if(z)G(B);let I=j(this.instrumentation,B.paths);if(z){if(this.handleSignals)U(()=>this.stop());this.settings=Z()}try{await this.app.waitForBoot()}catch(J){if(!z)this.app.shutdown({timeoutMs:X.providerTimeoutMs});throw J}if(z){let{httpProd:J}=await import("../chunk-8adt2k7j.js");this.server=await J(this.app,I)}else{f();let{httpDev:J}=await import("../chunk-qqh6h36y.js"),K=new Y(this.app);this.server=await J(this.app,K.track(I)),N(K)}return this.server}stop(z={}){let B=this.app.sockets();return this.stopping??=P({server:this.server,closeSockets:B?()=>B.shutdown():void 0,shutdownProviders:(I)=>this.app.shutdown(I),settings:{...this.settings??Z(),...z}}),this.stopping}}export{q as shutdownSignal,W as liveness,Q as isShuttingDown,w as holdShutdown,k as Server};
|
|
3
3
|
|
|
4
4
|
//# debugId=F4E787D6E78B88B764756E2164756E21
|
|
@@ -72,9 +72,8 @@ export declare class FileSystemDriver extends FileStorageDriver {
|
|
|
72
72
|
*/
|
|
73
73
|
private openForRead;
|
|
74
74
|
/**
|
|
75
|
-
* The object as a `Response` whose body
|
|
76
|
-
*
|
|
77
|
-
* file open until it is garbage-collected.
|
|
75
|
+
* The object as a `Response` whose body opens the file on its first read.
|
|
76
|
+
* A caller that only looks at the status or headers leaves nothing open.
|
|
78
77
|
*/
|
|
79
78
|
fetch(params: ReadFileParams | string, { signal }?: FetchFileOptions): Promise<Response>;
|
|
80
79
|
read(input: ReadFileParams | string): Promise<ReadResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FileSystemDriver.d.ts","sourceRoot":"","sources":["../../../../services/file-storage/drivers/FileSystemDriver.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAChB,mBAAmB,EACnB,gBAAgB,EAChB,kBAAkB,EAClB,YAAY,EACZ,cAAc,EACd,aAAa,EACb,eAAe,EACf,cAAc,EACd,UAAU,EACX,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,iBAAiB,EAAyB,MAAM,qBAAqB,CAAC;AAS/E,qBAAa,gBAAiB,SAAQ,iBAAiB;IACrD,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAS;gBAEzB,UAAU,CAAC,EAAE,MAAM;IAK/B;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,OAAO,KAAK,UAAU,GAErB;IAED;;;;;;OAMG;YACW,QAAQ;IAqBtB;;;;OAIG;YACW,iBAAiB;IAe/B;;;;;OAKG;YACW,iBAAiB;IAoB/B;;;;;;;;;OASG;YACW,qBAAqB;IA6B7B,GAAG,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI,EAAE,EAAE,MAAM,EAAE,GAAE,cAAmB;IA8BvE;;;OAGG;IACG,SAAS,CACb,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,eAAe,EAC/B,EAAE,MAAM,EAAE,GAAE,cAAmB,GAC9B,OAAO,CAAC,MAAM,CAAC;IAoBlB;;;;;;OAMG;YACW,WAAW;IAqBzB
|
|
1
|
+
{"version":3,"file":"FileSystemDriver.d.ts","sourceRoot":"","sources":["../../../../services/file-storage/drivers/FileSystemDriver.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAChB,mBAAmB,EACnB,gBAAgB,EAChB,kBAAkB,EAClB,YAAY,EACZ,cAAc,EACd,aAAa,EACb,eAAe,EACf,cAAc,EACd,UAAU,EACX,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,iBAAiB,EAAyB,MAAM,qBAAqB,CAAC;AAS/E,qBAAa,gBAAiB,SAAQ,iBAAiB;IACrD,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAS;gBAEzB,UAAU,CAAC,EAAE,MAAM;IAK/B;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,OAAO,KAAK,UAAU,GAErB;IAED;;;;;;OAMG;YACW,QAAQ;IAqBtB;;;;OAIG;YACW,iBAAiB;IAe/B;;;;;OAKG;YACW,iBAAiB;IAoB/B;;;;;;;;;OASG;YACW,qBAAqB;IA6B7B,GAAG,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI,EAAE,EAAE,MAAM,EAAE,GAAE,cAAmB;IA8BvE;;;OAGG;IACG,SAAS,CACb,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,eAAe,EAC/B,EAAE,MAAM,EAAE,GAAE,cAAmB,GAC9B,OAAO,CAAC,MAAM,CAAC;IAoBlB;;;;;;OAMG;YACW,WAAW;IAqBzB;;;OAGG;IACG,KAAK,CACT,MAAM,EAAE,cAAc,GAAG,MAAM,EAC/B,EAAE,MAAM,EAAE,GAAE,gBAAqB;IA4B7B,IAAI,CAAC,KAAK,EAAE,cAAc,GAAG,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IAyCzD,IAAI,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM;IAOpC,MAAM,CAAC,MAAM,EAAE,gBAAgB,GAAG,MAAM;IAkB9C;;;;;;OAMG;YACW,aAAa;IAgB3B;;;;;;;OAOG;IACI,OAAO,CACZ,MAAM,EAAE,MAAM,EACd,EAAE,MAAM,EAAE,GAAE,kBAAuB,GAClC,aAAa,CAAC,YAAY,CAAC;IA+C9B;;;;;;OAMG;IACG,YAAY,CAChB,MAAM,EAAE,MAAM,EACd,OAAO,GAAE,mBAAwB,GAChC,OAAO,CAAC,MAAM,CAAC;YAiBJ,cAAc;IAgC5B,yFAAyF;IACnF,IAAI;CAKX"}
|
package/dist/services/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{rb as z$}from"../chunk-g6tqje74.js";import{$b as r9,Ab as s1,Bb as F9,Cb as L9,Db as v9,Hb as I9,Ib as f9,Jb as y9,Kb as A9,Lb as g9,Mb as m9,Nb as c9,Ob as u9,Pb as p9,Qb as d9,Rb as l9,Sb as n4,Tb as v6,Ub as h,Vb as n9,Wb as i9,Xb as s9,Yb as o9,Zb as a9,_b as t9,ac as e9,bc as W$,cc as Z$,dc as $$,ec as Q$,fc as Y$,gc as K$,hc as J$,sb as z9,tb as G9,ub as X9,vb as B9,wb as j9,xb as u4,yb as M9,zb as g4}from"../chunk-q0k1j5a4.js";import{kc as d4}from"../chunk-11fc5nve.js";import"../chunk-hhka8j31.js";import{ge as D9,he as H9,ie as N9,je as U9,ke as x9,le as R9,me as O9,ne as _9,oe as V9,pe as k9,qe as C9,re as T9,se as P9,te as b9,ue as w9,ve as q9}from"../chunk-wr7xq82n.js";import{we as S9}from"../chunk-mc7p37d0.js";import{Ae as dZ,Be as lZ,Ee as nZ,Fe as iZ,Ge as sZ,He as oZ,Ie as aZ,Je as tZ,Ke as rZ,Le as eZ,Me as W9,Ne as Z9,Oe as $9,Pe as Q9,Qe as Y9,Re as K9,We as J9,xe as cZ,ye as uZ,ze as pZ}from"../chunk-nbdjbde4.js";import{Xe as h9,Ye as E9}from"../chunk-fgmd1hn7.js";import"../chunk-ptm1d4vp.js";import{$g as CZ,Af as Q8,Ag as zZ,Bf as Y8,Bg as GZ,Cf as K8,Df as J8,Dg as XZ,Ef as z8,Eg as BZ,Ff as G8,Fg as jZ,Gf as X8,Gg as MZ,Hf as B8,Hg as FZ,If as j8,Ig as LZ,Jf as Y6,Jg as DZ,Jh as E4,Kf as M8,Kg as HZ,Lf as F8,Lg as NZ,Mf as L8,Mg as UZ,Nf as D8,Of as H8,Rg as R,Sg as i,Tg as xZ,Ug as SZ,Vg as RZ,Wg as OZ,Xg as _Z,Zg as VZ,Zh as yZ,_g as kZ,_h as AZ,ah as TZ,bg as T8,cg as P8,ch as PZ,dg as b8,ef as V6,eg as w8,ff as e5,fg as q8,fh as bZ,gf as W8,gg as v8,gh as wZ,hf as Z8,hh as qZ,jf as $8,kh as vZ,ng as e8,og as q6,pf as k6,pg as WZ,ph as IZ,qf as C4,rf as B6,sf as T4,tf as P4,tg as ZZ,th as fZ,ug as $Z,vg as YZ,xf as f6,xh as i4,yf as y6,yg as KZ,yh as z1,zg as JZ}from"../chunk-t56z2zec.js";import"../chunk-kjzvrx2p.js";import"../chunk-gmkzq212.js";import{Aj as R8,Mj as mW,Nj as cW,Qj as O8,Rj as _8,Si as k4,Ti as O4,Tj as d1,Ui as k1,kj as h4,oj as j1,qj as Y1,tj as _4,uj as C1,vj as p1,wj as N8,xj as U8,yj as x8,zj as S8}from"../chunk-dapd4vkd.js";import"../chunk-2kt5kgaq.js";import{ck as V8,dk as k8,ek as C8}from"../chunk-gx5yhz2m.js";import{gk as q}from"../chunk-vq0gcvcy.js";import{ok as g8,pk as m8,qk as U,rk as c8,sk as b,tk as u8,uk as p8}from"../chunk-cyxsmd4q.js";import{Ak as A8,Bk as h8,Ck as E8}from"../chunk-qbm49b1t.js";import"../chunk-k5vt2kz6.js";import{jl as QZ}from"../chunk-8vzxnjp4.js";import{Al as r8,ll as I8,ml as f8,nl as y8,ol as d8,pl as l8,ql as n8,rl as i8,sl as s8,tl as o8,yl as a8,zl as t8}from"../chunk-z5wwhgsg.js";import"../chunk-mbfjxyq0.js";import"../chunk-kss2kkmm.js";import"../chunk-n26d4z3t.js";import"../chunk-5npzvdh9.js";import{Am as EZ,Bm as gZ,Dm as mZ,ym as w4,zm as hZ}from"../chunk-gm14dthh.js";import"../chunk-zez3fjnf.js";import{Nm as C}from"../chunk-xac2vwtq.js";import"../chunk-se0tnb9x.js";import"../chunk-dx4h7rap.js";import"../chunk-w31afsrx.js";import"../chunk-ket76475.js";import"../chunk-jzg9zdtj.js";import{qn as u1}from"../chunk-748evey0.js";import{Buffer as K6}from"buffer";class J6 extends C1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-71ap56wq.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket??K,Q=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);Q=Q||void 0;let J=$ instanceof K6?$:$ instanceof Blob||$ instanceof File?K6.from(await $.arrayBuffer()):"",{sdk:z,client:G}=await this.connect();return Z?.throwIfAborted(),await G.send(new z.PutObjectCommand({Bucket:K,Key:Y,Body:J,ContentType:Q}),{abortSignal:Z}),Y}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();try{await Y.send(new Q.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(K){if(K?.name==="NoSuchKey"||K?.$metadata?.httpStatusCode===404)return;throw K}}async*pages(W,{bucket:Z,signal:$}){let{sdk:Q,client:Y}=await this.connect(),K;do{$?.throwIfAborted();let J=await Y.send(new Q.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:K}),{abortSignal:$});yield(J.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),K=J.IsTruncated?J.NextContinuationToken:void 0}while(K)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){_4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect(),K=0;for await(let J of this.pages(W,{...Z,bucket:$})){if(J.length===0)continue;Z.signal?.throwIfAborted();let G=(await Y.send(new Q.DeleteObjectsCommand({Bucket:$,Delete:{Objects:J.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(G.length>0){let X=G[0];throw Error(`S3 could not delete ${G.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}K+=J.length}return K}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,Q;if(typeof W==="string")Q=W;else $=W.bucket??$,Q=W.name;if(!Q)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect();Z?.throwIfAborted();let J=await K.send(new Y.GetObjectCommand({Bucket:$,Key:Q}),{abortSignal:Z}),z=p1(J.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":J.ContentType,"Content-Length":J.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":J.LastModified?.toUTCString()||"",ETag:J.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:Q,range:Y=null}=Z;if(!Q)throw Error("Object name has to be specified");let{sdk:K,client:J}=await this.connect(),z;try{z=await J.send(new K.GetObjectCommand({Bucket:$,Key:Q,Range:Y?O4(Y):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new j1(await this.size({name:Q,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new Y1(Q);throw j}let G=k1(z.ContentRange),X=Boolean(G)&&z.$metadata?.httpStatusCode===206,B=G?.total??z.ContentLength??0;return{body:z.Body.transformToWebStream(),start:G?.start??0,end:G?.end??B-1,total:B,partial:X,type:z.ContentType??"application/octet-stream",etag:z.ETag||void 0,lastModified:z.LastModified,name:Q}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect();try{return(await Y.send(new Q.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(K){if(K?.name==="NotFound"||K?.$metadata?.httpStatusCode===404)throw new Y1(Z);throw K}}}import{Buffer as z6}from"buffer";import{Readable as dW}from"stream";function V4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function lW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class G6 extends C1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket,Q=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let J=$ instanceof z6?$:z6.from(await $.arrayBuffer()),z=await this.blob(Y,K);return Z?.throwIfAborted(),await z.uploadData(J,{blobHTTPHeaders:Q?{blobContentType:Q}:void 0,abortSignal:Z}),Y}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let Q=Z??this.config.container??process.env.BUCKET_NAME;if(!Q)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let K=(await this.serviceClient()).getContainerClient(Q);for await(let J of K.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:J.name,size:J.properties?.contentLength??0,lastModified:J.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,Q=(await this.serviceClient()).getContainerClient(Z),Y=[];for await(let K of Q.listBlobsFlat({prefix:W}))Y.push(K.name);return Y}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:Q,range:Y=null}=W,K=await this.blob($,Q);Z?.throwIfAborted();let J,z,G=Y?.kind==="suffix"||Y?.kind==="offset"&&Y.end===null&&Y.start===0;if(Y&&G){let V=await this.size({name:$,bucket:Q}),Q1=k4(Y,V);if(!Q1)throw new j1(V);J=Q1.start,z=Q1.length}else if(Y?.kind==="offset")J=Y.start,z=Y.end===null?void 0:Y.end-Y.start+1;let X;try{X=await K.download(J,z,Z?{abortSignal:Z}:void 0)}catch(V){if(lW(V))throw new j1(await this.size({name:$,bucket:Q}));if(V4(V))throw new Y1($);throw V}let B=k1(X.contentRange),j=Boolean(B),D=B?.total??X.contentLength??0,x=await nW(X);if(x instanceof ReadableStream)x=p1(x,Z);return Z?.throwIfAborted(),{body:x,start:B?.start??0,end:B?.end??D-1,total:D,partial:j,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{return(await Q.getProperties()).contentLength??0}catch(Y){if(V4(Y))throw new Y1(Z);throw Y}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{await Q.delete()}catch(Y){if(V4(Y))return;throw Y}}}async function nW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return dW.toWeb(W.readableStreamBody);return null}function iW(W){return W}class b4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class l1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var X6=1000,sW=60000,oW=`
|
|
2
|
+
import{rb as z$}from"../chunk-g6tqje74.js";import{$b as r9,Ab as s1,Bb as F9,Cb as L9,Db as v9,Hb as I9,Ib as f9,Jb as y9,Kb as A9,Lb as g9,Mb as m9,Nb as c9,Ob as u9,Pb as p9,Qb as d9,Rb as l9,Sb as n4,Tb as v6,Ub as h,Vb as n9,Wb as i9,Xb as s9,Yb as o9,Zb as a9,_b as t9,ac as e9,bc as W$,cc as Z$,dc as $$,ec as Q$,fc as Y$,gc as K$,hc as J$,sb as z9,tb as G9,ub as X9,vb as B9,wb as j9,xb as u4,yb as M9,zb as g4}from"../chunk-n626761s.js";import{kc as d4}from"../chunk-tm4kfnqh.js";import"../chunk-hhka8j31.js";import{ge as D9,he as H9,ie as N9,je as U9,ke as x9,le as R9,me as O9,ne as _9,oe as V9,pe as k9,qe as C9,re as T9,se as P9,te as b9,ue as w9,ve as q9}from"../chunk-wr7xq82n.js";import{we as S9}from"../chunk-mc7p37d0.js";import{Ae as dZ,Be as lZ,Ee as nZ,Fe as iZ,Ge as sZ,He as oZ,Ie as aZ,Je as tZ,Ke as rZ,Le as eZ,Me as W9,Ne as Z9,Oe as $9,Pe as Q9,Qe as Y9,Re as K9,We as J9,xe as cZ,ye as uZ,ze as pZ}from"../chunk-nbdjbde4.js";import{Xe as h9,Ye as E9}from"../chunk-fgmd1hn7.js";import"../chunk-ptm1d4vp.js";import{$g as CZ,Af as Q8,Ag as zZ,Bf as Y8,Bg as GZ,Cf as K8,Df as J8,Dg as XZ,Ef as z8,Eg as BZ,Ff as G8,Fg as jZ,Gf as X8,Gg as MZ,Hf as B8,Hg as FZ,If as j8,Ig as LZ,Jf as Y6,Jg as DZ,Jh as E4,Kf as M8,Kg as HZ,Lf as F8,Lg as NZ,Mf as L8,Mg as UZ,Nf as D8,Of as H8,Rg as R,Sg as i,Tg as xZ,Ug as SZ,Vg as RZ,Wg as OZ,Xg as _Z,Zg as VZ,Zh as yZ,_g as kZ,_h as AZ,ah as TZ,bg as T8,cg as P8,ch as PZ,dg as b8,ef as V6,eg as w8,ff as e5,fg as q8,fh as bZ,gf as W8,gg as v8,gh as wZ,hf as Z8,hh as qZ,jf as $8,kh as vZ,ng as e8,og as q6,pf as k6,pg as WZ,ph as IZ,qf as C4,rf as B6,sf as T4,tf as P4,tg as ZZ,th as fZ,ug as $Z,vg as YZ,xf as f6,xh as i4,yf as y6,yg as KZ,yh as z1,zg as JZ}from"../chunk-gv7eh0wd.js";import"../chunk-kjzvrx2p.js";import"../chunk-gmkzq212.js";import{Aj as R8,Mj as mW,Nj as cW,Qj as O8,Rj as _8,Si as k4,Ti as O4,Tj as d1,Ui as k1,kj as h4,oj as j1,qj as Y1,tj as _4,uj as C1,vj as p1,wj as N8,xj as U8,yj as x8,zj as S8}from"../chunk-pvs5qjs7.js";import"../chunk-2kt5kgaq.js";import{ck as V8,dk as k8,ek as C8}from"../chunk-gx5yhz2m.js";import{gk as q}from"../chunk-vq0gcvcy.js";import{ok as g8,pk as m8,qk as U,rk as c8,sk as b,tk as u8,uk as p8}from"../chunk-cyxsmd4q.js";import{Ak as A8,Bk as h8,Ck as E8}from"../chunk-qbm49b1t.js";import"../chunk-k5vt2kz6.js";import{jl as QZ}from"../chunk-8vzxnjp4.js";import{Al as r8,ll as I8,ml as f8,nl as y8,ol as d8,pl as l8,ql as n8,rl as i8,sl as s8,tl as o8,yl as a8,zl as t8}from"../chunk-z5wwhgsg.js";import"../chunk-mbfjxyq0.js";import"../chunk-kss2kkmm.js";import"../chunk-n26d4z3t.js";import"../chunk-5npzvdh9.js";import{Am as EZ,Bm as gZ,Dm as mZ,ym as w4,zm as hZ}from"../chunk-gm14dthh.js";import"../chunk-zez3fjnf.js";import{Nm as C}from"../chunk-xac2vwtq.js";import"../chunk-se0tnb9x.js";import"../chunk-dx4h7rap.js";import"../chunk-w31afsrx.js";import"../chunk-ket76475.js";import"../chunk-jzg9zdtj.js";import{qn as u1}from"../chunk-748evey0.js";import{Buffer as K6}from"buffer";class J6 extends C1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-71ap56wq.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket??K,Q=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);Q=Q||void 0;let J=$ instanceof K6?$:$ instanceof Blob||$ instanceof File?K6.from(await $.arrayBuffer()):"",{sdk:z,client:G}=await this.connect();return Z?.throwIfAborted(),await G.send(new z.PutObjectCommand({Bucket:K,Key:Y,Body:J,ContentType:Q}),{abortSignal:Z}),Y}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();try{await Y.send(new Q.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(K){if(K?.name==="NoSuchKey"||K?.$metadata?.httpStatusCode===404)return;throw K}}async*pages(W,{bucket:Z,signal:$}){let{sdk:Q,client:Y}=await this.connect(),K;do{$?.throwIfAborted();let J=await Y.send(new Q.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:K}),{abortSignal:$});yield(J.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),K=J.IsTruncated?J.NextContinuationToken:void 0}while(K)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){_4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect(),K=0;for await(let J of this.pages(W,{...Z,bucket:$})){if(J.length===0)continue;Z.signal?.throwIfAborted();let G=(await Y.send(new Q.DeleteObjectsCommand({Bucket:$,Delete:{Objects:J.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(G.length>0){let X=G[0];throw Error(`S3 could not delete ${G.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}K+=J.length}return K}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,Q;if(typeof W==="string")Q=W;else $=W.bucket??$,Q=W.name;if(!Q)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect();Z?.throwIfAborted();let J=await K.send(new Y.GetObjectCommand({Bucket:$,Key:Q}),{abortSignal:Z}),z=p1(J.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":J.ContentType,"Content-Length":J.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":J.LastModified?.toUTCString()||"",ETag:J.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:Q,range:Y=null}=Z;if(!Q)throw Error("Object name has to be specified");let{sdk:K,client:J}=await this.connect(),z;try{z=await J.send(new K.GetObjectCommand({Bucket:$,Key:Q,Range:Y?O4(Y):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new j1(await this.size({name:Q,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new Y1(Q);throw j}let G=k1(z.ContentRange),X=Boolean(G)&&z.$metadata?.httpStatusCode===206,B=G?.total??z.ContentLength??0;return{body:z.Body.transformToWebStream(),start:G?.start??0,end:G?.end??B-1,total:B,partial:X,type:z.ContentType??"application/octet-stream",etag:z.ETag||void 0,lastModified:z.LastModified,name:Q}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect();try{return(await Y.send(new Q.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(K){if(K?.name==="NotFound"||K?.$metadata?.httpStatusCode===404)throw new Y1(Z);throw K}}}import{Buffer as z6}from"buffer";import{Readable as dW}from"stream";function V4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function lW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class G6 extends C1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket,Q=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let J=$ instanceof z6?$:z6.from(await $.arrayBuffer()),z=await this.blob(Y,K);return Z?.throwIfAborted(),await z.uploadData(J,{blobHTTPHeaders:Q?{blobContentType:Q}:void 0,abortSignal:Z}),Y}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let Q=Z??this.config.container??process.env.BUCKET_NAME;if(!Q)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let K=(await this.serviceClient()).getContainerClient(Q);for await(let J of K.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:J.name,size:J.properties?.contentLength??0,lastModified:J.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,Q=(await this.serviceClient()).getContainerClient(Z),Y=[];for await(let K of Q.listBlobsFlat({prefix:W}))Y.push(K.name);return Y}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:Q,range:Y=null}=W,K=await this.blob($,Q);Z?.throwIfAborted();let J,z,G=Y?.kind==="suffix"||Y?.kind==="offset"&&Y.end===null&&Y.start===0;if(Y&&G){let V=await this.size({name:$,bucket:Q}),Q1=k4(Y,V);if(!Q1)throw new j1(V);J=Q1.start,z=Q1.length}else if(Y?.kind==="offset")J=Y.start,z=Y.end===null?void 0:Y.end-Y.start+1;let X;try{X=await K.download(J,z,Z?{abortSignal:Z}:void 0)}catch(V){if(lW(V))throw new j1(await this.size({name:$,bucket:Q}));if(V4(V))throw new Y1($);throw V}let B=k1(X.contentRange),j=Boolean(B),D=B?.total??X.contentLength??0,x=await nW(X);if(x instanceof ReadableStream)x=p1(x,Z);return Z?.throwIfAborted(),{body:x,start:B?.start??0,end:B?.end??D-1,total:D,partial:j,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{return(await Q.getProperties()).contentLength??0}catch(Y){if(V4(Y))throw new Y1(Z);throw Y}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{await Q.delete()}catch(Y){if(V4(Y))return;throw Y}}}async function nW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return dW.toWeb(W.readableStreamBody);return null}function iW(W){return W}class b4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class l1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var X6=1000,sW=60000,oW=`
|
|
3
3
|
local currentKey = KEYS[1]
|
|
4
4
|
local previousKey = KEYS[2]
|
|
5
5
|
local limit = tonumber(ARGV[1])
|
package/package.json
CHANGED
package/dist/chunk-dapd4vkd.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Wj as _,Xj as $1,Yj as X1}from"./chunk-2kt5kgaq.js";import{Zj as N1,bk as T0}from"./chunk-gx5yhz2m.js";import{kk as _1,nk as f}from"./chunk-vq0gcvcy.js";import{Jm as Q0}from"./chunk-zez3fjnf.js";import{Nm as e1}from"./chunk-xac2vwtq.js";import{in as O0}from"./chunk-ket76475.js";import{qn as I4}from"./chunk-748evey0.js";class q1{static kind="controller";constructor(){}}class S0 extends q1{}function z1(Q){let Z=new Map;if(!Q)return Z;for(let J of Q.split(";")){let K=J.indexOf("=");if(K===-1)continue;let $=J.slice(0,K).trim();if(!$)continue;Z.set($,J.slice(K+1).trim())}return Z}function E4(Q){return z1(Q.headers.get("cookie"))}function m(Q){if(!/^\d+$/.test(Q))return null;let Z=Number(Q);return Number.isSafeInteger(Z)?Z:null}function b1(Q){if(!Q)return null;let Z=Q.trim();if(!/^bytes=/i.test(Z))return null;let K=Z.slice(6).split(",").map((V)=>V.trim()).filter((V)=>V!=="");if(K.length!==1)return null;let $=K[0],X=$.indexOf("-");if(X===-1)return null;let Y=$.slice(0,X),H=$.slice(X+1);if(Y===""){let V=m(H);if(V===null)return null;return{kind:"suffix",suffixLength:V}}let G=m(Y);if(G===null)return null;if(H==="")return{kind:"offset",start:G,end:null};let W=m(H);if(W===null||W<G)return null;return{kind:"offset",start:G,end:W}}function v1(Q,Z){if(!Number.isFinite(Z)||Z<=0)return null;let J,K;if(Q.kind==="suffix"){if(Q.suffixLength<=0)return null;J=Math.max(0,Z-Q.suffixLength),K=Z-1}else{if(Q.start>=Z)return null;if(J=Q.start,K=Q.end===null?Z-1:Math.min(Q.end,Z-1),K<J)return null}return{start:J,end:K,length:K-J+1}}function q4(Q){if(Q.kind==="suffix")return`bytes=-${Q.suffixLength}`;return Q.end===null?`bytes=${Q.start}-`:`bytes=${Q.start}-${Q.end}`}function b4(Q){if(!Q)return null;let Z=/^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(Q.trim());if(!Z)return null;let J=m(Z[1]),K=m(Z[2]),$=m(Z[3]);if(J===null||K===null||$===null||K<J)return null;return{start:J,end:K,total:$}}function v4(Q,Z,J){return`bytes ${Q}-${Z}/${J}`}function f1(Q){return`bytes */${Q}`}import{randomBytes as k0}from"crypto";var P1=new WeakMap;function D1(Q){let Z=P1.get(Q);if(!Z)Z=k0(16).toString("base64"),P1.set(Q,Z);return Z}function h4(Q){return P1.get(Q)}function m4(){let Q=f.getStore()?.req?.rawRequest;if(!Q)throw Error("cspNonce() is only available while a request is being handled.");return D1(Q)}class o extends _{errors={};constructor(Q){super("Validation error");this.name="ValidationError",this.errors=Q,this.payload={api:{status:400,data:{error:{kind:"validation_error",messages:Q,status:400}},headers:{"Content-Type":"application/json"}},view:{status:400}}}}function g1(Q){let[Z,J]=Q.match(/\d+|\D+/g)??[];if(!Z||!J)return 0;let K=Number.parseInt(Z);switch(J){case"B":return K;case"KB":return K*1024;case"MB":return K*1024*1024;case"GB":return K*1024*1024*1024;case"TB":return K*1024*1024*1024*1024;default:return 0}}function E0(Q){switch(Q){case"image":return"image";case"png":return"image/png";case"jpg":return"image/jpeg";case"jpeg":return"image/jpeg";case"ttf":return"font/ttf";case"excel":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"csv":return"text/csv";case"word":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"pdf":return"application/pdf";case"json":return"application/json";default:return Q}}function y1(Q){if(typeof Q==="string"||Array.isArray(Q))return Q.length;return}function M1(Q){return typeof Q==="number"&&!Number.isNaN(Q)}var x0=["required","string","boolean","number","email","password","min","max","gte","lte","file","fileType","fileSize","array","object","in"];class x extends Error{name="InvalidValidationRuleError"}function K1(Q,Z){let J=Z===void 0||Z.trim()===""?Number.NaN:Number(Z);if(Number.isNaN(J))throw new x(`Validation rule "${Q}:${Z??""}" needs a number, e.g. "${Q}:3"`);return J}function h1(Q){let Z=!1,J=0;for(let K of Object.values(Q)){if(!K||typeof K!=="object")continue;for(let $ of Object.keys(K)){let X=$.indexOf(":"),Y=X===-1?$:$.slice(0,X);if(Y!=="file"&&Y!=="fileType"&&Y!=="fileSize")continue;if(Z=!0,Y==="fileSize")J+=g1($.slice(X+1))}}return Z?J:null}function m1(Q){let Z=Q.indexOf(":"),J=Z===-1?Q:Q.slice(0,Z),K=Z===-1?void 0:Q.slice(Z+1);switch(J){case"required":return($)=>{if($ instanceof Blob)return $.size>0;if($===null||$===void 0)return!1;if(typeof $==="string"||Array.isArray($))return $.length>0;return!0};case"string":return($)=>typeof $==="string";case"boolean":return($)=>typeof $==="boolean";case"number":return($)=>M1($);case"password":return($)=>{return typeof $==="string"&&/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/.test($)};case"min":{let $=K1(J,K);return(X)=>{let Y=y1(X);return Y!==void 0&&Y>=$}}case"max":{let $=K1(J,K);return(X)=>{let Y=y1(X);return Y!==void 0&&Y<=$}}case"gte":{let $=K1(J,K);return(X)=>M1(X)&&X>=$}case"lte":{let $=K1(J,K);return(X)=>M1(X)&&X<=$}case"email":return($)=>{return typeof $==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($)};case"file":return($)=>{return $ instanceof Blob};case"fileType":{if(!K)throw new x('Validation rule "fileType" needs a type, e.g. "fileType:png" or "fileType:image"');let $=E0(K);return(X)=>X instanceof Blob&&X.type.startsWith($)}case"fileSize":{let $=g1(K??"");if($===0&&!/^0+(B|KB|MB|GB|TB)$/.test(K??""))throw new x(`Validation rule "fileSize:${K??""}" needs a whole size in B, KB, MB, GB or TB, e.g. "fileSize:5MB"`);return(X)=>X instanceof Blob&&X.size<=$}case"array":return($)=>Array.isArray($);case"object":return($)=>typeof $==="object"&&$!==null&&!Array.isArray($)&&!($ instanceof Blob);case"in":{let $=(K??"").split(",").filter((X)=>X!=="");if($.length===0)throw new x('Validation rule "in" needs a comma-separated list, e.g. "in:draft,published"');return(X)=>typeof X==="string"&&$.includes(X)}default:throw new x(`Unknown validation rule "${Q}". Known rules: ${x0.join(", ")}`)}}class B1 extends _{limit;constructor(Q){super("The request body is too large.",{status:413});this.limit=Q}}var c1={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function i4(Q){if(typeof Q==="number"){if(Number.isFinite(Q)&&Q>=0)return Math.floor(Q);if(Q===1/0)return 1/0}else{let Z=Q.trim().toLowerCase();if(Z==="none"||Z==="off")return 1/0;let J=/^(\d+(?:\.\d+)?)\s*([a-z]*)$/.exec(Z);if(J&&(J[2]===""||(J[2]in c1)))return Math.floor(Number(J[1])*(c1[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify(Q)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var p=new WeakMap;function n4(Q){return p.has(Q)}function o4(Q){return p.get(Q)?.limit??null}function s4(Q){let Z=p.get(Q);return Z?Z.read>Z.limit:!1}function q0(Q){let Z=Q.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function L1(Q,Z){let J=q0(Q);if(J!==null&&J>Z)throw new B1(Z)}function a4(Q,Z,J={}){let K=J.uploadLimit??null,$=p.get(Q);if($)$.limit=Z,$.uploadLimit=K;else{let X={limit:Z,uploadLimit:K,read:0,stream:void 0,used:!1};p.set(Q,X),v0(Q,X)}if(J.checkDeclared!==!1)L1(Q,Z)}function u1(Q,Z){let J=p.get(Q);if(!J||J.uploadLimit===null||J.used||J.read>0)return;J.limit=Math.max(J.limit,J.uploadLimit,Z+J.limit),J.uploadLimit=null}function b0(Q){return Reflect.get(Object.getPrototypeOf(Q),"body",Q)??null}function U1(Q,Z){if(Z.stream!==void 0)return Z.stream;let J=b0(Q);if(!J)return Z.stream=null;let K;return Z.stream=new ReadableStream({async pull($){K??=J.getReader();let{done:X,value:Y}=await K.read();if(X){$.close();return}if(Z.read+=Y.byteLength,Z.read>Z.limit){let H=new B1(Z.limit);$.error(H),K.cancel(H).catch(()=>{});return}$.enqueue(Y)},cancel($){return K?K.cancel($):J.cancel($)}},{highWaterMark:0}),Z.stream}async function c(Q,Z){if(L1(Q,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=U1(Q,Z);if(!J)return new Uint8Array(0);let K=J.getReader(),$=[],X=0;for(;;){let{done:G,value:W}=await K.read();if(G)break;$.push(W),X+=W.byteLength}let Y=new Uint8Array(X),H=0;for(let G of $)Y.set(G,H),H+=G.byteLength;return Y}function p1(Q){return Q.headers.get("Content-Type")??""}function v0(Q,Z){let J=(K,$)=>Object.defineProperty(Q,K,{configurable:!0,...$});J("body",{get:()=>U1(Q,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf(Q),"bodyUsed",Q)}),J("bytes",{value:()=>c(Q,Z)}),J("arrayBuffer",{value:async()=>{let K=await c(Q,Z);return K.buffer.slice(K.byteOffset,K.byteOffset+K.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await c(Q,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await c(Q,Z)))}),J("blob",{value:async()=>new Blob([await c(Q,Z)],{type:p1(Q)})}),J("formData",{value:async()=>new Response(await c(Q,Z),{headers:{"Content-Type":p1(Q)}}).formData()}),J("clone",{value:()=>{L1(Q,Z.limit);let K=U1(Q,Z),$=null;if(K){let[X,Y]=K.tee();Z.stream=X,$=Y}return new Request(Q.url,{method:Q.method,headers:Q.headers,body:$,signal:Q.signal,duplex:"half"})}})}function d1(Q){if(typeof Q!=="string")return null;let[Z]=Q.split(";",1),J=Z.trim().toLowerCase();return J===""?null:J}function l1(Q){if(Q===null)return!1;if(Q==="application/json")return!0;let Z=Q.indexOf("/");return Z>0&&Q.endsWith("+json")&&Q.length>Z+1+5}var s=new WeakMap;function e4(Q,Z,J,K){s.set(Q,{clientAddress:Z,...J?{grant:Object.freeze({...J,scopes:Object.freeze([...J.scopes])})}:{},...K?{progress:K}:{}})}function i1(Q){return s.get(Q)?.progress}function n1(Q){return s.get(Q)?.grant}function o1(Q){return s.has(Q)}function QQ(Q){return s.get(Q)?.clientAddress}var s1=new WeakMap;function JQ(Q,Z){s1.set(Q,Z)}function a1(Q){return s1.get(Q)??null}var C1=new WeakMap;function KQ(Q,Z){let J=C1.get(Q)??[];if(!J.includes(Z))C1.set(Q,[...J,Z])}function $Q(Q){return C1.get(Q)??[]}class u{data;constructor(Q){this.data=Q}get(Q){return this.data[Q]}has(Q){return this.data[Q]!==void 0}toJSON(){return this.data}}function t1(Q){return typeof Q==="object"&&Q!==null&&!(Q instanceof Blob)}function f0(Q,Z){if(!Z.includes(".")||Object.hasOwn(Q,Z))return[{path:[Z],value:Q[Z]}];let J=[{path:[],value:Q}];for(let K of Z.split(".")){let $=[];for(let{path:X,value:Y}of J){if(K==="*"){if(Array.isArray(Y))Y.forEach((H,G)=>$.push({path:[...X,G],value:H}));else if(t1(Y))for(let[H,G]of Object.entries(Y))$.push({path:[...X,H],value:G});continue}if(Array.isArray(Y)&&/^\d+$/.test(K)){$.push({path:[...X,Number(K)],value:Y[Number(K)]});continue}$.push({path:[...X,K],value:t1(Y)&&Object.hasOwn(Y,K)?Y[K]:void 0})}J=$}return J}function r1(Q){return Q.join(".")}class y0{kind;rawRequest;headers;cookies;search;schema={};routePath;params;domain;state;constructor(Q,Z,J,K){if(!Q){let G=f.getStore().req;this.params=G.params,this.rawRequest=G.rawRequest,this.kind=G.kind,this.routePath=G.routePath,this.domain=G.domain??null,this.state=G.state??new _1}else this.params=Z,this.rawRequest=Q,this.routePath=K,this.kind=J??"api",this.domain=a1(Q),this.state=new _1;this.headers=this.rawRequest.headers;let $=z1(this.rawRequest.headers.get("Cookie")),X=new URL(this.rawRequest.url),Y=new Map;for(let[G,W]of X.searchParams)if(Y.has(G)){let V=Y.get(G);if(Array.isArray(V))V.push(W),Y.set(G,V);else Y.set(G,[V,W])}else Y.set(G,W);let H=Object.fromEntries(Y.entries());this.search=new u(H),this.cookies=$}locale(){let Q=f.getStore();if(Q.locale)return Q.locale;let Z=e1(Q0);return Z.isLocaleAware?Z.detectLocale(Q.req):Q.locale}ctx(){return f.getStore()}isModelOriginated(){return o1(this.rawRequest)}mcpGrant(){return n1(this.rawRequest)??null}cspNonce(){return D1(this.rawRequest)}reportProgress(Q){let Z=i1(this.rawRequest);if(!Z)return!1;return Z(Q),!0}get signal(){return this.rawRequest.signal}range(){return b1(this.rawRequest.headers.get("Range"))}refine(Q){return{}}async parseBody(){let Q=d1(this.rawRequest.headers.get("Content-Type"));if(l1(Q))return new u(await this.parseJsonBody());if(Q==="application/x-www-form-urlencoded"||Q==="multipart/form-data"){if(Q==="multipart/form-data"&&!N1(this.schema)){let K=h1(this.schema??{});if(K!==null)u1(this.rawRequest,K)}let Z;try{Z=await this.rawRequest.formData()}catch(K){if(K instanceof _)throw K;throw new _("The request body could not be read as a form.")}let J=new Map;for(let[K,$]of Z.entries())if(J.has(K)){let X=J.get(K);if(Array.isArray(X))X.push($);else J.set(K,[X,$])}else J.set(K,$);return new u(Object.fromEntries(J.entries()))}return new u({})}async parseJsonBody(){if(!this.rawRequest.body)return{};let Q;try{Q=await this.rawRequest.text()}catch(J){if(J instanceof _)throw J;throw new _("The request body could not be read.")}if(Q.trim()==="")return{};let Z;try{Z=JSON.parse(Q)}catch{throw new _("The request body is not valid JSON.")}if(Z===null||typeof Z!=="object")throw new _("The request body must be a JSON object.");return Z}validateInput(Q){if(N1(this.schema))return this.validateWithSchema(Q);let Z=Q.toJSON()??{},J={},K=Object.entries(this.schema).map(([$,X])=>({key:$,rules:Object.entries(X).map(([Y,H])=>({rule:Y,message:H,check:typeof H==="function"?null:this.ruleFor($,Y)}))}));for(let{key:$,rules:X}of K)for(let{path:Y,value:H}of f0(Z,$)){let G=this.checkField(H,X);if(G.length>0){let W=J[r1(Y)]??=[];for(let V of G)if(!W.includes(V))W.push(V)}}if(this.addRefinements(J,Z),Object.keys(J).length>0)throw new o(J);return Q}checkField(Q,Z){let J=Z.some(({rule:X})=>X==="required"),K=Q===void 0||Q===null||Q==="",$=[];for(let{rule:X,message:Y,check:H}of Z){let G=Y,W=!1;if(typeof Y==="function")G=Y(Q),W=typeof G>"u";else W=H(Q);if(W)continue;if(K&&!J)continue;if(X==="required")return[String(G)];if(!$.includes(String(G)))$.push(String(G))}return $}validateWithSchema(Q){let Z=this.schema.validate(Q.toJSON()),J={};if("issues"in Z)for(let $ of Z.issues){let X=r1($.path),Y=J[X]??=[];if(!Y.includes($.message))Y.push($.message)}let K="value"in Z?new u(Z.value):Q;if(this.addRefinements(J,K.toJSON()),Object.keys(J).length>0)throw new o(J);return K}addRefinements(Q,Z){for(let[J,K]of Object.entries(this.refine(Z)??{})){let $=Q[J]??[];Q[J]=$.includes(K)?$:[...$,K]}}ruleFor(Q,Z){try{return m1(Z)}catch(J){if(J instanceof x)throw new x(`${this.constructor.name}.schema.${Q}: ${J.message}`);throw J}}async input(){return this.validateInput(await this.parseBody())}async safeInput(){let Q=await this.parseBody();try{return{isValid:!0,errors:{},input:this.validateInput(Q)}}catch(Z){if(!(Z instanceof o))throw Z;return{isValid:!1,errors:Z.errors,input:Q}}}}var Z0="x-gemi-sign-in";class g0 extends _{error;constructor(Q="Not authorized"){super(Q);this.name="AuthorizationError",this.error=Q,this.payload={api:{status:401,data:{error:X1("authorization",this.error,401)}},view:{}}}}class R1 extends _{static apiStatus=403;error;constructor(Q="Insufficient permissions"){super(Q);this.name="InsufficientPermissionsError",this.error=Q,this.payload={api:{status:R1.apiStatus,data:{error:X1("permission",this.error,R1.apiStatus)}},view:{status:403}}}}class I1 extends _{total;constructor(Q){super("Range not satisfiable");this.total=Q;this.name="RangeNotSatisfiableError",this.payload={api:{status:416,data:{error:$1("range_not_satisfiable","Range not satisfiable",416)},headers:{"Content-Range":f1(Q),"Accept-Ranges":"bytes","Cache-Control":"no-store"}},view:{}}}}class h0 extends _{constructor(Q="Not found"){super(Q);this.name="NotFoundError",this.payload={api:{status:404,data:{error:$1("not_found",Q,404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class q extends _{fileName;constructor(Q){super("File not found");this.fileName=Q;this.name="FileNotFoundError",this.payload={api:{status:404,data:{error:$1("not_found","Not found",404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class m0 extends _{constructor(Q={}){super("Authentication error");this.name="AuthenticationError";let Z=Q.redirectTo??"/auth/sign-in";this.payload={api:{status:401,data:{error:X1("authentication","Authentication error",401)},headers:{[Z0]:Z}},viewData:{status:200,data:{},headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate"},directive:{kind:"Redirect",path:Z}},view:{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:Z}}}}}import{Buffer as c0}from"buffer";function Y1(Q){if(typeof Q!=="string"||/^[\s/.]*$/.test(Q))throw Error(`Refusing to delete by prefix ${JSON.stringify(Q)}: it would match the whole store`)}class a{async putStream({body:Q,...Z},J={}){J.signal?.throwIfAborted();let K=[],$=Q.getReader();try{for(;;){J.signal?.throwIfAborted();let{done:X,value:Y}=await $.read();if(X)break;K.push(Y)}}catch(X){throw await $.cancel(X).catch(()=>{}),X}return this.put({...Z,body:c0.concat(K)},J)}async*objects(Q,Z={}){throw Error(`${this.constructor.name} does not implement objects(). Override it to list objects in this backend.`)}async deletePrefix(Q,Z={}){Y1(Q);let J=[];for await(let K of this.objects(Q,Z))J.push(K.name);for(let K of J)Z.signal?.throwIfAborted(),await this.delete({name:K,bucket:Z.bucket});return J.length}async delete(Q){throw Error(`${this.constructor.name} does not implement delete(). Override it to remove objects from this backend.`)}async read(Q){let Z=typeof Q==="string"?{name:Q}:Q,J=await this.fetch({name:Z.name,bucket:Z.bucket});if(!J.ok)throw new q(Z.name);let K=J.headers.get("Content-Type")??"application/octet-stream",$=J.headers.get("ETag")??void 0,X=J.headers.get("Last-Modified"),Y=X?new Date(X):void 0;if(Z.range){let W=await J.blob();return{body:W,start:0,end:W.size-1,total:W.size,partial:!1,type:K,etag:$,lastModified:Y,name:Z.name}}let H=Number(J.headers.get("Content-Length")),G=Number.isFinite(H)?H:0;return{body:J.body,start:0,end:G-1,total:G,partial:!1,type:K,etag:$,lastModified:Y,name:Z.name}}async size(Q){let Z=typeof Q==="string"?Q:Q.name,J=typeof Q==="string"?void 0:Q.bucket,K=await this.fetch({name:Z,bucket:J});if(!K.ok)throw new q(Z);let $=Number(K.headers.get("Content-Length"));if(Number.isFinite($))return await K.body?.cancel(),$;return(await K.blob()).size}}function J0(Q,Z){if(!Z)return Q;let J=Q.getReader(),K=!1,$,X=()=>{if(K=!0,$)Z.removeEventListener("abort",$)};return new ReadableStream({start(Y){if($=()=>{if(K)return;X(),Y.error(Z.reason),J.cancel(Z.reason).catch(()=>{})},Z.aborted)$();else Z.addEventListener("abort",$,{once:!0})},async pull(Y){let H;try{H=await J.read()}catch(G){if(K)return;X(),Y.error(G);return}if(K)return;if(H.done){X(),Y.close();return}Y.enqueue(H.value)},cancel(Y){return X(),J.cancel(Y)}},{highWaterMark:0})}import{constants as K0}from"fs";import{lstat as A1,mkdir as $0,open as X0,readdir as w1,realpath as Y0,rename as p0,rmdir as u0,unlink as G0}from"fs/promises";import{dirname as d0,isAbsolute as W0,relative as G1,resolve as t,sep as E}from"path";class F1 extends a{configured;constructor(Q){super();this.configured=Q}get folderPath(){return this.configured??`${O0()}/storage`}async realRoot(Q){let Z=t(this.folderPath);try{return await Y0(Z)}catch(J){if(J?.code!=="ENOENT")throw J;if(Q!=="write")return Z}try{await $0(Z,{recursive:!0})}catch(J){if(J?.code==="EEXIST"&&(await A1(Z)).isSymbolicLink())throw Error(`The storage folder "${Z}" is a symbolic link to a missing directory`);throw J}return Y0(Z)}async passesThroughLink(Q,Z){if(!Z)return!1;let J=Q;for(let K of Z.split(E)){J=`${J}${E}${K}`;try{if((await A1(J)).isSymbolicLink())return!0}catch($){if($?.code==="ENOENT"||$?.code==="ENOTDIR")return!1;throw $}}return!1}async resolveObjectPath(Q,Z){if(!Q)throw Error("Object name has to be specified");let J=t(this.folderPath),K=G1(J,t(J,Q)),$=Q.includes("\x00");if($||!K||K===".."||K.startsWith(`..${E}`)||W0(K)){if(Z==="read")throw new q(Q);if($)throw Error(`Refusing to ${Z} an object name containing a NUL byte`);throw Error(`Refusing to ${Z} "${Q}": it is outside the storage folder`)}let X=await this.realRoot(Z);if(await this.passesThroughLink(X,K)){if(Z==="read")throw new q(Q);throw Error(`Refusing to ${Z} "${Q}": it is or passes through a symbolic link`)}return`${X}${E}${K}`}async writeThroughTemporary(Q,Z,J){let K=null;try{Z?.throwIfAborted();let $=await this.resolveObjectPath(Q,"write");await $0(d0($),{recursive:!0}),K=`${$}.${Bun.randomUUIDv7()}.partial`;let X=await X0(K,"wx");try{await J(X)}finally{await X.close()}if(Z?.throwIfAborted(),await this.resolveObjectPath(Q,"write")!==$)throw Error(`Refusing to write "${Q}": the storage folder moved during the write`);await p0(K,$)}catch($){if(K)await G0(K).catch(()=>{});throw $}}async put(Q,{signal:Z}={}){Z?.throwIfAborted();let J,K;if(Q instanceof Blob)J=Q,K=`${Bun.randomUUIDv7()}.${Q.type.split("/")[1].split(";")[0]}`;else J=Q.body,K=Q.name;return await this.writeThroughTemporary(K,Z,async($)=>{let X=J instanceof Buffer?J:J instanceof Blob||J instanceof File?new Uint8Array(await J.arrayBuffer()):new Uint8Array;Z?.throwIfAborted(),await H0($,X)}),K}async putStream({name:Q,body:Z},{signal:J}={}){let K=Z.getReader();try{return await this.writeThroughTemporary(Q,J,async($)=>{for(;;){J?.throwIfAborted();let{done:X,value:Y}=await K.read();if(X)break;await H0($,Y)}}),Q}catch($){throw await K.cancel($).catch(()=>{}),$}}async openForRead(Q){let Z=await this.resolveObjectPath(Q,"read"),J;try{J=await X0(Z,K0.O_RDONLY|(K0.O_NOFOLLOW??0))}catch(K){if(["ELOOP","ENOENT","ENOTDIR","EISDIR"].includes(K?.code))throw new q(Q);throw K}try{let K=await J.stat();if(!K.isFile())throw new q(Q);return{handle:J,info:K,path:Z}}catch(K){throw await J.close().catch(()=>{}),K}}async fetch(Q,{signal:Z}={}){Z?.throwIfAborted();let J=typeof Q==="string"?Q:Q.name,{handle:K,info:$,path:X}=await this.openForRead(J),Y=J0(l0(K),Z),H=$.mtime.toUTCString();return new Response(Y,{headers:{"Content-Type":Bun.file(X).type,"Content-Length":String($.size),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":H}})}async read(Q){let Z=typeof Q==="string"?{name:Q}:Q,{name:J,range:K=null}=Z,{handle:$,info:X,path:Y}=await this.openForRead(J);await $.close();let H=Bun.file(Y),G=X.size,W=K?v1(K,G):null;if(K&&!W)throw new I1(G);let V=W?.start??0,O=W?W.end:G-1;return{body:W?H.slice(V,O+1):H,start:V,end:O,total:G,partial:Boolean(W),type:H.type||"application/octet-stream",lastModified:X.mtime,name:J}}async size(Q){let Z=typeof Q==="string"?Q:Q.name,{handle:J,info:K}=await this.openForRead(Z);return await J.close(),K.size}async delete(Q){let Z=typeof Q==="string"?Q:Q.name,J=await this.resolveObjectPath(Z,"delete");try{await G0(J)}catch(K){if(K?.code==="ENOENT")return;throw K}}async resolvePrefix(Q){let Z=t(this.folderPath),J=Q.lastIndexOf("/"),K=J===-1?"":Q.slice(0,J),$=J===-1?Q:Q.slice(J+1),X=G1(Z,t(Z,K));if(X===".."||X.startsWith(`..${E}`)||W0(X))throw Error(`Refusing to list "${Q}": it is outside the storage folder`);let Y=await this.realRoot("read"),H=X?`${Y}${E}${X}`:Y,G=await this.passesThroughLink(Y,X),W=X.split(E).join("/");return{root:Y,dir:H,linked:G,match:W?`${W}/${$}`:$}}async*objects(Q,{signal:Z}={}){Z?.throwIfAborted();let{root:J,dir:K,linked:$,match:X}=await this.resolvePrefix(Q);if($)return;let Y=[],H=async(G)=>{let W;try{W=await w1(G,{withFileTypes:!0})}catch(V){if(V?.code==="ENOENT"||V?.code==="ENOTDIR")return;throw V}for(let V of W){let O=`${G}${E}${V.name}`,z=G1(J,O).split(E).join("/");if(V.isDirectory()){if(`${z}/`.startsWith(X)||X.startsWith(`${z}/`))await H(O)}else if(V.isFile()&&z.startsWith(X))Y.push(z)}};await H(K),Y.sort();for(let G of Y){Z?.throwIfAborted();let W;try{W=await A1(`${J}/${G}`)}catch(V){if(V?.code==="ENOENT")continue;throw V}if(!W.isFile())continue;yield{name:G,size:W.size,lastModified:W.mtime}}}async deletePrefix(Q,Z={}){Y1(Q);let{root:J,linked:K,match:$}=await this.resolvePrefix(Q);if(Y1($),K)throw Error(`Refusing to delete by prefix "${Q}": it passes through a symbolic link`);let X=await super.deletePrefix(Q,Z);if(X>0)await this.pruneEmptyDirs(J,$);return X}async pruneEmptyDirs(Q,Z){let J=[],K=async($)=>{let X;try{X=await w1($,{withFileTypes:!0})}catch{return}for(let Y of X){if(!Y.isDirectory())continue;let H=`${$}${E}${Y.name}`,G=G1(Q,H).split(E).join("/");if(`${G}/`.startsWith(Z)||Z.startsWith(`${G}/`)){if(await K(H),`${G}/`.startsWith(Z))J.push(H)}}};await K(Q);for(let $ of J)try{await u0($)}catch{}}async list(){return await w1(this.folderPath)}}async function H0(Q,Z){for(let J=0;J<Z.byteLength;){let{bytesWritten:K}=await Q.write(Z,J);J+=K}}var V0=65536;function l0(Q){let Z=0,J=!1,K=async()=>{if(J)return;J=!0,await Q.close().catch(()=>{})};return new ReadableStream({async pull($){try{let X=new Uint8Array(V0),{bytesRead:Y}=await Q.read(X,0,V0,Z);if(Y===0){await K(),$.close();return}Z+=Y,$.enqueue(X.subarray(0,Y))}catch(X){await K(),$.error(X)}},cancel:K},{highWaterMark:0})}var y=30000;function cQ(Q){return Q}function j0(){return{driver:new F1,fetchTimeoutMs:y,fetchIdleTimeoutMs:y}}class T1{static token="filesystem";driver;fetchTimeoutMs;fetchIdleTimeoutMs;constructor(Q={}){this.driver=Q.driver??j0().driver,this.fetchTimeoutMs=Q.fetchTimeoutMs??y,this.fetchIdleTimeoutMs=Q.fetchIdleTimeoutMs??y}}class z0 extends Error{driver;limit;timeoutMs;object;code="storage-fetch-timeout";constructor(Q,Z,J,K){super(Z==="fetchTimeoutMs"?`${Q}: no response for "${K}" within ${J}ms (fetchTimeoutMs)`:`${Q}: the body of "${K}" sent nothing for ${J}ms (fetchIdleTimeoutMs)`);this.driver=Q;this.limit=Z;this.timeoutMs=J;this.object=K;this.name="StorageFetchTimeoutError"}}async function P0(Q,Z,J,K){let{fetchTimeoutMs:$,fetchIdleTimeoutMs:X}=K;if(J.signal||!$&&!X)return Q.fetch(Z,J);let Y=new AbortController,H=Q.constructor?.name||"FileStorageDriver",G=typeof Z==="string"?Z:Z.name,W=(z,P)=>{let M=new z0(H,z,P,G);return Y.abort(M),M},V=Promise.resolve(Q.fetch(Z,{...J,signal:Y.signal})),O;if($){let z,P=new Promise((M,U)=>{z=setTimeout(()=>U(W("fetchTimeoutMs",$)),$)});try{O=await Promise.race([V,P])}catch(M){if(Y.signal.aborted)throw V.then((U)=>U.body?.cancel(Y.signal.reason).catch(()=>{}),()=>{}),Y.signal.reason;throw M}finally{clearTimeout(z)}}else O=await V;if(!X||!O.body)return O;return new Response(i0(O.body,X,()=>W("fetchIdleTimeoutMs",X)),{status:O.status,statusText:O.statusText,headers:O.headers})}function i0(Q,Z,J){let K=Q.getReader();return new ReadableStream({async pull($){let X,Y,H=new Promise((G,W)=>{X=setTimeout(()=>{Y=J(),W(Y)},Z)});try{let G=await Promise.race([K.read(),H]);if(G.done)$.close();else $.enqueue(G.value)}catch(G){let W=Y??G;$.error(W),K.cancel(W).catch(()=>{})}finally{clearTimeout(X)}},cancel($){return K.cancel($)}},{highWaterMark:0})}class A extends Error{code="safe-fetch";url;constructor(Q,Z,J){super(Q,J);this.name=new.target.name,this.url=Z}}class g extends A{reason;code="invalid-url";constructor(Q,Z,J){super(J,Q);this.reason=Z}}class W1 extends A{host;reason;code="blocked-host";constructor(Q,Z,J){super(J==="denied"?`Requests to ${Z} are not allowed.`:`${Z} is not on the list of hosts this request may reach.`,Q);this.host=Z;this.reason=J}}class d extends A{host;address;range;code="blocked-address";constructor(Q,Z,J,K){super(Z===J?`${J} is not a public address (${K}).`:`${Z} resolves to ${J}, which is not a public address (${K}).`,Q);this.host=Z;this.address=J;this.range=K}}class H1 extends A{host;code="dns";constructor(Q,Z,J){super(`Couldn't resolve ${Z}.`,Q,{cause:J});this.host=Z}}class V1 extends A{phase;ms;code="timeout";constructor(Q,Z,J){super(Z==="connect"?`Couldn't connect within ${J} ms.`:`The request didn't finish within ${J} ms.`,Q);this.phase=Z;this.ms=J}}class O1 extends A{limit;code="too-large";constructor(Q,Z){super(`The response is larger than ${Z} bytes.`,Q);this.limit=Z}}class r extends A{contentType;allowed;code="content-type";constructor(Q,Z,J){super(`The response is ${Z??"of no content type"}, not ${J.join(" or ")}.`,Q);this.contentType=Z;this.allowed=J}}class S1 extends A{limit;code="too-many-redirects";constructor(Q,Z){super(`More than ${Z} redirects.`,Q);this.limit=Z}}class l extends A{code="network";constructor(Q,Z){super(`The request failed: ${Z instanceof Error?Z.message:String(Z)}`,Q,{cause:Z})}}class k1 extends A{status;code="http-status";constructor(Q,Z){super(`The server answered ${Z}.`,Q);this.status=Z}}function n0(Q){if(Q==="")return null;let Z=Q.split(".");if(Z.length>1&&Z[Z.length-1]==="")Z.pop();if(Z.length===0||Z.length>4)return null;let J=[];for(let X of Z){let Y=o0(X);if(Y===null)return null;J.push(Y)}let K=J.pop();for(let X of J)if(X>255)return null;if(K>=256**(4-J.length))return null;let $=K;return J.forEach((X,Y)=>{$+=X*256**(3-Y)}),new Uint8Array([Math.floor($/16777216)&255,Math.floor($/65536)&255,Math.floor($/256)&255,$&255])}function o0(Q){if(Q==="")return null;let Z=Q,J=10;if(/^0x/i.test(Z)){if(Z=Z.slice(2),J=16,Z==="")return 0}else if(Z.length>1&&Z.startsWith("0"))Z=Z.slice(1),J=8;if(!(J===16?/^[0-9a-f]+$/i:J===8?/^[0-7]+$/:/^[0-9]+$/).test(Z))return null;let $=parseInt(Z,J);return Number.isSafeInteger($)?$:null}function D0(Q){let Z=Q;if(Z.startsWith("[")&&Z.endsWith("]"))Z=Z.slice(1,-1);let J=Z.indexOf("%");if(J!==-1)Z=Z.slice(0,J);if(!Z.includes(":"))return null;let K=Z.split("::");if(K.length>2)return null;let $=(W,V)=>{if(W==="")return[];let O=[],z=W.split(":");for(let P=0;P<z.length;P++){let M=z[P];if(V&&P===z.length-1&&M.includes(".")){if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(M))return null;let U=M.split(".").map(Number);if(U.some((w)=>w>255))return null;O.push(U[0]<<8|U[1],U[2]<<8|U[3]);continue}if(!/^[0-9a-f]{1,4}$/i.test(M))return null;O.push(parseInt(M,16))}return O},X=$(K[0],K.length===1),Y=K.length===2?$(K[1],!0):[];if(!X||!Y)return null;let H;if(K.length===2){let W=8-X.length-Y.length;if(W<1)return null;H=[...X,...Array.from({length:W},()=>0),...Y]}else H=X;if(H.length!==8)return null;let G=new Uint8Array(16);return H.forEach((W,V)=>{G[V*2]=W>>8,G[V*2+1]=W&255}),G}function e(Q){let Z=D0(Q);if(Z)return{family:6,bytes:Z};let J=n0(Q);if(J)return{family:4,bytes:J};return null}function h(Q){if(Q.family===6&&s0(Q.bytes))return{family:4,bytes:Q.bytes.slice(12)};return Q}function s0(Q){for(let Z=0;Z<10;Z++)if(Q[Z]!==0)return!1;return Q[10]===255&&Q[11]===255}function Q1(Q){if(Q.family===4)return Array.from(Q.bytes).join(".");let Z=[];for(let J=0;J<16;J+=2)Z.push((Q.bytes[J]<<8|Q.bytes[J+1]).toString(16));return Z.join(":")}function i(Q){let Z=Q.lastIndexOf("/"),J=Z===-1?Q:Q.slice(0,Z),K=/^[0-9.]+$/.test(J)?a0(J):D0(J);if(!K)return null;let $=h(K.length===4?{family:4,bytes:K}:{family:6,bytes:K}),X=$.family===4?32:128,Y=X;if(Z!==-1){let H=Q.slice(Z+1);if(!/^\d{1,3}$/.test(H))return null;if(Y=Number(H),K.length===16&&$.family===4)Y-=96;if(Y<0||Y>X)return null}return{family:$.family,bytes:$.bytes,prefix:Y}}function a0(Q){return/^\d{1,3}(\.\d{1,3}){3}$/.test(Q)&&Q.split(".").every((Z)=>Number(Z)<=255)?new Uint8Array(Q.split(".").map(Number)):null}function b(Q,Z){let J=h(Q);if(J.family!==Z.family)return!1;let K=Z.prefix;for(let $=0;K>0;$++){let X=Math.min(8,K),Y=255<<8-X&255;if((J.bytes[$]&Y)!==(Z.bytes[$]&Y))return!1;K-=X}return!0}var D=(Q,Z)=>({cidr:i(Q),kind:Z,text:Q}),t0=[D("0.0.0.0/8","unspecified"),D("10.0.0.0/8","private"),D("100.64.0.0/10","shared"),D("127.0.0.0/8","loopback"),D("169.254.169.254/32","metadata"),D("169.254.0.0/16","link-local"),D("168.63.129.16/32","metadata"),D("172.16.0.0/12","private"),D("192.0.0.0/24","reserved"),D("192.0.2.0/24","documentation"),D("192.88.99.0/24","reserved"),D("192.168.0.0/16","private"),D("198.18.0.0/15","benchmarking"),D("198.51.100.0/24","documentation"),D("203.0.113.0/24","documentation"),D("224.0.0.0/4","multicast"),D("255.255.255.255/32","broadcast"),D("240.0.0.0/4","reserved")],r0=[D("::/128","unspecified"),D("::1/128","loopback"),D("64:ff9b:1::/48","private"),D("::/8","reserved"),D("100::/64","reserved"),D("2001:db8::/32","documentation"),D("2001::/23","reserved"),D("3fff::/20","documentation"),D("fd00:ec2::254/128","metadata"),D("fc00::/7","unique-local"),D("fe80::/10","link-local"),D("fec0::/10","private"),D("ff00::/8","multicast")],e0=i("64:ff9b::/96"),Q4=i("2002::/16"),Z4=i("2000::/3");function j1(Q){let Z=typeof Q==="string"?e(Q):Q;if(!Z)return{kind:"reserved",range:"not an IP address"};let J=h(Z);if(J.family===4){let $=t0.find((X)=>b(J,X.cidr));return $?{kind:$.kind,range:$.text}:null}if(b(J,e0))return j1({family:4,bytes:J.bytes.slice(12)});if(b(J,Q4))return j1({family:4,bytes:J.bytes.slice(2,6)});let K=r0.find(($)=>b(J,$.cidr));if(K)return{kind:K.kind,range:K.text};return b(J,Z4)?null:{kind:"reserved",range:"outside 2000::/3"}}function M0(Q,Z){let J=h(Q),K=h(Z);return J.family===K.family&&J.bytes.every(($,X)=>$===K.bytes[X])}import{lookup as J4}from"dns/promises";import*as K4 from"http";import*as $4 from"https";import*as n from"zlib";class E1 extends Response{#Q;#Z;address;constructor(Q,Z,J){super(Q,Z);this.#Q=J.url,this.#Z=J.redirected,this.address=J.address}get url(){return this.#Q}get redirected(){return this.#Z}}var Z1={timeout:30000,connectTimeout:1e4,maxSize:10485760,maxRedirects:5,ports:[80,443]},X4=new Set([301,302,303,307,308]),Y4=new Set([101,103,204,205,304]),G4=["host","connection","content-length","transfer-encoding","keep-alive","upgrade"],W4=["authorization","cookie","proxy-authorization"];async function L0(Q,Z={}){let J=H4(Z),K=Z.signal;K?.throwIfAborted();let $=new AbortController,X=$.signal,Y=String(Q),H=(O)=>{if(!X.aborted)$.abort(O)},G=setTimeout(()=>H(new V1(Y,"total",J.timeout)),J.timeout),W=()=>H(K.reason);K?.addEventListener("abort",W,{once:!0});let V=()=>{clearTimeout(G),K?.removeEventListener("abort",W)};try{let O=B0(Y,J),z=(Z.method??"GET").toUpperCase(),P=new Headers(Z.headers);for(let U of G4)P.delete(U);if(!P.has("accept"))P.set("accept","*/*");if(!P.has("user-agent"))P.set("user-agent","gemi");if(!P.has("accept-encoding"))P.set("accept-encoding","gzip, deflate, br");let M=await z4(z,Z.body,P);for(let U=0;;U++){Y=O.href;let{request:w,response:C,address:S}=await P4(O,z,P,M,J,X),R=C.statusCode??0,I=C.headers.location;if(X4.has(R)&&I&&Z.redirect!=="manual"){if(w.destroy(),U>=J.maxRedirects)throw new S1(O.href,J.maxRedirects);let k;try{k=new URL(I,O)}catch{throw new g(I,"malformed",`The redirect to "${I}" is not a URL.`)}if(R===303?z!=="HEAD":(R===301||R===302)&&z==="POST"){z="GET",M=null;let L=[];P.forEach((B,j)=>{if(j.startsWith("content-"))L.push(j)});for(let B of L)P.delete(B)}if(k.origin!==O.origin)for(let L of W4)P.delete(L);O=B0(k.href,J);continue}return D4({url:O,hop:U,method:z,request:w,response:C,address:S,policy:J,signal:X,release:V})}}catch(O){throw V(),X.aborted?X.reason:O}}function H4(Q){let Z=(K,$)=>{let X={hosts:[],ranges:[]};for(let Y of K){let H=Y.includes("/")||Y.includes(":")||/^[\d.]+$/.test(Y),G=H?i(Y):null;if(G)X.ranges.push(G);else if(!H&&/^(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*\.?$/i.test(Y))X.hosts.push(C0(Y));else throw TypeError(`safeFetch: "${Y}" in ${$} is not a host name or an IP range.`)}return X},J=Q.allowPrivate;return{timeout:Q.timeout??Z1.timeout,connectTimeout:Q.connectTimeout??Z1.connectTimeout,maxSize:Q.maxSize??Z1.maxSize,maxRedirects:Q.maxRedirects??Z1.maxRedirects,ports:Q.ports??Z1.ports,allow:Q.allow&&Q.allow.length>0?Z(Q.allow,"allow"):null,deny:Z(Q.deny??[],"deny"),allowPrivate:J===!0?!0:Z(J||[],"allowPrivate").ranges,contentTypes:Q.contentTypes?.length?Q.contentTypes:null,resolve:Q.resolve??V4}}async function V4(Q){return(await J4(Q,{all:!0,verbatim:!0})).map((J)=>J.address)}function C0(Q){return Q.toLowerCase().replace(/\.$/,"")}function U0(Q,Z){return Z.some((J)=>J.startsWith("*.")?Q.endsWith(J.slice(1)):Q===J)}function B0(Q,Z){let J;try{J=new URL(Q)}catch{throw new g(Q,"malformed",`"${Q}" is not a URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new g(J.href,"scheme",`Only http and https URLs can be fetched, not ${J.protocol.slice(0,-1)}.`);if(J.username||J.password)throw new g(J.href,"credentials","The URL has a username or password in it.");let K=_0(J);if(Z.ports!=="any"&&!Z.ports.includes(K))throw new g(J.href,"port",`Port ${K} is not allowed.`);return J}function _0(Q){return Q.port?Number(Q.port):Q.protocol==="https:"?443:80}async function O4(Q,Z,J){let K=C0(Q.hostname.replace(/^\[(.*)\]$/,"$1")),$=e(K),X=$!==null&&(K.includes(":")||/^\d+\.\d+\.\d+\.\d+$/.test(K));if(!X&&U0(K,Z.deny.hosts))throw new W1(Q.href,K,"denied");let Y=!X&&Z.allow!==null&&U0(K,Z.allow.hosts);if(Z.allow&&!Y&&Z.allow.ranges.length===0)throw new W1(Q.href,K,"not-allowed");let H;if(X)H=[$];else{let G;try{G=await j4(Z.resolve(K),J)}catch(W){if(J.aborted)throw J.reason;throw new H1(Q.href,K,W)}if(H=G.map((W)=>e(W)).filter((W)=>W!==null),H.length===0)throw new H1(Q.href,K)}for(let G of H){let W=Q1(G);if(Z.deny.ranges.some((O)=>b(G,O)))throw new d(Q.href,K,W,"denied");if(Z.allow&&!Y&&!Z.allow.ranges.some((O)=>b(G,O)))throw new d(Q.href,K,W,"not-allowed");let V=j1(G);if(V&&Z.allowPrivate!==!0&&!Z.allowPrivate.some((O)=>b(G,O)))throw new d(Q.href,K,W,V.kind)}return{host:K,addresses:H,isLiteral:X}}function j4(Q,Z){if(Z.aborted)return Promise.reject(Z.reason);return new Promise((J,K)=>{let $=()=>K(Z.reason);Z.addEventListener("abort",$,{once:!0}),Q.then((X)=>{Z.removeEventListener("abort",$),J(X)},(X)=>{Z.removeEventListener("abort",$),K(X)})})}async function z4(Q,Z,J){if(Z===void 0||Z===null)return null;if(Q==="GET"||Q==="HEAD")throw TypeError(`safeFetch: a ${Q} request can't have a body.`);let K=new Request("http://body.invalid/",{method:"POST",body:Z}),$=K.headers.get("content-type");if($&&!J.has("content-type"))J.set("content-type",$);return new Uint8Array(await K.arrayBuffer())}async function P4(Q,Z,J,K,$,X){let Y=new AbortController,H=setTimeout(()=>Y.abort(new V1(Q.href,"connect",$.connectTimeout)),$.connectTimeout),G=AbortSignal.any([X,Y.signal]);try{let{host:W,addresses:V,isLiteral:O}=await O4(Q,$,G),z=Q.protocol==="https:",P={};if(J.forEach((M,U)=>{P[U]=M}),K)P["content-length"]=String(K.byteLength);return await new Promise((M,U)=>{let w={method:Z,host:W,port:_0(Q),path:`${Q.pathname}${Q.search}`,headers:P,agent:!1,lookup:(L,B,j)=>{let F=B?.family,N=V.filter((J1)=>!F||J1.family===F);if(N.length===0)j(Object.assign(Error(`No IPv${F} address for ${W}`),{code:"ENOTFOUND"}));else if(B?.all)j(null,N.map((J1)=>({address:Q1(J1),family:J1.family})));else j(null,Q1(N[0]),N[0].family)}};if(z&&!O)w.servername=W;let C=(z?$4:K4).request(w),S=null,R=(L)=>{G.removeEventListener("abort",I),C.destroy(),U(L)},I=()=>R(G.aborted?G.reason:X.reason);G.addEventListener("abort",I,{once:!0});let k=(L)=>{let B=L?.remoteAddress;if(!B||S!==null)return!0;let j=e(B);if(!j||!V.some((F)=>M0(F,j)))return R(new d(Q.href,W,B,"not-allowed")),!1;return S=Q1(h(j)),!0};C.once("socket",(L)=>{let B=()=>{if(k(L)&&!z)clearTimeout(H)};if(L.connecting)L.once("connect",B);else B();if(z)L.once("secureConnect",()=>clearTimeout(H))}),C.once("response",(L)=>{if(clearTimeout(H),L.on("error",()=>{}),!k(L.socket))return;G.removeEventListener("abort",I),M({request:C,response:L,address:S})}),C.on("error",(L)=>{if(G.aborted)return R(G.reason);R(L instanceof A?L:new l(Q.href,L))}),C.end(K??void 0)})}finally{clearTimeout(H)}}function D4({url:Q,hop:Z,method:J,request:K,response:$,address:X,policy:Y,signal:H,release:G}){let W=$.statusCode??0;if(W<200||W>599)throw K.destroy(),new l(Q.href,Error(`Unexpected status ${W}`));let V=new Headers,O=$.rawHeaders;for(let B=0;B<O.length;B+=2)V.append(O[B],O[B+1]);if(Y.contentTypes){let B=V.get("content-type")?.split(";")[0].trim().toLowerCase()??null;if(!B||!Y.contentTypes.some((j)=>M4(B,j)))throw K.destroy(),new r(Q.href,B,Y.contentTypes)}let z={url:Q.href,redirected:Z>0,address:X},P={status:W,statusText:$.statusMessage??"",headers:V};if(J==="HEAD"||Y4.has(W))return K.destroy(),G(),new E1(null,P,z);let M=V.get("content-encoding")?.trim().toLowerCase(),U=M==="gzip"||M==="x-gzip"?n.createGunzip():M==="deflate"?n.createInflate():M==="br"?n.createBrotliDecompress():null,w=Number(V.get("content-length"));if(!U&&Number.isFinite(w)&&w>Y.maxSize)throw K.destroy(),new O1(Q.href,Y.maxSize);if(U)V.delete("content-encoding"),V.delete("content-length");let C=U?$.pipe(U):$,S=0,R=!1,I=()=>{},k=()=>{R=!0,H.removeEventListener("abort",I),G()},L=new ReadableStream({start(B){let j=(N)=>{if(R)return;if(k(),N===void 0)B.close();else K.destroy(),U?.destroy(),B.error(N)};if(I=()=>j(H.reason),H.addEventListener("abort",I,{once:!0}),H.aborted)return I();C.on("data",(N)=>{if(R)return;if(S+=N.byteLength,S>Y.maxSize)return j(new O1(Q.href,Y.maxSize));if(B.enqueue(new Uint8Array(N)),(B.desiredSize??1)<=0)C.pause()}),C.once("end",()=>j());let F=(N)=>j(N instanceof A?N:new l(Q.href,N));if(C.on("error",F),U)$.on("error",F);$.once("aborted",()=>j(new l(Q.href,Error("The response was cut off."))))},pull(){C.resume()},cancel(){if(R)return;k(),K.destroy(),U?.destroy()}});return new E1(L,P,z)}function M4(Q,Z){let J=Z.toLowerCase();return J.endsWith("/*")?Q.startsWith(J.slice(0,-1)):Q===J}function R0(Q){return L4(Q)??_4(Q)??N4(Q)}var x1=4096,U4={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/avif":"avif","image/heic":"heic","image/heif":"heif","image/bmp":"bmp","image/tiff":"tiff","image/x-icon":"ico","image/svg+xml":"svg","audio/mpeg":"mp3","audio/aac":"aac","audio/mp4":"m4a","audio/ogg":"ogg","audio/flac":"flac","audio/wav":"wav","video/mp4":"mp4","video/quicktime":"mov","video/webm":"webm","video/x-matroska":"mkv","video/x-msvideo":"avi","font/woff":"woff","font/woff2":"woff2","font/ttf":"ttf","font/otf":"otf","application/pdf":"pdf","application/zip":"zip","application/gzip":"gz","application/xml":"xml","text/html":"html","text/plain":"txt","application/octet-stream":"bin"};function I0(Q){return U4[Q]??"bin"}function T(Q,Z,J=0){if(Q.length<J+Z.length)return!1;return Z.every((K,$)=>Q[J+$]===K)}function v(Q,Z,J){return String.fromCharCode(...Q.subarray(Z,J))}var B4={avif:"image/avif",avis:"image/avif",heic:"image/heic",heix:"image/heic",hevc:"image/heic",hevx:"image/heic",heim:"image/heic",heis:"image/heic",mif1:"image/heif",msf1:"image/heif","qt ":"video/quicktime","M4A ":"audio/mp4","M4B ":"audio/mp4"};function L4(Q){if(T(Q,[137,80,78,71,13,10,26,10]))return"image/png";if(T(Q,[255,216,255]))return"image/jpeg";if(Q.length>=6&&(v(Q,0,6)==="GIF87a"||v(Q,0,6)==="GIF89a"))return"image/gif";if(Q.length>=12&&v(Q,0,4)==="RIFF"){let Z=v(Q,8,12);if(Z==="WEBP")return"image/webp";if(Z==="WAVE")return"audio/wav";if(Z==="AVI ")return"video/x-msvideo"}if(Q.length>=12&&v(Q,4,8)==="ftyp"){let Z=v(Q,8,12);return B4[Z]??"video/mp4"}if(T(Q,[73,73,42,0])||T(Q,[77,77,0,42]))return"image/tiff";if(T(Q,[66,77])&&T(Q,[0,0,0,0],6))return"image/bmp";if(T(Q,[0,0,1,0])&&Q.length>=6&&Q[4]>0)return"image/x-icon";if(T(Q,[37,80,68,70,45]))return"application/pdf";if(T(Q,[80,75,3,4]))return"application/zip";if(T(Q,[31,139]))return"application/gzip";if(T(Q,[26,69,223,163]))return v(Q,0,Math.min(Q.length,64)).includes("webm")?"video/webm":"video/x-matroska";if(Q.length>=4){let Z=v(Q,0,4);if(Z==="OggS")return"audio/ogg";if(Z==="fLaC")return"audio/flac";if(Z==="wOFF")return"font/woff";if(Z==="wOF2")return"font/woff2";if(Z==="OTTO")return"font/otf"}if(T(Q,[0,1,0,0,0]))return"font/ttf";if(Q.length>=3&&v(Q,0,3)==="ID3")return"audio/mpeg";if(Q.length>=2&&Q[0]===255){if((Q[1]&246)===240)return"audio/aac";if((Q[1]&224)===224&&(Q[1]&6)!==0)return"audio/mpeg"}return null}var C4=["!doctype html","html","head","script","iframe","h1","div","font","table","a","style","title","b","body","br","p","!--"];function _4(Q){let Z=new TextDecoder("utf-8",{fatal:!1}).decode(Q);if(Z.charCodeAt(0)===65279)Z=Z.slice(1);if(Z=Z.trimStart(),!Z.startsWith("<"))return null;let J=Z.toLowerCase(),K=J;for(;;){K=K.trimStart();let $=/^(<\?[\s\S]*?\?>|<!--[\s\S]*?-->|<!doctype[^>]*>)/.exec(K);if(!$)break;K=K.slice($[0].length)}if(/^<svg[\s>/]/.test(K))return"image/svg+xml";for(let $ of C4){if(!J.startsWith(`<${$}`))continue;if(/^[\s>]/.test(J.charAt($.length+1)))return"text/html"}if(/^<(html|head|body)[\s>]/.test(K))return"text/html";if(J.startsWith("<?xml"))return"application/xml";return null}function N4(Q){if(Q.length===0)return"application/octet-stream";for(let Z of Q)if(Z<32&&Z!==9&&Z!==10&&Z!==12&&Z!==13&&Z!==27)return"application/octet-stream";try{return new TextDecoder("utf-8",{fatal:!0}).decode(Q,{stream:!0}),"text/plain"}catch{return"application/octet-stream"}}var R4=new Set(["text/html","application/xhtml+xml","image/svg+xml","text/xml","application/xml","text/xsl","application/xslt+xml"]);function N0(Q){let Z=Q.split(";")[0].trim().toLowerCase();return R4.has(Z)||Z.endsWith("+xml")}function A0(Q,Z){let J=Q.split(";")[0].trim().toLowerCase();return Z.some((K)=>{let $=K.split(";")[0].trim().toLowerCase();if($==="*/*"||$==="*")return!N0(J);if($.endsWith("/*"))return J.startsWith($.slice(0,-1))&&!N0(J);return J===$})}import{Buffer as w4}from"buffer";async function w0(Q){try{return(await import("sharp")).default}catch(Z){throw Error(`${Q} requires the 'sharp' package. Install it with \`bun add sharp\`.`,{cause:Z})}}async function F0(Q,Z,J={}){let{name:K,directory:$,bucket:X,maxSize:Y,timeout:H,contentTypes:G,signal:W}=J;if(K!==void 0&&$!==void 0)throw TypeError("Storage.putFromUrl(): pass `name` or `directory`, not both.");if(K!==void 0&&!K)throw TypeError("Storage.putFromUrl(): `name` is empty.");let V=await L0(Z,{...J.fetch,method:"GET",redirect:"follow",contentTypes:void 0,signal:W,timeout:H,maxSize:Y});if(!V.ok)throw await V.body?.cancel().catch(()=>{}),new k1(V.url,V.status);let O=(V.body??new Response(new Uint8Array).body).getReader(),z=async(j)=>{throw await O.cancel(j).catch(()=>{}),j},P=[],M=0,U=!1;while(M<x1){let{done:j,value:F}=await O.read();if(j){U=!0;break}P.push(F),M+=F.byteLength}let w=A4(P,M),C=R0(w.subarray(0,Math.min(M,x1))),S=G?.length?G:["*/*"];if(!A0(C,S))await z(new r(V.url,C,S));let R=K??[($??"").replace(/\/+$/,""),`${Bun.randomUUIDv7()}.${I0(C)}`].filter(Boolean).join("/"),I=M,k=new ReadableStream({start(j){if(M>0)j.enqueue(w);if(U)j.close()},async pull(j){let{done:F,value:N}=await O.read();if(F){j.close();return}I+=N.byteLength,j.enqueue(N)},cancel(j){return O.cancel(j)}}),L={name:R,bucket:X,body:k,contentType:C},B;try{B=Q.putStream?await Q.putStream(L,{signal:W}):await a.prototype.putStream.call(Q,L,{signal:W})}catch(j){throw await z(j),j}return{name:B,contentType:C,size:I,url:V.url}}function A4(Q,Z){if(Q.length===1)return Q[0];let J=new Uint8Array(Z),K=0;for(let $ of Q)J.set($,K),K+=$.byteLength;return J}class F4 extends T0{static getFacadeAccessor(){return T1}static async put(Q,Z={}){return this.getFacadeRoot().driver.put(Q,Z)}static async putFromUrl(Q,Z={}){return F0(this.getFacadeRoot().driver,Q,Z)}static async metadata(Q){let Z=w4.from(await Q.arrayBuffer()),J=await w0("Storage.metadata()");try{return await J(Z).metadata()}catch{return{}}}static async fetch(Q,Z={}){Z.signal?.throwIfAborted();let J=this.getFacadeRoot();return P0(J.driver,Q,Z,{fetchTimeoutMs:J.fetchTimeoutMs??y,fetchIdleTimeoutMs:J.fetchIdleTimeoutMs??y})}static async read(Q,Z={}){let J=typeof Q==="string"?{name:Q}:{...Q},K="range"in Z?Z.range??null:J.range!==void 0?J.range:f.getStore()?.rangeRequest??null;return this.getFacadeRoot().driver.read({...J,range:K})}static list(Q){return this.getFacadeRoot().driver.list(Q)}static objects(Q,Z={}){return this.getFacadeRoot().driver.objects(Q,Z)}static async deletePrefix(Q,Z={}){return this.getFacadeRoot().driver.deletePrefix(Q,Z)}static async delete(Q){return this.getFacadeRoot().driver.delete(Q)}}class T4{config;static token="redis";instance=null;connectingSince=null;downSince=null;replaceDelay=500;constructor(Q={}){this.config=Q}get client(){if(this.instance===null)return this.build();let Q=this.instance;if(this.isDown(Q,Date.now())){this.instance=null;try{Q.close()}catch{}return this.build()}return Q}set client(Q){this.instance=Q,this.connectingSince=null,this.downSince=null,this.replaceDelay=500}close(){let Q=this.instance;this.instance=null,this.connectingSince=null,this.downSince=null,this.replaceDelay=500,Q?.close()}build(){let Q=new(S4())(this.config.url,this.config.options);if(this.instance=Q,this.downSince=null,this.connectingSince=null,typeof Q.connect==="function"){this.connectingSince=Date.now();let Z;try{Z=Promise.resolve(Q.connect())}catch(J){Z=Promise.reject(J)}Z.then(()=>{if(this.instance!==Q)return;this.connectingSince=null,this.replaceDelay=500},()=>{if(this.instance!==Q)return;this.connectingSince=null})}return Q}isDown(Q,Z){if(Q.connected!==!1||typeof Q.connect!=="function")return this.downSince=null,!1;if(this.connectingSince!==null){let J=(this.config.options?.connectionTimeout??1e4)+5000;if(Z-this.connectingSince<J)return!1;this.connectingSince=null}if(this.downSince??=Z,Z-this.downSince<this.replaceDelay)return!1;return this.replaceDelay=Math.min(this.replaceDelay*2,1e4),!0}}function S4(){let Q=globalThis.Bun?.RedisClient;if(typeof Q!=="function")throw Error("Redis requires Bun's built-in Redis client, which this runtime does not provide. Run the app under Bun, or bind your own client for the 'redis' token.");return Q}
|
|
3
|
-
export{q1 as Ki,S0 as Li,E4 as Mi,d1 as Ni,e4 as Oi,n1 as Pi,QQ as Qi,b1 as Ri,v1 as Si,q4 as Ti,b4 as Ui,v4 as Vi,f1 as Wi,D1 as Xi,h4 as Yi,m4 as Zi,JQ as _i,a1 as $i,KQ as aj,$Q as bj,o as cj,x as dj,B1 as ej,i4 as fj,n4 as gj,o4 as hj,s4 as ij,a4 as jj,y0 as kj,Z0 as lj,g0 as mj,R1 as nj,I1 as oj,h0 as pj,q as qj,m0 as rj,w0 as sj,Y1 as tj,a as uj,J0 as vj,F1 as wj,cQ as xj,j0 as yj,T1 as zj,z0 as Aj,A as Bj,g as Cj,W1 as Dj,d as Ej,H1 as Fj,V1 as Gj,O1 as Hj,r as Ij,S1 as Jj,l as Kj,k1 as Lj,e as Mj,j1 as Nj,E1 as Oj,L0 as Pj,R0 as Qj,N0 as Rj,F4 as Sj,T4 as Tj};
|
|
4
|
-
|
|
5
|
-
//# debugId=B6F5C37487A3998F64756E2164756E21
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|