gemi 0.119.1 → 0.120.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/app/index.js +2 -2
- package/dist/app/index.js.map +1 -1
- package/dist/auth/routes.d.ts.map +1 -1
- package/dist/bin/gemi.js +32 -5
- package/dist/bin/gemi.js.map +6 -5
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-xfw8zyvn.js → chunk-0ejjgzwc.js} +2 -2
- package/dist/{chunk-xfw8zyvn.js.map → chunk-0ejjgzwc.js.map} +1 -1
- package/dist/{chunk-33s2xqv1.js → chunk-0k02tza1.js} +1 -1
- package/dist/{chunk-a1qt8aky.js → chunk-0yj0s1pn.js} +2 -2
- package/dist/{chunk-a1qt8aky.js.map → chunk-0yj0s1pn.js.map} +1 -1
- package/dist/{chunk-y09r0wsw.js → chunk-19dpzp4y.js} +3 -3
- package/dist/{chunk-y09r0wsw.js.map → chunk-19dpzp4y.js.map} +1 -1
- package/dist/{chunk-cvfg88cx.js → chunk-1wnnkde0.js} +3 -3
- package/dist/{chunk-cvfg88cx.js.map → chunk-1wnnkde0.js.map} +1 -1
- package/dist/{chunk-xx7necqt.js → chunk-1xdrs2hx.js} +3 -3
- package/dist/{chunk-xx7necqt.js.map → chunk-1xdrs2hx.js.map} +1 -1
- package/dist/{chunk-mdp2dsbb.js → chunk-231a9920.js} +3 -3
- package/dist/{chunk-mdp2dsbb.js.map → chunk-231a9920.js.map} +3 -3
- package/dist/{chunk-scc0j5k9.js → chunk-2c0s0561.js} +2 -2
- package/dist/{chunk-scc0j5k9.js.map → chunk-2c0s0561.js.map} +1 -1
- package/dist/{chunk-8wcpxm41.js → chunk-2n3pgfnb.js} +2 -2
- package/dist/{chunk-8wcpxm41.js.map → chunk-2n3pgfnb.js.map} +1 -1
- package/dist/{chunk-q290tgza.js → chunk-32n8t8x6.js} +2 -2
- package/dist/{chunk-q290tgza.js.map → chunk-32n8t8x6.js.map} +1 -1
- package/dist/{chunk-pvz90a49.js → chunk-3gsv1vv1.js} +2 -2
- package/dist/{chunk-hm9cjxy2.js.map → chunk-3gsv1vv1.js.map} +1 -1
- package/dist/{chunk-sce5jes2.js → chunk-3wnghdsx.js} +2 -2
- package/dist/{chunk-sce5jes2.js.map → chunk-3wnghdsx.js.map} +1 -1
- package/dist/{chunk-01ehxca0.js → chunk-471htqmz.js} +2 -2
- package/dist/{chunk-01ehxca0.js.map → chunk-471htqmz.js.map} +1 -1
- package/dist/{chunk-dwpn6fze.js → chunk-48gmyaxc.js} +2 -2
- package/dist/{chunk-dwpn6fze.js.map → chunk-48gmyaxc.js.map} +1 -1
- package/dist/{chunk-3zxfd7pn.js → chunk-4acpw92g.js} +3 -3
- package/dist/{chunk-3zxfd7pn.js.map → chunk-4acpw92g.js.map} +1 -1
- package/dist/{chunk-d806cy7p.js → chunk-4fx8p02c.js} +2 -2
- package/dist/{chunk-d806cy7p.js.map → chunk-4fx8p02c.js.map} +1 -1
- package/dist/{chunk-xtzn0qfh.js → chunk-51w5ktv2.js} +3 -3
- package/dist/{chunk-xtzn0qfh.js.map → chunk-51w5ktv2.js.map} +1 -1
- package/dist/{chunk-cte6ysqd.js → chunk-5nj94s66.js} +4 -4
- package/dist/{chunk-cte6ysqd.js.map → chunk-5nj94s66.js.map} +1 -1
- package/dist/{chunk-bgwtdbfw.js → chunk-5tdxbwzg.js} +3 -3
- package/dist/{chunk-bgwtdbfw.js.map → chunk-5tdxbwzg.js.map} +1 -1
- package/dist/{chunk-hkf2k2eq.js → chunk-65beps2q.js} +3 -3
- package/dist/{chunk-hkf2k2eq.js.map → chunk-65beps2q.js.map} +1 -1
- package/dist/{chunk-1z1rj2zq.js → chunk-6yhpprzs.js} +3 -3
- package/dist/{chunk-1z1rj2zq.js.map → chunk-6yhpprzs.js.map} +1 -1
- package/dist/{chunk-j5858bz7.js → chunk-7ftj43vp.js} +2 -2
- package/dist/{chunk-j5858bz7.js.map → chunk-7ftj43vp.js.map} +1 -1
- package/dist/{chunk-qf4bmee9.js → chunk-7g649j8h.js} +2 -2
- package/dist/{chunk-qf4bmee9.js.map → chunk-7g649j8h.js.map} +1 -1
- package/dist/{chunk-675kzd7z.js → chunk-7mmw0jr2.js} +2 -2
- package/dist/{chunk-675kzd7z.js.map → chunk-7mmw0jr2.js.map} +1 -1
- package/dist/{chunk-pkr5dsbk.js → chunk-9d2d08qm.js} +2 -2
- package/dist/{chunk-pkr5dsbk.js.map → chunk-9d2d08qm.js.map} +1 -1
- package/dist/{chunk-r1favzz4.js → chunk-9rr5h818.js} +3 -3
- package/dist/{chunk-r1favzz4.js.map → chunk-9rr5h818.js.map} +1 -1
- package/dist/{chunk-30xxc6r7.js → chunk-9xyxbxgk.js} +2 -2
- package/dist/{chunk-30xxc6r7.js.map → chunk-9xyxbxgk.js.map} +1 -1
- package/dist/{chunk-6ggmk2eg.js → chunk-c0v61fp5.js} +2 -2
- package/dist/{chunk-6ggmk2eg.js.map → chunk-c0v61fp5.js.map} +1 -1
- package/dist/{chunk-hzepfrzy.js → chunk-c7qs1xp3.js} +2 -2
- package/dist/{chunk-hzepfrzy.js.map → chunk-c7qs1xp3.js.map} +1 -1
- package/dist/{chunk-1m3hvy3q.js → chunk-cca0grq3.js} +2 -2
- package/dist/{chunk-1m3hvy3q.js.map → chunk-cca0grq3.js.map} +1 -1
- package/dist/{chunk-g9hhdcax.js → chunk-cskqet01.js} +2 -2
- package/dist/{chunk-g9hhdcax.js.map → chunk-cskqet01.js.map} +1 -1
- package/dist/{chunk-8t6dwwz6.js → chunk-cvr5624r.js} +1 -1
- package/dist/{chunk-xzn2nmny.js → chunk-d2c3947c.js} +2 -2
- package/dist/{chunk-xzn2nmny.js.map → chunk-d2c3947c.js.map} +1 -1
- package/dist/{chunk-jg79n382.js → chunk-d5f1m3d2.js} +2 -2
- package/dist/{chunk-jg79n382.js.map → chunk-d5f1m3d2.js.map} +1 -1
- package/dist/{chunk-rpwb1t5z.js → chunk-dbx3g5ck.js} +2 -2
- package/dist/{chunk-rpwb1t5z.js.map → chunk-dbx3g5ck.js.map} +1 -1
- package/dist/chunk-dc8gyybt.js +24 -0
- package/dist/{chunk-rbm57mck.js.map → chunk-dc8gyybt.js.map} +3 -3
- package/dist/{chunk-tfdmvxza.js → chunk-dedqr5wb.js} +2 -2
- package/dist/{chunk-tfdmvxza.js.map → chunk-dedqr5wb.js.map} +1 -1
- package/dist/{chunk-aedkrck1.js → chunk-dhbgrv58.js} +1 -1
- package/dist/{chunk-nang3847.js → chunk-dwedx1jb.js} +3 -3
- package/dist/{chunk-nang3847.js.map → chunk-dwedx1jb.js.map} +1 -1
- package/dist/{chunk-m4kmetpb.js → chunk-ep0baa9g.js} +2 -2
- package/dist/{chunk-m4kmetpb.js.map → chunk-ep0baa9g.js.map} +1 -1
- package/dist/{chunk-kk77x2v4.js → chunk-er8acmch.js} +7 -7
- package/dist/{chunk-kk77x2v4.js.map → chunk-er8acmch.js.map} +3 -3
- package/dist/{chunk-thz75w6e.js → chunk-fcqx2t0p.js} +2 -2
- package/dist/{chunk-thz75w6e.js.map → chunk-fcqx2t0p.js.map} +1 -1
- package/dist/{chunk-z759yah5.js → chunk-fenc5tpv.js} +2 -2
- package/dist/{chunk-z759yah5.js.map → chunk-fenc5tpv.js.map} +1 -1
- package/dist/{chunk-hr1r3g0d.js → chunk-gc2dz11k.js} +2 -2
- package/dist/{chunk-hr1r3g0d.js.map → chunk-gc2dz11k.js.map} +1 -1
- package/dist/{chunk-pqc16rrx.js → chunk-gemzbw7f.js} +2 -2
- package/dist/{chunk-pqc16rrx.js.map → chunk-gemzbw7f.js.map} +1 -1
- package/dist/{chunk-sn04cyw0.js → chunk-gy81nd9a.js} +2 -2
- package/dist/{chunk-sn04cyw0.js.map → chunk-gy81nd9a.js.map} +1 -1
- package/dist/{chunk-gqfqnv3f.js → chunk-h43jp8ws.js} +2 -2
- package/dist/{chunk-gqfqnv3f.js.map → chunk-h43jp8ws.js.map} +1 -1
- package/dist/chunk-hhymaj0m.js +57 -0
- package/dist/{chunk-dxag6enj.js.map → chunk-hhymaj0m.js.map} +9 -7
- package/dist/chunk-htgmy3x7.js +5 -0
- package/dist/{chunk-3nf95j9e.js.map → chunk-htgmy3x7.js.map} +1 -1
- package/dist/{chunk-fsj5k511.js → chunk-jaa6xkeh.js} +2 -2
- package/dist/{chunk-fsj5k511.js.map → chunk-jaa6xkeh.js.map} +1 -1
- package/dist/{chunk-2bja99cq.js → chunk-kk18xqgc.js} +2 -2
- package/dist/{chunk-2bja99cq.js.map → chunk-kk18xqgc.js.map} +1 -1
- package/dist/{chunk-ebret82e.js → chunk-krk7mcgm.js} +3 -3
- package/dist/{chunk-ebret82e.js.map → chunk-krk7mcgm.js.map} +1 -1
- package/dist/{chunk-bz8xssrc.js → chunk-krtybgz1.js} +2 -2
- package/dist/{chunk-bz8xssrc.js.map → chunk-krtybgz1.js.map} +1 -1
- package/dist/{chunk-eke2frrm.js → chunk-m53fgf20.js} +3 -3
- package/dist/{chunk-eke2frrm.js.map → chunk-m53fgf20.js.map} +1 -1
- package/dist/{chunk-490sbcma.js → chunk-m83zm86m.js} +2 -2
- package/dist/{chunk-490sbcma.js.map → chunk-m83zm86m.js.map} +1 -1
- package/dist/{chunk-xx3zvc3g.js → chunk-meg8rtr6.js} +2 -2
- package/dist/{chunk-xx3zvc3g.js.map → chunk-meg8rtr6.js.map} +1 -1
- package/dist/{chunk-39kyz4k6.js → chunk-mr94nfp1.js} +3 -3
- package/dist/{chunk-39kyz4k6.js.map → chunk-mr94nfp1.js.map} +1 -1
- package/dist/{chunk-g5ppst76.js → chunk-nz8z8jr1.js} +3 -3
- package/dist/{chunk-g5ppst76.js.map → chunk-nz8z8jr1.js.map} +1 -1
- package/dist/{chunk-n4sdm0jn.js → chunk-pemhmjzp.js} +3 -3
- package/dist/{chunk-n4sdm0jn.js.map → chunk-pemhmjzp.js.map} +1 -1
- package/dist/{chunk-76p0rf4d.js → chunk-pn2x59ge.js} +3 -3
- package/dist/{chunk-76p0rf4d.js.map → chunk-pn2x59ge.js.map} +1 -1
- package/dist/{chunk-aqpaw4jq.js → chunk-qsz9241c.js} +2 -2
- package/dist/{chunk-aqpaw4jq.js.map → chunk-qsz9241c.js.map} +1 -1
- package/dist/{chunk-5dbpgyrx.js → chunk-qy8c0gzr.js} +2 -2
- package/dist/{chunk-5dbpgyrx.js.map → chunk-qy8c0gzr.js.map} +1 -1
- package/dist/{chunk-qkxnvpaj.js → chunk-r01aqf0q.js} +2 -2
- package/dist/{chunk-qkxnvpaj.js.map → chunk-r01aqf0q.js.map} +1 -1
- package/dist/{chunk-jf6qqzat.js → chunk-rhvc1axc.js} +2 -2
- package/dist/{chunk-jf6qqzat.js.map → chunk-rhvc1axc.js.map} +1 -1
- package/dist/{chunk-kkte8nze.js → chunk-s07v65x6.js} +3 -3
- package/dist/{chunk-kkte8nze.js.map → chunk-s07v65x6.js.map} +1 -1
- package/dist/{chunk-5cgq9c43.js → chunk-s5k3yq6t.js} +2 -2
- package/dist/{chunk-5cgq9c43.js.map → chunk-s5k3yq6t.js.map} +1 -1
- package/dist/{chunk-453rmkpm.js → chunk-sx340k85.js} +2 -2
- package/dist/{chunk-453rmkpm.js.map → chunk-sx340k85.js.map} +1 -1
- package/dist/{chunk-hm9cjxy2.js → chunk-tewhms9w.js} +2 -2
- package/dist/{chunk-pvz90a49.js.map → chunk-tewhms9w.js.map} +1 -1
- package/dist/{chunk-tzdenj0n.js → chunk-tk135gmj.js} +3 -3
- package/dist/{chunk-tzdenj0n.js.map → chunk-tk135gmj.js.map} +1 -1
- package/dist/{chunk-4c1kdd8p.js → chunk-vx7hvyvq.js} +2 -2
- package/dist/{chunk-4c1kdd8p.js.map → chunk-vx7hvyvq.js.map} +1 -1
- package/dist/{chunk-razjfecn.js → chunk-wjkh2gem.js} +1 -1
- package/dist/{chunk-vkkt7j2y.js → chunk-wnj7q0th.js} +3 -3
- package/dist/{chunk-vkkt7j2y.js.map → chunk-wnj7q0th.js.map} +1 -1
- package/dist/{chunk-p83erprx.js → chunk-wqe47c0j.js} +2 -2
- package/dist/{chunk-p83erprx.js.map → chunk-wqe47c0j.js.map} +1 -1
- package/dist/{chunk-nrezmscd.js → chunk-y6wt5b6t.js} +1 -1
- package/dist/{chunk-9pkj7sk6.js → chunk-yds7zwc3.js} +2 -2
- package/dist/{chunk-9pkj7sk6.js.map → chunk-yds7zwc3.js.map} +1 -1
- package/dist/{chunk-x6v2zex2.js → chunk-zefs2b6h.js} +2 -2
- package/dist/{chunk-x6v2zex2.js.map → chunk-zefs2b6h.js.map} +1 -1
- package/dist/{chunk-de4t48j9.js → chunk-zg6hmc48.js} +1 -1
- package/dist/{chunk-5ses4tcz.js → chunk-zrcd9hxr.js} +2 -2
- package/dist/{chunk-5ses4tcz.js.map → chunk-zrcd9hxr.js.map} +1 -1
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +26 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/staticNavigation.d.ts +26 -0
- package/dist/client/staticNavigation.d.ts.map +1 -0
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/SameSiteBounceMiddleware.d.ts +42 -0
- package/dist/http/SameSiteBounceMiddleware.d.ts.map +1 -0
- package/dist/http/ViewRouter.d.ts +36 -2
- package/dist/http/ViewRouter.d.ts.map +1 -1
- package/dist/http/index.d.ts +2 -1
- package/dist/http/index.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +2 -2
- package/dist/internal/islandRuntime.d.ts +16 -0
- package/dist/internal/islandRuntime.d.ts.map +1 -1
- package/dist/internal/staticNavigationRuntime.d.ts +8 -0
- package/dist/internal/staticNavigationRuntime.d.ts.map +1 -0
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +2 -2
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/server/devFetch.d.ts.map +1 -1
- package/dist/server/httpProd.d.ts.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +3 -3
- package/dist/services/index.js.map +2 -2
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts +5 -0
- package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
- package/dist/services/router/staticDocument.d.ts +30 -21
- package/dist/services/router/staticDocument.d.ts.map +1 -1
- package/dist/stats/bundleStats.d.ts +6 -2
- package/dist/stats/bundleStats.d.ts.map +1 -1
- package/dist/stats/route-table.js +2 -2
- package/dist/stats/route-table.js.map +3 -3
- package/dist/stats/routeTable.d.ts +5 -1
- package/dist/stats/routeTable.d.ts.map +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/testing/index.d.ts +2 -0
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +185 -2
- package/dist/testing/index.js.map +1 -1
- package/dist/testing/staticDocument.d.ts +80 -0
- package/dist/testing/staticDocument.d.ts.map +1 -0
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-3nf95j9e.js +0 -5
- package/dist/chunk-dxag6enj.js +0 -57
- package/dist/chunk-rbm57mck.js +0 -24
- /package/dist/{chunk-33s2xqv1.js.map → chunk-0k02tza1.js.map} +0 -0
- /package/dist/{chunk-8t6dwwz6.js.map → chunk-cvr5624r.js.map} +0 -0
- /package/dist/{chunk-aedkrck1.js.map → chunk-dhbgrv58.js.map} +0 -0
- /package/dist/{chunk-razjfecn.js.map → chunk-wjkh2gem.js.map} +0 -0
- /package/dist/{chunk-nrezmscd.js.map → chunk-y6wt5b6t.js.map} +0 -0
- /package/dist/{chunk-de4t48j9.js.map → chunk-zg6hmc48.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{constants as X}from"os";var U=Symbol.for("gemi.server.shutdown");function P(){let j=globalThis;return j[U]??={shuttingDown:!1,drained:!1},j[U]}function Y(){return P().shuttingDown}function Z(){P().shuttingDown=!0}function $(){P().drained=!0}function y(j=process.env){let z={timeoutMs:Q(j.GEMI_SHUTDOWN_TIMEOUT,20),delayMs:Q(j.GEMI_SHUTDOWN_DELAY,0),providerTimeoutMs:Q(j.GEMI_SHUTDOWN_PROVIDER_TIMEOUT,5)};if(z.delayMs>0&&z.delayMs>=z.timeoutMs)console.warn(`[gemi] GEMI_SHUTDOWN_DELAY (${z.delayMs/1000}s) leaves no time to drain within GEMI_SHUTDOWN_TIMEOUT (${z.timeoutMs/1000}s); in-flight requests will be abandoned on every shutdown. Raise the timeout.`);return z}function Q(j,z){let B=j===void 0||j.trim()===""?NaN:Number(j);if(Number.isFinite(B)&&B>=0)return B*1000;if(j!==void 0)console.warn(`[gemi] Ignoring shutdown setting "${j}": expected a number of seconds.`);return z*1000}async function G(j){let{server:z,settings:B}=j,H=Date.now()+B.timeoutMs;Z(),console.log(`[gemi] Shutting down: draining in-flight requests (up to ${B.timeoutMs/1000}s).`);let F=!0;if(z){if(B.delayMs>0)await M(Math.min(B.delayMs,H-Date.now()));let O=z.stop(),R=H-Date.now();if(F=R>0?await C(O,R):z.pendingRequests===0,!F)console.error(`[gemi] Shutdown grace period elapsed with ${z.pendingRequests} request(s) still in flight; abandoning them.`),z.stop(!0).catch(()=>{})}$();let K=await j.shutdownProviders({timeoutMs:B.providerTimeoutMs}),J=F&&K.failed.length===0&&K.timedOut.length===0;return console.log(`[gemi] Shutdown ${J?"complete":"finished with errors"}.`),J?0:1}async function C(j,z){if(z<=0)return!1;let B,H=await Promise.race([j.then(()=>!0,()=>!0),new Promise((F)=>{B=setTimeout(()=>F(!1),z)})]);return clearTimeout(B),H}function M(j){return new Promise((z)=>setTimeout(z,Math.max(0,j)))}function f(j){if(!Y())return j;try{return j.headers.set("Connection","close"),j}catch{let z=new Response(j.body,j);return z.headers.set("Connection","close"),z}}function _(j){return async(z,B)=>{if(P().drained)return new Response("Service Unavailable",{status:503,headers:{Connection:"close"}});return f(await j(z,B))}}var V=Symbol.for("gemi.server.signalsInstalled"),q=1000;function w(j,z={}){let B=globalThis;if(B[V])return;B[V]=!0;let H=z.repeatWindowMs??q,F,K=(J)=>{if(F!==void 0){if(Date.now()-F<H)return;console.error(`[gemi] ${J} received again; exiting without waiting for the drain.`),process.exit(128+X.signals[J])}F=Date.now(),console.log(`[gemi] ${J} received.`),j().then((O)=>process.exit(O),(O)=>{console.error("[gemi] Shutdown failed:",O),process.exit(1)})};process.on("SIGTERM",K),process.on("SIGINT",K)}
|
|
3
|
-
export{Y as
|
|
3
|
+
export{Y as Yi,Z as Zi,y as _i,G as $i,_ as aj,w as bj};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=5354B4538A37316B64756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"import { constants } from \"node:os\";\nimport type { ShutdownReport } from \"../foundation/Application\";\nimport type { Instrumentation } from \"./types\";\n\n// On `globalThis` under a registry symbol rather than in a module variable, so\n// the flag an app's health route reads is the one the server set even when two\n// copies of this module are loaded — the built CLI bundles its own gemi (see\n// `app/App.ts`), and `bun --hot` re-evaluates every module on a reload.\nconst STATE = Symbol.for(\"gemi.server.shutdown\");\n\ntype ShutdownState = { shuttingDown: boolean; drained: boolean };\n\nfunction state(): ShutdownState {\n const global = globalThis as { [STATE]?: ShutdownState };\n global[STATE] ??= { shuttingDown: false, drained: false };\n return global[STATE];\n}\n\n/**\n * True from the moment this server process has been told to stop — before it\n * stops accepting connections — until it exits.\n *\n * gemi has no health endpoint of its own, so taking an instance out of a load\n * balancer is the app's health route's job: answer it with a `503` while this\n * is true, and the platform's probe pulls the instance while the in-flight\n * requests are still draining. Every response sent in that window also carries\n * `Connection: close`, so a client that honours it opens its next request on a\n * new connection — one the load balancer can route elsewhere — instead of\n * reusing this one.\n */\nexport function isShuttingDown(): boolean {\n return state().shuttingDown;\n}\n\nexport function markShuttingDown() {\n state().shuttingDown = true;\n}\n\n/**\n * The request drain is over and the providers' `shutdown()` may be running:\n * from here on a request must not reach the app. See `serveForShutdown`.\n */\nexport function markDrained() {\n state().drained = true;\n}\n\n/** Test seam: a fresh process starts false, and so should each test. */\nexport function resetShuttingDown() {\n state().shuttingDown = false;\n state().drained = false;\n}\n\nexport type ShutdownSettings = {\n /**\n * From the signal to the end of the request drain, in milliseconds — the\n * delay below included. Requests still in flight when it runs out are\n * abandoned. `GEMI_SHUTDOWN_TIMEOUT`, in seconds; default 20. `0` means\n * \"close the listener and do not wait\": a shutdown with nothing in flight is\n * still a clean one.\n */\n timeoutMs: number;\n /**\n * How long to keep accepting new requests after `isShuttingDown()` turns\n * true, in milliseconds, so a health probe can see the `503` and the load\n * balancer stop routing here before the listener closes.\n * `GEMI_SHUTDOWN_DELAY`, in seconds; default 0.\n */\n delayMs: number;\n /**\n * The shared deadline for every provider's `shutdown()`, in milliseconds,\n * after the drain. `GEMI_SHUTDOWN_PROVIDER_TIMEOUT`, in seconds; default 5.\n * `0` skips the hooks — deliberately, so it is not reported as a failure.\n */\n providerTimeoutMs: number;\n};\n\n/**\n * 20s to drain plus 5s for providers is 25s: under the 30s that Kubernetes,\n * Azure Container Apps and ECS give by default between `SIGTERM` and `SIGKILL`,\n * with 5s left for the `gemi start` relay, the process exit and clock skew\n * between the platform's timer and ours. A platform with a shorter window\n * (Cloud Run's 10s, Fly's 5s) needs these lowered, not the other way round —\n * a drain that outlives the grace period ends in the same `SIGKILL` as no drain.\n *\n * The delay defaults to 0 because it only helps where a probe is watching, and\n * otherwise every shutdown would pay it for nothing.\n */\nexport function shutdownSettings(\n env: Record<string, string | undefined> = process.env,\n): ShutdownSettings {\n const settings = {\n timeoutMs: seconds(env.GEMI_SHUTDOWN_TIMEOUT, 20),\n delayMs: seconds(env.GEMI_SHUTDOWN_DELAY, 0),\n providerTimeoutMs: seconds(env.GEMI_SHUTDOWN_PROVIDER_TIMEOUT, 5),\n };\n // Warned, not clamped: the delay is sized to a probe, the timeout to the\n // platform's grace period, and which one is wrong only the operator knows.\n // Left alone, every shutdown spends the whole timeout in the delay and then\n // abandons whatever is in flight without draining it.\n if (settings.delayMs > 0 && settings.delayMs >= settings.timeoutMs) {\n console.warn(\n `[gemi] GEMI_SHUTDOWN_DELAY (${settings.delayMs / 1000}s) leaves no time to drain within GEMI_SHUTDOWN_TIMEOUT (${settings.timeoutMs / 1000}s); in-flight requests will be abandoned on every shutdown. Raise the timeout.`,\n );\n }\n return settings;\n}\n\nfunction seconds(value: string | undefined, fallback: number): number {\n const parsed = value === undefined || value.trim() === \"\" ? NaN : Number(value);\n if (Number.isFinite(parsed) && parsed >= 0) return parsed * 1000;\n if (value !== undefined) {\n console.warn(`[gemi] Ignoring shutdown setting \"${value}\": expected a number of seconds.`);\n }\n return fallback * 1000;\n}\n\n/** The part of `Bun.Server` a drain needs. */\nexport type Stoppable = {\n stop(closeActiveConnections?: boolean): Promise<void>;\n readonly pendingRequests: number;\n};\n\n/**\n * The shutdown sequence, in its order:\n *\n * 1. `isShuttingDown()` turns true — first, so the health route answers `503`\n * and responses carry `Connection: close` while the listener is still open.\n * 2. After `delayMs`, the listener closes (`server.stop()` without force):\n * new connections are refused, while every request in flight — a streamed\n * response included, to its last chunk — runs to completion.\n * 3. That completion is awaited until `timeoutMs` from the start.\n * 4. From here a request is refused with a `503` before it reaches the app\n * (`serveForShutdown`), and every provider's `shutdown()` runs, reverse\n * order, `providerTimeoutMs`.\n *\n * Resolves with the exit code: 0 when every step finished in time, 1 when the\n * drain was cut short or a provider failed or overran.\n *\n * Two things `stop()` does not do, both measured on Bun 1.3.14, and both why\n * the process exit that follows is what actually ends the server:\n *\n * - It does not close a kept-alive connection. One that is idle when the\n * listener closes stays open, and a request sent down it afterwards is\n * served. That is what the `Connection: close` on every response in the\n * window is for: a client (or a proxy in front) that honours it opens its\n * next request on a new connection, which the closed listener refuses. A\n * client that does not honour it is what step 4's `503` is for — Bun does\n * not close the socket after a `Connection: close` response either (#566).\n * - `stop(true)` issued after a graceful `stop()` does not cut the remaining\n * requests off; it waits for the same ones. It is still called when the\n * drain times out, for a Bun that does, but nothing here depends on it. Nor\n * does it close an idle kept-alive connection. Only a `stop(true)` issued\n * *first* does that, and it cuts off the requests in flight with it, which\n * is the drain given up — so the idle ones are refused, not closed.\n */\nexport async function drain(params: {\n server: Stoppable | undefined;\n shutdownProviders: (options: { timeoutMs: number }) => Promise<ShutdownReport>;\n settings: ShutdownSettings;\n}): Promise<number> {\n const { server, settings } = params;\n const deadline = Date.now() + settings.timeoutMs;\n\n markShuttingDown();\n console.log(\n `[gemi] Shutting down: draining in-flight requests (up to ${settings.timeoutMs / 1000}s).`,\n );\n\n let drained = true;\n if (server) {\n if (settings.delayMs > 0) {\n await sleep(Math.min(settings.delayMs, deadline - Date.now()));\n }\n const stopped = server.stop();\n // No time left to wait — a `GEMI_SHUTDOWN_TIMEOUT` of 0, or a delay that\n // spent all of it — is \"do not wait for what is in flight\", and that is\n // only a failure when something *is* in flight. Reading it as one made\n // every clean shutdown log an abandonment and exit 1 for the operator who\n // zeroed the budget to fit a 5s grace period, with nothing to abandon.\n const remaining = deadline - Date.now();\n drained =\n remaining > 0 ? await settlesWithin(stopped, remaining) : server.pendingRequests === 0;\n if (!drained) {\n console.error(\n `[gemi] Shutdown grace period elapsed with ${server.pendingRequests} request(s) still in flight; abandoning them.`,\n );\n void server.stop(true).catch(() => {});\n }\n }\n\n // Whether or not the drain finished: a request that arrives now, down a\n // kept-alive connection the listener's close left open, would run against\n // providers that are being shut down underneath it.\n markDrained();\n const report = await params.shutdownProviders({ timeoutMs: settings.providerTimeoutMs });\n const clean = drained && report.failed.length === 0 && report.timedOut.length === 0;\n console.log(`[gemi] Shutdown ${clean ? \"complete\" : \"finished with errors\"}.`);\n return clean ? 0 : 1;\n}\n\nasync function settlesWithin(promise: Promise<unknown>, ms: number): Promise<boolean> {\n // `drain` decides for itself what a budget that is already spent means, so\n // this is only a guard: a race against `setTimeout(0)` is a coin toss, and\n // \"did not settle within no time at all\" is the honest answer to it.\n if (ms <= 0) return false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const result = await Promise.race([\n promise.then(\n () => true,\n () => true,\n ),\n new Promise<false>((resolve) => {\n timer = setTimeout(() => resolve(false), ms);\n }),\n ]);\n clearTimeout(timer);\n return result;\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));\n}\n\n/**\n * `Connection: close` on a response sent while shutting down, so the client's\n * next request opens a connection — which the load balancer can send elsewhere\n * — instead of reusing this one.\n *\n * The spec makes some responses' headers immutable (a `Response.redirect`, a\n * proxied `fetch`), and setting one throws. Bun 1.3.14 lets both be set, so\n * the copy is for a Bun that follows the spec — a throw here would turn every\n * such response in the drain window into a 500.\n */\nexport function closeConnectionWhileShuttingDown(res: Response): Response {\n if (!isShuttingDown()) return res;\n try {\n res.headers.set(\"Connection\", \"close\");\n return res;\n } catch {\n const copy = new Response(res.body, res);\n copy.headers.set(\"Connection\", \"close\");\n return copy;\n }\n}\n\n/**\n * What every response goes through while this process serves: the app's\n * instrumentation, with the two changes a shutdown makes to it.\n *\n * - While the requests in flight drain, a response carries `Connection: close`\n * (`closeConnectionWhileShuttingDown`).\n * - Once they have drained, a request is answered `503` with\n * `Connection: close` and reaches neither the app nor its instrumentation.\n * The listener is closed by then, so only a kept-alive connection can still\n * deliver one, and `server.stop()` leaves those open. Serving it would run a\n * handler against providers whose `shutdown()` is closing the pool, the\n * queue or the cache it uses — until the process exits. The instrumentation\n * is skipped too because it is app code, and a tracer or error reporter is\n * exactly what a provider flushes and closes at this point.\n */\nexport function serveForShutdown(instrumentation: Instrumentation): Instrumentation {\n return async (req, next) => {\n if (state().drained) {\n return new Response(\"Service Unavailable\", {\n status: 503,\n headers: { Connection: \"close\" },\n });\n }\n return closeConnectionWhileShuttingDown(await instrumentation(req, next));\n };\n}\n\n// Installed once per process, not once per `Server`: a listener per instance\n// would each start a shutdown of its own, and read the other's signal as the\n// second one.\nconst SIGNALS_INSTALLED = Symbol.for(\"gemi.server.signalsInstalled\");\n\n/**\n * A repeat of the first signal inside this window is the same shutdown\n * delivered twice, not an operator asking to skip the drain. One shutdown\n * routinely arrives more than once, milliseconds apart: Ctrl+C on\n * `bun run start` reaches the server directly (the whole foreground group is\n * signalled), and again through `gemi start`'s relay — twice over, since\n * `bun run` forwards it to `gemi start` too. systemd's default\n * `KillMode=control-group` and `tini -g` do the same to every process in the\n * group. A person pressing Ctrl+C again is well outside a second.\n */\nconst REPEAT_WINDOW_MS = 1000;\n\n/**\n * `SIGTERM` or `SIGINT` runs `stop` and exits with the code it resolves with.\n * Another signal of either kind, more than `repeatWindowMs` after the first,\n * exits at once with `128 + n` — an operator pressing Ctrl+C again does not\n * want to wait out the grace period. Without a listener the first signal would\n * do that too: the default action for both is to terminate the process on the\n * spot.\n */\nexport function installShutdownSignals(\n stop: () => Promise<number>,\n options: { repeatWindowMs?: number } = {},\n) {\n const global = globalThis as { [SIGNALS_INSTALLED]?: boolean };\n if (global[SIGNALS_INSTALLED]) return;\n global[SIGNALS_INSTALLED] = true;\n\n const repeatWindowMs = options.repeatWindowMs ?? REPEAT_WINDOW_MS;\n let receivedAt: number | undefined;\n const onSignal = (signal: \"SIGTERM\" | \"SIGINT\") => {\n if (receivedAt !== undefined) {\n if (Date.now() - receivedAt < repeatWindowMs) return;\n console.error(`[gemi] ${signal} received again; exiting without waiting for the drain.`);\n process.exit(128 + constants.signals[signal]);\n }\n receivedAt = Date.now();\n console.log(`[gemi] ${signal} received.`);\n stop().then(\n (code) => process.exit(code),\n (error) => {\n console.error(\"[gemi] Shutdown failed:\", error);\n process.exit(1);\n },\n );\n };\n process.on(\"SIGTERM\", onSignal);\n process.on(\"SIGINT\", onSignal);\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": "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",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "5354B4538A37316B64756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{jj as y}from"./chunk-tewhms9w.js";var v=y((x)=>{class s extends Error{name="ProviderError";tryNextLink;constructor(r,t=!0){let n,e=!0;if(typeof t==="boolean")n=void 0,e=t;else if(t!=null&&typeof t==="object")n=t.logger,e=t.tryNextLink??!0;super(r);this.tryNextLink=e,Object.setPrototypeOf(this,s.prototype),n?.debug?.(`@smithy/property-provider ${e?"->":"(!)"} ${r}`)}static from(r,t=!0){return Object.assign(new this(r.message,t),r)}}class f extends s{name="CredentialsProviderError";constructor(r,t=!0){super(r,t);Object.setPrototypeOf(this,f.prototype)}}class l extends s{name="TokenProviderError";constructor(r,t=!0){super(r,t);Object.setPrototypeOf(this,l.prototype)}}var p=(...r)=>async()=>{if(r.length===0)throw new s("No providers in chain");let t;for(let n of r)try{return await n()}catch(e){if(t=e,e?.tryNextLink)continue;throw e}throw t},d=(r)=>()=>Promise.resolve(r),h=(r,t,n)=>{let e,o,i,c=!1,a=async()=>{if(!o)o=r();try{e=await o,i=!0,c=!1}finally{o=void 0}return e};if(t===void 0)return async(u)=>{if(!i||u?.forceRefresh)e=await a();return e};return async(u)=>{if(!i||u?.forceRefresh)e=await a();if(c)return e;if(n&&!n(e))return c=!0,e;if(t(e))return await a(),e;return e}};x.CredentialsProviderError=f;x.ProviderError=s;x.TokenProviderError=l;x.chain=p;x.fromStatic=d;x.memoize=h});
|
|
3
3
|
export{v as aa};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=CCF2AF203AF5370F64756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"'use strict';\n\nclass ProviderError extends Error {\n name = \"ProviderError\";\n tryNextLink;\n constructor(message, options = true) {\n let logger;\n let tryNextLink = true;\n if (typeof options === \"boolean\") {\n logger = undefined;\n tryNextLink = options;\n }\n else if (options != null && typeof options === \"object\") {\n logger = options.logger;\n tryNextLink = options.tryNextLink ?? true;\n }\n super(message);\n this.tryNextLink = tryNextLink;\n Object.setPrototypeOf(this, ProviderError.prototype);\n logger?.debug?.(`@smithy/property-provider ${tryNextLink ? \"->\" : \"(!)\"} ${message}`);\n }\n static from(error, options = true) {\n return Object.assign(new this(error.message, options), error);\n }\n}\n\nclass CredentialsProviderError extends ProviderError {\n name = \"CredentialsProviderError\";\n constructor(message, options = true) {\n super(message, options);\n Object.setPrototypeOf(this, CredentialsProviderError.prototype);\n }\n}\n\nclass TokenProviderError extends ProviderError {\n name = \"TokenProviderError\";\n constructor(message, options = true) {\n super(message, options);\n Object.setPrototypeOf(this, TokenProviderError.prototype);\n }\n}\n\nconst chain = (...providers) => async () => {\n if (providers.length === 0) {\n throw new ProviderError(\"No providers in chain\");\n }\n let lastProviderError;\n for (const provider of providers) {\n try {\n const credentials = await provider();\n return credentials;\n }\n catch (err) {\n lastProviderError = err;\n if (err?.tryNextLink) {\n continue;\n }\n throw err;\n }\n }\n throw lastProviderError;\n};\n\nconst fromStatic = (staticValue) => () => Promise.resolve(staticValue);\n\nconst memoize = (provider, isExpired, requiresRefresh) => {\n let resolved;\n let pending;\n let hasResult;\n let isConstant = false;\n const coalesceProvider = async () => {\n if (!pending) {\n pending = provider();\n }\n try {\n resolved = await pending;\n hasResult = true;\n isConstant = false;\n }\n finally {\n pending = undefined;\n }\n return resolved;\n };\n if (isExpired === undefined) {\n return async (options) => {\n if (!hasResult || options?.forceRefresh) {\n resolved = await coalesceProvider();\n }\n return resolved;\n };\n }\n return async (options) => {\n if (!hasResult || options?.forceRefresh) {\n resolved = await coalesceProvider();\n }\n if (isConstant) {\n return resolved;\n }\n if (requiresRefresh && !requiresRefresh(resolved)) {\n isConstant = true;\n return resolved;\n }\n if (isExpired(resolved)) {\n await coalesceProvider();\n return resolved;\n }\n return resolved;\n };\n};\n\nexports.CredentialsProviderError = CredentialsProviderError;\nexports.ProviderError = ProviderError;\nexports.TokenProviderError = TokenProviderError;\nexports.chain = chain;\nexports.fromStatic = fromStatic;\nexports.memoize = memoize;\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";uDAEA,MAAM,UAAsB,KAAM,CAC9B,KAAO,gBACP,YACA,WAAW,CAAC,EAAS,EAAU,GAAM,CACjC,IAAI,EACA,EAAc,GAClB,GAAI,OAAO,IAAY,UACnB,EAAS,OACT,EAAc,EAEb,QAAI,GAAW,MAAQ,OAAO,IAAY,SAC3C,EAAS,EAAQ,OACjB,EAAc,EAAQ,aAAe,GAEzC,MAAM,CAAO,EACb,KAAK,YAAc,EACnB,OAAO,eAAe,KAAM,EAAc,SAAS,EACnD,GAAQ,QAAQ,6BAA6B,EAAc,KAAO,SAAS,GAAS,QAEjF,KAAI,CAAC,EAAO,EAAU,GAAM,CAC/B,OAAO,OAAO,OAAO,IAAI,KAAK,EAAM,QAAS,CAAO,EAAG,CAAK,EAEpE,CAEA,MAAM,UAAiC,CAAc,CACjD,KAAO,2BACP,WAAW,CAAC,EAAS,EAAU,GAAM,CACjC,MAAM,EAAS,CAAO,EACtB,OAAO,eAAe,KAAM,EAAyB,SAAS,EAEtE,CAEA,MAAM,UAA2B,CAAc,CAC3C,KAAO,qBACP,WAAW,CAAC,EAAS,EAAU,GAAM,CACjC,MAAM,EAAS,CAAO,EACtB,OAAO,eAAe,KAAM,EAAmB,SAAS,EAEhE,CAEA,IAAM,EAAQ,IAAI,IAAc,SAAY,CACxC,GAAI,EAAU,SAAW,EACrB,MAAM,IAAI,EAAc,uBAAuB,EAEnD,IAAI,EACJ,QAAW,KAAY,EACnB,GAAI,CAEA,OADoB,MAAM,EAAS,EAGvC,MAAO,EAAK,CAER,GADA,EAAoB,EAChB,GAAK,YACL,SAEJ,MAAM,EAGd,MAAM,GAGJ,EAAa,CAAC,IAAgB,IAAM,QAAQ,QAAQ,CAAW,EAE/D,EAAU,CAAC,EAAU,EAAW,IAAoB,CACtD,IAAI,EACA,EACA,EACA,EAAa,GACX,EAAmB,SAAY,CACjC,GAAI,CAAC,EACD,EAAU,EAAS,EAEvB,GAAI,CACA,EAAW,MAAM,EACjB,EAAY,GACZ,EAAa,UAEjB,CACI,EAAU,OAEd,OAAO,GAEX,GAAI,IAAc,OACd,MAAO,OAAO,IAAY,CACtB,GAAI,CAAC,GAAa,GAAS,aACvB,EAAW,MAAM,EAAiB,EAEtC,OAAO,GAGf,MAAO,OAAO,IAAY,CACtB,GAAI,CAAC,GAAa,GAAS,aACvB,EAAW,MAAM,EAAiB,EAEtC,GAAI,EACA,OAAO,EAEX,GAAI,GAAmB,CAAC,EAAgB,CAAQ,EAE5C,OADA,EAAa,GACN,EAEX,GAAI,EAAU,CAAQ,EAElB,OADA,MAAM,EAAiB,EAChB,EAEX,OAAO,IAIP,2BAA2B,EAC3B,gBAAgB,EAChB,qBAAqB,EACrB,QAAQ,EACR,aAAa,EACb,UAAU",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "CCF2AF203AF5370F64756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{jj as s}from"./chunk-tewhms9w.js";var i=s((t,e)=>{e.exports={name:"@aws-sdk/nested-clients",version:"3.996.14",description:"Nested clients for AWS SDK packages.",main:"./dist-cjs/index.js",module:"./dist-es/index.js",types:"./dist-types/index.d.ts",scripts:{build:"yarn lint && concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs","build:cjs":"node ../../scripts/compilation/inline nested-clients","build:es":"tsc -p tsconfig.es.json","build:include:deps":'yarn g:turbo run build -F="$npm_package_name"',"build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4",clean:"premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo",lint:"node ../../scripts/validation/submodules-linter.js --pkg nested-clients",test:"yarn g:vitest run","test:watch":"yarn g:vitest watch"},engines:{node:">=20.0.0"},sideEffects:!1,author:{name:"AWS SDK for JavaScript Team",url:"https://aws.amazon.com/javascript/"},license:"Apache-2.0",dependencies:{"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"^3.973.24","@aws-sdk/middleware-host-header":"^3.972.8","@aws-sdk/middleware-logger":"^3.972.8","@aws-sdk/middleware-recursion-detection":"^3.972.8","@aws-sdk/middleware-user-agent":"^3.972.25","@aws-sdk/region-config-resolver":"^3.972.9","@aws-sdk/types":"^3.973.6","@aws-sdk/util-endpoints":"^3.996.5","@aws-sdk/util-user-agent-browser":"^3.972.8","@aws-sdk/util-user-agent-node":"^3.973.11","@smithy/config-resolver":"^4.4.13","@smithy/core":"^3.23.12","@smithy/fetch-http-handler":"^5.3.15","@smithy/hash-node":"^4.2.12","@smithy/invalid-dependency":"^4.2.12","@smithy/middleware-content-length":"^4.2.12","@smithy/middleware-endpoint":"^4.4.27","@smithy/middleware-retry":"^4.4.44","@smithy/middleware-serde":"^4.2.15","@smithy/middleware-stack":"^4.2.12","@smithy/node-config-provider":"^4.3.12","@smithy/node-http-handler":"^4.5.0","@smithy/protocol-http":"^5.3.12","@smithy/smithy-client":"^4.12.7","@smithy/types":"^4.13.1","@smithy/url-parser":"^4.2.12","@smithy/util-base64":"^4.3.2","@smithy/util-body-length-browser":"^4.2.2","@smithy/util-body-length-node":"^4.2.3","@smithy/util-defaults-mode-browser":"^4.3.43","@smithy/util-defaults-mode-node":"^4.2.47","@smithy/util-endpoints":"^3.3.3","@smithy/util-middleware":"^4.2.12","@smithy/util-retry":"^4.2.12","@smithy/util-utf8":"^4.2.2",tslib:"^2.6.2"},devDependencies:{concurrently:"7.0.0","downlevel-dts":"0.10.1",premove:"4.0.0",typescript:"~5.8.3"},typesVersions:{"<4.5":{"dist-types/*":["dist-types/ts3.4/*"]}},files:["./cognito-identity.d.ts","./cognito-identity.js","./signin.d.ts","./signin.js","./sso-oidc.d.ts","./sso-oidc.js","./sso.d.ts","./sso.js","./sts.d.ts","./sts.js","dist-*/**"],browser:{"./dist-es/submodules/cognito-identity/runtimeConfig":"./dist-es/submodules/cognito-identity/runtimeConfig.browser","./dist-es/submodules/signin/runtimeConfig":"./dist-es/submodules/signin/runtimeConfig.browser","./dist-es/submodules/sso-oidc/runtimeConfig":"./dist-es/submodules/sso-oidc/runtimeConfig.browser","./dist-es/submodules/sso/runtimeConfig":"./dist-es/submodules/sso/runtimeConfig.browser","./dist-es/submodules/sts/runtimeConfig":"./dist-es/submodules/sts/runtimeConfig.browser"},"react-native":{},homepage:"https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients",repository:{type:"git",url:"https://github.com/aws/aws-sdk-js-v3.git",directory:"packages/nested-clients"},exports:{"./package.json":"./package.json","./sso-oidc":{types:"./dist-types/submodules/sso-oidc/index.d.ts",module:"./dist-es/submodules/sso-oidc/index.js",node:"./dist-cjs/submodules/sso-oidc/index.js",import:"./dist-es/submodules/sso-oidc/index.js",require:"./dist-cjs/submodules/sso-oidc/index.js"},"./sts":{types:"./dist-types/submodules/sts/index.d.ts",module:"./dist-es/submodules/sts/index.js",node:"./dist-cjs/submodules/sts/index.js",import:"./dist-es/submodules/sts/index.js",require:"./dist-cjs/submodules/sts/index.js"},"./signin":{types:"./dist-types/submodules/signin/index.d.ts",module:"./dist-es/submodules/signin/index.js",node:"./dist-cjs/submodules/signin/index.js",import:"./dist-es/submodules/signin/index.js",require:"./dist-cjs/submodules/signin/index.js"},"./cognito-identity":{types:"./dist-types/submodules/cognito-identity/index.d.ts",module:"./dist-es/submodules/cognito-identity/index.js",node:"./dist-cjs/submodules/cognito-identity/index.js",import:"./dist-es/submodules/cognito-identity/index.js",require:"./dist-cjs/submodules/cognito-identity/index.js"},"./sso":{types:"./dist-types/submodules/sso/index.d.ts",module:"./dist-es/submodules/sso/index.js",node:"./dist-cjs/submodules/sso/index.js",import:"./dist-es/submodules/sso/index.js",require:"./dist-cjs/submodules/sso/index.js"}}}});
|
|
3
3
|
export{i as h};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=6CBDACEEABA88B7D64756E2164756E21
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{jj as t,mj as A}from"./chunk-tewhms9w.js";var o=t((b)=>{var i=(r)=>typeof ArrayBuffer==="function"&&r instanceof ArrayBuffer||Object.prototype.toString.call(r)==="[object ArrayBuffer]";b.isArrayBuffer=i});var y=t((g)=>{var m=o(),f=A("buffer"),B=(r,e=0,u=r.byteLength-e)=>{if(!m.isArrayBuffer(r))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof r} (${r})`);return f.Buffer.from(r,e,u)},a=(r,e)=>{if(typeof r!=="string")throw TypeError(`The "input" argument must be of type string. Received type ${typeof r} (${r})`);return e?f.Buffer.from(r,e):f.Buffer.from(r)};g.fromArrayBuffer=B;g.fromString=a});var x=t((w)=>{var n=y(),s=(r)=>{let e=n.fromString(r,"utf8");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT)},h=(r)=>{if(typeof r==="string")return s(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(r)},p=(r)=>{if(typeof r==="string")return r;if(typeof r!=="object"||typeof r.byteOffset!=="number"||typeof r.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return n.fromArrayBuffer(r.buffer,r.byteOffset,r.byteLength).toString("utf8")};w.fromUtf8=s;w.toUint8Array=h;w.toUtf8=p});
|
|
3
3
|
export{o as V,y as W,x as X};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=7754E1DB5218141E64756E2164756E21
|
|
@@ -7,6 +7,6 @@
|
|
|
7
7
|
"'use strict';\n\nvar utilBufferFrom = require('@smithy/util-buffer-from');\n\nconst fromUtf8 = (input) => {\n const buf = utilBufferFrom.fromString(input, \"utf8\");\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);\n};\n\nconst toUint8Array = (data) => {\n if (typeof data === \"string\") {\n return fromUtf8(data);\n }\n if (ArrayBuffer.isView(data)) {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);\n }\n return new Uint8Array(data);\n};\n\nconst toUtf8 = (input) => {\n if (typeof input === \"string\") {\n return input;\n }\n if (typeof input !== \"object\" || typeof input.byteOffset !== \"number\" || typeof input.byteLength !== \"number\") {\n throw new Error(\"@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.\");\n }\n return utilBufferFrom.fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString(\"utf8\");\n};\n\nexports.fromUtf8 = fromUtf8;\nexports.toUint8Array = toUint8Array;\nexports.toUtf8 = toUtf8;\n"
|
|
8
8
|
],
|
|
9
9
|
"mappings": ";+DAEA,IAAM,EAAgB,CAAC,IAAS,OAAO,cAAgB,YAAc,aAAe,aAChF,OAAO,UAAU,SAAS,KAAK,CAAG,IAAM,uBAEpC,gBAAgB,kBCHxB,IAAI,MACA,cAEE,EAAkB,CAAC,EAAO,EAAS,EAAG,EAAS,EAAM,WAAa,IAAW,CAC/E,GAAI,CAAC,EAAc,cAAc,CAAK,EAClC,MAAU,UAAU,2DAA2D,OAAO,MAAU,IAAQ,EAE5G,OAAO,EAAO,OAAO,KAAK,EAAO,EAAQ,CAAM,GAE7C,EAAa,CAAC,EAAO,IAAa,CACpC,GAAI,OAAO,IAAU,SACjB,MAAU,UAAU,8DAA8D,OAAO,MAAU,IAAQ,EAE/G,OAAO,EAAW,EAAO,OAAO,KAAK,EAAO,CAAQ,EAAI,EAAO,OAAO,KAAK,CAAK,GAG5E,kBAAkB,EAClB,aAAa,kBCjBrB,IAAI,MAEE,EAAW,CAAC,IAAU,CACxB,IAAM,EAAM,EAAe,WAAW,EAAO,MAAM,EACnD,OAAO,IAAI,WAAW,EAAI,OAAQ,EAAI,WAAY,EAAI,WAAa,WAAW,iBAAiB,GAG7F,EAAe,CAAC,IAAS,CAC3B,GAAI,OAAO,IAAS,SAChB,OAAO,EAAS,CAAI,EAExB,GAAI,YAAY,OAAO,CAAI,EACvB,OAAO,IAAI,WAAW,EAAK,OAAQ,EAAK,WAAY,EAAK,WAAa,WAAW,iBAAiB,EAEtG,OAAO,IAAI,WAAW,CAAI,GAGxB,EAAS,CAAC,IAAU,CACtB,GAAI,OAAO,IAAU,SACjB,OAAO,EAEX,GAAI,OAAO,IAAU,UAAY,OAAO,EAAM,aAAe,UAAY,OAAO,EAAM,aAAe,SACjG,MAAU,MAAM,8EAA8E,EAElG,OAAO,EAAe,gBAAgB,EAAM,OAAQ,EAAM,WAAY,EAAM,UAAU,EAAE,SAAS,MAAM,GAGnG,WAAW,EACX,eAAe,EACf,SAAS",
|
|
10
|
-
"debugId": "
|
|
10
|
+
"debugId": "7754E1DB5218141E64756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{X as M}from"./chunk-
|
|
2
|
+
import{X as M}from"./chunk-3wnghdsx.js";import{lj as E}from"./chunk-tewhms9w.js";class x{marshaller;serializer;deserializer;serdeContext;defaultContentType;constructor({marshaller:i,serializer:n,deserializer:o,serdeContext:c,defaultContentType:y}){this.marshaller=i,this.serializer=n,this.deserializer=o,this.serdeContext=c,this.defaultContentType=y}async serializeEventStream({eventStream:i,requestSchema:n,initialRequest:o}){let c=this.marshaller,y=n.getEventStreamMember(),p=n.getMemberSchema(y),d=this.serializer,f=this.defaultContentType,h=Symbol("initialRequestMarker"),S={async*[Symbol.asyncIterator](){if(o){let r={":event-type":{type:"string",value:"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:f}};d.write(n,o);let t=d.flush();yield{[h]:!0,headers:r,body:t}}for await(let r of i)yield r}};return c.serialize(S,(r)=>{if(r[h])return{headers:r.headers,body:r.body};let t=Object.keys(r).find((s)=>{return s!=="__type"})??"",{additionalHeaders:e,body:a,eventType:l,explicitPayloadContentType:m}=this.writeEventBody(t,p,r);return{headers:{":event-type":{type:"string",value:l},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:m??f},...e},body:a}})}async deserializeEventStream({response:i,responseSchema:n,initialResponseContainer:o}){let c=this.marshaller,y=n.getEventStreamMember(),d=n.getMemberSchema(y).getMemberSchemas(),f=Symbol("initialResponseMarker"),h=c.deserialize(i.body,async(t)=>{let e=Object.keys(t).find((l)=>{return l!=="__type"})??"",a=t[e].body;if(e==="initial-response"){let l=await this.deserializer.read(n,a);return delete l[y],{[f]:!0,...l}}else if(e in d){let l=d[e];if(l.isStructSchema()){let m={},u=!1;for(let[s,g]of l.structIterator()){let{eventHeader:v,eventPayload:w}=g.getMergedTraits();if(u=u||Boolean(v||w),w){if(g.isBlobSchema())m[s]=a;else if(g.isStringSchema())m[s]=(this.serdeContext?.utf8Encoder??z.toUtf8)(a);else if(g.isStructSchema())m[s]=await this.deserializer.read(g,a)}else if(v){let b=t[e].headers[s]?.value;if(b!=null)if(g.isNumericSchema())if(b&&typeof b==="object"&&"bytes"in b)m[s]=BigInt(b.toString());else m[s]=Number(b);else m[s]=b}}if(u)return{[e]:m};if(a.byteLength===0)return{[e]:{}}}return{[e]:await this.deserializer.read(l,a)}}else return{$unknown:t}}),S=h[Symbol.asyncIterator](),r=await S.next();if(r.done)return h;if(r.value?.[f]){if(!n)throw Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let[t,e]of Object.entries(r.value))o[t]=e}return{async*[Symbol.asyncIterator](){if(!r?.value?.[f])yield r.value;while(!0){let{done:t,value:e}=await S.next();if(t)break;yield e}}}}writeEventBody(i,n,o){let c=this.serializer,y=i,p=null,d,f=(()=>{return n.getSchema()[4].includes(i)})(),h={};if(!f){let[t,e]=o[i];y=t,c.write(15,e)}else{let t=n.getMemberSchema(i);if(t.isStructSchema()){for(let[e,a]of t.structIterator()){let{eventHeader:l,eventPayload:m}=a.getMergedTraits();if(m)p=e;else if(l){let u=o[i][e],s="binary";if(a.isNumericSchema())if(-2147483648<=u&&u<=2147483647)s="integer";else s="long";else if(a.isTimestampSchema())s="timestamp";else if(a.isStringSchema())s="string";else if(a.isBooleanSchema())s="boolean";if(u!=null)h[e]={type:s,value:u},delete o[i][e]}}if(p!==null){let e=t.getMemberSchema(p);if(e.isBlobSchema())d="application/octet-stream";else if(e.isStringSchema())d="text/plain";c.write(e,o[i][p])}else c.write(t,o[i])}else if(t.isUnitSchema())c.write(t,{});else throw Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}let S=c.flush()??new Uint8Array;return{body:typeof S==="string"?(this.serdeContext?.utf8Decoder??z.fromUtf8)(S):S,eventType:y,explicitPayloadContentType:d,additionalHeaders:h}}}var z,T;var C=E(()=>{z=M();T=x});C();export{T as EventStreamSerde};export default {get EventStreamSerde(){return T}};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=74FF6EAEFDAA6FDA64756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"'use strict';\n\nvar utilUtf8 = require('@smithy/util-utf8');\n\nclass EventStreamSerde {\n marshaller;\n serializer;\n deserializer;\n serdeContext;\n defaultContentType;\n constructor({ marshaller, serializer, deserializer, serdeContext, defaultContentType, }) {\n this.marshaller = marshaller;\n this.serializer = serializer;\n this.deserializer = deserializer;\n this.serdeContext = serdeContext;\n this.defaultContentType = defaultContentType;\n }\n async serializeEventStream({ eventStream, requestSchema, initialRequest, }) {\n const marshaller = this.marshaller;\n const eventStreamMember = requestSchema.getEventStreamMember();\n const unionSchema = requestSchema.getMemberSchema(eventStreamMember);\n const serializer = this.serializer;\n const defaultContentType = this.defaultContentType;\n const initialRequestMarker = Symbol(\"initialRequestMarker\");\n const eventStreamIterable = {\n async *[Symbol.asyncIterator]() {\n if (initialRequest) {\n const headers = {\n \":event-type\": { type: \"string\", value: \"initial-request\" },\n \":message-type\": { type: \"string\", value: \"event\" },\n \":content-type\": { type: \"string\", value: defaultContentType },\n };\n serializer.write(requestSchema, initialRequest);\n const body = serializer.flush();\n yield {\n [initialRequestMarker]: true,\n headers,\n body,\n };\n }\n for await (const page of eventStream) {\n yield page;\n }\n },\n };\n return marshaller.serialize(eventStreamIterable, (event) => {\n if (event[initialRequestMarker]) {\n return {\n headers: event.headers,\n body: event.body,\n };\n }\n const unionMember = Object.keys(event).find((key) => {\n return key !== \"__type\";\n }) ?? \"\";\n const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody(unionMember, unionSchema, event);\n const headers = {\n \":event-type\": { type: \"string\", value: eventType },\n \":message-type\": { type: \"string\", value: \"event\" },\n \":content-type\": { type: \"string\", value: explicitPayloadContentType ?? defaultContentType },\n ...additionalHeaders,\n };\n return {\n headers,\n body,\n };\n });\n }\n async deserializeEventStream({ response, responseSchema, initialResponseContainer, }) {\n const marshaller = this.marshaller;\n const eventStreamMember = responseSchema.getEventStreamMember();\n const unionSchema = responseSchema.getMemberSchema(eventStreamMember);\n const memberSchemas = unionSchema.getMemberSchemas();\n const initialResponseMarker = Symbol(\"initialResponseMarker\");\n const asyncIterable = marshaller.deserialize(response.body, async (event) => {\n const unionMember = Object.keys(event).find((key) => {\n return key !== \"__type\";\n }) ?? \"\";\n const body = event[unionMember].body;\n if (unionMember === \"initial-response\") {\n const dataObject = await this.deserializer.read(responseSchema, body);\n delete dataObject[eventStreamMember];\n return {\n [initialResponseMarker]: true,\n ...dataObject,\n };\n }\n else if (unionMember in memberSchemas) {\n const eventStreamSchema = memberSchemas[unionMember];\n if (eventStreamSchema.isStructSchema()) {\n const out = {};\n let hasBindings = false;\n for (const [name, member] of eventStreamSchema.structIterator()) {\n const { eventHeader, eventPayload } = member.getMergedTraits();\n hasBindings = hasBindings || Boolean(eventHeader || eventPayload);\n if (eventPayload) {\n if (member.isBlobSchema()) {\n out[name] = body;\n }\n else if (member.isStringSchema()) {\n out[name] = (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)(body);\n }\n else if (member.isStructSchema()) {\n out[name] = await this.deserializer.read(member, body);\n }\n }\n else if (eventHeader) {\n const value = event[unionMember].headers[name]?.value;\n if (value != null) {\n if (member.isNumericSchema()) {\n if (value && typeof value === \"object\" && \"bytes\" in value) {\n out[name] = BigInt(value.toString());\n }\n else {\n out[name] = Number(value);\n }\n }\n else {\n out[name] = value;\n }\n }\n }\n }\n if (hasBindings) {\n return {\n [unionMember]: out,\n };\n }\n if (body.byteLength === 0) {\n return {\n [unionMember]: {},\n };\n }\n }\n return {\n [unionMember]: await this.deserializer.read(eventStreamSchema, body),\n };\n }\n else {\n return {\n $unknown: event,\n };\n }\n });\n const asyncIterator = asyncIterable[Symbol.asyncIterator]();\n const firstEvent = await asyncIterator.next();\n if (firstEvent.done) {\n return asyncIterable;\n }\n if (firstEvent.value?.[initialResponseMarker]) {\n if (!responseSchema) {\n throw new Error(\"@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.\");\n }\n for (const [key, value] of Object.entries(firstEvent.value)) {\n initialResponseContainer[key] = value;\n }\n }\n return {\n async *[Symbol.asyncIterator]() {\n if (!firstEvent?.value?.[initialResponseMarker]) {\n yield firstEvent.value;\n }\n while (true) {\n const { done, value } = await asyncIterator.next();\n if (done) {\n break;\n }\n yield value;\n }\n },\n };\n }\n writeEventBody(unionMember, unionSchema, event) {\n const serializer = this.serializer;\n let eventType = unionMember;\n let explicitPayloadMember = null;\n let explicitPayloadContentType;\n const isKnownSchema = (() => {\n const struct = unionSchema.getSchema();\n return struct[4].includes(unionMember);\n })();\n const additionalHeaders = {};\n if (!isKnownSchema) {\n const [type, value] = event[unionMember];\n eventType = type;\n serializer.write(15, value);\n }\n else {\n const eventSchema = unionSchema.getMemberSchema(unionMember);\n if (eventSchema.isStructSchema()) {\n for (const [memberName, memberSchema] of eventSchema.structIterator()) {\n const { eventHeader, eventPayload } = memberSchema.getMergedTraits();\n if (eventPayload) {\n explicitPayloadMember = memberName;\n }\n else if (eventHeader) {\n const value = event[unionMember][memberName];\n let type = \"binary\";\n if (memberSchema.isNumericSchema()) {\n if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) {\n type = \"integer\";\n }\n else {\n type = \"long\";\n }\n }\n else if (memberSchema.isTimestampSchema()) {\n type = \"timestamp\";\n }\n else if (memberSchema.isStringSchema()) {\n type = \"string\";\n }\n else if (memberSchema.isBooleanSchema()) {\n type = \"boolean\";\n }\n if (value != null) {\n additionalHeaders[memberName] = {\n type,\n value,\n };\n delete event[unionMember][memberName];\n }\n }\n }\n if (explicitPayloadMember !== null) {\n const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember);\n if (payloadSchema.isBlobSchema()) {\n explicitPayloadContentType = \"application/octet-stream\";\n }\n else if (payloadSchema.isStringSchema()) {\n explicitPayloadContentType = \"text/plain\";\n }\n serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]);\n }\n else {\n serializer.write(eventSchema, event[unionMember]);\n }\n }\n else if (eventSchema.isUnitSchema()) {\n serializer.write(eventSchema, {});\n }\n else {\n throw new Error(\"@smithy/core/event-streams - non-struct member not supported in event stream union.\");\n }\n }\n const messageSerialization = serializer.flush() ?? new Uint8Array();\n const body = typeof messageSerialization === \"string\"\n ? (this.serdeContext?.utf8Decoder ?? utilUtf8.fromUtf8)(messageSerialization)\n : messageSerialization;\n return {\n body,\n eventType,\n explicitPayloadContentType,\n additionalHeaders,\n };\n }\n}\n\nexports.EventStreamSerde = EventStreamSerde;\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";uFAIA,AAAM,CAAiB,CACnB,WACA,WACA,aACA,aACA,mBACA,WAAW,EAAG,aAAY,aAAY,eAAc,eAAc,sBAAuB,CACrF,KAAK,WAAa,EAClB,KAAK,WAAa,EAClB,KAAK,aAAe,EACpB,KAAK,aAAe,EACpB,KAAK,mBAAqB,OAExB,qBAAoB,EAAG,cAAa,gBAAe,kBAAmB,CACxE,IAAM,EAAa,KAAK,WAClB,EAAoB,EAAc,qBAAqB,EACvD,EAAc,EAAc,gBAAgB,CAAiB,EAC7D,EAAa,KAAK,WAClB,EAAqB,KAAK,mBAC1B,EAAuB,OAAO,sBAAsB,EACpD,EAAsB,QAChB,OAAO,cAAc,EAAG,CAC5B,GAAI,EAAgB,CAChB,IAAM,EAAU,CACZ,cAAe,CAAE,KAAM,SAAU,MAAO,iBAAkB,EAC1D,gBAAiB,CAAE,KAAM,SAAU,MAAO,OAAQ,EAClD,gBAAiB,CAAE,KAAM,SAAU,MAAO,CAAmB,CACjE,EACA,EAAW,MAAM,EAAe,CAAc,EAC9C,IAAM,EAAO,EAAW,MAAM,EAC9B,KAAM,EACD,GAAuB,GACxB,UACA,MACJ,EAEJ,cAAiB,KAAQ,EACrB,MAAM,EAGlB,EACA,OAAO,EAAW,UAAU,EAAqB,CAAC,IAAU,CACxD,GAAI,EAAM,GACN,MAAO,CACH,QAAS,EAAM,QACf,KAAM,EAAM,IAChB,EAEJ,IAAM,EAAc,OAAO,KAAK,CAAK,EAAE,KAAK,CAAC,IAAQ,CACjD,OAAO,IAAQ,SAClB,GAAK,IACE,oBAAmB,OAAM,YAAW,8BAA+B,KAAK,eAAe,EAAa,EAAa,CAAK,EAO9H,MAAO,CACH,QAPY,CACZ,cAAe,CAAE,KAAM,SAAU,MAAO,CAAU,EAClD,gBAAiB,CAAE,KAAM,SAAU,MAAO,OAAQ,EAClD,gBAAiB,CAAE,KAAM,SAAU,MAAO,GAA8B,CAAmB,KACxF,CACP,EAGI,MACJ,EACH,OAEC,uBAAsB,EAAG,WAAU,iBAAgB,4BAA6B,CAClF,IAAM,EAAa,KAAK,WAClB,EAAoB,EAAe,qBAAqB,EAExD,EADc,EAAe,gBAAgB,CAAiB,EAClC,iBAAiB,EAC7C,EAAwB,OAAO,uBAAuB,EACtD,EAAgB,EAAW,YAAY,EAAS,KAAM,MAAO,IAAU,CACzE,IAAM,EAAc,OAAO,KAAK,CAAK,EAAE,KAAK,CAAC,IAAQ,CACjD,OAAO,IAAQ,SAClB,GAAK,GACA,EAAO,EAAM,GAAa,KAChC,GAAI,IAAgB,mBAAoB,CACpC,IAAM,EAAa,MAAM,KAAK,aAAa,KAAK,EAAgB,CAAI,EAEpE,OADA,OAAO,EAAW,GACX,EACF,GAAwB,MACtB,CACP,EAEC,QAAI,KAAe,EAAe,CACnC,IAAM,EAAoB,EAAc,GACxC,GAAI,EAAkB,eAAe,EAAG,CACpC,IAAM,EAAM,CAAC,EACT,EAAc,GAClB,QAAY,EAAM,KAAW,EAAkB,eAAe,EAAG,CAC7D,IAAQ,cAAa,gBAAiB,EAAO,gBAAgB,EAE7D,GADA,EAAc,GAAe,QAAQ,GAAe,CAAY,EAC5D,GACA,GAAI,EAAO,aAAa,EACpB,EAAI,GAAQ,EAEX,QAAI,EAAO,eAAe,EAC3B,EAAI,IAAS,KAAK,cAAc,aAAe,EAAS,QAAQ,CAAI,EAEnE,QAAI,EAAO,eAAe,EAC3B,EAAI,GAAQ,MAAM,KAAK,aAAa,KAAK,EAAQ,CAAI,EAGxD,QAAI,EAAa,CAClB,IAAM,EAAQ,EAAM,GAAa,QAAQ,IAAO,MAChD,GAAI,GAAS,KACT,GAAI,EAAO,gBAAgB,EACvB,GAAI,GAAS,OAAO,IAAU,UAAY,UAAW,EACjD,EAAI,GAAQ,OAAO,EAAM,SAAS,CAAC,EAGnC,OAAI,GAAQ,OAAO,CAAK,EAI5B,OAAI,GAAQ,GAK5B,GAAI,EACA,MAAO,EACF,GAAc,CACnB,EAEJ,GAAI,EAAK,aAAe,EACpB,MAAO,EACF,GAAc,CAAC,CACpB,EAGR,MAAO,EACF,GAAc,MAAM,KAAK,aAAa,KAAK,EAAmB,CAAI,CACvE,EAGA,WAAO,CACH,SAAU,CACd,EAEP,EACK,EAAgB,EAAc,OAAO,eAAe,EACpD,EAAa,MAAM,EAAc,KAAK,EAC5C,GAAI,EAAW,KACX,OAAO,EAEX,GAAI,EAAW,QAAQ,GAAwB,CAC3C,GAAI,CAAC,EACD,MAAU,MAAM,4GAA4G,EAEhI,QAAY,EAAK,KAAU,OAAO,QAAQ,EAAW,KAAK,EACtD,EAAyB,GAAO,EAGxC,MAAO,QACK,OAAO,cAAc,EAAG,CAC5B,GAAI,CAAC,GAAY,QAAQ,GACrB,MAAM,EAAW,MAErB,MAAO,GAAM,CACT,IAAQ,OAAM,SAAU,MAAM,EAAc,KAAK,EACjD,GAAI,EACA,MAEJ,MAAM,GAGlB,EAEJ,cAAc,CAAC,EAAa,EAAa,EAAO,CAC5C,IAAM,EAAa,KAAK,WACpB,EAAY,EACZ,EAAwB,KACxB,EACE,GAAiB,IAAM,CAEzB,OADe,EAAY,UAAU,EACvB,GAAG,SAAS,CAAW,IACtC,EACG,EAAoB,CAAC,EAC3B,GAAI,CAAC,EAAe,CAChB,IAAO,EAAM,GAAS,EAAM,GAC5B,EAAY,EACZ,EAAW,MAAM,GAAI,CAAK,EAEzB,KACD,IAAM,EAAc,EAAY,gBAAgB,CAAW,EAC3D,GAAI,EAAY,eAAe,EAAG,CAC9B,QAAY,EAAY,KAAiB,EAAY,eAAe,EAAG,CACnE,IAAQ,cAAa,gBAAiB,EAAa,gBAAgB,EACnE,GAAI,EACA,EAAwB,EAEvB,QAAI,EAAa,CAClB,IAAM,EAAQ,EAAM,GAAa,GAC7B,EAAO,SACX,GAAI,EAAa,gBAAgB,EAC7B,GAAK,aAAa,GAAS,GAAS,WAChC,EAAO,UAGP,OAAO,OAGV,QAAI,EAAa,kBAAkB,EACpC,EAAO,YAEN,QAAI,EAAa,eAAe,EACjC,EAAO,SAEN,QAAI,EAAa,gBAAgB,EAClC,EAAO,UAEX,GAAI,GAAS,KACT,EAAkB,GAAc,CAC5B,OACA,OACJ,EACA,OAAO,EAAM,GAAa,IAItC,GAAI,IAA0B,KAAM,CAChC,IAAM,EAAgB,EAAY,gBAAgB,CAAqB,EACvE,GAAI,EAAc,aAAa,EAC3B,EAA6B,2BAE5B,QAAI,EAAc,eAAe,EAClC,EAA6B,aAEjC,EAAW,MAAM,EAAe,EAAM,GAAa,EAAsB,EAGzE,OAAW,MAAM,EAAa,EAAM,EAAY,EAGnD,QAAI,EAAY,aAAa,EAC9B,EAAW,MAAM,EAAa,CAAC,CAAC,EAGhC,WAAU,MAAM,qFAAqF,EAG7G,IAAM,EAAuB,EAAW,MAAM,GAAK,IAAI,WAIvD,MAAO,CACH,KAJS,OAAO,IAAyB,UACtC,KAAK,cAAc,aAAe,EAAS,UAAU,CAAoB,EAC1E,EAGF,YACA,6BACA,mBACJ,EAER,KA9PI,EAgQI,eAhQJ,MAgQI,EAAmB",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "74FF6EAEFDAA6FDA64756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Q as C}from"./chunk-
|
|
2
|
+
import{Q as C}from"./chunk-0ejjgzwc.js";import{aa as A}from"./chunk-32n8t8x6.js";import{ij as _}from"./chunk-tewhms9w.js";var S=_(C(),1),p=_(A(),1),N="AWS_ACCESS_KEY_ID",a="AWS_SECRET_ACCESS_KEY",i="AWS_SESSION_TOKEN",I="AWS_CREDENTIAL_EXPIRATION",d="AWS_CREDENTIAL_SCOPE",v="AWS_ACCOUNT_ID",T=(e)=>async()=>{e?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv");let o=process.env[N],r=process.env[a],n=process.env[i],s=process.env[I],t=process.env[d],E=process.env[v];if(o&&r){let c={accessKeyId:o,secretAccessKey:r,...n&&{sessionToken:n},...s&&{expiration:new Date(s)},...t&&{credentialScope:t},...E&&{accountId:E}};return S.setCredentialFeature(c,"CREDENTIALS_ENV_VARS","g"),c}throw new p.CredentialsProviderError("Unable to find environment variable credentials.",{logger:e?.logger})};export{N as a,a as b,i as c,I as d,d as e,v as f,T as g};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=26B378C83BD3647164756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError } from \"@smithy/property-provider\";\nexport const ENV_KEY = \"AWS_ACCESS_KEY_ID\";\nexport const ENV_SECRET = \"AWS_SECRET_ACCESS_KEY\";\nexport const ENV_SESSION = \"AWS_SESSION_TOKEN\";\nexport const ENV_EXPIRATION = \"AWS_CREDENTIAL_EXPIRATION\";\nexport const ENV_CREDENTIAL_SCOPE = \"AWS_CREDENTIAL_SCOPE\";\nexport const ENV_ACCOUNT_ID = \"AWS_ACCOUNT_ID\";\nexport const fromEnv = (init) => async () => {\n init?.logger?.debug(\"@aws-sdk/credential-provider-env - fromEnv\");\n const accessKeyId = process.env[ENV_KEY];\n const secretAccessKey = process.env[ENV_SECRET];\n const sessionToken = process.env[ENV_SESSION];\n const expiry = process.env[ENV_EXPIRATION];\n const credentialScope = process.env[ENV_CREDENTIAL_SCOPE];\n const accountId = process.env[ENV_ACCOUNT_ID];\n if (accessKeyId && secretAccessKey) {\n const credentials = {\n accessKeyId,\n secretAccessKey,\n ...(sessionToken && { sessionToken }),\n ...(expiry && { expiration: new Date(expiry) }),\n ...(credentialScope && { credentialScope }),\n ...(accountId && { accountId }),\n };\n setCredentialFeature(credentials, \"CREDENTIALS_ENV_VARS\", \"g\");\n return credentials;\n }\n throw new CredentialsProviderError(\"Unable to find environment variable credentials.\", { logger: init?.logger });\n};\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";sIAAA,SACA,KACa,EAAU,oBACV,EAAa,wBACb,EAAc,oBACd,EAAiB,4BACjB,EAAuB,uBACvB,EAAiB,iBACjB,EAAU,CAAC,IAAS,SAAY,CACzC,GAAM,QAAQ,MAAM,4CAA4C,EAChE,IAAM,EAAc,QAAQ,IAAI,GAC1B,EAAkB,QAAQ,IAAI,GAC9B,EAAe,QAAQ,IAAI,GAC3B,EAAS,QAAQ,IAAI,GACrB,EAAkB,QAAQ,IAAI,GAC9B,EAAY,QAAQ,IAAI,GAC9B,GAAI,GAAe,EAAiB,CAChC,IAAM,EAAc,CAChB,cACA,qBACI,GAAgB,CAAE,cAAa,KAC/B,GAAU,CAAE,WAAY,IAAI,KAAK,CAAM,CAAE,KACzC,GAAmB,CAAE,iBAAgB,KACrC,GAAa,CAAE,WAAU,CACjC,EAEA,OADA,uBAAqB,EAAa,uBAAwB,GAAG,EACtD,EAEX,MAAM,IAAI,2BAAyB,mDAAoD,CAAE,OAAQ,GAAM,MAAO,CAAC",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "26B378C83BD3647164756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Jg as q,Kg as L0,Lg as _0}from"./chunk-1m3hvy3q.js";import{Og as b}from"./chunk-490sbcma.js";import{Ri as zQ}from"./chunk-g5ppst76.js";import{bj as Y0}from"./chunk-jg79n382.js";import{ij as mZ}from"./chunk-hm9cjxy2.js";class i0{static kind="controller";constructor(){}}class SQ extends i0{}function q0(Q){let Z=new Map;if(!Q)return Z;for(let $ of Q.split(";")){let X=$.indexOf("=");if(X===-1)continue;let G=$.slice(0,X).trim();if(!G)continue;Z.set(G,$.slice(X+1).trim())}return Z}function $1(Q){return q0(Q.headers.get("cookie"))}function p(Q){if(!/^\d+$/.test(Q))return null;let Z=Number(Q);return Number.isSafeInteger(Z)?Z:null}function n0(Q){if(!Q)return null;let Z=Q.trim();if(!/^bytes=/i.test(Z))return null;let X=Z.slice(6).split(",").map((D)=>D.trim()).filter((D)=>D!=="");if(X.length!==1)return null;let G=X[0],H=G.indexOf("-");if(H===-1)return null;let Y=G.slice(0,H),M=G.slice(H+1);if(Y===""){let D=p(M);if(D===null)return null;return{kind:"suffix",suffixLength:D}}let K=p(Y);if(K===null)return null;if(M==="")return{kind:"offset",start:K,end:null};let J=p(M);if(J===null||J<K)return null;return{kind:"offset",start:K,end:J}}function o0(Q,Z){if(!Number.isFinite(Z)||Z<=0)return null;let $,X;if(Q.kind==="suffix"){if(Q.suffixLength<=0)return null;$=Math.max(0,Z-Q.suffixLength),X=Z-1}else{if(Q.start>=Z)return null;if($=Q.start,X=Q.end===null?Z-1:Math.min(Q.end,Z-1),X<$)return null}return{start:$,end:X,length:X-$+1}}function G1(Q){if(Q.kind==="suffix")return`bytes=-${Q.suffixLength}`;return Q.end===null?`bytes=${Q.start}-`:`bytes=${Q.start}-${Q.end}`}function H1(Q){if(!Q)return null;let Z=/^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(Q.trim());if(!Z)return null;let $=p(Z[1]),X=p(Z[2]),G=p(Z[3]);if($===null||X===null||G===null||X<$)return null;return{start:$,end:X,total:G}}function Y1(Q,Z,$){return`bytes ${Q}-${Z}/${$}`}function t0(Q){return`bytes */${Q}`}class s extends q{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 xQ(Q){let[Z,$]=Q.match(/\d+|\D+/g)??[];if(!Z||!$)return 0;let X=Number.parseInt(Z);switch($){case"B":return X;case"KB":return X*1024;case"MB":return X*1024*1024;case"GB":return X*1024*1024*1024;case"TB":return X*1024*1024*1024*1024;default:return 0}}function kQ(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 s0(Q){if(typeof Q==="string"||Array.isArray(Q))return Q.length;return}function N0(Q){return typeof Q==="number"&&!Number.isNaN(Q)}var gQ=["required","string","boolean","number","email","password","min","max","gte","lte","file","fileType","fileSize","array","object","in"];class k extends Error{name="InvalidValidationRuleError"}function V0(Q,Z){let $=Z===void 0||Z.trim()===""?Number.NaN:Number(Z);if(Number.isNaN($))throw new k(`Validation rule "${Q}:${Z??""}" needs a number, e.g. "${Q}:3"`);return $}function a0(Q){let Z=Q.indexOf(":"),$=Z===-1?Q:Q.slice(0,Z),X=Z===-1?void 0:Q.slice(Z+1);switch($){case"required":return(G)=>{if(G instanceof Blob)return G.size>0;if(G===null||G===void 0)return!1;if(typeof G==="string"||Array.isArray(G))return G.length>0;return!0};case"string":return(G)=>typeof G==="string";case"boolean":return(G)=>typeof G==="boolean";case"number":return(G)=>N0(G);case"password":return(G)=>{return typeof G==="string"&&/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/.test(G)};case"min":{let G=V0($,X);return(H)=>{let Y=s0(H);return Y!==void 0&&Y>=G}}case"max":{let G=V0($,X);return(H)=>{let Y=s0(H);return Y!==void 0&&Y<=G}}case"gte":{let G=V0($,X);return(H)=>N0(H)&&H>=G}case"lte":{let G=V0($,X);return(H)=>N0(H)&&H<=G}case"email":return(G)=>{return typeof G==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(G)};case"file":return(G)=>{return G instanceof Blob};case"fileType":{if(!X)throw new k('Validation rule "fileType" needs a type, e.g. "fileType:png" or "fileType:image"');let G=kQ(X);return(H)=>H instanceof Blob&&H.type.startsWith(G)}case"fileSize":{let G=xQ(X??"");if(G===0&&!/^0+(B|KB|MB|GB|TB)$/.test(X??""))throw new k(`Validation rule "fileSize:${X??""}" needs a whole size in B, KB, MB, GB or TB, e.g. "fileSize:5MB"`);return(H)=>H instanceof Blob&&H.size<=G}case"array":return(G)=>Array.isArray(G);case"object":return(G)=>typeof G==="object"&&G!==null&&!Array.isArray(G)&&!(G instanceof Blob);case"in":{let G=(X??"").split(",").filter((H)=>H!=="");if(G.length===0)throw new k('Validation rule "in" needs a comma-separated list, e.g. "in:draft,published"');return(H)=>typeof H==="string"&&G.includes(H)}default:throw new k(`Unknown validation rule "${Q}". Known rules: ${gQ.join(", ")}`)}}function u(Q){if(!Q.definition)throw Error(`gemi/ai: the recursive schema "${Q.name}" was used before its definition returned; \`self\` can be nested into the schema, but not parsed or emitted inside the callback`);return Q.definition}var j0=new WeakMap;function QQ(Q){return typeof Q==="object"&&Q!==null&&j0.has(Q)}function U0(Q){let Z=j0.get(Q);if(!Z)throw Error("gemi/ai: expected a schema built with `s`, got a foreign object");return Z}function yQ(Q){let Z={defs:{},cells:new Map},$=Q;if(Q.node.kind==="ref"){let G=u(Q.node.cell);$={...G,...Q.description?{description:Q.description}:{},optional:Q.optional,nullable:Q.nullable||G.nullable}}let X=r($,Z);return Object.keys(Z.defs).length>0?{...X,$defs:Z.defs}:X}function r(Q,Z){let $=(Q.optional||Q.nullable)&&Q.node.kind!=="json",X=vQ(fQ(Q.node,Z),$),G=[Q.description,bQ(Q.node)].filter(Boolean).join(" ");if(G&&X.$ref!==void 0)X={anyOf:[X]};return G?{description:G,...X}:X}function bQ(Q){let Z=[];if(Q.kind==="string"||Q.kind==="enum"){let $=Q.checks;if($?.format)Z.push(`Format: ${$.format.name}.`);if($?.minLength!==void 0)Z.push(`At least ${$.minLength} characters.`);if($?.maxLength!==void 0)Z.push(`At most ${$.maxLength} characters.`)}else if(Q.kind==="number"){let $=Q.checks;if($?.minimum!==void 0)Z.push(`Minimum ${$.minimum}.`);if($?.exclusiveMinimum!==void 0)Z.push(`Greater than ${$.exclusiveMinimum}.`);if($?.maximum!==void 0)Z.push(`Maximum ${$.maximum}.`);if($?.exclusiveMaximum!==void 0)Z.push(`Less than ${$.exclusiveMaximum}.`)}else if(Q.kind==="array"){let $=Q.checks;if($?.minItems!==void 0)Z.push(`At least ${$.minItems} items.`);if($?.maxItems!==void 0)Z.push(`At most ${$.maxItems} items.`)}return Z.join(" ")}function fQ(Q,Z){switch(Q.kind){case"string":return{type:"string"};case"number":return{type:Q.checks?.integer?"integer":"number"};case"boolean":return{type:"boolean"};case"literal":return{type:typeof Q.value,const:Q.value};case"enum":return{type:"string",enum:Q.values};case"array":return{type:"array",items:r(Q.item,Z)};case"object":return{type:"object",properties:Object.fromEntries(Object.entries(Q.shape).map(([$,X])=>[$,r(X,Z)])),required:Object.keys(Q.shape),additionalProperties:!1};case"union":return{anyOf:Q.members.map(($)=>r($,Z))};case"json":return{};case"ref":{let{cell:$}=Q,X=Z.cells.get($.name);if(X&&X!==$)throw Error(`gemi/ai: two different recursive schemas are named "${$.name}" in one schema; give each s.recursive(...) its own name`);if(!X)Z.cells.set($.name,$),Z.defs[$.name]={},Z.defs[$.name]=r(u($),Z);return{$ref:`#/$defs/${$.name}`}}}}function vQ(Q,Z){if(!Z)return Q;if(Q.anyOf)return{...Q,anyOf:[...Q.anyOf,{type:"null"}]};if(Q.enum||Q.const!==void 0)return{anyOf:[Q,{type:"null"}]};if(typeof Q.type==="string")return{...Q,type:[Q.type,"null"]};return{anyOf:[Q,{type:"null"}]}}function hQ(Q){if(Q===null)return"null";if(Array.isArray(Q))return"array";return typeof Q}function mQ(Q,Z){if(typeof Z==="number"&&!Number.isFinite(Z))return String(Z);if(Q.kind==="literal"||Q.kind==="enum"){if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")return JSON.stringify(Z)}return hQ(Z)}function ZQ(Q){let Z=Q.node,$=(()=>{switch(Z.kind){case"number":return Z.checks?.integer?"integer":"number";case"string":case"boolean":return Z.kind;case"literal":return JSON.stringify(Z.value);case"enum":return`one of ${Z.values.map((X)=>JSON.stringify(X)).join(" | ")}`;case"array":return"array";case"object":return"object";case"union":return"one of the variants";case"json":return"a JSON value";case"ref":return ZQ({...u(Z.cell),optional:!1,nullable:!1})}})();return Q.optional||Q.nullable?`${$} or null`:$}function cQ(Q){let Z="";for(let $ of Q)Z+=typeof $==="number"?`[${$}]`:Z?`.${$}`:$;return Z}function pQ(Q){let Z=cQ(Q);return Z?`${Z}: `:""}function w0(Q){return`${pQ(Q.path)}${Q.message}`}function B0(Q,Z){if(Z===null||Z===void 0)return Q.optional||Q.nullable?1:0;let $=Q.node;switch($.kind){case"string":return typeof Z==="string"?1:0;case"number":return typeof Z==="number"?1:0;case"boolean":return typeof Z==="boolean"?1:0;case"literal":return Z===$.value?10:0;case"enum":return typeof Z==="string"&&$.values.includes(Z)?10:0;case"array":return Array.isArray(Z)?1:0;case"object":{if(typeof Z!=="object"||Array.isArray(Z))return 0;let X=Z,G=1;for(let[H,Y]of Object.entries($.shape))G+=B0(Y,X[H]);return G}case"union":return $.members.reduce((X,G)=>Math.max(X,B0(G,Z)),0);case"json":return 1;case"ref":return $Q($.cell,Z,()=>1,()=>B0(u($.cell),Z))}}function $Q(Q,Z,$,X){if(typeof Z!=="object"||Z===null)return X();if(Q.active.has(Z))return $();Q.active.add(Z);try{return X()}finally{Q.active.delete(Z)}}function v(Q,Z,$,X){if(Q.optional&&(Z===null||Z===void 0))return{drop:!0,value:void 0};if(Q.nullable&&Z===null)return{drop:!1,value:null};return{drop:!1,value:uQ(Q,Z,$,X)}}function uQ(Q,Z,$,X){let G=Q.node,H=()=>{let Y=Z===void 0?"required":G.kind==="literal"?"const":G.kind==="enum"&&typeof Z==="string"?"enum":"type",M=Y==="const"?{allowedValue:G.value}:Y==="enum"?{allowedValues:G.values}:{};X.push({path:$,code:Y,message:`expected ${ZQ(Q)}, got ${mQ(G,Z)}`,params:M});return};switch(G.kind){case"string":if(typeof Z!=="string")return H();return r0(G.checks,Z,$,X),Z;case"number":if(typeof Z!=="number"||!Number.isFinite(Z))return H();if(G.checks?.integer&&!Number.isInteger(Z))return H();return lQ(G.checks,Z,$,X),Z;case"boolean":return typeof Z==="boolean"?Z:H();case"literal":return Z===G.value?Z:H();case"enum":if(typeof Z!=="string"||!G.values.includes(Z))return H();return r0(G.checks,Z,$,X),Z;case"array":{if(!Array.isArray(Z))return H();let Y=Z.map((J,D)=>{let V=v(G.item,J,[...$,D],X);return V.drop?void 0:V.value}),{minItems:M,maxItems:K}=G.checks??{};if(M!==void 0&&Z.length<M)X.push({path:$,code:"minItems",message:`expected at least ${M} items, got ${Z.length}`,params:{limit:M}});if(K!==void 0&&Z.length>K)X.push({path:$,code:"maxItems",message:`expected at most ${K} items, got ${Z.length}`,params:{limit:K}});return Y}case"object":{if(typeof Z!=="object"||Z===null||Array.isArray(Z))return H();let Y=Z,M={};for(let[K,J]of Object.entries(G.shape)){let D=v(J,Y[K],[...$,K],X);if(!D.drop)M[K]=D.value}if(G.unknownKeys)for(let K of Object.keys(Y)){if(Object.hasOwn(G.shape,K)||Y[K]===void 0)continue;if(G.unknownKeys==="error"){X.push({path:[...$,K],code:"additionalProperties",message:"unknown key",params:{additionalProperty:K}});continue}Z0(Y[K],[...$,K],X,new Set),Object.defineProperty(M,K,{value:Y[K],enumerable:!0,writable:!0,configurable:!0})}return M}case"union":{let Y;for(let M of G.members){let K=[],J=v(M,Z,$,K);if(K.length===0)return J.drop?void 0:J.value;let D=B0(M,Z);if(!Y||D>Y.score)Y={issues:K,score:D}}X.push({path:$,code:"anyOf",message:`no matching variant; closest: ${Y.issues.map(w0).join("; ")}`,params:{closest:Y.issues}});return}case"json":if(Z===void 0)return H();return Z0(Z,$,X,new Set),Z;case"ref":return $Q(G.cell,Z,()=>{X.push({path:$,code:"type",message:"expected a finite tree, got a circular reference",params:{}});return},()=>v(u(G.cell),Z,$,X).value)}}function dQ(Q){let Z=0;for(let $ of Q)Z++;return Z}function r0(Q,Z,$,X){if(!Q)return;let{minLength:G,maxLength:H,format:Y}=Q;if(G!==void 0||H!==void 0){let M=dQ(Z);if(G!==void 0&&M<G)X.push({path:$,code:"minLength",message:`expected at least ${G} characters, got ${M}`,params:{limit:G}});if(H!==void 0&&M>H)X.push({path:$,code:"maxLength",message:`expected at most ${H} characters, got ${M}`,params:{limit:H}})}if(Y){let M=!1;try{M=Y.test(Z)===!0}catch{}if(!M)X.push({path:$,code:"format",message:`expected a string in format "${Y.name}"`,params:{format:Y.name}})}}function lQ(Q,Z,$,X){if(!Q)return;let G=(H,Y,M,K)=>{if(Y===void 0||M(Y))return;X.push({path:$,code:H,message:`expected ${K} ${Y}, got ${Z}`,params:{limit:Y}})};G("minimum",Q.minimum,(H)=>Z>=H,"at least"),G("exclusiveMinimum",Q.exclusiveMinimum,(H)=>Z>H,"more than"),G("maximum",Q.maximum,(H)=>Z<=H,"at most"),G("exclusiveMaximum",Q.exclusiveMaximum,(H)=>Z<H,"less than")}function Z0(Q,Z,$,X,G=!0){let H=(M)=>{$.push({path:Z,code:"type",message:`expected a JSON value, got ${M}`,params:{}})};switch(typeof Q){case"undefined":case"string":case"boolean":return;case"number":if(!Number.isFinite(Q))H(String(Q));return;case"bigint":return H("a bigint");case"function":return H("a function");case"symbol":return H("a symbol")}if(Q===null)return;let Y=Q;if(X.has(Y))return H("a circular reference");X.add(Y);try{let M=G?Y.toJSON:void 0;if(typeof M==="function"){let K;try{K=M.call(Y)}catch{return H("a toJSON that threw")}if(K===void 0)return H("a toJSON that returns undefined");return Z0(K,Z,$,X,!1)}if(Array.isArray(Q))Q.forEach((K,J)=>Z0(K,[...Z,J],$,X));else for(let[K,J]of Object.entries(Y))Z0(J,[...Z,K],$,X)}finally{X.delete(Y)}}function E(Q){return R0(Q)}function R0(Q){let Z={toJSONSchema:()=>yQ(Q),parse($){let X=[],G=v(Q,$,[],X);if(X.length>0)throw Error(X.map(w0).join("; "));return G.drop?void 0:G.value},safeParse($){let X=[],G=v(Q,$,[],X);if(X.length>0)return{ok:!1,errors:X.map(w0)};return{ok:!0,value:G.drop?void 0:G.value}},validate($){let X=[],G=v(Q,$,[],X);if(X.length>0)return{ok:!1,issues:X};return{ok:!0,value:G.drop?void 0:G.value}},describe:($)=>R0({...Q,description:$}),optional:()=>R0({...Q,optional:!0}),nullable:()=>R0({...Q,nullable:!0,optional:!1})};return j0.set(Z,Q),Z}function x(Q){return{node:Q,optional:!1,nullable:!1}}var e0=["strip","error","passthrough"];class XQ extends Error{problems;constructor(Q){super(`gemi/ai: s.fromJSONSchema cannot model this schema:
|
|
2
|
+
import{Hg as q,Ig as L0,Jg as _0}from"./chunk-cca0grq3.js";import{Mg as b}from"./chunk-m83zm86m.js";import{Pi as zQ}from"./chunk-nz8z8jr1.js";import{fj as Y0}from"./chunk-d5f1m3d2.js";import{mj as mZ}from"./chunk-tewhms9w.js";class i0{static kind="controller";constructor(){}}class SQ extends i0{}function q0(Q){let Z=new Map;if(!Q)return Z;for(let $ of Q.split(";")){let X=$.indexOf("=");if(X===-1)continue;let G=$.slice(0,X).trim();if(!G)continue;Z.set(G,$.slice(X+1).trim())}return Z}function $1(Q){return q0(Q.headers.get("cookie"))}function p(Q){if(!/^\d+$/.test(Q))return null;let Z=Number(Q);return Number.isSafeInteger(Z)?Z:null}function n0(Q){if(!Q)return null;let Z=Q.trim();if(!/^bytes=/i.test(Z))return null;let X=Z.slice(6).split(",").map((D)=>D.trim()).filter((D)=>D!=="");if(X.length!==1)return null;let G=X[0],H=G.indexOf("-");if(H===-1)return null;let Y=G.slice(0,H),M=G.slice(H+1);if(Y===""){let D=p(M);if(D===null)return null;return{kind:"suffix",suffixLength:D}}let K=p(Y);if(K===null)return null;if(M==="")return{kind:"offset",start:K,end:null};let J=p(M);if(J===null||J<K)return null;return{kind:"offset",start:K,end:J}}function o0(Q,Z){if(!Number.isFinite(Z)||Z<=0)return null;let $,X;if(Q.kind==="suffix"){if(Q.suffixLength<=0)return null;$=Math.max(0,Z-Q.suffixLength),X=Z-1}else{if(Q.start>=Z)return null;if($=Q.start,X=Q.end===null?Z-1:Math.min(Q.end,Z-1),X<$)return null}return{start:$,end:X,length:X-$+1}}function G1(Q){if(Q.kind==="suffix")return`bytes=-${Q.suffixLength}`;return Q.end===null?`bytes=${Q.start}-`:`bytes=${Q.start}-${Q.end}`}function H1(Q){if(!Q)return null;let Z=/^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(Q.trim());if(!Z)return null;let $=p(Z[1]),X=p(Z[2]),G=p(Z[3]);if($===null||X===null||G===null||X<$)return null;return{start:$,end:X,total:G}}function Y1(Q,Z,$){return`bytes ${Q}-${Z}/${$}`}function t0(Q){return`bytes */${Q}`}class s extends q{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 xQ(Q){let[Z,$]=Q.match(/\d+|\D+/g)??[];if(!Z||!$)return 0;let X=Number.parseInt(Z);switch($){case"B":return X;case"KB":return X*1024;case"MB":return X*1024*1024;case"GB":return X*1024*1024*1024;case"TB":return X*1024*1024*1024*1024;default:return 0}}function kQ(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 s0(Q){if(typeof Q==="string"||Array.isArray(Q))return Q.length;return}function N0(Q){return typeof Q==="number"&&!Number.isNaN(Q)}var gQ=["required","string","boolean","number","email","password","min","max","gte","lte","file","fileType","fileSize","array","object","in"];class k extends Error{name="InvalidValidationRuleError"}function V0(Q,Z){let $=Z===void 0||Z.trim()===""?Number.NaN:Number(Z);if(Number.isNaN($))throw new k(`Validation rule "${Q}:${Z??""}" needs a number, e.g. "${Q}:3"`);return $}function a0(Q){let Z=Q.indexOf(":"),$=Z===-1?Q:Q.slice(0,Z),X=Z===-1?void 0:Q.slice(Z+1);switch($){case"required":return(G)=>{if(G instanceof Blob)return G.size>0;if(G===null||G===void 0)return!1;if(typeof G==="string"||Array.isArray(G))return G.length>0;return!0};case"string":return(G)=>typeof G==="string";case"boolean":return(G)=>typeof G==="boolean";case"number":return(G)=>N0(G);case"password":return(G)=>{return typeof G==="string"&&/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/.test(G)};case"min":{let G=V0($,X);return(H)=>{let Y=s0(H);return Y!==void 0&&Y>=G}}case"max":{let G=V0($,X);return(H)=>{let Y=s0(H);return Y!==void 0&&Y<=G}}case"gte":{let G=V0($,X);return(H)=>N0(H)&&H>=G}case"lte":{let G=V0($,X);return(H)=>N0(H)&&H<=G}case"email":return(G)=>{return typeof G==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(G)};case"file":return(G)=>{return G instanceof Blob};case"fileType":{if(!X)throw new k('Validation rule "fileType" needs a type, e.g. "fileType:png" or "fileType:image"');let G=kQ(X);return(H)=>H instanceof Blob&&H.type.startsWith(G)}case"fileSize":{let G=xQ(X??"");if(G===0&&!/^0+(B|KB|MB|GB|TB)$/.test(X??""))throw new k(`Validation rule "fileSize:${X??""}" needs a whole size in B, KB, MB, GB or TB, e.g. "fileSize:5MB"`);return(H)=>H instanceof Blob&&H.size<=G}case"array":return(G)=>Array.isArray(G);case"object":return(G)=>typeof G==="object"&&G!==null&&!Array.isArray(G)&&!(G instanceof Blob);case"in":{let G=(X??"").split(",").filter((H)=>H!=="");if(G.length===0)throw new k('Validation rule "in" needs a comma-separated list, e.g. "in:draft,published"');return(H)=>typeof H==="string"&&G.includes(H)}default:throw new k(`Unknown validation rule "${Q}". Known rules: ${gQ.join(", ")}`)}}function u(Q){if(!Q.definition)throw Error(`gemi/ai: the recursive schema "${Q.name}" was used before its definition returned; \`self\` can be nested into the schema, but not parsed or emitted inside the callback`);return Q.definition}var j0=new WeakMap;function QQ(Q){return typeof Q==="object"&&Q!==null&&j0.has(Q)}function U0(Q){let Z=j0.get(Q);if(!Z)throw Error("gemi/ai: expected a schema built with `s`, got a foreign object");return Z}function yQ(Q){let Z={defs:{},cells:new Map},$=Q;if(Q.node.kind==="ref"){let G=u(Q.node.cell);$={...G,...Q.description?{description:Q.description}:{},optional:Q.optional,nullable:Q.nullable||G.nullable}}let X=r($,Z);return Object.keys(Z.defs).length>0?{...X,$defs:Z.defs}:X}function r(Q,Z){let $=(Q.optional||Q.nullable)&&Q.node.kind!=="json",X=vQ(fQ(Q.node,Z),$),G=[Q.description,bQ(Q.node)].filter(Boolean).join(" ");if(G&&X.$ref!==void 0)X={anyOf:[X]};return G?{description:G,...X}:X}function bQ(Q){let Z=[];if(Q.kind==="string"||Q.kind==="enum"){let $=Q.checks;if($?.format)Z.push(`Format: ${$.format.name}.`);if($?.minLength!==void 0)Z.push(`At least ${$.minLength} characters.`);if($?.maxLength!==void 0)Z.push(`At most ${$.maxLength} characters.`)}else if(Q.kind==="number"){let $=Q.checks;if($?.minimum!==void 0)Z.push(`Minimum ${$.minimum}.`);if($?.exclusiveMinimum!==void 0)Z.push(`Greater than ${$.exclusiveMinimum}.`);if($?.maximum!==void 0)Z.push(`Maximum ${$.maximum}.`);if($?.exclusiveMaximum!==void 0)Z.push(`Less than ${$.exclusiveMaximum}.`)}else if(Q.kind==="array"){let $=Q.checks;if($?.minItems!==void 0)Z.push(`At least ${$.minItems} items.`);if($?.maxItems!==void 0)Z.push(`At most ${$.maxItems} items.`)}return Z.join(" ")}function fQ(Q,Z){switch(Q.kind){case"string":return{type:"string"};case"number":return{type:Q.checks?.integer?"integer":"number"};case"boolean":return{type:"boolean"};case"literal":return{type:typeof Q.value,const:Q.value};case"enum":return{type:"string",enum:Q.values};case"array":return{type:"array",items:r(Q.item,Z)};case"object":return{type:"object",properties:Object.fromEntries(Object.entries(Q.shape).map(([$,X])=>[$,r(X,Z)])),required:Object.keys(Q.shape),additionalProperties:!1};case"union":return{anyOf:Q.members.map(($)=>r($,Z))};case"json":return{};case"ref":{let{cell:$}=Q,X=Z.cells.get($.name);if(X&&X!==$)throw Error(`gemi/ai: two different recursive schemas are named "${$.name}" in one schema; give each s.recursive(...) its own name`);if(!X)Z.cells.set($.name,$),Z.defs[$.name]={},Z.defs[$.name]=r(u($),Z);return{$ref:`#/$defs/${$.name}`}}}}function vQ(Q,Z){if(!Z)return Q;if(Q.anyOf)return{...Q,anyOf:[...Q.anyOf,{type:"null"}]};if(Q.enum||Q.const!==void 0)return{anyOf:[Q,{type:"null"}]};if(typeof Q.type==="string")return{...Q,type:[Q.type,"null"]};return{anyOf:[Q,{type:"null"}]}}function hQ(Q){if(Q===null)return"null";if(Array.isArray(Q))return"array";return typeof Q}function mQ(Q,Z){if(typeof Z==="number"&&!Number.isFinite(Z))return String(Z);if(Q.kind==="literal"||Q.kind==="enum"){if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")return JSON.stringify(Z)}return hQ(Z)}function ZQ(Q){let Z=Q.node,$=(()=>{switch(Z.kind){case"number":return Z.checks?.integer?"integer":"number";case"string":case"boolean":return Z.kind;case"literal":return JSON.stringify(Z.value);case"enum":return`one of ${Z.values.map((X)=>JSON.stringify(X)).join(" | ")}`;case"array":return"array";case"object":return"object";case"union":return"one of the variants";case"json":return"a JSON value";case"ref":return ZQ({...u(Z.cell),optional:!1,nullable:!1})}})();return Q.optional||Q.nullable?`${$} or null`:$}function cQ(Q){let Z="";for(let $ of Q)Z+=typeof $==="number"?`[${$}]`:Z?`.${$}`:$;return Z}function pQ(Q){let Z=cQ(Q);return Z?`${Z}: `:""}function w0(Q){return`${pQ(Q.path)}${Q.message}`}function B0(Q,Z){if(Z===null||Z===void 0)return Q.optional||Q.nullable?1:0;let $=Q.node;switch($.kind){case"string":return typeof Z==="string"?1:0;case"number":return typeof Z==="number"?1:0;case"boolean":return typeof Z==="boolean"?1:0;case"literal":return Z===$.value?10:0;case"enum":return typeof Z==="string"&&$.values.includes(Z)?10:0;case"array":return Array.isArray(Z)?1:0;case"object":{if(typeof Z!=="object"||Array.isArray(Z))return 0;let X=Z,G=1;for(let[H,Y]of Object.entries($.shape))G+=B0(Y,X[H]);return G}case"union":return $.members.reduce((X,G)=>Math.max(X,B0(G,Z)),0);case"json":return 1;case"ref":return $Q($.cell,Z,()=>1,()=>B0(u($.cell),Z))}}function $Q(Q,Z,$,X){if(typeof Z!=="object"||Z===null)return X();if(Q.active.has(Z))return $();Q.active.add(Z);try{return X()}finally{Q.active.delete(Z)}}function v(Q,Z,$,X){if(Q.optional&&(Z===null||Z===void 0))return{drop:!0,value:void 0};if(Q.nullable&&Z===null)return{drop:!1,value:null};return{drop:!1,value:uQ(Q,Z,$,X)}}function uQ(Q,Z,$,X){let G=Q.node,H=()=>{let Y=Z===void 0?"required":G.kind==="literal"?"const":G.kind==="enum"&&typeof Z==="string"?"enum":"type",M=Y==="const"?{allowedValue:G.value}:Y==="enum"?{allowedValues:G.values}:{};X.push({path:$,code:Y,message:`expected ${ZQ(Q)}, got ${mQ(G,Z)}`,params:M});return};switch(G.kind){case"string":if(typeof Z!=="string")return H();return r0(G.checks,Z,$,X),Z;case"number":if(typeof Z!=="number"||!Number.isFinite(Z))return H();if(G.checks?.integer&&!Number.isInteger(Z))return H();return lQ(G.checks,Z,$,X),Z;case"boolean":return typeof Z==="boolean"?Z:H();case"literal":return Z===G.value?Z:H();case"enum":if(typeof Z!=="string"||!G.values.includes(Z))return H();return r0(G.checks,Z,$,X),Z;case"array":{if(!Array.isArray(Z))return H();let Y=Z.map((J,D)=>{let V=v(G.item,J,[...$,D],X);return V.drop?void 0:V.value}),{minItems:M,maxItems:K}=G.checks??{};if(M!==void 0&&Z.length<M)X.push({path:$,code:"minItems",message:`expected at least ${M} items, got ${Z.length}`,params:{limit:M}});if(K!==void 0&&Z.length>K)X.push({path:$,code:"maxItems",message:`expected at most ${K} items, got ${Z.length}`,params:{limit:K}});return Y}case"object":{if(typeof Z!=="object"||Z===null||Array.isArray(Z))return H();let Y=Z,M={};for(let[K,J]of Object.entries(G.shape)){let D=v(J,Y[K],[...$,K],X);if(!D.drop)M[K]=D.value}if(G.unknownKeys)for(let K of Object.keys(Y)){if(Object.hasOwn(G.shape,K)||Y[K]===void 0)continue;if(G.unknownKeys==="error"){X.push({path:[...$,K],code:"additionalProperties",message:"unknown key",params:{additionalProperty:K}});continue}Z0(Y[K],[...$,K],X,new Set),Object.defineProperty(M,K,{value:Y[K],enumerable:!0,writable:!0,configurable:!0})}return M}case"union":{let Y;for(let M of G.members){let K=[],J=v(M,Z,$,K);if(K.length===0)return J.drop?void 0:J.value;let D=B0(M,Z);if(!Y||D>Y.score)Y={issues:K,score:D}}X.push({path:$,code:"anyOf",message:`no matching variant; closest: ${Y.issues.map(w0).join("; ")}`,params:{closest:Y.issues}});return}case"json":if(Z===void 0)return H();return Z0(Z,$,X,new Set),Z;case"ref":return $Q(G.cell,Z,()=>{X.push({path:$,code:"type",message:"expected a finite tree, got a circular reference",params:{}});return},()=>v(u(G.cell),Z,$,X).value)}}function dQ(Q){let Z=0;for(let $ of Q)Z++;return Z}function r0(Q,Z,$,X){if(!Q)return;let{minLength:G,maxLength:H,format:Y}=Q;if(G!==void 0||H!==void 0){let M=dQ(Z);if(G!==void 0&&M<G)X.push({path:$,code:"minLength",message:`expected at least ${G} characters, got ${M}`,params:{limit:G}});if(H!==void 0&&M>H)X.push({path:$,code:"maxLength",message:`expected at most ${H} characters, got ${M}`,params:{limit:H}})}if(Y){let M=!1;try{M=Y.test(Z)===!0}catch{}if(!M)X.push({path:$,code:"format",message:`expected a string in format "${Y.name}"`,params:{format:Y.name}})}}function lQ(Q,Z,$,X){if(!Q)return;let G=(H,Y,M,K)=>{if(Y===void 0||M(Y))return;X.push({path:$,code:H,message:`expected ${K} ${Y}, got ${Z}`,params:{limit:Y}})};G("minimum",Q.minimum,(H)=>Z>=H,"at least"),G("exclusiveMinimum",Q.exclusiveMinimum,(H)=>Z>H,"more than"),G("maximum",Q.maximum,(H)=>Z<=H,"at most"),G("exclusiveMaximum",Q.exclusiveMaximum,(H)=>Z<H,"less than")}function Z0(Q,Z,$,X,G=!0){let H=(M)=>{$.push({path:Z,code:"type",message:`expected a JSON value, got ${M}`,params:{}})};switch(typeof Q){case"undefined":case"string":case"boolean":return;case"number":if(!Number.isFinite(Q))H(String(Q));return;case"bigint":return H("a bigint");case"function":return H("a function");case"symbol":return H("a symbol")}if(Q===null)return;let Y=Q;if(X.has(Y))return H("a circular reference");X.add(Y);try{let M=G?Y.toJSON:void 0;if(typeof M==="function"){let K;try{K=M.call(Y)}catch{return H("a toJSON that threw")}if(K===void 0)return H("a toJSON that returns undefined");return Z0(K,Z,$,X,!1)}if(Array.isArray(Q))Q.forEach((K,J)=>Z0(K,[...Z,J],$,X));else for(let[K,J]of Object.entries(Y))Z0(J,[...Z,K],$,X)}finally{X.delete(Y)}}function E(Q){return R0(Q)}function R0(Q){let Z={toJSONSchema:()=>yQ(Q),parse($){let X=[],G=v(Q,$,[],X);if(X.length>0)throw Error(X.map(w0).join("; "));return G.drop?void 0:G.value},safeParse($){let X=[],G=v(Q,$,[],X);if(X.length>0)return{ok:!1,errors:X.map(w0)};return{ok:!0,value:G.drop?void 0:G.value}},validate($){let X=[],G=v(Q,$,[],X);if(X.length>0)return{ok:!1,issues:X};return{ok:!0,value:G.drop?void 0:G.value}},describe:($)=>R0({...Q,description:$}),optional:()=>R0({...Q,optional:!0}),nullable:()=>R0({...Q,nullable:!0,optional:!1})};return j0.set(Z,Q),Z}function x(Q){return{node:Q,optional:!1,nullable:!1}}var e0=["strip","error","passthrough"];class XQ extends Error{problems;constructor(Q){super(`gemi/ai: s.fromJSONSchema cannot model this schema:
|
|
3
3
|
${Q.map((Z)=>`- ${Z}`).join(`
|
|
4
4
|
`)}`);this.name="JSONSchemaError",this.problems=Q}}var iQ=new Set(["title","$schema","$id","$comment","examples","default","deprecated","readOnly","writeOnly"]),a={string:["minLength","maxLength","format"],number:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],integer:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],boolean:[],object:["properties","required","additionalProperties"],array:["items","minItems","maxItems"]};function z0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function P0(Q,Z,$,X){let G=(W,U=$)=>{X.push(U?`${U}: ${W}`:W);return},H=(W)=>$?`${$}.${W}`:W;if(!z0(Q))return G("expected a schema object");let Y=new Set(Z.ignoreKeywords??[]),M=(W)=>iQ.has(W)||W.startsWith("x-")||Y.has(W),K=!1,J=Q.type;if(Array.isArray(J)){let W=J.filter((U)=>U!=="null");if(W.length!==1)return G(`type ${JSON.stringify(J)} is not supported; only one type, optionally with "null". Use anyOf for alternatives`,H("type"));K=W.length<J.length,J=W[0]}if(J!==void 0&&(typeof J!=="string"||!(J in a)))return G(`type ${JSON.stringify(J)} is not supported; expected one of ${Object.keys(a).join(", ")}`,H("type"));let D=new Set(["type","description","enum","const","anyOf",...J?a[J]:[]]),V=!1;for(let W of Object.keys(Q)){if(D.has(W)||M(W))continue;V=!0;let U=Object.entries(a).find(([,z])=>z.includes(W));G(U&&U[0]!==J?`"${W}" applies to type ${U[0]}, and this schema is ${J?`type ${J}`:"untyped"}`:`"${W}" is not supported by s.fromJSONSchema`,H(W))}if(V)return;if(Q.description!==void 0&&typeof Q.description!=="string")return G("expected a string",H("description"));let O=Q.description,B=(W)=>({node:W,optional:!1,nullable:K,...O?{description:O}:{}});if(Q.anyOf!==void 0){if(J!==void 0||Q.enum!==void 0||Q.const!==void 0)return G("anyOf cannot be combined with type, enum or const here",H("anyOf"));if(!Array.isArray(Q.anyOf)||Q.anyOf.length===0)return G("expected a non-empty array",H("anyOf"));let W=[],U=!1;if(Q.anyOf.forEach((z,R)=>{if(z0(z)&&z.type==="null"&&Object.keys(z).length===1){K=!0;return}let F=P0(z,Z,H(`anyOf[${R}]`),X);if(F)W.push(F);else U=!0}),U)return;if(W.length===0)return G("anyOf has only null in it",H("anyOf"));if(W.length===1){let z=W[0];return{...z,nullable:z.nullable||K,...O?{description:O}:{}}}return B({kind:"union",members:W})}if(Q.const!==void 0){let W=Q.const;if(typeof W!=="string"&&typeof W!=="number"&&typeof W!=="boolean")return G("only a string, number or boolean const is supported",H("const"));if(J!==void 0&&typeof W!==(J==="integer"?"number":J))return G(`const ${JSON.stringify(W)} is not of type ${J}`,H("const"));return B({kind:"literal",value:W})}let L;if(J==="string"){if(L=nQ(Q,Z,H,X),L===null)return}if(Q.enum!==void 0){if(!Array.isArray(Q.enum)||Q.enum.length===0)return G("expected a non-empty array",H("enum"));let W=Q.enum.filter((R)=>R!==null);if(W.length<Q.enum.length)K=!0;let U=W.find((R)=>!(typeof R==="string"||typeof R==="number"||typeof R==="boolean")||J!==void 0&&typeof R!==(J==="integer"?"number":J));if(U!==void 0||W.length===0)return G(J?`every value must be of type ${J}${W.length===0?", and there must be one":`; ${JSON.stringify(U)} is not`}`:"only strings, numbers and booleans are supported",H("enum"));if(W.every((R)=>typeof R==="string"))return B({kind:"enum",values:[...new Set(W)],...L?{checks:L}:{}});let z=[...new Set(W)];if(z.length===1)return B({kind:"literal",value:z[0]});return B({kind:"union",members:z.map((R)=>x({kind:"literal",value:R}))})}switch(J){case void 0:return G("a schema needs a type, an enum, a const or an anyOf");case"string":return B({kind:"string",...L?{checks:L}:{}});case"number":case"integer":{let W=J==="integer"?{integer:!0}:{},U=!1;for(let z of a.number){let R=Q[z];if(R===void 0)continue;if(typeof R!=="number"||!Number.isFinite(R)){G("expected a number",H(z)),U=!0;continue}W[z]=R}if(U)return;return B({kind:"number",...Object.keys(W).length>0?{checks:W}:{}})}case"boolean":return B({kind:"boolean"});case"array":{if(!z0(Q.items))return G('an array needs "items" to be one schema (tuples are not supported)',H("items"));let W={},U=!1;for(let R of["minItems","maxItems"]){let F=Q[R];if(F===void 0)continue;if(typeof F!=="number"||!Number.isInteger(F)||F<0){G("expected a non-negative integer",H(R)),U=!0;continue}W[R]=F}let z=P0(Q.items,Z,H("items"),X);if(!z||U)return;return B({kind:"array",item:z,...Object.keys(W).length>0?{checks:W}:{}})}case"object":{let W=Q.properties??{};if(!z0(W))return G("expected an object",H("properties"));if(Q.additionalProperties!==void 0&&Q.additionalProperties!==!1)return G("only false is supported; a record with arbitrary keys has no strict-mode form (use s.json())",H("additionalProperties"));let U=Q.required??[];if(!Array.isArray(U)||!U.every((T)=>typeof T==="string"))return G("expected an array of property names",H("required"));let z=U.filter((T)=>!Object.hasOwn(W,T));if(z.length>0)return G(`lists properties the schema doesn't have: ${z.join(", ")}`,H("required"));let R={},F=!1;for(let[T,C]of Object.entries(W)){let j=P0(C,Z,H(`properties.${T}`),X);if(!j){F=!0;continue}R[T]=U.includes(T)?j:{...j,optional:!0}}if(F)return;let I=Z.unknownKeys;return B({kind:"object",shape:R,...I==="error"||I==="passthrough"?{unknownKeys:I}:{}})}}return}function nQ(Q,Z,$,X){let G={},H=!1;for(let Y of["minLength","maxLength"]){let M=Q[Y];if(M===void 0)continue;if(typeof M!=="number"||!Number.isInteger(M)||M<0){X.push(`${$(Y)}: expected a non-negative integer`),H=!0;continue}G[Y]=M}if(Q.format!==void 0){let Y=Q.format,M=typeof Y==="string"?Z.formats?.[Y]:void 0;if(typeof Y!=="string")X.push(`${$("format")}: expected a string`),H=!0;else if(!M||!Object.hasOwn(Z.formats,Y))X.push(`${$("format")}: unknown format ${JSON.stringify(Y)}; pass a check for it in the formats option`),H=!0;else G.format={name:Y,test:oQ(M)}}if(H)return null;return Object.keys(G).length>0?G:void 0}function oQ(Q){if(Q===!0)return()=>!0;if(Q instanceof RegExp)return(Z)=>{return Q.lastIndex=0,Q.test(Z)};return Q}var D1={string:()=>E(x({kind:"string"})),number:()=>E(x({kind:"number"})),boolean:()=>E(x({kind:"boolean"})),literal:(Q)=>E(x({kind:"literal",value:Q})),enum:(Q)=>E(x({kind:"enum",values:Q})),object:(Q)=>E(x({kind:"object",shape:Object.fromEntries(Object.entries(Q).map(([Z,$])=>[Z,U0($)]))})),array:(Q)=>E(x({kind:"array",item:U0(Q)})),union:(Q)=>E(x({kind:"union",members:Q.map(U0)})),json:()=>E(x({kind:"json"})),recursive:sQ,fromJSONSchema:(Q,Z={})=>{let $=[];if(Z.unknownKeys!==void 0&&!e0.includes(Z.unknownKeys))throw Error(`gemi/ai: s.fromJSONSchema's unknownKeys option must be one of ${e0.map((G)=>JSON.stringify(G)).join(", ")}, got ${JSON.stringify(Z.unknownKeys)}`);let X=P0(Q,Z,"",$);if(!X||$.length>0)throw new XQ($.length>0?$:["unreadable schema"]);return E(X)}};function V1(Q){let Z=j0.get(Q);if(Z)return Q0(Z.node);return e(Q.toJSONSchema())}function e(Q){if(!(Q.$ref!==void 0||Q.type!==void 0||Q.enum!==void 0||Q.const!==void 0||Q.anyOf!==void 0||Q.properties!==void 0||Q.items!==void 0))return!1;for(let $ of Object.values(Q.properties??{}))if(!e($))return!1;if(Q.items&&!e(Q.items))return!1;for(let $ of Q.anyOf??[])if(!e($))return!1;for(let $ of Object.values(Q.$defs??{}))if(!e($))return!1;return!0}function Q0(Q,Z=new Set){switch(Q.kind){case"string":case"number":case"boolean":case"literal":case"enum":return!0;case"object":return Object.values(Q.shape).every(($)=>Q0($.node,Z));case"array":return Q0(Q.item.node,Z);case"union":return Q.members.every(($)=>Q0($.node,Z));case"json":return!1;case"ref":if(Z.has(Q.cell))return!0;return Z.add(Q.cell),Q0(u(Q.cell).node,Z)}}function E0(Q,Z,$=new Set){let X=Q.node;if(X.kind==="union")return X.members.some((G)=>E0(G,Z,$));if(X.kind!=="ref")return!1;if(X.cell===Z)return!0;if($.has(X.cell)||!X.cell.definition)return!1;return $.add(X.cell),E0(X.cell.definition,Z,$)}var tQ=/^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;function sQ(Q,Z){if(typeof Q!=="string"||!tQ.test(Q))throw Error(`gemi/ai: s.recursive needs a name of letters, digits, "_" and "-" (starting with a letter or "_", at most 64), got ${JSON.stringify(Q)}`);let $={name:Q,active:new Set},X=()=>x({kind:"ref",cell:$}),G=U0(Z(E(X())));if(G.optional)throw Error(`gemi/ai: the recursive schema "${Q}" is optional() as a whole; mark the places that use it optional instead`);if(E0(G,$))throw Error(`gemi/ai: the recursive schema "${Q}" refers to itself outside any object or array, so it describes no finite value; nest \`self\` in an s.object(...) field or an s.array(...)`);return $.definition=G,E(X())}function GQ(Q){if(typeof Q!=="string")return null;let[Z]=Q.split(";",1),$=Z.trim().toLowerCase();return $===""?null:$}function HQ(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 $0=new WeakMap;function B1(Q,Z,$,X){$0.set(Q,{clientAddress:Z,...$?{grant:Object.freeze({...$,scopes:Object.freeze([...$.scopes])})}:{},...X?{progress:X}:{}})}function YQ(Q){return $0.get(Q)?.progress}function MQ(Q){return $0.get(Q)?.grant}function KQ(Q){return $0.has(Q)}function R1(Q){return $0.get(Q)?.clientAddress}var JQ=new WeakMap;function j1(Q,Z){JQ.set(Q,Z)}function WQ(Q){return JQ.get(Q)??null}var S0=new WeakMap;function L1(Q,Z){let $=S0.get(Q)??[];if(!$.includes(Z))S0.set(Q,[...$,Z])}function _1(Q){return S0.get(Q)??[]}class d{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 DQ(Q){return typeof Q==="object"&&Q!==null&&!(Q instanceof Blob)}function aQ(Q,Z){if(!Z.includes(".")||Object.hasOwn(Q,Z))return[{path:[Z],value:Q[Z]}];let $=[{path:[],value:Q}];for(let X of Z.split(".")){let G=[];for(let{path:H,value:Y}of $){if(X==="*"){if(Array.isArray(Y))Y.forEach((M,K)=>G.push({path:[...H,K],value:M}));else if(DQ(Y))for(let[M,K]of Object.entries(Y))G.push({path:[...H,M],value:K});continue}if(Array.isArray(Y)&&/^\d+$/.test(X)){G.push({path:[...H,Number(X)],value:Y[Number(X)]});continue}G.push({path:[...H,X],value:DQ(Y)&&Object.hasOwn(Y,X)?Y[X]:void 0})}$=G}return $}function VQ(Q){return Q.join(".")}class rQ{kind;rawRequest;headers;cookies;search;schema={};routePath;params;domain;constructor(Q,Z,$,X){if(!Q){let K=b.getStore().req;this.params=K.params,this.rawRequest=K.rawRequest,this.kind=K.kind,this.routePath=K.routePath,this.domain=K.domain??null}else this.params=Z,this.rawRequest=Q,this.routePath=X,this.kind=$??"api",this.domain=WQ(Q);this.headers=this.rawRequest.headers;let G=q0(this.rawRequest.headers.get("Cookie")),H=new URL(this.rawRequest.url),Y=new Map;for(let[K,J]of H.searchParams)if(Y.has(K)){let D=Y.get(K);if(Array.isArray(D))D.push(J),Y.set(K,D);else Y.set(K,[D,J])}else Y.set(K,J);let M=Object.fromEntries(Y.entries());this.search=new d(M),this.cookies=G}locale(){return b.getStore().locale}ctx(){return b.getStore()}isModelOriginated(){return KQ(this.rawRequest)}mcpGrant(){return MQ(this.rawRequest)??null}reportProgress(Q){let Z=YQ(this.rawRequest);if(!Z)return!1;return Z(Q),!0}get signal(){return this.rawRequest.signal}range(){return n0(this.rawRequest.headers.get("Range"))}refine(Q){return{}}async parseBody(){let Q=GQ(this.rawRequest.headers.get("Content-Type"));if(HQ(Q))return new d(await this.parseJsonBody());if(Q==="application/x-www-form-urlencoded"||Q==="multipart/form-data"){let Z;try{Z=await this.rawRequest.formData()}catch(X){if(X instanceof q)throw X;throw new q("The request body could not be read as a form.")}let $=new Map;for(let[X,G]of Z.entries())if($.has(X)){let H=$.get(X);if(Array.isArray(H))H.push(G);else $.set(X,[H,G])}else $.set(X,G);return new d(Object.fromEntries($.entries()))}return new d({})}async parseJsonBody(){if(!this.rawRequest.body)return{};let Q;try{Q=await this.rawRequest.text()}catch($){if($ instanceof q)throw $;throw new q("The request body could not be read.")}if(Q.trim()==="")return{};let Z;try{Z=JSON.parse(Q)}catch{throw new q("The request body is not valid JSON.")}if(Z===null||typeof Z!=="object")throw new q("The request body must be a JSON object.");return Z}validateInput(Q){if(QQ(this.schema))return this.validateWithSchema(Q);let Z=Q.toJSON()??{},$={},X=Object.entries(this.schema).map(([G,H])=>({key:G,rules:Object.entries(H).map(([Y,M])=>({rule:Y,message:M,check:typeof M==="function"?null:this.ruleFor(G,Y)}))}));for(let{key:G,rules:H}of X)for(let{path:Y,value:M}of aQ(Z,G)){let K=this.checkField(M,H);if(K.length>0){let J=$[VQ(Y)]??=[];for(let D of K)if(!J.includes(D))J.push(D)}}if(this.addRefinements($,Z),Object.keys($).length>0)throw new s($);return Q}checkField(Q,Z){let $=Z.some(({rule:H})=>H==="required"),X=Q===void 0||Q===null||Q==="",G=[];for(let{rule:H,message:Y,check:M}of Z){let K=Y,J=!1;if(typeof Y==="function")K=Y(Q),J=typeof K>"u";else J=M(Q);if(J)continue;if(X&&!$)continue;if(H==="required")return[String(K)];if(!G.includes(String(K)))G.push(String(K))}return G}validateWithSchema(Q){let Z=this.schema.validate(Q.toJSON()),$={};if("issues"in Z)for(let G of Z.issues){let H=VQ(G.path),Y=$[H]??=[];if(!Y.includes(G.message))Y.push(G.message)}let X="value"in Z?new d(Z.value):Q;if(this.addRefinements($,X.toJSON()),Object.keys($).length>0)throw new s($);return X}addRefinements(Q,Z){for(let[$,X]of Object.entries(this.refine(Z)??{})){let G=Q[$]??[];Q[$]=G.includes(X)?G:[...G,X]}}ruleFor(Q,Z){try{return a0(Z)}catch($){if($ instanceof k)throw new k(`${this.constructor.name}.schema.${Q}: ${$.message}`);throw $}}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 s))throw Z;return{isValid:!1,errors:Z.errors,input:Q}}}}class eQ extends q{error;constructor(Q="Not authorized"){super(Q);this.name="AuthorizationError",this.error=Q,this.payload={api:{status:401,data:{error:_0("authorization",this.error,401)}},view:{}}}}class x0 extends q{static apiStatus=403;error;constructor(Q="Insufficient permissions"){super(Q);this.name="InsufficientPermissionsError",this.error=Q,this.payload={api:{status:x0.apiStatus,data:{error:_0("permission",this.error,x0.apiStatus)}},view:{status:403}}}}class k0 extends q{total;constructor(Q){super("Range not satisfiable");this.total=Q;this.name="RangeNotSatisfiableError",this.payload={api:{status:416,data:{error:L0("range_not_satisfiable","Range not satisfiable",416)},headers:{"Content-Range":t0(Q),"Accept-Ranges":"bytes","Cache-Control":"no-store"}},view:{}}}}class QZ extends q{constructor(Q="Not found"){super(Q);this.name="NotFoundError",this.payload={api:{status:404,data:{error:L0("not_found",Q,404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class h extends q{fileName;constructor(Q){super("File not found");this.fileName=Q;this.name="FileNotFoundError",this.payload={api:{status:404,data:{error:L0("not_found","Not found",404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class ZZ extends q{constructor(Q={}){super("Authentication error");this.name="AuthenticationError";let Z=Q.redirectTo??"/auth/sign-in";this.payload={api:{status:401,data:{error:_0("authentication","Authentication error",401)}},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}}}}}class X0{static getFacadeAccessor(){throw Error(`Facade [${this.name}] does not implement getFacadeAccessor().`)}static getFacadeRoot(){return zQ(this.getFacadeAccessor())}}import{Buffer as $Z}from"buffer";function C0(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 G0{async putStream({body:Q,...Z},$={}){$.signal?.throwIfAborted();let X=[],G=Q.getReader();try{for(;;){$.signal?.throwIfAborted();let{done:H,value:Y}=await G.read();if(H)break;X.push(Y)}}catch(H){throw await G.cancel(H).catch(()=>{}),H}return this.put({...Z,body:$Z.concat(X)},$)}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={}){C0(Q);let $=[];for await(let X of this.objects(Q,Z))$.push(X.name);for(let X of $)Z.signal?.throwIfAborted(),await this.delete({name:X,bucket:Z.bucket});return $.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,$=await this.fetch({name:Z.name,bucket:Z.bucket});if(!$.ok)throw new h(Z.name);let X=$.headers.get("Content-Type")??"application/octet-stream",G=$.headers.get("ETag")??void 0,H=$.headers.get("Last-Modified"),Y=H?new Date(H):void 0;if(Z.range){let J=await $.blob();return{body:J,start:0,end:J.size-1,total:J.size,partial:!1,type:X,etag:G,lastModified:Y,name:Z.name}}let M=Number($.headers.get("Content-Length")),K=Number.isFinite(M)?M:0;return{body:$.body,start:0,end:K-1,total:K,partial:!1,type:X,etag:G,lastModified:Y,name:Z.name}}async size(Q){let Z=typeof Q==="string"?Q:Q.name,$=typeof Q==="string"?void 0:Q.bucket,X=await this.fetch({name:Z,bucket:$});if(!X.ok)throw new h(Z);let G=Number(X.headers.get("Content-Length"));if(Number.isFinite(G))return await X.body?.cancel(),G;return(await X.blob()).size}}function UQ(Q,Z){if(!Z)return Q;let $=Q.getReader(),X=!1,G,H=()=>{if(X=!0,G)Z.removeEventListener("abort",G)};return new ReadableStream({start(Y){if(G=()=>{if(X)return;H(),Y.error(Z.reason),$.cancel(Z.reason).catch(()=>{})},Z.aborted)G();else Z.addEventListener("abort",G,{once:!0})},async pull(Y){let M;try{M=await $.read()}catch(K){if(X)return;H(),Y.error(K);return}if(X)return;if(M.done){H(),Y.close();return}Y.enqueue(M.value)},cancel(Y){return H(),$.cancel(Y)}},{highWaterMark:0})}import{mkdir as XZ,open as GZ,readdir as g0,rename as HZ,rmdir as YZ,stat as MZ,unlink as BQ}from"fs/promises";import{dirname as KZ,isAbsolute as y0,relative as H0,resolve as l,sep as f}from"path";class b0 extends G0{configured;constructor(Q){super();this.configured=Q}get folderPath(){return this.configured??`${Y0()}/storage`}async put(Q,{signal:Z}={}){Z?.throwIfAborted();let $,X;if(Q instanceof Blob)$=Q,X=`${Bun.randomUUIDv7()}.${Q.type.split("/")[1].split(";")[0]}`;else $=Q.body,X=Q.name;let G=$ instanceof Buffer?$:$ instanceof Blob||$ instanceof File?Buffer.from(await $.arrayBuffer()):"",H=`${this.folderPath}/${X}`;return Z?.throwIfAborted(),await Bun.write(H,G),X}async putStream({name:Q,body:Z},{signal:$}={}){let X=Z.getReader(),G=null;try{if($?.throwIfAborted(),!Q)throw Error("Object name has to be specified");let H=l(this.folderPath),Y=l(H,Q),M=H0(H,Y);if(!M||M===".."||M.startsWith(`..${f}`)||y0(M))throw Error(`Refusing to write "${Q}": it is outside the storage folder`);await XZ(KZ(Y),{recursive:!0}),G=`${Y}.${Bun.randomUUIDv7()}.partial`;let K=await GZ(G,"wx");try{for(;;){$?.throwIfAborted();let{done:J,value:D}=await X.read();if(J)break;for(let V=0;V<D.byteLength;){let{bytesWritten:O}=await K.write(D,V);V+=O}}}finally{await K.close()}return $?.throwIfAborted(),await HZ(G,Y),Q}catch(H){if(await X.cancel(H).catch(()=>{}),G)await BQ(G).catch(()=>{});throw H}}async fetch(Q,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,X;if(typeof Q==="string")X=Q;else $=Q.bucket??$,X=Q.name;if(!X)throw Error("Object name has to be specified");let G=`${this.folderPath}/${X}`,H=Bun.file(G),Y=UQ(Bun.file(G).stream(),Z),M=new Date(H.lastModified).toUTCString();return new Response(Y,{headers:{"Content-Type":H.type,"Content-Length":String(H.size),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":M}})}async read(Q){let Z=typeof Q==="string"?{name:Q}:Q,{name:$,range:X=null}=Z;if(!$)throw Error("Object name has to be specified");let G=Bun.file(`${this.folderPath}/${$}`);if(!await G.exists())throw new h($);let H=G.size,Y=X?o0(X,H):null;if(X&&!Y)throw new k0(H);let M=Y?.start??0,K=Y?Y.end:H-1;return{body:Y?G.slice(M,K+1):G,start:M,end:K,total:H,partial:Boolean(Y),type:G.type||"application/octet-stream",lastModified:new Date(G.lastModified),name:$}}async size(Q){let Z=typeof Q==="string"?Q:Q.name,$=Bun.file(`${this.folderPath}/${Z}`);if(!await $.exists())throw new h(Z);return $.size}async delete(Q){let Z=typeof Q==="string"?Q:Q.name;if(!Z)throw Error("Object name has to be specified");let $=l(this.folderPath),X=l($,Z),G=H0($,X);if(!G||G===".."||G.startsWith(`..${f}`)||y0(G))throw Error(`Refusing to delete "${Z}": it is outside the storage folder`);try{await BQ(X)}catch(H){if(H?.code==="ENOENT")return;throw H}}resolvePrefix(Q){let Z=l(this.folderPath),$=Q.lastIndexOf("/"),X=$===-1?"":Q.slice(0,$),G=$===-1?Q:Q.slice($+1),H=l(Z,X),Y=H0(Z,H);if(Y===".."||Y.startsWith(`..${f}`)||y0(Y))throw Error(`Refusing to list "${Q}": it is outside the storage folder`);let M=Y.split(f).join("/");return{root:Z,dir:H,match:M?`${M}/${G}`:G}}async*objects(Q,{signal:Z}={}){Z?.throwIfAborted();let{root:$,dir:X,match:G}=this.resolvePrefix(Q),H=[],Y=async(M)=>{let K;try{K=await g0(M,{withFileTypes:!0})}catch(J){if(J?.code==="ENOENT"||J?.code==="ENOTDIR")return;throw J}for(let J of K){let D=`${M}${f}${J.name}`,V=H0($,D).split(f).join("/");if(J.isDirectory()){if(`${V}/`.startsWith(G)||G.startsWith(`${V}/`))await Y(D)}else if(J.isFile()&&V.startsWith(G))H.push(V)}};await Y(X),H.sort();for(let M of H){Z?.throwIfAborted();let K;try{K=await MZ(`${$}/${M}`)}catch(J){if(J?.code==="ENOENT")continue;throw J}yield{name:M,size:K.size,lastModified:K.mtime}}}async deletePrefix(Q,Z={}){C0(Q);let{root:$,match:X}=this.resolvePrefix(Q);C0(X);let G=await super.deletePrefix(Q,Z);if(G>0)await this.pruneEmptyDirs($,X);return G}async pruneEmptyDirs(Q,Z){let $=[],X=async(G)=>{let H;try{H=await g0(G,{withFileTypes:!0})}catch{return}for(let Y of H){if(!Y.isDirectory())continue;let M=`${G}${f}${Y.name}`,K=H0(Q,M).split(f).join("/");if(`${K}/`.startsWith(Z)||Z.startsWith(`${K}/`)){if(await X(M),`${K}/`.startsWith(Z))$.push(M)}}};await X(Q);for(let G of $)try{await YZ(G)}catch{}}async list(){return await g0(this.folderPath)}}function a1(Q){return Q}function RQ(){return{driver:new b0}}class f0{static token="filesystem";driver;constructor(Q={}){this.driver=Q.driver??RQ().driver}}class N extends Error{code="safe-fetch";url;constructor(Q,Z,$){super(Q,$);this.name=new.target.name,this.url=Z}}class m extends N{reason;code="invalid-url";constructor(Q,Z,$){super($,Q);this.reason=Z}}class O0 extends N{host;reason;code="blocked-host";constructor(Q,Z,$){super($==="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=$}}class i extends N{host;address;range;code="blocked-address";constructor(Q,Z,$,X){super(Z===$?`${$} is not a public address (${X}).`:`${Z} resolves to ${$}, which is not a public address (${X}).`,Q);this.host=Z;this.address=$;this.range=X}}class F0 extends N{host;code="dns";constructor(Q,Z,$){super(`Couldn't resolve ${Z}.`,Q,{cause:$});this.host=Z}}class I0 extends N{phase;ms;code="timeout";constructor(Q,Z,$){super(Z==="connect"?`Couldn't connect within ${$} ms.`:`The request didn't finish within ${$} ms.`,Q);this.phase=Z;this.ms=$}}class T0 extends N{limit;code="too-large";constructor(Q,Z){super(`The response is larger than ${Z} bytes.`,Q);this.limit=Z}}class M0 extends N{contentType;allowed;code="content-type";constructor(Q,Z,$){super(`The response is ${Z??"of no content type"}, not ${$.join(" or ")}.`,Q);this.contentType=Z;this.allowed=$}}class v0 extends N{limit;code="too-many-redirects";constructor(Q,Z){super(`More than ${Z} redirects.`,Q);this.limit=Z}}class n extends N{code="network";constructor(Q,Z){super(`The request failed: ${Z instanceof Error?Z.message:String(Z)}`,Q,{cause:Z})}}class h0 extends N{status;code="http-status";constructor(Q,Z){super(`The server answered ${Z}.`,Q);this.status=Z}}function JZ(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 $=[];for(let H of Z){let Y=WZ(H);if(Y===null)return null;$.push(Y)}let X=$.pop();for(let H of $)if(H>255)return null;if(X>=256**(4-$.length))return null;let G=X;return $.forEach((H,Y)=>{G+=H*256**(3-Y)}),new Uint8Array([Math.floor(G/16777216)&255,Math.floor(G/65536)&255,Math.floor(G/256)&255,G&255])}function WZ(Q){if(Q==="")return null;let Z=Q,$=10;if(/^0x/i.test(Z)){if(Z=Z.slice(2),$=16,Z==="")return 0}else if(Z.length>1&&Z.startsWith("0"))Z=Z.slice(1),$=8;if(!($===16?/^[0-9a-f]+$/i:$===8?/^[0-7]+$/:/^[0-9]+$/).test(Z))return null;let G=parseInt(Z,$);return Number.isSafeInteger(G)?G:null}function PQ(Q){let Z=Q;if(Z.startsWith("[")&&Z.endsWith("]"))Z=Z.slice(1,-1);let $=Z.indexOf("%");if($!==-1)Z=Z.slice(0,$);if(!Z.includes(":"))return null;let X=Z.split("::");if(X.length>2)return null;let G=(J,D)=>{if(J==="")return[];let V=[],O=J.split(":");for(let B=0;B<O.length;B++){let L=O[B];if(D&&B===O.length-1&&L.includes(".")){if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(L))return null;let W=L.split(".").map(Number);if(W.some((U)=>U>255))return null;V.push(W[0]<<8|W[1],W[2]<<8|W[3]);continue}if(!/^[0-9a-f]{1,4}$/i.test(L))return null;V.push(parseInt(L,16))}return V},H=G(X[0],X.length===1),Y=X.length===2?G(X[1],!0):[];if(!H||!Y)return null;let M;if(X.length===2){let J=8-H.length-Y.length;if(J<1)return null;M=[...H,...Array.from({length:J},()=>0),...Y]}else M=H;if(M.length!==8)return null;let K=new Uint8Array(16);return M.forEach((J,D)=>{K[D*2]=J>>8,K[D*2+1]=J&255}),K}function K0(Q){let Z=PQ(Q);if(Z)return{family:6,bytes:Z};let $=JZ(Q);if($)return{family:4,bytes:$};return null}function c(Q){if(Q.family===6&&DZ(Q.bytes))return{family:4,bytes:Q.bytes.slice(12)};return Q}function DZ(Q){for(let Z=0;Z<10;Z++)if(Q[Z]!==0)return!1;return Q[10]===255&&Q[11]===255}function J0(Q){if(Q.family===4)return Array.from(Q.bytes).join(".");let Z=[];for(let $=0;$<16;$+=2)Z.push((Q.bytes[$]<<8|Q.bytes[$+1]).toString(16));return Z.join(":")}function o(Q){let Z=Q.lastIndexOf("/"),$=Z===-1?Q:Q.slice(0,Z),X=/^[0-9.]+$/.test($)?VZ($):PQ($);if(!X)return null;let G=c(X.length===4?{family:4,bytes:X}:{family:6,bytes:X}),H=G.family===4?32:128,Y=H;if(Z!==-1){let M=Q.slice(Z+1);if(!/^\d{1,3}$/.test(M))return null;if(Y=Number(M),X.length===16&&G.family===4)Y-=96;if(Y<0||Y>H)return null}return{family:G.family,bytes:G.bytes,prefix:Y}}function VZ(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 g(Q,Z){let $=c(Q);if($.family!==Z.family)return!1;let X=Z.prefix;for(let G=0;X>0;G++){let H=Math.min(8,X),Y=255<<8-H&255;if(($.bytes[G]&Y)!==(Z.bytes[G]&Y))return!1;X-=H}return!0}var _=(Q,Z)=>({cidr:o(Q),kind:Z,text:Q}),zZ=[_("0.0.0.0/8","unspecified"),_("10.0.0.0/8","private"),_("100.64.0.0/10","shared"),_("127.0.0.0/8","loopback"),_("169.254.169.254/32","metadata"),_("169.254.0.0/16","link-local"),_("168.63.129.16/32","metadata"),_("172.16.0.0/12","private"),_("192.0.0.0/24","reserved"),_("192.0.2.0/24","documentation"),_("192.88.99.0/24","reserved"),_("192.168.0.0/16","private"),_("198.18.0.0/15","benchmarking"),_("198.51.100.0/24","documentation"),_("203.0.113.0/24","documentation"),_("224.0.0.0/4","multicast"),_("255.255.255.255/32","broadcast"),_("240.0.0.0/4","reserved")],UZ=[_("::/128","unspecified"),_("::1/128","loopback"),_("64:ff9b:1::/48","private"),_("::/8","reserved"),_("100::/64","reserved"),_("2001:db8::/32","documentation"),_("2001::/23","reserved"),_("3fff::/20","documentation"),_("fd00:ec2::254/128","metadata"),_("fc00::/7","unique-local"),_("fe80::/10","link-local"),_("fec0::/10","private"),_("ff00::/8","multicast")],BZ=o("64:ff9b::/96"),RZ=o("2002::/16"),PZ=o("2000::/3");function A0(Q){let Z=typeof Q==="string"?K0(Q):Q;if(!Z)return{kind:"reserved",range:"not an IP address"};let $=c(Z);if($.family===4){let G=zZ.find((H)=>g($,H.cidr));return G?{kind:G.kind,range:G.text}:null}if(g($,BZ))return A0({family:4,bytes:$.bytes.slice(12)});if(g($,RZ))return A0({family:4,bytes:$.bytes.slice(2,6)});let X=UZ.find((G)=>g($,G.cidr));if(X)return{kind:X.kind,range:X.text};return g($,PZ)?null:{kind:"reserved",range:"outside 2000::/3"}}function jQ(Q,Z){let $=c(Q),X=c(Z);return $.family===X.family&&$.bytes.every((G,H)=>G===X.bytes[H])}import{lookup as jZ}from"dns/promises";import*as LZ from"http";import*as _Z from"https";import*as t from"zlib";class m0 extends Response{#Q;#Z;address;constructor(Q,Z,$){super(Q,Z);this.#Q=$.url,this.#Z=$.redirected,this.address=$.address}get url(){return this.#Q}get redirected(){return this.#Z}}var W0={timeout:30000,connectTimeout:1e4,maxSize:10485760,maxRedirects:5,ports:[80,443]},CZ=new Set([301,302,303,307,308]),OZ=new Set([101,103,204,205,304]),FZ=["host","connection","content-length","transfer-encoding","keep-alive","upgrade"],IZ=["authorization","cookie","proxy-authorization"];async function CQ(Q,Z={}){let $=TZ(Z),X=Z.signal;X?.throwIfAborted();let G=new AbortController,H=G.signal,Y=String(Q),M=(V)=>{if(!H.aborted)G.abort(V)},K=setTimeout(()=>M(new I0(Y,"total",$.timeout)),$.timeout),J=()=>M(X.reason);X?.addEventListener("abort",J,{once:!0});let D=()=>{clearTimeout(K),X?.removeEventListener("abort",J)};try{let V=_Q(Y,$),O=(Z.method??"GET").toUpperCase(),B=new Headers(Z.headers);for(let W of FZ)B.delete(W);if(!B.has("accept"))B.set("accept","*/*");if(!B.has("user-agent"))B.set("user-agent","gemi");if(!B.has("accept-encoding"))B.set("accept-encoding","gzip, deflate, br");let L=await wZ(O,Z.body,B);for(let W=0;;W++){Y=V.href;let{request:U,response:z,address:R}=await EZ(V,O,B,L,$,H),F=z.statusCode??0,I=z.headers.location;if(CZ.has(F)&&I&&Z.redirect!=="manual"){if(U.destroy(),W>=$.maxRedirects)throw new v0(V.href,$.maxRedirects);let T;try{T=new URL(I,V)}catch{throw new m(I,"malformed",`The redirect to "${I}" is not a URL.`)}if(F===303?O!=="HEAD":(F===301||F===302)&&O==="POST"){O="GET",L=null;let C=[];B.forEach((j,P)=>{if(P.startsWith("content-"))C.push(P)});for(let j of C)B.delete(j)}if(T.origin!==V.origin)for(let C of IZ)B.delete(C);V=_Q(T.href,$);continue}return SZ({url:V,hop:W,method:O,request:U,response:z,address:R,policy:$,signal:H,release:D})}}catch(V){throw D(),H.aborted?H.reason:V}}function TZ(Q){let Z=(X,G)=>{let H={hosts:[],ranges:[]};for(let Y of X){let M=Y.includes("/")||Y.includes(":")||/^[\d.]+$/.test(Y),K=M?o(Y):null;if(K)H.ranges.push(K);else if(!M&&/^(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*\.?$/i.test(Y))H.hosts.push(OQ(Y));else throw TypeError(`safeFetch: "${Y}" in ${G} is not a host name or an IP range.`)}return H},$=Q.allowPrivate;return{timeout:Q.timeout??W0.timeout,connectTimeout:Q.connectTimeout??W0.connectTimeout,maxSize:Q.maxSize??W0.maxSize,maxRedirects:Q.maxRedirects??W0.maxRedirects,ports:Q.ports??W0.ports,allow:Q.allow&&Q.allow.length>0?Z(Q.allow,"allow"):null,deny:Z(Q.deny??[],"deny"),allowPrivate:$===!0?!0:Z($||[],"allowPrivate").ranges,contentTypes:Q.contentTypes?.length?Q.contentTypes:null,resolve:Q.resolve??AZ}}async function AZ(Q){return(await jZ(Q,{all:!0,verbatim:!0})).map(($)=>$.address)}function OQ(Q){return Q.toLowerCase().replace(/\.$/,"")}function LQ(Q,Z){return Z.some(($)=>$.startsWith("*.")?Q.endsWith($.slice(1)):Q===$)}function _Q(Q,Z){let $;try{$=new URL(Q)}catch{throw new m(Q,"malformed",`"${Q}" is not a URL.`)}if($.protocol!=="http:"&&$.protocol!=="https:")throw new m($.href,"scheme",`Only http and https URLs can be fetched, not ${$.protocol.slice(0,-1)}.`);if($.username||$.password)throw new m($.href,"credentials","The URL has a username or password in it.");let X=FQ($);if(Z.ports!=="any"&&!Z.ports.includes(X))throw new m($.href,"port",`Port ${X} is not allowed.`);return $}function FQ(Q){return Q.port?Number(Q.port):Q.protocol==="https:"?443:80}async function qZ(Q,Z,$){let X=OQ(Q.hostname.replace(/^\[(.*)\]$/,"$1")),G=K0(X),H=G!==null&&(X.includes(":")||/^\d+\.\d+\.\d+\.\d+$/.test(X));if(!H&&LQ(X,Z.deny.hosts))throw new O0(Q.href,X,"denied");let Y=!H&&Z.allow!==null&&LQ(X,Z.allow.hosts);if(Z.allow&&!Y&&Z.allow.ranges.length===0)throw new O0(Q.href,X,"not-allowed");let M;if(H)M=[G];else{let K;try{K=await NZ(Z.resolve(X),$)}catch(J){if($.aborted)throw $.reason;throw new F0(Q.href,X,J)}if(M=K.map((J)=>K0(J)).filter((J)=>J!==null),M.length===0)throw new F0(Q.href,X)}for(let K of M){let J=J0(K);if(Z.deny.ranges.some((V)=>g(K,V)))throw new i(Q.href,X,J,"denied");if(Z.allow&&!Y&&!Z.allow.ranges.some((V)=>g(K,V)))throw new i(Q.href,X,J,"not-allowed");let D=A0(K);if(D&&Z.allowPrivate!==!0&&!Z.allowPrivate.some((V)=>g(K,V)))throw new i(Q.href,X,J,D.kind)}return{host:X,addresses:M,isLiteral:H}}function NZ(Q,Z){if(Z.aborted)return Promise.reject(Z.reason);return new Promise(($,X)=>{let G=()=>X(Z.reason);Z.addEventListener("abort",G,{once:!0}),Q.then((H)=>{Z.removeEventListener("abort",G),$(H)},(H)=>{Z.removeEventListener("abort",G),X(H)})})}async function wZ(Q,Z,$){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 X=new Request("http://body.invalid/",{method:"POST",body:Z}),G=X.headers.get("content-type");if(G&&!$.has("content-type"))$.set("content-type",G);return new Uint8Array(await X.arrayBuffer())}async function EZ(Q,Z,$,X,G,H){let Y=new AbortController,M=setTimeout(()=>Y.abort(new I0(Q.href,"connect",G.connectTimeout)),G.connectTimeout),K=AbortSignal.any([H,Y.signal]);try{let{host:J,addresses:D,isLiteral:V}=await qZ(Q,G,K),O=Q.protocol==="https:",B={};if($.forEach((L,W)=>{B[W]=L}),X)B["content-length"]=String(X.byteLength);return await new Promise((L,W)=>{let U={method:Z,host:J,port:FQ(Q),path:`${Q.pathname}${Q.search}`,headers:B,agent:!1,lookup:(C,j,P)=>{let w=j?.family,A=D.filter((D0)=>!w||D0.family===w);if(A.length===0)P(Object.assign(Error(`No IPv${w} address for ${J}`),{code:"ENOTFOUND"}));else if(j?.all)P(null,A.map((D0)=>({address:J0(D0),family:D0.family})));else P(null,J0(A[0]),A[0].family)}};if(O&&!V)U.servername=J;let z=(O?_Z:LZ).request(U),R=null,F=(C)=>{K.removeEventListener("abort",I),z.destroy(),W(C)},I=()=>F(K.aborted?K.reason:H.reason);K.addEventListener("abort",I,{once:!0});let T=(C)=>{let j=C?.remoteAddress;if(!j||R!==null)return!0;let P=K0(j);if(!P||!D.some((w)=>jQ(w,P)))return F(new i(Q.href,J,j,"not-allowed")),!1;return R=J0(c(P)),!0};z.once("socket",(C)=>{let j=()=>{if(T(C)&&!O)clearTimeout(M)};if(C.connecting)C.once("connect",j);else j();if(O)C.once("secureConnect",()=>clearTimeout(M))}),z.once("response",(C)=>{if(clearTimeout(M),C.on("error",()=>{}),!T(C.socket))return;K.removeEventListener("abort",I),L({request:z,response:C,address:R})}),z.on("error",(C)=>{if(K.aborted)return F(K.reason);F(C instanceof N?C:new n(Q.href,C))}),z.end(X??void 0)})}finally{clearTimeout(M)}}function SZ({url:Q,hop:Z,method:$,request:X,response:G,address:H,policy:Y,signal:M,release:K}){let J=G.statusCode??0;if(J<200||J>599)throw X.destroy(),new n(Q.href,Error(`Unexpected status ${J}`));let D=new Headers,V=G.rawHeaders;for(let j=0;j<V.length;j+=2)D.append(V[j],V[j+1]);if(Y.contentTypes){let j=D.get("content-type")?.split(";")[0].trim().toLowerCase()??null;if(!j||!Y.contentTypes.some((P)=>xZ(j,P)))throw X.destroy(),new M0(Q.href,j,Y.contentTypes)}let O={url:Q.href,redirected:Z>0,address:H},B={status:J,statusText:G.statusMessage??"",headers:D};if($==="HEAD"||OZ.has(J))return X.destroy(),K(),new m0(null,B,O);let L=D.get("content-encoding")?.trim().toLowerCase(),W=L==="gzip"||L==="x-gzip"?t.createGunzip():L==="deflate"?t.createInflate():L==="br"?t.createBrotliDecompress():null,U=Number(D.get("content-length"));if(!W&&Number.isFinite(U)&&U>Y.maxSize)throw X.destroy(),new T0(Q.href,Y.maxSize);if(W)D.delete("content-encoding"),D.delete("content-length");let z=W?G.pipe(W):G,R=0,F=!1,I=()=>{},T=()=>{F=!0,M.removeEventListener("abort",I),K()},C=new ReadableStream({start(j){let P=(A)=>{if(F)return;if(T(),A===void 0)j.close();else X.destroy(),W?.destroy(),j.error(A)};if(I=()=>P(M.reason),M.addEventListener("abort",I,{once:!0}),M.aborted)return I();z.on("data",(A)=>{if(F)return;if(R+=A.byteLength,R>Y.maxSize)return P(new T0(Q.href,Y.maxSize));if(j.enqueue(new Uint8Array(A)),(j.desiredSize??1)<=0)z.pause()}),z.once("end",()=>P());let w=(A)=>P(A instanceof N?A:new n(Q.href,A));if(z.on("error",w),W)G.on("error",w);G.once("aborted",()=>P(new n(Q.href,Error("The response was cut off."))))},pull(){z.resume()},cancel(){if(F)return;T(),X.destroy(),W?.destroy()}});return new m0(C,B,O)}function xZ(Q,Z){let $=Z.toLowerCase();return $.endsWith("/*")?Q.startsWith($.slice(0,-1)):Q===$}function TQ(Q){return yZ(Q)??fZ(Q)??vZ(Q)}var c0=4096,kZ={"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 AQ(Q){return kZ[Q]??"bin"}function S(Q,Z,$=0){if(Q.length<$+Z.length)return!1;return Z.every((X,G)=>Q[$+G]===X)}function y(Q,Z,$){return String.fromCharCode(...Q.subarray(Z,$))}var gZ={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 yZ(Q){if(S(Q,[137,80,78,71,13,10,26,10]))return"image/png";if(S(Q,[255,216,255]))return"image/jpeg";if(Q.length>=6&&(y(Q,0,6)==="GIF87a"||y(Q,0,6)==="GIF89a"))return"image/gif";if(Q.length>=12&&y(Q,0,4)==="RIFF"){let Z=y(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&&y(Q,4,8)==="ftyp"){let Z=y(Q,8,12);return gZ[Z]??"video/mp4"}if(S(Q,[73,73,42,0])||S(Q,[77,77,0,42]))return"image/tiff";if(S(Q,[66,77])&&S(Q,[0,0,0,0],6))return"image/bmp";if(S(Q,[0,0,1,0])&&Q.length>=6&&Q[4]>0)return"image/x-icon";if(S(Q,[37,80,68,70,45]))return"application/pdf";if(S(Q,[80,75,3,4]))return"application/zip";if(S(Q,[31,139]))return"application/gzip";if(S(Q,[26,69,223,163]))return y(Q,0,Math.min(Q.length,64)).includes("webm")?"video/webm":"video/x-matroska";if(Q.length>=4){let Z=y(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(S(Q,[0,1,0,0,0]))return"font/ttf";if(Q.length>=3&&y(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 bZ=["!doctype html","html","head","script","iframe","h1","div","font","table","a","style","title","b","body","br","p","!--"];function fZ(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 $=Z.toLowerCase(),X=$;for(;;){X=X.trimStart();let G=/^(<\?[\s\S]*?\?>|<!--[\s\S]*?-->|<!doctype[^>]*>)/.exec(X);if(!G)break;X=X.slice(G[0].length)}if(/^<svg[\s>/]/.test(X))return"image/svg+xml";for(let G of bZ){if(!$.startsWith(`<${G}`))continue;if(/^[\s>]/.test($.charAt(G.length+1)))return"text/html"}if(/^<(html|head|body)[\s>]/.test(X))return"text/html";if($.startsWith("<?xml"))return"application/xml";return null}function vZ(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 hZ=new Set(["text/html","application/xhtml+xml","image/svg+xml","text/xml","application/xml","text/xsl","application/xslt+xml"]);function IQ(Q){let Z=Q.split(";")[0].trim().toLowerCase();return hZ.has(Z)||Z.endsWith("+xml")}function qQ(Q,Z){let $=Q.split(";")[0].trim().toLowerCase();return Z.some((X)=>{let G=X.split(";")[0].trim().toLowerCase();if(G==="*/*"||G==="*")return!IQ($);if(G.endsWith("/*"))return $.startsWith(G.slice(0,-1))&&!IQ($);return $===G})}import{Buffer as pZ}from"buffer";async function NQ(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 wQ(Q,Z,$={}){let{name:X,directory:G,bucket:H,maxSize:Y,timeout:M,contentTypes:K,signal:J}=$;if(X!==void 0&&G!==void 0)throw TypeError("Storage.putFromUrl(): pass `name` or `directory`, not both.");if(X!==void 0&&!X)throw TypeError("Storage.putFromUrl(): `name` is empty.");let D=await CQ(Z,{...$.fetch,method:"GET",redirect:"follow",contentTypes:void 0,signal:J,timeout:M,maxSize:Y});if(!D.ok)throw await D.body?.cancel().catch(()=>{}),new h0(D.url,D.status);let V=(D.body??new Response(new Uint8Array).body).getReader(),O=async(P)=>{throw await V.cancel(P).catch(()=>{}),P},B=[],L=0,W=!1;while(L<c0){let{done:P,value:w}=await V.read();if(P){W=!0;break}B.push(w),L+=w.byteLength}let U=cZ(B,L),z=TQ(U.subarray(0,Math.min(L,c0))),R=K?.length?K:["*/*"];if(!qQ(z,R))await O(new M0(D.url,z,R));let F=X??[(G??"").replace(/\/+$/,""),`${Bun.randomUUIDv7()}.${AQ(z)}`].filter(Boolean).join("/"),I=L,T=new ReadableStream({start(P){if(L>0)P.enqueue(U);if(W)P.close()},async pull(P){let{done:w,value:A}=await V.read();if(w){P.close();return}I+=A.byteLength,P.enqueue(A)},cancel(P){return V.cancel(P)}}),C={name:F,bucket:H,body:T,contentType:z},j;try{j=Q.putStream?await Q.putStream(C,{signal:J}):await G0.prototype.putStream.call(Q,C,{signal:J})}catch(P){throw await O(P),P}return{name:j,contentType:z,size:I,url:D.url}}function cZ(Q,Z){if(Q.length===1)return Q[0];let $=new Uint8Array(Z),X=0;for(let G of Q)$.set(G,X),X+=G.byteLength;return $}class uZ extends X0{static getFacadeAccessor(){return f0}static async put(Q,Z={}){return this.getFacadeRoot().driver.put(Q,Z)}static async putFromUrl(Q,Z={}){return wQ(this.getFacadeRoot().driver,Q,Z)}static async metadata(Q){let Z=pZ.from(await Q.arrayBuffer()),$=await NQ("Storage.metadata()");try{return await $(Z).metadata()}catch{return{}}}static async fetch(Q,Z={}){return Z.signal?.throwIfAborted(),this.getFacadeRoot().driver.fetch(Q,Z)}static async read(Q,Z={}){let $=typeof Q==="string"?{name:Q}:{...Q},X="range"in Z?Z.range??null:$.range!==void 0?$.range:b.getStore()?.rangeRequest??null;return this.getFacadeRoot().driver.read({...$,range:X})}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)}}import{mkdir as p0,readdir as dZ,access as lZ}from"fs/promises";async function u0(Q){try{return await lZ(Q),!0}catch{return!1}}class d0{config;static token="log";writer;isReady=!1;flushTimeout;fileSize=0;writerSize=0;isCreatingFile=!1;bootPromise=null;currentLogFilePath;get logsDirPath(){return`${Y0()}/storage/logs`}constructor(Q){this.config=Q}boot(){if(!this.bootPromise)this.bootPromise=this.createStorage().catch((Q)=>{console.error("Log storage unavailable, file logging disabled",Q)}).then(()=>{this.isReady=!0});return this.bootPromise}async createStorage(){let Q=`${Y0()}/storage`;if(!await u0(Q))await p0(Q);if(!await u0(this.logsDirPath))await p0(this.logsDirPath);await this.newLogFile()}async newLogFile(){if(!await u0(this.logsDirPath))await p0(this.logsDirPath);if(this.isCreatingFile=!0,this.currentLogFilePath){this.writer.flush(),this.writer.end(),this.writer=null;let $=new File([await Bun.file(this.currentLogFilePath).arrayBuffer()],this.currentLogFilePath.split("/").pop(),{type:"text/plain"});this.config.onLogFileClosed($),this.fileSize=0,this.writerSize=0}let Z=(await dZ(this.logsDirPath)).sort().reverse()[0];if(Z){let $=Bun.file(`${this.logsDirPath}/${Z}`);if($.size<this.config.maxFileSize)this.currentLogFilePath=`${this.logsDirPath}/${Z}`,this.writer=$.writer(),this.writer.write(await $.text()),this.writer.write(`
|
|
5
5
|
`),this.writer.flush(),this.fileSize=$.size}if(!this.writer){let $=`${new Date(Date.now()).toISOString()}.log`.replaceAll(":","-");this.currentLogFilePath=`${this.logsDirPath}/${$}`;let X=Bun.file(`${this.logsDirPath}/${$}`);this.writer=X.writer(),this.fileSize=0,this.writerSize=0}this.isCreatingFile=!1}async log(Q,Z,$={}){if(!this.isReady)await this.boot();let X=b.getStore(),G={};if(X)G={url:X.req.rawRequest.url,method:X.req.rawRequest.method,headers:X.req.rawRequest.headers,body:X.req.rawRequest.body};let H={timestamp:new Date(Date.now()).toISOString(),env:Bun.env.NODE_ENV,level:Q,message:Z,metadata:{...G,...$}},Y="";try{Y=JSON.stringify(H)}catch(M){console.log("Error parsing log object",M)}try{let M=this.config.onLogCreated(H);if(M instanceof Promise)M.catch((K)=>console.error("Error in onLogCreated",K))}catch(M){console.error("Error in onLogCreated",M)}if(!this.writer)return;this.writerSize+=Y.length,this.fileSize+=Y.length;try{this.writer.write(Y),this.writer.write(`
|
|
@@ -9,6 +9,6 @@ data: ${JSON.stringify(Q.event)}
|
|
|
9
9
|
`}var tZ=5000,sZ=`: keepalive
|
|
10
10
|
|
|
11
11
|
`;function aZ(Q,Z=tZ){let $=null,X=!1,G=()=>{if(X)return;if($!==null)clearTimeout($);$=setTimeout(()=>{if($=null,X)return;try{Q.enqueue(l0.encode(sZ))}catch{H();return}G()},Z)},H=()=>{if(X=!0,$!==null)clearTimeout($);$=null};return G(),{touch:G,stop:H}}function rZ(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function w8(Q,Z=200){let $=Q[Symbol.asyncIterator](),X=-1,G,H=new ReadableStream({start(Y){G=aZ(Y)},async pull(Y){try{let M=await $.next();if(M.done){G.stop(),Y.close();return}X=M.value.seq,Y.enqueue(l0.encode(EQ(M.value))),G.touch()}catch(M){let K={type:"error",error:Q1(M)};G.stop(),Y.enqueue(l0.encode(EQ({seq:X+1,event:K}))),Y.close()}},cancel(Y){G.stop(),$.return?.(Y)}});return new Response(H,{status:Z,headers:rZ()})}var eZ=new Set(["frame_cursor_evicted","live_run_not_found"]);function Q1(Q){let Z=Q&&typeof Q==="object"?Q.code:void 0;if(Q instanceof Error&&typeof Z==="string"&&eZ.has(Z))return{code:"unknown",message:Q.message,retryable:!1};return console.error("[gemi/ai] agent stream failed",Q),{code:"unknown",message:"The run's stream failed.",retryable:!1}}
|
|
12
|
-
export{i0 as
|
|
12
|
+
export{i0 as xf,SQ as yf,$1 as zf,GQ as Af,B1 as Bf,MQ as Cf,R1 as Df,n0 as Ef,o0 as Ff,G1 as Gf,H1 as Hf,Y1 as If,t0 as Jf,j1 as Kf,WQ as Lf,L1 as Mf,_1 as Nf,s as Of,k as Pf,XQ as Qf,D1 as Rf,V1 as Sf,rQ as Tf,eQ as Uf,x0 as Vf,k0 as Wf,QZ as Xf,h as Yf,ZZ as Zf,X0 as _f,NQ as $f,C0 as ag,G0 as bg,UQ as cg,b0 as dg,a1 as eg,RQ as fg,f0 as gg,N as hg,m as ig,O0 as jg,i as kg,F0 as lg,I0 as mg,T0 as ng,M0 as og,v0 as pg,n as qg,h0 as rg,A0 as sg,m0 as tg,CQ as ug,TQ as vg,IQ as wg,uZ as xg,d0 as yg,iZ as zg,nZ as Ag,sZ as Bg,aZ as Cg,rZ as Dg,w8 as Eg};
|
|
13
13
|
|
|
14
|
-
//# debugId=
|
|
14
|
+
//# debugId=4327C247E9DD71D164756E2164756E21
|