gemi 0.138.0 → 0.140.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/Agent.d.ts +53 -1
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/FallbackProvider.d.ts.map +1 -1
- package/dist/ai/index.d.ts +1 -1
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +21 -21
- package/dist/ai/index.js.map +6 -6
- package/dist/ai/providers/call.d.ts +21 -1
- package/dist/ai/providers/call.d.ts.map +1 -1
- package/dist/ai/providers/http.d.ts +13 -0
- package/dist/ai/providers/http.d.ts.map +1 -1
- package/dist/ai/runtime.d.ts +10 -1
- package/dist/ai/runtime.d.ts.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-qvx8473q.js → chunk-0c553zfq.js} +3 -3
- package/dist/{chunk-qvx8473q.js.map → chunk-0c553zfq.js.map} +1 -1
- package/dist/{chunk-78zfqt54.js → chunk-18y8n1r3.js} +2 -2
- package/dist/{chunk-78zfqt54.js.map → chunk-18y8n1r3.js.map} +1 -1
- package/dist/{chunk-a2fhbstt.js → chunk-1cdz01em.js} +3 -3
- package/dist/{chunk-a2fhbstt.js.map → chunk-1cdz01em.js.map} +1 -1
- package/dist/{chunk-fwmmy0jn.js → chunk-1fe07ge4.js} +1 -1
- package/dist/{chunk-y6gr3stt.js → chunk-23mcs80p.js} +3 -3
- package/dist/{chunk-y6gr3stt.js.map → chunk-23mcs80p.js.map} +1 -1
- package/dist/{chunk-bg0e39dk.js → chunk-3v4esxbd.js} +2 -2
- package/dist/{chunk-bg0e39dk.js.map → chunk-3v4esxbd.js.map} +1 -1
- package/dist/{chunk-ted0qjps.js → chunk-3wpxqcw7.js} +1 -1
- package/dist/{chunk-5benn2ys.js → chunk-5013raxj.js} +3 -3
- package/dist/{chunk-5benn2ys.js.map → chunk-5013raxj.js.map} +1 -1
- package/dist/{chunk-f9w78tbd.js → chunk-5aj27bgc.js} +2 -2
- package/dist/{chunk-f9w78tbd.js.map → chunk-5aj27bgc.js.map} +1 -1
- package/dist/chunk-5gkzbhts.js +5 -0
- package/dist/{chunk-fs4ntgdr.js.map → chunk-5gkzbhts.js.map} +1 -1
- package/dist/{chunk-qk6vmvr2.js → chunk-6d9f4vw0.js} +4 -4
- package/dist/{chunk-qk6vmvr2.js.map → chunk-6d9f4vw0.js.map} +1 -1
- package/dist/{chunk-skmdmqv7.js → chunk-6hs102jh.js} +2 -2
- package/dist/{chunk-skmdmqv7.js.map → chunk-6hs102jh.js.map} +1 -1
- package/dist/{chunk-zvzvgrrn.js → chunk-6jd0e1dz.js} +2 -2
- package/dist/{chunk-zvzvgrrn.js.map → chunk-6jd0e1dz.js.map} +1 -1
- package/dist/{chunk-kpb8xvrv.js → chunk-6qydm38w.js} +2 -2
- package/dist/{chunk-kpb8xvrv.js.map → chunk-6qydm38w.js.map} +1 -1
- package/dist/{chunk-85k70cme.js → chunk-6zz3kez5.js} +3 -3
- package/dist/{chunk-85k70cme.js.map → chunk-6zz3kez5.js.map} +1 -1
- package/dist/{chunk-z88axcxg.js → chunk-7dwgex81.js} +9 -9
- package/dist/chunk-7dwgex81.js.map +27 -0
- package/dist/{chunk-yhp70t40.js → chunk-7hdfbp2x.js} +2 -2
- package/dist/{chunk-yhp70t40.js.map → chunk-7hdfbp2x.js.map} +1 -1
- package/dist/{chunk-vz5rrcnh.js → chunk-7p64zc6a.js} +2 -2
- package/dist/{chunk-vz5rrcnh.js.map → chunk-7p64zc6a.js.map} +1 -1
- package/dist/{chunk-nbfksexg.js → chunk-8gfgsmxk.js} +2 -2
- package/dist/{chunk-nbfksexg.js.map → chunk-8gfgsmxk.js.map} +1 -1
- package/dist/{chunk-c6c7p43e.js → chunk-8r9kna46.js} +2 -2
- package/dist/{chunk-c6c7p43e.js.map → chunk-8r9kna46.js.map} +1 -1
- package/dist/{chunk-7d26eqv1.js → chunk-98dxtkbt.js} +2 -2
- package/dist/{chunk-7d26eqv1.js.map → chunk-98dxtkbt.js.map} +1 -1
- package/dist/{chunk-n7576zsr.js → chunk-9b4ypfcw.js} +3 -3
- package/dist/{chunk-n7576zsr.js.map → chunk-9b4ypfcw.js.map} +1 -1
- package/dist/{chunk-aj2sr77y.js → chunk-9yfg4nqq.js} +2 -2
- package/dist/{chunk-aj2sr77y.js.map → chunk-9yfg4nqq.js.map} +1 -1
- package/dist/{chunk-c83e4ghx.js → chunk-apfk702c.js} +2 -2
- package/dist/{chunk-c83e4ghx.js.map → chunk-apfk702c.js.map} +1 -1
- package/dist/{chunk-7t7jh8t2.js → chunk-b3tmkge9.js} +2 -2
- package/dist/{chunk-7t7jh8t2.js.map → chunk-b3tmkge9.js.map} +1 -1
- package/dist/{chunk-6qzyq0g5.js → chunk-b4qh3ywd.js} +2 -2
- package/dist/{chunk-6qzyq0g5.js.map → chunk-b4qh3ywd.js.map} +1 -1
- package/dist/{chunk-d368es1y.js → chunk-b9d021hx.js} +2 -2
- package/dist/{chunk-d368es1y.js.map → chunk-b9d021hx.js.map} +1 -1
- package/dist/{chunk-46bwknb5.js → chunk-c7ecv545.js} +3 -3
- package/dist/{chunk-46bwknb5.js.map → chunk-c7ecv545.js.map} +1 -1
- package/dist/{chunk-wbvb1hcx.js → chunk-ct3sgfpj.js} +2 -2
- package/dist/{chunk-wbvb1hcx.js.map → chunk-ct3sgfpj.js.map} +1 -1
- package/dist/{chunk-965gfa41.js → chunk-d0kw04ym.js} +2 -2
- package/dist/{chunk-965gfa41.js.map → chunk-d0kw04ym.js.map} +1 -1
- package/dist/{chunk-vmr4d6hc.js → chunk-d1whcvyn.js} +1 -1
- package/dist/{chunk-1y6hxv30.js → chunk-d7a092vd.js} +2 -2
- package/dist/{chunk-1y6hxv30.js.map → chunk-d7a092vd.js.map} +1 -1
- package/dist/{chunk-p1y58p84.js → chunk-dje31gme.js} +2 -2
- package/dist/{chunk-p1y58p84.js.map → chunk-dje31gme.js.map} +1 -1
- package/dist/{chunk-3jkem5gq.js → chunk-dptp6ceg.js} +2 -2
- package/dist/{chunk-3jkem5gq.js.map → chunk-dptp6ceg.js.map} +1 -1
- package/dist/{chunk-an1nja68.js → chunk-dvwdehnp.js} +2 -2
- package/dist/{chunk-an1nja68.js.map → chunk-dvwdehnp.js.map} +1 -1
- package/dist/{chunk-v4dp93qv.js → chunk-dzvp8ynr.js} +3 -3
- package/dist/{chunk-v4dp93qv.js.map → chunk-dzvp8ynr.js.map} +1 -1
- package/dist/{chunk-d492ae5e.js → chunk-e3y72vzw.js} +2 -2
- package/dist/{chunk-d492ae5e.js.map → chunk-e3y72vzw.js.map} +1 -1
- package/dist/{chunk-9s203ks3.js → chunk-e9eh5k8a.js} +2 -2
- package/dist/{chunk-9s203ks3.js.map → chunk-e9eh5k8a.js.map} +1 -1
- package/dist/{chunk-pv2mtg8n.js → chunk-e9xbdgb2.js} +2 -2
- package/dist/{chunk-pv2mtg8n.js.map → chunk-e9xbdgb2.js.map} +1 -1
- package/dist/{chunk-md6wfc1h.js → chunk-eve0hewa.js} +3 -3
- package/dist/{chunk-md6wfc1h.js.map → chunk-eve0hewa.js.map} +1 -1
- package/dist/{chunk-kzdkpz04.js → chunk-eydahc2f.js} +1 -1
- package/dist/{chunk-z969a4nt.js → chunk-eyqsvzej.js} +2 -2
- package/dist/{chunk-z969a4nt.js.map → chunk-eyqsvzej.js.map} +1 -1
- package/dist/{chunk-cedmppcy.js → chunk-gp4s95kn.js} +2 -2
- package/dist/{chunk-cedmppcy.js.map → chunk-gp4s95kn.js.map} +1 -1
- package/dist/{chunk-es3mah07.js → chunk-gx202f9t.js} +2 -2
- package/dist/{chunk-es3mah07.js.map → chunk-gx202f9t.js.map} +1 -1
- package/dist/{chunk-ant9ck0r.js → chunk-gy307m19.js} +2 -2
- package/dist/{chunk-ant9ck0r.js.map → chunk-gy307m19.js.map} +1 -1
- package/dist/{chunk-h0ydk8cc.js → chunk-j9hf1jyd.js} +2 -2
- package/dist/{chunk-h0ydk8cc.js.map → chunk-j9hf1jyd.js.map} +1 -1
- package/dist/{chunk-7vxeqxxr.js → chunk-jrvg80jw.js} +2 -2
- package/dist/{chunk-7vxeqxxr.js.map → chunk-jrvg80jw.js.map} +1 -1
- package/dist/{chunk-8dmhbj4m.js → chunk-k732d7x5.js} +2 -2
- package/dist/{chunk-8dmhbj4m.js.map → chunk-k732d7x5.js.map} +1 -1
- package/dist/{chunk-4jc7wbet.js → chunk-kc2z9z3m.js} +2 -2
- package/dist/{chunk-4jc7wbet.js.map → chunk-kc2z9z3m.js.map} +1 -1
- package/dist/{chunk-xwmy6fby.js → chunk-kddgfct7.js} +3 -3
- package/dist/{chunk-xwmy6fby.js.map → chunk-kddgfct7.js.map} +1 -1
- package/dist/{chunk-qfhcec6q.js → chunk-ks7msv3e.js} +2 -2
- package/dist/{chunk-qfhcec6q.js.map → chunk-ks7msv3e.js.map} +1 -1
- package/dist/{chunk-9wc53ywv.js → chunk-me6mmvbq.js} +2 -2
- package/dist/{chunk-9wc53ywv.js.map → chunk-me6mmvbq.js.map} +1 -1
- package/dist/{chunk-c0m8pcbd.js → chunk-mj55jdwp.js} +1 -1
- package/dist/chunk-mxqnrn1k.js +10 -0
- package/dist/{chunk-4wyhf6j2.js.map → chunk-mxqnrn1k.js.map} +4 -4
- package/dist/{chunk-n1n7qb34.js → chunk-ny01tp0y.js} +4 -4
- package/dist/{chunk-n1n7qb34.js.map → chunk-ny01tp0y.js.map} +1 -1
- package/dist/{chunk-8ef5c93d.js → chunk-p131vmpy.js} +2 -2
- package/dist/{chunk-8ef5c93d.js.map → chunk-p131vmpy.js.map} +1 -1
- package/dist/{chunk-g22q8j2s.js → chunk-pfgbkhmm.js} +2 -2
- package/dist/{chunk-g22q8j2s.js.map → chunk-pfgbkhmm.js.map} +1 -1
- package/dist/{chunk-n2czjpz9.js → chunk-pxavt1j3.js} +2 -2
- package/dist/{chunk-n2czjpz9.js.map → chunk-pxavt1j3.js.map} +1 -1
- package/dist/{chunk-jys3n8xv.js → chunk-qdz4dqbf.js} +3 -3
- package/dist/{chunk-jys3n8xv.js.map → chunk-qdz4dqbf.js.map} +1 -1
- package/dist/{chunk-gqcmnyc8.js → chunk-qvtmn7mn.js} +2 -2
- package/dist/{chunk-gqcmnyc8.js.map → chunk-qvtmn7mn.js.map} +1 -1
- package/dist/{chunk-gq4fr0zn.js → chunk-r1x5ms0y.js} +3 -3
- package/dist/{chunk-gq4fr0zn.js.map → chunk-r1x5ms0y.js.map} +1 -1
- package/dist/{chunk-w17p2k8g.js → chunk-r6thf4ge.js} +3 -3
- package/dist/{chunk-w17p2k8g.js.map → chunk-r6thf4ge.js.map} +1 -1
- package/dist/{chunk-z0jazehw.js → chunk-rw4z3n9b.js} +2 -2
- package/dist/{chunk-z0jazehw.js.map → chunk-rw4z3n9b.js.map} +1 -1
- package/dist/{chunk-e440f645.js → chunk-rwrcsfzv.js} +2 -2
- package/dist/{chunk-e440f645.js.map → chunk-rwrcsfzv.js.map} +1 -1
- package/dist/{chunk-27xv8kty.js → chunk-s58hbczk.js} +2 -2
- package/dist/{chunk-27xv8kty.js.map → chunk-s58hbczk.js.map} +1 -1
- package/dist/{chunk-8p4t8x9c.js → chunk-t6n490ha.js} +2 -2
- package/dist/{chunk-8p4t8x9c.js.map → chunk-t6n490ha.js.map} +1 -1
- package/dist/{chunk-80fjsb26.js → chunk-t7qp951h.js} +3 -3
- package/dist/{chunk-80fjsb26.js.map → chunk-t7qp951h.js.map} +1 -1
- package/dist/{chunk-038xtqpm.js → chunk-tbhtx2t0.js} +2 -2
- package/dist/{chunk-chyt9th4.js.map → chunk-tbhtx2t0.js.map} +1 -1
- package/dist/{chunk-974p7em0.js → chunk-tghh8r2q.js} +2 -2
- package/dist/{chunk-974p7em0.js.map → chunk-tghh8r2q.js.map} +1 -1
- package/dist/{chunk-p2c7z2nr.js → chunk-v2cv3wcw.js} +2 -2
- package/dist/{chunk-p2c7z2nr.js.map → chunk-v2cv3wcw.js.map} +1 -1
- package/dist/{chunk-rqb52m93.js → chunk-vp4x2c0k.js} +2 -2
- package/dist/{chunk-rqb52m93.js.map → chunk-vp4x2c0k.js.map} +1 -1
- package/dist/{chunk-chyt9th4.js → chunk-vtqvq9ca.js} +2 -2
- package/dist/{chunk-038xtqpm.js.map → chunk-vtqvq9ca.js.map} +1 -1
- package/dist/{chunk-eqzxvfvt.js → chunk-x4g0r9d3.js} +2 -2
- package/dist/{chunk-eqzxvfvt.js.map → chunk-x4g0r9d3.js.map} +1 -1
- package/dist/{chunk-zj8y4ak5.js → chunk-y7v30zd8.js} +1 -1
- package/dist/{chunk-vtc1khbm.js → chunk-ygyjtrzb.js} +2 -2
- package/dist/{chunk-vtc1khbm.js.map → chunk-ygyjtrzb.js.map} +1 -1
- package/dist/{chunk-26yghzet.js → chunk-yxhg3wjf.js} +2 -2
- package/dist/{chunk-26yghzet.js.map → chunk-yxhg3wjf.js.map} +1 -1
- package/dist/{chunk-ghbzre7k.js → chunk-yxjfghq3.js} +3 -3
- package/dist/{chunk-ghbzre7k.js.map → chunk-yxjfghq3.js.map} +1 -1
- 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/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 +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/mcp/McpRegistry.d.ts +25 -1
- package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
- package/dist/services/mcp/http/McpHttpServer.d.ts.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-4wyhf6j2.js +0 -10
- package/dist/chunk-fs4ntgdr.js +0 -5
- package/dist/chunk-z88axcxg.js.map +0 -27
- /package/dist/{chunk-fwmmy0jn.js.map → chunk-1fe07ge4.js.map} +0 -0
- /package/dist/{chunk-ted0qjps.js.map → chunk-3wpxqcw7.js.map} +0 -0
- /package/dist/{chunk-vmr4d6hc.js.map → chunk-d1whcvyn.js.map} +0 -0
- /package/dist/{chunk-kzdkpz04.js.map → chunk-eydahc2f.js.map} +0 -0
- /package/dist/{chunk-c0m8pcbd.js.map → chunk-mj55jdwp.js.map} +0 -0
- /package/dist/{chunk-zj8y4ak5.js.map → chunk-y7v30zd8.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{P as ue}from"./chunk-eqzxvfvt.js";import{Q as w}from"./chunk-26yghzet.js";import{_}from"./chunk-cedmppcy.js";import"./chunk-9wc53ywv.js";import{aa as l}from"./chunk-7vxeqxxr.js";import{ml as o,ql as d}from"./chunk-038xtqpm.js";var g=o(_(),1);var ie=o(l(),1);var O=o(w(),1),R=o(l(),1),J=o(_(),1);var j=o(w(),1),E=o(l(),1),U=(e,s,t)=>{let n={EcsContainer:async(r)=>{let{fromHttp:a}=await import("./chunk-p1y58p84.js"),{fromContainerMetadata:c}=await import("./chunk-974p7em0.js");return t?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"),async()=>E.chain(a(r??{}),c(r))().then(L)},Ec2InstanceMetadata:async(r)=>{t?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");let{fromInstanceMetadata:a}=await import("./chunk-974p7em0.js");return async()=>a(r)().then(L)},Environment:async(r)=>{t?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");let{fromEnv:a}=await import("./chunk-ted0qjps.js");return async()=>a(r)().then(L)}};if(e in n)return n[e];else throw new E.CredentialsProviderError(`Unsupported credential source in profile ${s}. Got ${e}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:t})},L=(e)=>j.setCredentialFeature(e,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p");var N=(e,{profile:s="default",logger:t}={})=>{return Boolean(e)&&typeof e==="object"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1&&["undefined","string"].indexOf(typeof e.external_id)>-1&&["undefined","string"].indexOf(typeof e.mfa_serial)>-1&&(he(e,{profile:s,logger:t})||ye(e,{profile:s,logger:t}))},he=(e,{profile:s,logger:t})=>{let n=typeof e.source_profile==="string"&&typeof e.credential_source>"u";if(n)t?.debug?.(` ${s} isAssumeRoleWithSourceProfile source_profile=${e.source_profile}`);return n},ye=(e,{profile:s,logger:t})=>{let n=typeof e.credential_source==="string"&&typeof e.source_profile>"u";if(n)t?.debug?.(` ${s} isCredentialSourceProfile credential_source=${e.credential_source}`);return n},v=async(e,s,t,n,r={},a)=>{t.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");let c=s[e],{source_profile:h,region:I}=c;if(!t.roleAssumer){let{getDefaultRoleAssumer:i}=await import("./chunk-h0ydk8cc.js").then((m)=>o(m.default,1));t.roleAssumer=i({...t.clientConfig,credentialProviderLogger:t.logger,parentClientConfig:{...n,...t?.parentClientConfig,region:I??t?.parentClientConfig?.region??n?.region}},t.clientPlugins)}if(h&&h in r)throw new R.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${J.getProfileName(t)}. Profiles visited: `+Object.keys(r).join(", "),{logger:t.logger});t.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${h?`source_profile=[${h}]`:`profile=[${e}]`}`);let T=h?a(h,s,t,n,{...r,[h]:!0},G(s[h]??{})):(await U(c.credential_source,e,t.logger)(t))();if(G(c))return T.then((i)=>O.setCredentialFeature(i,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));else{let i={RoleArn:c.role_arn,RoleSessionName:c.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:c.external_id,DurationSeconds:parseInt(c.duration_seconds||"3600",10)},{mfa_serial:u}=c;if(u){if(!t.mfaCodeProvider)throw new R.CredentialsProviderError(`Profile ${e} requires multi-factor authentication, but no MFA code callback was provided.`,{logger:t.logger,tryNextLink:!1});i.SerialNumber=u,i.TokenCode=await t.mfaCodeProvider(u)}let y=await T;return t.roleAssumer(y,i).then((m)=>O.setCredentialFeature(m,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}},G=(e)=>{return!e.role_arn&&!!e.credential_source};var V=o(w(),1);var C=o(w(),1),X=o(l(),1),K=o(_(),1);var k=o(l(),1),W=o(ue(),1),z=o(_(),1);import{createHash as de,createPrivateKey as we,createPublicKey as ke,sign as me}from"crypto";import{promises as D}from"fs";import{homedir as fe}from"os";import{dirname as Ie,join as Y}from"path";class b{profileData;init;callerClientConfig;static REFRESH_THRESHOLD=300000;constructor(e,s,t){this.profileData=e,this.init=s,this.callerClientConfig=t}async loadCredentials(){let e=await this.loadToken();if(!e)throw new k.CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`,{tryNextLink:!1,logger:this.logger});let s=e.accessToken,t=Date.now();if(new Date(s.expiresAt).getTime()-t<=b.REFRESH_THRESHOLD)return this.refresh(e);return{accessKeyId:s.accessKeyId,secretAccessKey:s.secretAccessKey,sessionToken:s.sessionToken,accountId:s.accountId,expiration:new Date(s.expiresAt)}}get logger(){return this.init?.logger}get loginSession(){return this.profileData.login_session}async refresh(e){let{SigninClient:s,CreateOAuth2TokenCommand:t}=await import("./chunk-d368es1y.js").then((m)=>o(m.default,1)),{logger:n,userAgentAppId:r}=this.callerClientConfig??{},c=((i)=>{return i?.metadata?.handlerProtocol==="h2"})(this.callerClientConfig?.requestHandler)?void 0:this.callerClientConfig?.requestHandler,h=this.profileData.region??await this.callerClientConfig?.region?.()??process.env.AWS_REGION,I=new s({credentials:{accessKeyId:"",secretAccessKey:""},region:h,requestHandler:c,logger:n,userAgentAppId:r,...this.init?.clientConfig});this.createDPoPInterceptor(I.middlewareStack);let T={tokenInput:{clientId:e.clientId,refreshToken:e.refreshToken,grantType:"refresh_token"}};try{let i=await I.send(new t(T)),{accessKeyId:u,secretAccessKey:y,sessionToken:m}=i.tokenOutput?.accessToken??{},{refreshToken:x,expiresIn:H}=i.tokenOutput??{};if(!u||!y||!m||!x)throw new k.CredentialsProviderError("Token refresh response missing required fields",{logger:this.logger,tryNextLink:!1});let A=(H??900)*1000,f=new Date(Date.now()+A),q={...e,accessToken:{...e.accessToken,accessKeyId:u,secretAccessKey:y,sessionToken:m,expiresAt:f.toISOString()},refreshToken:x};await this.saveToken(q);let S=q.accessToken;return{accessKeyId:S.accessKeyId,secretAccessKey:S.secretAccessKey,sessionToken:S.sessionToken,accountId:S.accountId,expiration:f}}catch(i){if(i.name==="AccessDeniedException"){let u=i.error,y;switch(u){case"TOKEN_EXPIRED":y="Your session has expired. Please reauthenticate.";break;case"USER_CREDENTIALS_CHANGED":y="Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.";break;case"INSUFFICIENT_PERMISSIONS":y="Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.";break;default:y=`Failed to refresh token: ${String(i)}. Please re-authenticate using \`aws login\``}throw new k.CredentialsProviderError(y,{logger:this.logger,tryNextLink:!1})}throw new k.CredentialsProviderError(`Failed to refresh token: ${String(i)}. Please re-authenticate using aws login`,{logger:this.logger})}}async loadToken(){let e=this.getTokenFilePath();try{let s;try{s=await z.readFile(e,{ignoreCache:this.init?.ignoreCache})}catch{s=await D.readFile(e,"utf8")}let t=JSON.parse(s),n=["accessToken","clientId","refreshToken","dpopKey"].filter((r)=>!t[r]);if(!t.accessToken?.accountId)n.push("accountId");if(n.length>0)throw new k.CredentialsProviderError(`Token validation failed, missing fields: ${n.join(", ")}`,{logger:this.logger,tryNextLink:!1});return t}catch(s){throw new k.CredentialsProviderError(`Failed to load token from ${e}: ${String(s)}`,{logger:this.logger,tryNextLink:!1})}}async saveToken(e){let s=this.getTokenFilePath(),t=Ie(s);try{await D.mkdir(t,{recursive:!0})}catch(n){}await D.writeFile(s,JSON.stringify(e,null,2),"utf8")}getTokenFilePath(){let e=process.env.AWS_LOGIN_CACHE_DIRECTORY??Y(fe(),".aws","login","cache"),s=Buffer.from(this.loginSession,"utf8"),t=de("sha256").update(s).digest("hex");return Y(e,`${t}.json`)}derToRawSignature(e){let s=2;if(e[s]!==2)throw Error("Invalid DER signature");s++;let t=e[s++],n=e.subarray(s,s+t);if(s+=t,e[s]!==2)throw Error("Invalid DER signature");s++;let r=e[s++],a=e.subarray(s,s+r);n=n[0]===0?n.subarray(1):n,a=a[0]===0?a.subarray(1):a;let c=Buffer.concat([Buffer.alloc(32-n.length),n]),h=Buffer.concat([Buffer.alloc(32-a.length),a]);return Buffer.concat([c,h])}createDPoPInterceptor(e){e.add((s)=>async(t)=>{if(W.HttpRequest.isInstance(t.request)){let n=t.request,r=`${n.protocol}//${n.hostname}${n.port?`:${n.port}`:""}${n.path}`,a=await this.generateDpop(n.method,r);n.headers={...n.headers,DPoP:a}}return s(t)},{step:"finalizeRequest",name:"dpopInterceptor",override:!0})}async generateDpop(e="POST",s){let t=await this.loadToken();try{let n=we({key:t.dpopKey,format:"pem",type:"sec1"}),a=ke(n).export({format:"der",type:"spki"}),c=-1;for(let f=0;f<a.length;f++)if(a[f]===4){c=f;break}let h=a.slice(c+1,c+33),I=a.slice(c+33,c+65),T={alg:"ES256",typ:"dpop+jwt",jwk:{kty:"EC",crv:"P-256",x:h.toString("base64url"),y:I.toString("base64url")}},i={jti:crypto.randomUUID(),htm:e,htu:s,iat:Math.floor(Date.now()/1000)},u=Buffer.from(JSON.stringify(T)).toString("base64url"),y=Buffer.from(JSON.stringify(i)).toString("base64url"),m=`${u}.${y}`,x=me("sha256",Buffer.from(m),n),A=this.derToRawSignature(x).toString("base64url");return`${m}.${A}`}catch(n){throw new k.CredentialsProviderError(`Failed to generate Dpop proof: ${n instanceof Error?n.message:String(n)}`,{logger:this.logger,tryNextLink:!1})}}}var Q=(e)=>async({callerClientConfig:s}={})=>{e?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials");let t=await K.parseKnownFiles(e||{}),n=K.getProfileName({profile:e?.profile??s?.profile}),r=t[n];if(!r?.login_session)throw new X.CredentialsProviderError(`Profile ${n} does not contain login_session.`,{tryNextLink:!0,logger:e?.logger});let c=await new b(r,e,s).loadCredentials();return C.setCredentialFeature(c,"CREDENTIALS_LOGIN","AD")};var Z=(e)=>{return Boolean(e&&e.login_session)},M=async(e,s,t)=>{let n=await Q({...s,profile:e})({callerClientConfig:t});return V.setCredentialFeature(n,"CREDENTIALS_PROFILE_LOGIN","AC")};var p=o(w(),1),ee=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.credential_process==="string",te=async(e,s)=>import("./chunk-kpb8xvrv.js").then(({fromProcess:t})=>t({...e,profile:s})().then((n)=>p.setCredentialFeature(n,"CREDENTIALS_PROFILE_PROCESS","v")));var $=o(w(),1),se=async(e,s,t={},n)=>{let{fromSSO:r}=await import("./chunk-8ef5c93d.js");return r({profile:e,logger:t.logger,parentClientConfig:t.parentClientConfig,clientConfig:t.clientConfig})({callerClientConfig:n}).then((a)=>{if(s.sso_session)return $.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO","r");else return $.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO_LEGACY","t")})},ne=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var ce=o(w(),1),P=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.aws_access_key_id==="string"&&typeof e.aws_secret_access_key==="string"&&["undefined","string"].indexOf(typeof e.aws_session_token)>-1&&["undefined","string"].indexOf(typeof e.aws_account_id)>-1,F=async(e,s)=>{s?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");let t={accessKeyId:e.aws_access_key_id,secretAccessKey:e.aws_secret_access_key,sessionToken:e.aws_session_token,...e.aws_credential_scope&&{credentialScope:e.aws_credential_scope},...e.aws_account_id&&{accountId:e.aws_account_id}};return ce.setCredentialFeature(t,"CREDENTIALS_PROFILE","n")};var re=o(w(),1),ae=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.web_identity_token_file==="string"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1,oe=async(e,s,t)=>import("./chunk-g22q8j2s.js").then(({fromTokenFile:n})=>n({webIdentityTokenFile:e.web_identity_token_file,roleArn:e.role_arn,roleSessionName:e.role_session_name,roleAssumerWithWebIdentity:s.roleAssumerWithWebIdentity,logger:s.logger,parentClientConfig:s.parentClientConfig})({callerClientConfig:t}).then((r)=>re.setCredentialFeature(r,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q")));var B=async(e,s,t,n,r={},a=!1)=>{let c=s[e];if(Object.keys(r).length>0&&P(c))return F(c,t);if(a||N(c,{profile:e,logger:t.logger}))return v(e,s,t,n,r,B);if(P(c))return F(c,t);if(ae(c))return oe(c,t,n);if(ee(c))return te(t,e);if(ne(c))return await se(e,c,t,n);if(Z(c))return M(e,t,n);throw new ie.CredentialsProviderError(`Could not resolve credentials using profile: [${e}] in configuration/credentials file(s).`,{logger:t.logger})};var Ne=(e={})=>async({callerClientConfig:s}={})=>{e.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");let t=await g.parseKnownFiles(e);return B(g.getProfileName({profile:e.profile??s?.profile}),t,e,s)};export{Ne as fromIni};
|
|
2
|
+
import{P as ue}from"./chunk-x4g0r9d3.js";import{Q as w}from"./chunk-yxhg3wjf.js";import{_}from"./chunk-gp4s95kn.js";import"./chunk-me6mmvbq.js";import{aa as l}from"./chunk-jrvg80jw.js";import{nl as o,rl as d}from"./chunk-tbhtx2t0.js";var g=o(_(),1);var ie=o(l(),1);var O=o(w(),1),R=o(l(),1),J=o(_(),1);var j=o(w(),1),E=o(l(),1),U=(e,s,t)=>{let n={EcsContainer:async(r)=>{let{fromHttp:a}=await import("./chunk-dje31gme.js"),{fromContainerMetadata:c}=await import("./chunk-tghh8r2q.js");return t?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"),async()=>E.chain(a(r??{}),c(r))().then(L)},Ec2InstanceMetadata:async(r)=>{t?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");let{fromInstanceMetadata:a}=await import("./chunk-tghh8r2q.js");return async()=>a(r)().then(L)},Environment:async(r)=>{t?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");let{fromEnv:a}=await import("./chunk-3wpxqcw7.js");return async()=>a(r)().then(L)}};if(e in n)return n[e];else throw new E.CredentialsProviderError(`Unsupported credential source in profile ${s}. Got ${e}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:t})},L=(e)=>j.setCredentialFeature(e,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p");var N=(e,{profile:s="default",logger:t}={})=>{return Boolean(e)&&typeof e==="object"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1&&["undefined","string"].indexOf(typeof e.external_id)>-1&&["undefined","string"].indexOf(typeof e.mfa_serial)>-1&&(he(e,{profile:s,logger:t})||ye(e,{profile:s,logger:t}))},he=(e,{profile:s,logger:t})=>{let n=typeof e.source_profile==="string"&&typeof e.credential_source>"u";if(n)t?.debug?.(` ${s} isAssumeRoleWithSourceProfile source_profile=${e.source_profile}`);return n},ye=(e,{profile:s,logger:t})=>{let n=typeof e.credential_source==="string"&&typeof e.source_profile>"u";if(n)t?.debug?.(` ${s} isCredentialSourceProfile credential_source=${e.credential_source}`);return n},v=async(e,s,t,n,r={},a)=>{t.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");let c=s[e],{source_profile:h,region:I}=c;if(!t.roleAssumer){let{getDefaultRoleAssumer:i}=await import("./chunk-j9hf1jyd.js").then((m)=>o(m.default,1));t.roleAssumer=i({...t.clientConfig,credentialProviderLogger:t.logger,parentClientConfig:{...n,...t?.parentClientConfig,region:I??t?.parentClientConfig?.region??n?.region}},t.clientPlugins)}if(h&&h in r)throw new R.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${J.getProfileName(t)}. Profiles visited: `+Object.keys(r).join(", "),{logger:t.logger});t.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${h?`source_profile=[${h}]`:`profile=[${e}]`}`);let T=h?a(h,s,t,n,{...r,[h]:!0},G(s[h]??{})):(await U(c.credential_source,e,t.logger)(t))();if(G(c))return T.then((i)=>O.setCredentialFeature(i,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));else{let i={RoleArn:c.role_arn,RoleSessionName:c.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:c.external_id,DurationSeconds:parseInt(c.duration_seconds||"3600",10)},{mfa_serial:u}=c;if(u){if(!t.mfaCodeProvider)throw new R.CredentialsProviderError(`Profile ${e} requires multi-factor authentication, but no MFA code callback was provided.`,{logger:t.logger,tryNextLink:!1});i.SerialNumber=u,i.TokenCode=await t.mfaCodeProvider(u)}let y=await T;return t.roleAssumer(y,i).then((m)=>O.setCredentialFeature(m,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}},G=(e)=>{return!e.role_arn&&!!e.credential_source};var V=o(w(),1);var C=o(w(),1),X=o(l(),1),K=o(_(),1);var k=o(l(),1),W=o(ue(),1),z=o(_(),1);import{createHash as de,createPrivateKey as we,createPublicKey as ke,sign as me}from"crypto";import{promises as D}from"fs";import{homedir as fe}from"os";import{dirname as Ie,join as Y}from"path";class b{profileData;init;callerClientConfig;static REFRESH_THRESHOLD=300000;constructor(e,s,t){this.profileData=e,this.init=s,this.callerClientConfig=t}async loadCredentials(){let e=await this.loadToken();if(!e)throw new k.CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`,{tryNextLink:!1,logger:this.logger});let s=e.accessToken,t=Date.now();if(new Date(s.expiresAt).getTime()-t<=b.REFRESH_THRESHOLD)return this.refresh(e);return{accessKeyId:s.accessKeyId,secretAccessKey:s.secretAccessKey,sessionToken:s.sessionToken,accountId:s.accountId,expiration:new Date(s.expiresAt)}}get logger(){return this.init?.logger}get loginSession(){return this.profileData.login_session}async refresh(e){let{SigninClient:s,CreateOAuth2TokenCommand:t}=await import("./chunk-b9d021hx.js").then((m)=>o(m.default,1)),{logger:n,userAgentAppId:r}=this.callerClientConfig??{},c=((i)=>{return i?.metadata?.handlerProtocol==="h2"})(this.callerClientConfig?.requestHandler)?void 0:this.callerClientConfig?.requestHandler,h=this.profileData.region??await this.callerClientConfig?.region?.()??process.env.AWS_REGION,I=new s({credentials:{accessKeyId:"",secretAccessKey:""},region:h,requestHandler:c,logger:n,userAgentAppId:r,...this.init?.clientConfig});this.createDPoPInterceptor(I.middlewareStack);let T={tokenInput:{clientId:e.clientId,refreshToken:e.refreshToken,grantType:"refresh_token"}};try{let i=await I.send(new t(T)),{accessKeyId:u,secretAccessKey:y,sessionToken:m}=i.tokenOutput?.accessToken??{},{refreshToken:x,expiresIn:H}=i.tokenOutput??{};if(!u||!y||!m||!x)throw new k.CredentialsProviderError("Token refresh response missing required fields",{logger:this.logger,tryNextLink:!1});let A=(H??900)*1000,f=new Date(Date.now()+A),q={...e,accessToken:{...e.accessToken,accessKeyId:u,secretAccessKey:y,sessionToken:m,expiresAt:f.toISOString()},refreshToken:x};await this.saveToken(q);let S=q.accessToken;return{accessKeyId:S.accessKeyId,secretAccessKey:S.secretAccessKey,sessionToken:S.sessionToken,accountId:S.accountId,expiration:f}}catch(i){if(i.name==="AccessDeniedException"){let u=i.error,y;switch(u){case"TOKEN_EXPIRED":y="Your session has expired. Please reauthenticate.";break;case"USER_CREDENTIALS_CHANGED":y="Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.";break;case"INSUFFICIENT_PERMISSIONS":y="Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.";break;default:y=`Failed to refresh token: ${String(i)}. Please re-authenticate using \`aws login\``}throw new k.CredentialsProviderError(y,{logger:this.logger,tryNextLink:!1})}throw new k.CredentialsProviderError(`Failed to refresh token: ${String(i)}. Please re-authenticate using aws login`,{logger:this.logger})}}async loadToken(){let e=this.getTokenFilePath();try{let s;try{s=await z.readFile(e,{ignoreCache:this.init?.ignoreCache})}catch{s=await D.readFile(e,"utf8")}let t=JSON.parse(s),n=["accessToken","clientId","refreshToken","dpopKey"].filter((r)=>!t[r]);if(!t.accessToken?.accountId)n.push("accountId");if(n.length>0)throw new k.CredentialsProviderError(`Token validation failed, missing fields: ${n.join(", ")}`,{logger:this.logger,tryNextLink:!1});return t}catch(s){throw new k.CredentialsProviderError(`Failed to load token from ${e}: ${String(s)}`,{logger:this.logger,tryNextLink:!1})}}async saveToken(e){let s=this.getTokenFilePath(),t=Ie(s);try{await D.mkdir(t,{recursive:!0})}catch(n){}await D.writeFile(s,JSON.stringify(e,null,2),"utf8")}getTokenFilePath(){let e=process.env.AWS_LOGIN_CACHE_DIRECTORY??Y(fe(),".aws","login","cache"),s=Buffer.from(this.loginSession,"utf8"),t=de("sha256").update(s).digest("hex");return Y(e,`${t}.json`)}derToRawSignature(e){let s=2;if(e[s]!==2)throw Error("Invalid DER signature");s++;let t=e[s++],n=e.subarray(s,s+t);if(s+=t,e[s]!==2)throw Error("Invalid DER signature");s++;let r=e[s++],a=e.subarray(s,s+r);n=n[0]===0?n.subarray(1):n,a=a[0]===0?a.subarray(1):a;let c=Buffer.concat([Buffer.alloc(32-n.length),n]),h=Buffer.concat([Buffer.alloc(32-a.length),a]);return Buffer.concat([c,h])}createDPoPInterceptor(e){e.add((s)=>async(t)=>{if(W.HttpRequest.isInstance(t.request)){let n=t.request,r=`${n.protocol}//${n.hostname}${n.port?`:${n.port}`:""}${n.path}`,a=await this.generateDpop(n.method,r);n.headers={...n.headers,DPoP:a}}return s(t)},{step:"finalizeRequest",name:"dpopInterceptor",override:!0})}async generateDpop(e="POST",s){let t=await this.loadToken();try{let n=we({key:t.dpopKey,format:"pem",type:"sec1"}),a=ke(n).export({format:"der",type:"spki"}),c=-1;for(let f=0;f<a.length;f++)if(a[f]===4){c=f;break}let h=a.slice(c+1,c+33),I=a.slice(c+33,c+65),T={alg:"ES256",typ:"dpop+jwt",jwk:{kty:"EC",crv:"P-256",x:h.toString("base64url"),y:I.toString("base64url")}},i={jti:crypto.randomUUID(),htm:e,htu:s,iat:Math.floor(Date.now()/1000)},u=Buffer.from(JSON.stringify(T)).toString("base64url"),y=Buffer.from(JSON.stringify(i)).toString("base64url"),m=`${u}.${y}`,x=me("sha256",Buffer.from(m),n),A=this.derToRawSignature(x).toString("base64url");return`${m}.${A}`}catch(n){throw new k.CredentialsProviderError(`Failed to generate Dpop proof: ${n instanceof Error?n.message:String(n)}`,{logger:this.logger,tryNextLink:!1})}}}var Q=(e)=>async({callerClientConfig:s}={})=>{e?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials");let t=await K.parseKnownFiles(e||{}),n=K.getProfileName({profile:e?.profile??s?.profile}),r=t[n];if(!r?.login_session)throw new X.CredentialsProviderError(`Profile ${n} does not contain login_session.`,{tryNextLink:!0,logger:e?.logger});let c=await new b(r,e,s).loadCredentials();return C.setCredentialFeature(c,"CREDENTIALS_LOGIN","AD")};var Z=(e)=>{return Boolean(e&&e.login_session)},M=async(e,s,t)=>{let n=await Q({...s,profile:e})({callerClientConfig:t});return V.setCredentialFeature(n,"CREDENTIALS_PROFILE_LOGIN","AC")};var p=o(w(),1),ee=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.credential_process==="string",te=async(e,s)=>import("./chunk-6qydm38w.js").then(({fromProcess:t})=>t({...e,profile:s})().then((n)=>p.setCredentialFeature(n,"CREDENTIALS_PROFILE_PROCESS","v")));var $=o(w(),1),se=async(e,s,t={},n)=>{let{fromSSO:r}=await import("./chunk-p131vmpy.js");return r({profile:e,logger:t.logger,parentClientConfig:t.parentClientConfig,clientConfig:t.clientConfig})({callerClientConfig:n}).then((a)=>{if(s.sso_session)return $.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO","r");else return $.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO_LEGACY","t")})},ne=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var ce=o(w(),1),P=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.aws_access_key_id==="string"&&typeof e.aws_secret_access_key==="string"&&["undefined","string"].indexOf(typeof e.aws_session_token)>-1&&["undefined","string"].indexOf(typeof e.aws_account_id)>-1,F=async(e,s)=>{s?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");let t={accessKeyId:e.aws_access_key_id,secretAccessKey:e.aws_secret_access_key,sessionToken:e.aws_session_token,...e.aws_credential_scope&&{credentialScope:e.aws_credential_scope},...e.aws_account_id&&{accountId:e.aws_account_id}};return ce.setCredentialFeature(t,"CREDENTIALS_PROFILE","n")};var re=o(w(),1),ae=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.web_identity_token_file==="string"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1,oe=async(e,s,t)=>import("./chunk-pfgbkhmm.js").then(({fromTokenFile:n})=>n({webIdentityTokenFile:e.web_identity_token_file,roleArn:e.role_arn,roleSessionName:e.role_session_name,roleAssumerWithWebIdentity:s.roleAssumerWithWebIdentity,logger:s.logger,parentClientConfig:s.parentClientConfig})({callerClientConfig:t}).then((r)=>re.setCredentialFeature(r,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q")));var B=async(e,s,t,n,r={},a=!1)=>{let c=s[e];if(Object.keys(r).length>0&&P(c))return F(c,t);if(a||N(c,{profile:e,logger:t.logger}))return v(e,s,t,n,r,B);if(P(c))return F(c,t);if(ae(c))return oe(c,t,n);if(ee(c))return te(t,e);if(ne(c))return await se(e,c,t,n);if(Z(c))return M(e,t,n);throw new ie.CredentialsProviderError(`Could not resolve credentials using profile: [${e}] in configuration/credentials file(s).`,{logger:t.logger})};var Ne=(e={})=>async({callerClientConfig:s}={})=>{e.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");let t=await g.parseKnownFiles(e);return B(g.getProfileName({profile:e.profile??s?.profile}),t,e,s)};export{Ne as fromIni};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=63D8E3A4E412161E64756E2164756E21
|
|
@@ -15,6 +15,6 @@
|
|
|
15
15
|
"import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isWebIdentityProfile = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.web_identity_token_file === \"string\" &&\n typeof arg.role_arn === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.role_session_name) > -1;\nexport const resolveWebIdentityCredentials = async (profile, options, callerClientConfig) => import(\"@aws-sdk/credential-provider-web-identity\").then(({ fromTokenFile }) => fromTokenFile({\n webIdentityTokenFile: profile.web_identity_token_file,\n roleArn: profile.role_arn,\n roleSessionName: profile.role_session_name,\n roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity,\n logger: options.logger,\n parentClientConfig: options.parentClientConfig,\n})({\n callerClientConfig,\n}).then((creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN\", \"q\")));\n"
|
|
16
16
|
],
|
|
17
17
|
"mappings": ";wQAAA,SCAA,UCAA,S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AqB,MAAO,EAAa,EAAU,EAAS,EAAoB,EAAkB,CAAC,EAAG,EAA4B,KAAU,CACrJ,IAAM,EAAO,EAAS,GACtB,GAAI,OAAO,KAAK,CAAe,EAAE,OAAS,GAAK,EAAqB,CAAI,EACpE,OAAO,EAAyB,EAAM,CAAO,EAEjD,GAAI,GAA6B,EAAoB,EAAM,CAAE,QAAS,EAAa,OAAQ,EAAQ,MAAO,CAAC,EACvG,OAAO,EAA6B,EAAa,EAAU,EAAS,EAAoB,EAAiB,CAAkB,EAE/H,GAAI,EAAqB,CAAI,EACzB,OAAO,EAAyB,EAAM,CAAO,EAEjD,GAAI,GAAqB,CAAI,EACzB,OAAO,GAA8B,EAAM,EAAS,CAAkB,EAE1E,GAAI,GAAiB,CAAI,EACrB,OAAO,GAA0B,EAAS,CAAW,EAEzD,GAAI,GAAa,CAAI,EACjB,OAAO,MAAM,GAAsB,EAAa,EAAM,EAAS,CAAkB,EAErF,GAAI,EAAe,CAAI,EACnB,OAAO,EAAwB,EAAa,EAAS,CAAkB,EAE3E,MAAM,IAAI,4BAAyB,iDAAiD,2CAAsD,CAAE,OAAQ,EAAQ,MAAO,CAAC,GD5BjK,IAAM,GAAU,CAAC,EAAO,CAAC,IAAM,OAAS,sBAAuB,CAAC,IAAM,CACzE,EAAK,QAAQ,MAAM,4CAA4C,EAC/D,IAAM,EAAW,MAAM,kBAAgB,CAAI,EAC3C,OAAO,EAAmB,iBAAe,CACrC,QAAS,EAAK,SAAW,GAAoB,OACjD,CAAC,EAAG,EAAU,EAAM,CAAkB",
|
|
18
|
-
"debugId": "
|
|
18
|
+
"debugId": "63D8E3A4E412161E64756E2164756E21",
|
|
19
19
|
"names": []
|
|
20
20
|
}
|
|
@@ -45,6 +45,6 @@ Say which, and registerModels will leave it alone:
|
|
|
45
45
|
register("${j}", ${z[0]})
|
|
46
46
|
|
|
47
47
|
A class that is only a typed view over the same rows belongs in a module you do not hand to registerModels.`);this.model=j;this.candidates=z;this.name="AmbiguousModelRegistrationError"}}class C extends Error{model;operation;required;limit;dialect;constructor(j,z,B,G,H,I){super(`${j}.${z} would bind ${B} parameters, and the '${H}' driver accepts at most ${G} in one statement. ${I}`+(z==="createMany"?" A createMany over the ceiling is normally split across statements inside one transaction, so reaching this means splitting cannot help: a single row binds more than the driver accepts.":" Splitting is not something this operation can do for you \u2014 one "+"statement has to carry one answer. Narrow the query."));this.model=j;this.operation=z;this.required=B;this.limit=G;this.dialect=H;this.name="ParameterLimitError"}}class D extends Error{model;operation;field;constructor(j,z,B){super(`${j}.${z} is missing a value for '${B}', which is required and has no default.`);this.model=j;this.operation=z;this.field=B;this.name="MissingRequiredValueError"}}class F extends Error{relation;model;constructor(j,z,B){super(`'${j}' is not a relation on model ${z}. `+(B.length>0?`Known relations: ${B.join(", ")}.`:`${z} declares no relations.`));this.relation=j;this.model=z;this.name="UnknownRelationError"}}class b extends Error{model;limit;constructor(j,z){super(`The include tree nests more than ${z} relations deep (at model ${j}). Deeply nested includes are legal, so this is a guard against a generated or malformed argument tree rather than a limit on `+"modelling \u2014 every level costs at least one query.");this.model=j;this.limit=z;this.name="RelationDepthExceededError"}}class P extends Error{model;relation;target;constructor(j,z,B,G){super(`${j}.${z} points at model '${B}', which nothing has registered. The generated artifact and the registry disagree: re-run \`prisma generate\`, and check that app/models/generated/index.ts is imported. `+(G.length>0?`Registered models: ${G.join(", ")}.`:"Nothing is registered at all."));this.model=j;this.relation=z;this.target=B;this.name="UnregisteredRelationTargetError"}}class R extends Error{model;relation;constructor(j,z,B){super(`Cannot resolve how ${j}.${z} joins: ${B} This means `+"app/models/generated is stale or hand-edited \u2014 re-run "+"`prisma generate`.");this.model=j;this.relation=z;this.name="MalformedRelationError"}}class v extends Error{constructor(j,z){super(`No model is registered under the name '${j}'. `+(z.length>0?`Registered models: ${z.join(", ")}.`:"Nothing is registered \u2014 is app/models/generated/index.ts imported?"));this.name="ModelNotRegisteredError"}}class N extends Error{constructor(j){super(`${j} has no $schema. Model subclasses must extend a generated base class from app/models/generated/models.ts.`);this.name="MissingModelSchemaError"}}class Q extends Error{model;operation;constructor(j,z){super(`${j}.${z} was given 'lock' outside a transaction. A row lock lasts until the transaction that took it ends, so outside one it is released as soon as the row is read and protects nothing. Run the read and the writes it guards inside Model.transaction(async () => { ... }).`);this.model=j;this.operation=z;this.name="LockOutsideTransactionError"}}
|
|
48
|
-
export{K as
|
|
48
|
+
export{K as lj,Z as mj,_ as nj,$ as oj,L as pj,M as qj,U as rj,V as sj,y as tj,O as uj,W as vj,E as wj,S as xj,T as yj,x as zj,A as Aj,C as Bj,D as Cj,F as Dj,b as Ej,P as Fj,R as Gj,v as Hj,N as Ij,Q as Jj};
|
|
49
49
|
|
|
50
|
-
//# debugId=
|
|
50
|
+
//# debugId=17ABF8609633A14164756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"/**\n * Thrown when the compiler is handed an argument it does not implement yet.\n *\n * Every public operation accepts the full Prisma argument type from iteration 1\n * — signatures are final, capability grows underneath them. The price of that is\n * that anything unimplemented has to fail loudly: silently dropping a `take: 10`\n * and returning the whole table is the worst failure mode this ORM has.\n */\nexport class UnsupportedQueryError extends Error {\n constructor(\n public readonly argument: string,\n public readonly model: string,\n public readonly operation: string,\n /**\n * What cannot work, and what to do instead.\n *\n * **Required**, which is the second half of #61 — the first being the\n * `UnsupportedByDesignError` split beside this. It was optional, and the\n * refusals that omitted it were the highest-traffic ones: an argument the\n * operation does not accept, on the path a typo takes. Those said only\n * *that* something was refused, to the reader least likely to know why.\n *\n * Required rather than conventionally-supplied for the reason five other\n * parameters here are — `render`'s `origin`, `changedFields`' `schema`,\n * `RelationExecutor.exec`'s `preScoped`, `resolveLink`'s `operation`,\n * `assertPageArgument`'s reported name: where omitting an argument produces\n * a *worse* result rather than an error, `tsc` is the only thing that keeps\n * a convention. Ninety-five of a hundred call sites already passed one; the\n * five that did not are exactly the ones nobody revisited.\n *\n * `UnknownFieldError` and `UnknownRelationError` set the standard this\n * meets: both enumerate the valid names rather than only rejecting the\n * invalid one.\n */\n detail: string,\n ) {\n super(\n `gemi ORM does not support '${argument}' yet (${model}.${operation}). ` +\n detail,\n );\n this.name = \"UnsupportedQueryError\";\n }\n}\n\n/**\n * An argument the ORM has **decided not to implement**, as opposed to one it has\n * not implemented yet.\n *\n * The distinction is the whole point, and it is a distinction a caller can act\n * on: \"yet\" means wait for a release, \"will not\" means change the code. Sharing\n * one error for both meant `docs/orm.md` could list `omit` under *Not in scope*\n * while the runtime said \"yet\" — a contradiction a reader has no way to\n * resolve, and the one #68 exists to end.\n *\n * A subclass rather than a sibling, so `catch (e) { if (e instanceof\n * UnsupportedQueryError) … }` keeps working for callers that do not care which\n * kind it is.\n */\n/**\n * An argument the ORM **does** implement, given a value it cannot mean.\n *\n * The third category, and the one that made \"yet\" wrong four separate times —\n * #82, #88, #100 and #101 each corrected it at their own call site before #61\n * was found to own the problem. The taxonomy the three classes now draw:\n *\n * not implemented yet UnsupportedQueryError wait for a release\n * decided against UnsupportedByDesignError change the call (#78)\n * implemented, bad value InvalidArgumentError fix the value\n *\n * `take: \"-2\"` is the clearest case. `take` is implemented; `\"-2\"` is not a\n * take. Telling that caller the ORM \"does not support 'take' yet\" is wrong on\n * both halves — it does, and there is nothing to wait for — and it sends them\n * to a changelog when the fix is one character in their own code.\n *\n * **Extends `UnsupportedQueryError`**, so every existing `catch` and every test\n * asserting the base class keeps working. That is the same choice\n * `UnsupportedByDesignError` made, and it is what lets a taxonomy be added to a\n * shipped ORM without a breaking change: the specific classes are for the\n * reader, the base class is for the handler.\n *\n * **Where the taxonomy stops, and why it stops there.** An argument that is not\n * in the grammar at all keeps the base class and its \"yet\" — `{ nope: 1 }`\n * reports \"does not support 'nope' yet\". That is right for half of what reaches\n * that path and wrong for the other half: the same check refuses a typo and a\n * real Prisma argument this ORM has genuinely not implemented, and nothing at\n * that point can tell them apart. Splitting it would mean carrying Prisma's\n * full argument grammar per operation, which is a large amount of duplicated\n * schema for a small gain.\n *\n * What makes it tolerable is the sentence after it. Since #61's other half made\n * `detail` mandatory, that refusal always continues *\"findMany takes include,\n * omit, orderBy, select, skip, take, where\"* — so a caller who typed `nope`\n * learns it is not coming from the very next clause, without the class having\n * to know. Recorded here rather than left to be re-derived, because \"the third\n * class did not cover this one\" is the obvious first reading and it is not the\n * interesting part.\n */\nexport class InvalidArgumentError extends UnsupportedQueryError {\n constructor(\n argument: string,\n model: string,\n operation: string,\n /** What is wrong with the value, and what a good one looks like. */\n reason: string,\n ) {\n super(argument, model, operation, reason);\n this.name = \"InvalidArgumentError\";\n this.message = `Invalid '${argument}' (${model}.${operation}). ${reason}`;\n }\n}\n\nexport class UnsupportedByDesignError extends UnsupportedQueryError {\n constructor(\n argument: string,\n model: string,\n operation: string,\n /** What to use instead. Required — see #61: a refusal owes the caller a next step. */\n reason: string,\n ) {\n super(argument, model, operation, reason);\n this.name = \"UnsupportedByDesignError\";\n this.message =\n `gemi ORM does not implement '${argument}' (${model}.${operation}), ` +\n `and this is a decision rather than a gap. ${reason}`;\n }\n}\n\n/**\n * Thrown when an argument names something that is not a field on the model. A\n * `where` key with no matching field is an error, never a passthrough — that is\n * the rule that keeps user input out of the identifier positions in the SQL.\n */\nexport class UnknownFieldError extends Error {\n constructor(\n public readonly field: string,\n public readonly model: string,\n known: string[],\n ) {\n super(\n `'${field}' is not a field on model ${model}. ` +\n `Known fields: ${known.join(\", \")}.`,\n );\n this.name = \"UnknownFieldError\";\n }\n}\n\n/**\n * Thrown when a column holds something the generated schema says it cannot —\n * an unparseable timestamp, a fractional value in a `BigInt` column, malformed\n * JSON. Every dialect needs it, which is why it lives here rather than beside\n * one of them.\n *\n * It exists so those cases fail rather than decode into a plausible wrong\n * value: `new Date(\"nonsense\")` is an `Invalid Date`, not an error, and it\n * would travel a long way before anyone noticed.\n */\nexport class DecodeError extends Error {\n constructor(\n public readonly field: { column: string; type: string },\n public readonly value: unknown,\n ) {\n super(\n `Could not decode the value ${JSON.stringify(String(value))} from column ` +\n `'${field.column}' as ${field.type}. The column's contents do not match ` +\n `the Prisma schema — was it written by something other than Prisma or ` +\n `the gemi ORM?`,\n );\n this.name = \"DecodeError\";\n }\n}\n\n/**\n * Thrown by the `*OrThrow` operations when the query matched nothing. Prisma\n * raises `NotFoundError` / `P2025` for the same case; the differential harness\n * compares the fact of throwing, not the error type.\n */\nexport class RecordNotFoundError extends Error {\n constructor(\n public readonly model: string,\n public readonly operation: string,\n ) {\n super(`No ${model} found (${model}.${operation}).`);\n this.name = \"RecordNotFoundError\";\n }\n}\n\n/**\n * The dispatchers' test for a lookup that matched nothing and should be\n * answered with a 404.\n *\n * Matches the name as well as the class for the reason `isPolicyDeniedError`\n * and `isUniqueConstraintError` do: `instanceof` compares against *this*\n * module instance's class object, so a second copy of `gemi/orm` — two\n * versions in one dependency tree, a linked package beside a bundled one —\n * throws an error this would not recognise, and the request would go back to\n * being a 500 carrying the model's name in its body.\n *\n * The name is the identity here, so an application error that calls itself\n * `RecordNotFoundError` is deliberately matched too. That is the same bargain\n * the other two predicates make, and the failure it trades against — a 500\n * where a 404 was meant — is the worse one.\n */\nexport function isRecordNotFoundError(error: unknown): error is RecordNotFoundError {\n if (error instanceof RecordNotFoundError) return true;\n\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as { name?: unknown }).name === \"RecordNotFoundError\"\n );\n}\n\n/**\n * Thrown when a write violates a unique constraint.\n *\n * DECISION — gemi defines its own error rather than mirroring Prisma's codes.\n *\n * Prisma raises `PrismaClientKnownRequestError` with code `P2002` and\n * `meta.target` holding the field names. Mirroring that would ease a migration\n * for code already branching on `P2002`.\n *\n * **The premise this note used to rest on was wrong, and the conclusion is\n * unchanged.** It said \"nothing in this repository does (checked)\", which was\n * true of *this* repository and was never the question — the code that branches\n * on `P2002` lives in the applications the ORM is for. The first real port\n * measured four such guards, every one of them in concurrency-recovery code\n * (catch the collision, re-read, retry), and every one of them silently dead the\n * moment the write moved onto gemi: the `catch` still ran, the condition was\n * false, the recovery did not happen. Nor was the repository itself clean —\n * `templates/saas-starter/app/models/differential.ts:621` branches on `P2002`\n * today, and did when this was written.\n *\n * What the premise was doing was answering \"would anyone notice?\", and the\n * answer is that four people noticed at once. The decision never depended on it.\n * Carrying a `P` code implies the rest of the taxonomy is implemented too:\n * `P2003`, `P2025`, and the fifty others an application might reasonably then\n * expect to catch. Claiming a compatibility surface we have not built is worse\n * than asking the call sites that need it to catch a gemi error instead —\n * *especially* when the code in question is a retry loop, because a\n * compatibility surface that covers `P2002` and not `P2034` fails in exactly\n * the same silent way, one layer further in.\n *\n * A porter reaches for `isUniqueConstraintError` below. `UPGRADE.md` carries\n * the temporary `|| error.code === \"P2002\"` bridge, for a codebase halfway\n * through the move, with the marker that says when to delete it; it is\n * deliberately not exported, because a Prisma code in gemi's permanent surface\n * is the thing this note declined.\n *\n * What the contract does promise is the part that matters: the error is typed,\n * catchable, and names the fields — as *field* names, the way Prisma's\n * `meta.target` does, not as the database columns the driver reported.\n */\nexport class UniqueConstraintError extends Error {\n constructor(\n public readonly model: string,\n public readonly operation: string,\n /** Field names, mapped back through the schema from the driver's columns. */\n public readonly fields: string[],\n /** The constraint's own name, when the dialect reports one. */\n public readonly constraint?: string,\n options?: { cause?: unknown },\n ) {\n super(\n `Unique constraint violated on ${model}.${operation}` +\n (fields.length > 0 ? ` for ${fields.join(\", \")}` : \"\") +\n (constraint ? ` (constraint '${constraint}')` : \"\") +\n `. A ${model} with those values already exists.`,\n options,\n );\n this.name = \"UniqueConstraintError\";\n }\n}\n\n/**\n * The guard to write in a retry-on-collision `catch`, which is where a\n * `code === \"P2002\"` test almost always was:\n *\n * try {\n * return await Invite.create({ data: { token } })\n * } catch (error) {\n * if (!isUniqueConstraintError(error)) throw error\n * return await Invite.findUniqueOrThrow({ where: { token } })\n * }\n *\n * **Why this is worth shipping rather than telling people to write\n * `instanceof`**, which is the obvious objection and the reason it nearly was\n * not shipped. The second half of the test is the whole of it:\n *\n * error instanceof UniqueConstraintError || error.name === \"UniqueConstraintError\"\n *\n * `instanceof` compares against *this module instance's* class object, so it is\n * false across a duplicate copy of `gemi/orm` — two versions in one dependency\n * tree, a bundled build alongside a linked one, a monorepo package resolving\n * its own. The error is the right error, thrown by the right code, and the\n * guard silently does not fire. That is not a hypothetical: duck-typing rather\n * than importing the class is precisely what the ported application had already\n * done for Prisma's error, for precisely this reason, and shipping a predicate\n * that only does `instanceof` would hand it back the same trap under a new\n * name.\n *\n * So the name is load-bearing rather than a convenience: it is the identity\n * that survives module duplication, which is why every error in this file sets\n * `this.name` explicitly instead of relying on the class name surviving\n * minification.\n *\n * **The narrowing is a claim, and this is what it rests on.** The name branch\n * asserts `UniqueConstraintError` on the strength of a string — a second copy\n * of this module really does carry `model`, `operation` and `fields`, so the\n * claim holds for the case it exists for. An unrelated object named\n * `\"UniqueConstraintError\"` would defeat it, and that is not something that\n * happens by accident.\n *\n * **It deliberately does not match `code === \"P2002\"`.** See the DECISION\n * above: the temporary bridge for a half-ported codebase is in `UPGRADE.md`,\n * where it can carry a delete-me marker, rather than in gemi's permanent\n * surface, where it would have neither.\n */\nexport function isUniqueConstraintError(\n error: unknown,\n): error is UniqueConstraintError {\n if (error instanceof UniqueConstraintError) return true;\n\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as { name?: unknown }).name === \"UniqueConstraintError\"\n );\n}\n\n/**\n * Thrown when a write needs `RETURNING` and the dialect has none.\n *\n * Unreachable on SQLite and Postgres, which both support it. It exists so that\n * the MySQL / MariaDB path is a named gap rather than a wrong answer: the\n * fallback there is `lastInsertRowid` plus a re-select, which is a different\n * statement shape and is not implemented.\n */\nexport class ReturningUnsupportedError extends Error {\n constructor(\n public readonly model: string,\n public readonly operation: string,\n public readonly dialect: string,\n ) {\n super(\n `${model}.${operation} needs RETURNING to report its result, and the ` +\n `'${dialect}' dialect does not support it. The fallback — ` +\n `lastInsertRowid plus a re-select — is not implemented.`,\n );\n this.name = \"ReturningUnsupportedError\";\n }\n}\n\n/**\n * Thrown when a policy denies an operation.\n *\n * Two ways to get here, and the message distinguishes them because the fixes\n * are different: a policy's `before` returned false, or the model is policied\n * and there is no user in scope at all.\n *\n * The second is the deny-by-default rule, and it is the reason this error is\n * loud. A cron tick or a queue worker reading a policied model has no user, and\n * the alternative — treating \"no user\" as \"no policy\" — means the dangerous\n * case is the silent one: a request whose auth middleware was misconfigured\n * would read every tenant's rows rather than failing. So unscoped access is\n * always a decision written at the call site, through `Model.asSystem`.\n */\nexport class PolicyDeniedError extends Error {\n constructor(\n public readonly model: string,\n public readonly operation: string,\n public readonly reason: \"denied\" | \"no-user\" = \"denied\",\n ) {\n super(\n reason === \"no-user\"\n ? `${model}.${operation} is governed by a policy and there is no user ` +\n `in scope. If this is a cron tick, a queue worker or a script, say ` +\n `so at the call site: Model.asSystem(() => ...). Policies are ` +\n `never skipped just because a user failed to turn up.`\n : `${model}.${operation} was denied by ${model}'s policy.`,\n );\n this.name = \"PolicyDeniedError\";\n }\n}\n\n/**\n * The api dispatcher's test for a denial it should answer with a 403. It\n * matches the name as well as the class for the reason\n * `isUniqueConstraintError` does: a second copy of `gemi/orm` throws an error\n * that is not `instanceof` this class, and a denial that failed the test would\n * go back to being a 500 that carries the policy's message.\n */\nexport function isPolicyDeniedError(error: unknown): error is PolicyDeniedError {\n if (error instanceof PolicyDeniedError) return true;\n\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as { name?: unknown }).name === \"PolicyDeniedError\"\n );\n}\n\n/**\n * Thrown when an `update` writes to a column its own policy's `scope` selects on,\n * and the policy has no `onUpdate` saying what that should mean.\n *\n * The shape it catches:\n *\n * scope: (ctx) => ({ organizationId: ctx.user.organizationId })\n * // ...and then\n * User.update({ where: { id }, data: { organizationId: 999 } })\n *\n * The scope did its job — only rows in the caller's own tenant could be selected\n * — and the statement still hands one of them to another tenant. Afterwards the\n * row is outside the scope, so it cannot be read back and cannot be put right by\n * the same caller: a one-way door rather than a visible failure. The usual way in\n * is not malice but mass assignment, a handler forwarding request fields into\n * `data`.\n *\n * This is `assertCreateCovered`'s question asked of the other write. There it is\n * \"you scoped reads but never said what an insert means\"; here it is \"you scoped\n * reads but never said whether an update may move a row out\". Both are answered\n * by writing the hook, including when the answer is \"allow it\" —\n * `onUpdate: (_ctx, data) => data` is a complete and legitimate answer, and\n * saying it out loud is the point.\n *\n * **What it cannot see.** The scope-owned columns are read off the top level of\n * the fragment the policy returned, so `{ organizationId: 7 }` is understood and\n * `{ OR: [...] }` is not — a scope built from combinators is not attributed to\n * any column and an update through it is not checked. Narrowing that would mean\n * either interpreting arbitrary `where` grammar or refusing every update on such\n * a model, and neither is worth it: the guard is a rail on the common shape, not\n * a proof.\n */\nexport class ScopeEscapeError extends Error {\n constructor(\n public readonly model: string,\n public readonly operation: string,\n public readonly fields: readonly string[],\n ) {\n const named = fields.map((field) => `'${field}'`).join(\", \");\n super(\n `${model}.${operation} writes ${named}, which ${model}'s policy also ` +\n `scopes on — so this update can move a row outside the scope that ` +\n `selected it, where the caller can no longer read or repair it.\\n\\n` +\n `Add an onUpdate to that policy. It may reassert the column ` +\n `(data => ({ ...data, ${fields[0]}: ctx.user.${fields[0]} })), reject ` +\n `the write, or allow it explicitly with (_ctx, data) => data — all ` +\n `three are fine, and the point is that the policy says which.`,\n );\n this.name = \"ScopeEscapeError\";\n }\n}\n\n/**\n * Thrown when a model class carries policies but is not the class the registry\n * resolves its name to.\n *\n * This exists because of a cross-tenant leak that shipped past review. The\n * generated `index.ts` registers the *generated* base — `register(\"Account\",\n * AccountModel)` — while an application authors its policy on a subclass:\n *\n * export class Account extends AccountModel {\n * static $policies = [{ scope: (ctx) => ({ organizationId: … }) }]\n * }\n *\n * A root query goes through `Account`, so `policiesFor(this)` finds the policy\n * and the scope applies. A **nested** relation read resolves through the\n * registry, gets `AccountModel`, and walks a prototype chain the policy is not\n * on — so `User.findMany({ include: { accounts: true } })` returned every\n * tenant's accounts. Root queries scoped, nested reads unscoped: exactly the\n * Prisma behaviour policies exist to fix, and silent.\n *\n * Raised at the first query through the unregistered class, naming the one-line\n * fix, because the alternative is data crossing a tenant boundary with nothing\n * to notice it.\n *\n * It fires on a divergence in the resolved policy *chain*, not merely on the two\n * classes differing. A plain subclass that adds no policy of its own inherits\n * the same policy objects in the same order, so a nested read resolving to its\n * parent applies exactly what the root query applied — no divergence, nothing\n * to refuse. An earlier version compared class identity and rejected\n * `class AdminUser extends User {}` for policies it had not written.\n */\nexport class UnregisteredPolicyClassError extends Error {\n constructor(\n public readonly model: string,\n /**\n * Under `carries: \"narrowing\"` this is the *ancestor* — the class the model\n * belongs to — rather than whatever the registry currently holds. The two\n * classes are on one prototype chain there, and which of them is registered\n * is the thing in question, so naming them by their relationship is what\n * makes the message readable.\n */\n public readonly registered: string,\n /** Under `carries: \"narrowing\"`, the descendant: the view that narrows. */\n public readonly queried: string,\n /**\n * Which side carries the policies that would be skipped, and therefore what\n * the author should do about it. Three, because they need three different\n * answers: a missing registration, a query through the wrong class, and a\n * view that should not be competing for the name at all.\n */\n public readonly carries: \"queried\" | \"registered\" | \"narrowing\" = \"queried\",\n ) {\n super(\n carries === \"narrowing\"\n ? `${queried} extends ${registered}, which owns the model '${model}', ` +\n `and carries policies of its own on top of it. A class that ` +\n `narrows an existing model is a view, and the registry holds one ` +\n `class per name — so registering ${queried} would apply its ` +\n `narrowing to every nested read of ${model}, and leaving ` +\n `${registered} registered would skip ${queried}'s policies ` +\n `entirely. Neither is a thing to choose for you.\\n\\n` +\n `Keep the view out of the modules you hand to Kernel.models, and ` +\n `query it directly where you want it:\\n\\n` +\n ` ${queried}.findMany(…) // narrowed, at the call site\\n\\n` +\n `If it is not a view but the model itself, move the policies onto ` +\n `${registered} — the class the model's name resolves to — and ` +\n `${queried} inherits them everywhere.\\n`\n : carries === \"queried\"\n ? `${queried} carries policies but the registry resolves '${model}' to ` +\n `${registered}. Nested relation reads go through the registry, so ` +\n `they would run on ${registered} and skip every policy on ` +\n `${queried} — scoped at the root, unscoped inside an include. ` +\n `Register the class that carries the policy:\\n\\n` +\n ` import { register } from \"gemi/orm\"\\n` +\n ` export class ${queried} extends ${registered} { … }\\n` +\n ` register(\"${model}\", ${queried})\\n`\n : `This query goes through ${queried}, but the registry resolves ` +\n `'${model}' to ${registered}, which carries policies ${queried} ` +\n `does not. Nested relation reads would be scoped and this query is ` +\n `not — the same policy applying to some queries and not others. ` +\n `Query ${registered} instead:\\n\\n` +\n ` ${registered}.findMany(…)\\n\\n` +\n `If skipping policies is intended, say so at the call site — that ` +\n `is what Model.asSystem() is for, and it is the only way to do it ` +\n `that a reader can see.\\n`,\n );\n this.name = \"UnregisteredPolicyClassError\";\n }\n}\n\n/**\n * Thrown when a `$policies` array holds something that is not a usable policy.\n *\n * Every case it covers is refused today — by `tsc`, at the class declaration,\n * with `TS2417`, because `Model` declares `static $policies?: readonly\n * PolicyEntry[]` and `ModelPolicy`'s members are all optional, so a typo'd key\n * trips weak-type detection. This is therefore a guard on the paths that import\n * user code *without* having type-checked it: `registerModels` at boot, and\n * `gemi check models`, whose whole job is to find mistakes in a file somebody is\n * still writing.\n *\n * Two failures, and the second is the one that matters.\n *\n * **A function the ORM cannot get a policy out of.** `resolveEntry` instantiates\n * every function entry with no arguments, and there are two ways that goes\n * wrong. A factory nobody called — `softDeletes` rather than\n * `softDeletes({ field })` — is not constructable at all and reached `new entry`\n * to produce `TypeError: function is not a constructor`. A class that *is*\n * constructable and whose constructor wants an argument gets through that check\n * and dies inside its own body instead, with\n * `TypeError: undefined is not an object (evaluating 'opts.field')`. Both are\n * loud and neither named the model, the index or the file, which on a 79-model\n * app leaves the first question unanswered; the second is the case that survived\n * a first pass at this error, because \"constructable\" is a fact about\n * `[[Construct]]` and says nothing about what the constructor then does.\n *\n * **An entry with no recognised hook.** `{ scopes: … }` and\n * `{ default: { scope: … } }` were accepted in silence: `applyPolicies`\n * dispatches on `before` / `scope` / `onCreate` / `onUpdate` and\n * `applyRedaction` on `redact`, so an entry spelling none of them contributes\n * nothing. The model then carries a visible `$policies` array, passes\n * `gemi check models` as correctly registered, and **reads unscoped** — the same\n * written-believed-not-in-effect shape `UnregisteredPolicyClassError` exists\n * for, arriving through a typo instead of through the registry.\n *\n * The line between *empty but valid* and *malformed* is drawn at \"would this\n * ever run\": an entry with at least one recognised hook that is callable is\n * accepted whatever else it carries, because a factory's return value and a\n * policy class routinely hold configuration and helpers beside the hooks, and\n * refusing unknown *extra* keys would reject code that works. An entry with no\n * callable hook at all is refused, `{}` included — it is indistinguishable from\n * a policy that was meant to do something, and a conditional policy belongs in\n * the array rather than in the entry.\n */\nexport class InvalidPolicyEntryError extends Error {\n constructor(\n /**\n * The class whose **own** `$policies` array holds the entry — the class the\n * author wrote the array on, which is not necessarily the model being\n * queried when the array is on a base.\n */\n public readonly model: string,\n /** The entry's index in that array. */\n public readonly index: number,\n public readonly reason:\n | \"not-a-policy\"\n | \"not-constructable\"\n | \"constructor-threw\"\n | \"no-hooks\"\n | \"hook-not-callable\",\n /** What was found in the entry's place, rendered for a human. */\n public readonly found: string,\n /**\n * The hook names the runtime dispatches on, supplied by `policy.ts` so the\n * list lives beside the code that reads it rather than being restated here.\n */\n hooks: readonly string[],\n /**\n * A key the entry actually spells and the hook it is within one edit of.\n *\n * **The pair, not the hook alone.** An unattributed \"Did you mean `scope`?\"\n * after a list of five keys does not say which of them was read as a\n * misspelling, so a reader who can see that none of them are has no way to\n * dismiss it — and this error is about an authorization rule that is not in\n * effect, where a suggestion followed wrongly costs a rename of something\n * that was never the problem.\n */\n public readonly suggestion?: { key: string; hook: string },\n options?: { cause?: unknown },\n ) {\n const where = `${model}.$policies[${index}]`;\n const named =\n hooks.length > 1\n ? `${hooks.slice(0, -1).join(\", \")} or ${hooks[hooks.length - 1]}`\n : (hooks[0] ?? \"\");\n\n super(\n reason === \"not-a-policy\"\n ? `${where} is ${found}, which is not a policy. An entry is either a ` +\n `policy object — { scope, onCreate, … } — or a class the ORM ` +\n `constructs with no arguments.\\n\\n` +\n `A policy that only sometimes applies belongs in the array rather ` +\n `than in the entry:\\n\\n` +\n ` static $policies = [...(multiTenant ? [tenantScope] : [])]\\n`\n : reason === \"not-constructable\"\n ? `${where} is ${found}, and a function entry is instantiated with ` +\n `no arguments — so an arrow function, a plain function, or a ` +\n `factory that was never called cannot be one.\\n\\n` +\n `If it is a factory, call it:\\n\\n` +\n ` static $policies = [softDeletes({ field: \"deletedAt\" })]\\n`\n : reason === \"constructor-threw\"\n ? `${where} is ${found}\\n\\n` +\n `A class entry is constructed with no arguments. If this one ` +\n `needs some, construct it yourself and put the instance in the ` +\n `array:\\n\\n` +\n ` static $policies = [new TenantPolicy({ field: \"orgId\" })]\\n\\n` +\n `If the constructor reaches for something that is not ready yet, ` +\n `note that it runs on the first query through this model, not at ` +\n `boot.\\n`\n : reason === \"hook-not-callable\"\n ? `${where} has a ${found}, and every hook is called — so this ` +\n `would throw on the first query that reached it rather than ` +\n `doing whatever it was meant to do. Give it a function, or ` +\n `leave the key out.\\n`\n : `${where} has none of ${named}, so it would never run. The ` +\n `model carries a visible $policies array and nothing in it ` +\n `applies to any query — which for a scope means the model ` +\n `reads unscoped. ${found}` +\n (suggestion\n ? ` Is '${suggestion.key}' meant to be \\`${suggestion.hook}\\`?`\n : \"\") +\n `\\n`,\n options,\n );\n this.name = \"InvalidPolicyEntryError\";\n }\n}\n\n/**\n * Thrown when `registerModels` finds two unrelated classes in one module both\n * claiming the same model name.\n *\n * Deriving registration from a module namespace works because the candidates\n * are normally a chain — a generated base, the application's subclass, perhaps\n * a typed view over it — and a chain has a least element to elect. Two classes\n * that extend the same base without extending each other do not: both were\n * written for this model, and only the author knows which one nested reads\n * should run.\n *\n * Refused rather than guessed at, because both guesses are silent. Picking\n * either would scope every `include` of the model by one class's policies while\n * the other's code keeps reading as though its own applied.\n *\n * **\"In one module\" is the exact scope, and the asymmetry is deliberate.**\n * Election happens per module, so two unrelated claims split across *different*\n * modules never meet inside one — the later import simply wins. What catches\n * that is the audit at the end of `registerModels` rather than this error, and\n * only when the two diverge in policies. Two unrelated *unpolicied* claims on\n * one name resolve by import order and nothing reports it, which is tolerable\n * for the same reason it is invisible: with no policies on either, the choice\n * changes no query's scope.\n */\nexport class AmbiguousModelRegistrationError extends Error {\n constructor(\n public readonly model: string,\n public readonly candidates: readonly string[],\n ) {\n const named = candidates.map((candidate) => `'${candidate}'`).join(\", \");\n super(\n `Two classes in one module claim the model '${model}' — ${named} — and ` +\n `neither extends the other, so there is no way to tell which one ` +\n `nested relation reads should run.\\n\\n` +\n `Say which, and registerModels will leave it alone:\\n\\n` +\n ` import { register } from \"gemi/orm\"\\n` +\n ` register(\"${model}\", ${candidates[0]})\\n\\n` +\n `A class that is only a typed view over the same rows belongs in a ` +\n `module you do not hand to registerModels.`,\n );\n this.name = \"AmbiguousModelRegistrationError\";\n }\n}\n\n/**\n * Thrown when a statement would bind more parameters than the driver's wire\n * protocol can carry.\n *\n * Three shapes reach it, all of them scaling with the caller's *data* rather\n * than with the query's shape: `createMany` at `rows × columns`, an `in` list on\n * SQLite (one placeholder per element, and such a list is routinely\n * request-derived), and a to-many `include` on SQLite, which batches an `in`\n * over the parent keys. Both limits are hard and low enough to hit with an\n * ordinary import — Postgres counts parameters in an int16 (65535), SQLite\n * defaults `SQLITE_MAX_VARIABLE_NUMBER` to 32766. Postgres escapes the last two\n * either way: `= any($1)` is one parameter however long the array.\n *\n * Prisma chunks the insert automatically. Doing that here means several\n * statements, which without a transaction is a partially-applied `createMany`\n * on failure — so it waits for iteration 5, and until then this is a named gap\n * rather than a driver error naming neither the model nor the cause. Same\n * treatment as `ReturningUnsupportedError`, for the same reason.\n */\nexport class ParameterLimitError extends Error {\n constructor(\n public readonly model: string,\n public readonly operation: string,\n public readonly required: number,\n public readonly limit: number,\n public readonly dialect: string,\n detail: string,\n ) {\n super(\n `${model}.${operation} would bind ${required} parameters, and the ` +\n `'${dialect}' driver accepts at most ${limit} in one statement. ` +\n `${detail}` +\n (operation === \"createMany\"\n ? ` A createMany over the ceiling is normally split across statements ` +\n `inside one transaction, so reaching this means splitting cannot ` +\n `help: a single row binds more than the driver accepts.`\n : ` Splitting is not something this operation can do for you — one ` +\n `statement has to carry one answer. Narrow the query.`),\n );\n this.name = \"ParameterLimitError\";\n }\n}\n\n/**\n * Thrown when a write omits a column that has no value to fall back on: not\n * supplied, no client-side default, no database default, and not nullable.\n *\n * Raised in the compiler rather than left to the database so the message names\n * the field and the model, instead of surfacing as `NOT NULL constraint failed`\n * with a column name and no context.\n */\nexport class MissingRequiredValueError extends Error {\n constructor(\n public readonly model: string,\n public readonly operation: string,\n public readonly field: string,\n ) {\n super(\n `${model}.${operation} is missing a value for '${field}', which is ` +\n `required and has no default.`,\n );\n this.name = \"MissingRequiredValueError\";\n }\n}\n\n/**\n * Thrown when an `include` — or a relation-shaped key inside a `select` — names\n * something the model does not declare as a relation.\n */\nexport class UnknownRelationError extends Error {\n constructor(\n public readonly relation: string,\n public readonly model: string,\n known: string[],\n ) {\n super(\n `'${relation}' is not a relation on model ${model}. ` +\n (known.length > 0\n ? `Known relations: ${known.join(\", \")}.`\n : `${model} declares no relations.`),\n );\n this.name = \"UnknownRelationError\";\n }\n}\n\n/**\n * Thrown when an include tree nests deeper than the guard allows.\n *\n * A cyclic include is legal and finite — `user -> accounts -> user` terminates\n * because the caller wrote a finite tree. What this catches is an *unbounded*\n * one: an argument tree built by a loop, or forwarded from a request body, that\n * describes a thousand levels. Under the batched planner every level is at least\n * one query, so the guard is what stops a malformed argument from becoming a\n * self-inflicted denial of service.\n */\nexport class RelationDepthExceededError extends Error {\n constructor(\n public readonly model: string,\n public readonly limit: number,\n ) {\n super(\n `The include tree nests more than ${limit} relations deep (at model ` +\n `${model}). Deeply nested includes are legal, so this is a guard ` +\n `against a generated or malformed argument tree rather than a limit on ` +\n `modelling — every level costs at least one query.`,\n );\n this.name = \"RelationDepthExceededError\";\n }\n}\n\n/**\n * Thrown when a relation names a model the registry does not hold. Every\n * relation in a generated artifact was emitted from a model in the same\n * `schema.prisma`, so this can only mean the artifact and the registry disagree.\n */\nexport class UnregisteredRelationTargetError extends Error {\n constructor(\n public readonly model: string,\n public readonly relation: string,\n public readonly target: string,\n known: string[],\n ) {\n super(\n `${model}.${relation} points at model '${target}', which nothing has ` +\n `registered. The generated artifact and the registry disagree: re-run ` +\n `\\`prisma generate\\`, and check that app/models/generated/index.ts is ` +\n `imported. ` +\n (known.length > 0\n ? `Registered models: ${known.join(\", \")}.`\n : `Nothing is registered at all.`),\n );\n this.name = \"UnregisteredRelationTargetError\";\n }\n}\n\n/**\n * Thrown when a relation is registered on both sides but the two sides do not\n * describe a link the planner can follow: no matching `relationName` on the\n * other model, or a `from` / `to` naming a field that is not there. Like\n * `UnregisteredRelationTargetError`, it means a stale generated artifact — a\n * consistent one cannot produce it.\n */\nexport class MalformedRelationError extends Error {\n constructor(\n public readonly model: string,\n public readonly relation: string,\n detail: string,\n ) {\n super(\n `Cannot resolve how ${model}.${relation} joins: ${detail} This means ` +\n `app/models/generated is stale or hand-edited — re-run ` +\n `\\`prisma generate\\`.`,\n );\n this.name = \"MalformedRelationError\";\n }\n}\n\n/** Thrown when a relation resolves to a model name nothing registered. */\nexport class ModelNotRegisteredError extends Error {\n constructor(name: string, known: string[]) {\n super(\n `No model is registered under the name '${name}'. ` +\n (known.length > 0\n ? `Registered models: ${known.join(\", \")}.`\n : `Nothing is registered — is app/models/generated/index.ts imported?`),\n );\n this.name = \"ModelNotRegisteredError\";\n }\n}\n\n/** Thrown when a model class is used before the generator has given it a schema. */\nexport class MissingModelSchemaError extends Error {\n constructor(className: string) {\n super(\n `${className} has no $schema. Model subclasses must extend a generated ` +\n `base class from app/models/generated/models.ts.`,\n );\n this.name = \"MissingModelSchemaError\";\n }\n}\n\n/**\n * A `lock` asked for outside a transaction.\n *\n * A row lock is held until the transaction that took it ends. Outside one, the\n * statement is its own transaction, so the lock is released the moment the row\n * comes back — before the write it was meant to guard has even been issued. The\n * read would succeed and protect nothing, which is the failure this refuses: the\n * race the lock was written to close stays open, silently.\n *\n * Raised on SQLite too, where the lock itself compiles to nothing, so code that\n * forgot its transaction fails in development rather than first on Postgres.\n */\nexport class LockOutsideTransactionError extends Error {\n constructor(\n public readonly model: string,\n public readonly operation: string,\n ) {\n super(\n `${model}.${operation} was given 'lock' outside a transaction. A row ` +\n `lock lasts until the transaction that took it ends, so outside one it ` +\n `is released as soon as the row is read and protects nothing. Run the ` +\n `read and the writes it guards inside Model.transaction(async () => { ` +\n `... }).`,\n );\n this.name = \"LockOutsideTransactionError\";\n }\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";AAQO,MAAM,UAA8B,KAAM,CAE7B,SACA,MACA,UAHlB,WAAW,CACO,EACA,EACA,EAsBhB,EACA,CACA,MACE,8BAA8B,WAAkB,KAAS,OACvD,CACJ,EA7BgB,gBACA,aACA,iBA4BhB,KAAK,KAAO,wBAEhB,CAuDO,MAAM,UAA6B,CAAsB,CAC9D,WAAW,CACT,EACA,EACA,EAEA,EACA,CACA,MAAM,EAAU,EAAO,EAAW,CAAM,EACxC,KAAK,KAAO,uBACZ,KAAK,QAAU,YAAY,OAAc,KAAS,OAAe,IAErE,CAEO,MAAM,UAAiC,CAAsB,CAClE,WAAW,CACT,EACA,EACA,EAEA,EACA,CACA,MAAM,EAAU,EAAO,EAAW,CAAM,EACxC,KAAK,KAAO,2BACZ,KAAK,QACH,gCAAgC,OAAc,KAAS,iDACV,IAEnD,CAOO,MAAM,UAA0B,KAAM,CAEzB,MACA,MAFlB,WAAW,CACO,EACA,EAChB,EACA,CACA,MACE,IAAI,8BAAkC,oBACnB,EAAM,KAAK,IAAI,IACpC,EAPgB,aACA,aAOhB,KAAK,KAAO,oBAEhB,CAYO,MAAM,UAAoB,KAAM,CAEnB,MACA,MAFlB,WAAW,CACO,EACA,EAChB,CACA,MACE,8BAA8B,KAAK,UAAU,OAAO,CAAK,CAAC,kBACpD,EAAM,cAAc,EAAM,4CAC9B,6EACA,eACJ,EARgB,aACA,aAQhB,KAAK,KAAO,cAEhB,CAOO,MAAM,UAA4B,KAAM,CAE3B,MACA,UAFlB,WAAW,CACO,EAC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,UAAwC,KAAM,CAEvC,MACA,SACA,OAHlB,WAAW,CACO,EACA,EACA,EAChB,EACA,CACA,MACE,GAAG,KAAS,sBAA6B,8KAItC,EAAM,OAAS,EACZ,sBAAsB,EAAM,KAAK,IAAI,KACrC,gCACR,EAbgB,aACA,gBACA,cAYhB,KAAK,KAAO,kCAEhB,CASO,MAAM,UAA+B,KAAM,CAE9B,MACA,SAFlB,WAAW,CACO,EACA,EAChB,EACA,CACA,MACE,sBAAsB,KAAS,YAAmB,gBAChD,8DACA,oBACJ,EARgB,aACA,gBAQhB,KAAK,KAAO,yBAEhB,CAGO,MAAM,UAAgC,KAAM,CACjD,WAAW,CAAC,EAAc,EAAiB,CACzC,MACE,0CAA0C,QACvC,EAAM,OAAS,EACZ,sBAAsB,EAAM,KAAK,IAAI,KACrC,0EACR,EACA,KAAK,KAAO,0BAEhB,CAGO,MAAM,UAAgC,KAAM,CACjD,WAAW,CAAC,EAAmB,CAC7B,MACE,GAAG,4GAEL,EACA,KAAK,KAAO,0BAEhB,CAcO,MAAM,UAAoC,KAAM,CAEnC,MACA,UAFlB,WAAW,CACO,EACA,EAChB,CACA,MACE,GAAG,KAAS,yQAKd,EATgB,aACA,iBAShB,KAAK,KAAO,8BAEhB",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "17ABF8609633A14164756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Di as N,Ei as _0,Fi as L0}from"./chunk-p2c7z2nr.js";import{Ki as x0,Ni as b}from"./chunk-yhp70t40.js";import{Sk as BQ}from"./chunk-xwmy6fby.js";import{jl as Y0}from"./chunk-aj2sr77y.js";import{ql as iZ}from"./chunk-038xtqpm.js";class o0{static kind="controller";constructor(){}}class bQ extends o0{}function N0(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 W1(Q){return N0(Q.headers.get("cookie"))}function p(Q){if(!/^\d+$/.test(Q))return null;let Z=Number(Q);return Number.isSafeInteger(Z)?Z:null}function t0(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 s0(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 z1(Q){if(Q.kind==="suffix")return`bytes=-${Q.suffixLength}`;return Q.end===null?`bytes=${Q.start}-`:`bytes=${Q.start}-${Q.end}`}function U1(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 V1(Q,Z,$){return`bytes ${Q}-${Z}/${$}`}function r0(Q){return`bytes */${Q}`}class s extends N{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 fQ(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 vQ(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 a0(Q){if(typeof Q==="string"||Array.isArray(Q))return Q.length;return}function q0(Q){return typeof Q==="number"&&!Number.isNaN(Q)}var hQ=["required","string","boolean","number","email","password","min","max","gte","lte","file","fileType","fileSize","array","object","in"];class k extends Error{name="InvalidValidationRuleError"}function z0(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 e0(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)=>q0(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=z0($,X);return(H)=>{let Y=a0(H);return Y!==void 0&&Y>=G}}case"max":{let G=z0($,X);return(H)=>{let Y=a0(H);return Y!==void 0&&Y<=G}}case"gte":{let G=z0($,X);return(H)=>q0(H)&&H>=G}case"lte":{let G=z0($,X);return(H)=>q0(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=vQ(X);return(H)=>H instanceof Blob&&H.type.startsWith(G)}case"fileSize":{let G=fQ(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: ${hQ.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 R0=new WeakMap;function $Q(Q){return typeof Q==="object"&&Q!==null&&R0.has(Q)}function V0(Q){let Z=R0.get(Q);if(!Z)throw Error("gemi/ai: expected a schema built with `s`, got a foreign object");return Z}function mQ(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=a($,Z);return Object.keys(Z.defs).length>0?{...X,$defs:Z.defs}:X}function a(Q,Z){let $=(Q.optional||Q.nullable)&&Q.node.kind!=="json",X=uQ(pQ(Q.node,Z),$),G=[Q.description,cQ(Q.node)].filter(Boolean).join(" ");if(G&&X.$ref!==void 0)X={anyOf:[X]};return G?{description:G,...X}:X}function cQ(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 pQ(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:a(Q.item,Z)};case"object":return{type:"object",properties:Object.fromEntries(Object.entries(Q.shape).map(([$,X])=>[$,a(X,Z)])),required:Object.keys(Q.shape),additionalProperties:!1};case"union":return{anyOf:Q.members.map(($)=>a($,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]=a(u($),Z);return{$ref:`#/$defs/${$.name}`}}}}function uQ(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 dQ(Q){if(Q===null)return"null";if(Array.isArray(Q))return"array";return typeof Q}function iQ(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 dQ(Z)}function XQ(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 XQ({...u(Z.cell),optional:!1,nullable:!1})}})();return Q.optional||Q.nullable?`${$} or null`:$}function lQ(Q){let Z="";for(let $ of Q)Z+=typeof $==="number"?`[${$}]`:Z?`.${$}`:$;return Z}function nQ(Q){let Z=lQ(Q);return Z?`${Z}: `:""}function w0(Q){return`${nQ(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 GQ($.cell,Z,()=>1,()=>B0(u($.cell),Z))}}function GQ(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:oQ(Q,Z,$,X)}}function oQ(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 ${XQ(Q)}, got ${iQ(G,Z)}`,params:M});return};switch(G.kind){case"string":if(typeof Z!=="string")return H();return QQ(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 sQ(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 QQ(G.checks,Z,$,X),Z;case"array":{if(!Array.isArray(Z))return H();let Y=Z.map((J,D)=>{let z=v(G.item,J,[...$,D],X);return z.drop?void 0:z.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 GQ(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 tQ(Q){let Z=0;for(let $ of Q)Z++;return Z}function QQ(Q,Z,$,X){if(!Q)return;let{minLength:G,maxLength:H,format:Y}=Q;if(G!==void 0||H!==void 0){let M=tQ(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 sQ(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 P0(Q)}function P0(Q){let Z={toJSONSchema:()=>mQ(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:($)=>P0({...Q,description:$}),optional:()=>P0({...Q,optional:!0}),nullable:()=>P0({...Q,nullable:!0,optional:!1})};return R0.set(Z,Q),Z}function x(Q){return{node:Q,optional:!1,nullable:!1}}var ZQ=["strip","error","passthrough"];class HQ extends Error{problems;constructor(Q){super(`gemi/ai: s.fromJSONSchema cannot model this schema:
|
|
2
|
+
import{Ei as N,Fi as _0,Gi as L0}from"./chunk-v2cv3wcw.js";import{Li as x0,Oi as b}from"./chunk-7hdfbp2x.js";import{Tk as BQ}from"./chunk-kddgfct7.js";import{kl as Y0}from"./chunk-9yfg4nqq.js";import{rl as iZ}from"./chunk-tbhtx2t0.js";class o0{static kind="controller";constructor(){}}class bQ extends o0{}function N0(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 W1(Q){return N0(Q.headers.get("cookie"))}function p(Q){if(!/^\d+$/.test(Q))return null;let Z=Number(Q);return Number.isSafeInteger(Z)?Z:null}function t0(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 s0(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 z1(Q){if(Q.kind==="suffix")return`bytes=-${Q.suffixLength}`;return Q.end===null?`bytes=${Q.start}-`:`bytes=${Q.start}-${Q.end}`}function U1(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 V1(Q,Z,$){return`bytes ${Q}-${Z}/${$}`}function r0(Q){return`bytes */${Q}`}class s extends N{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 fQ(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 vQ(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 a0(Q){if(typeof Q==="string"||Array.isArray(Q))return Q.length;return}function q0(Q){return typeof Q==="number"&&!Number.isNaN(Q)}var hQ=["required","string","boolean","number","email","password","min","max","gte","lte","file","fileType","fileSize","array","object","in"];class k extends Error{name="InvalidValidationRuleError"}function z0(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 e0(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)=>q0(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=z0($,X);return(H)=>{let Y=a0(H);return Y!==void 0&&Y>=G}}case"max":{let G=z0($,X);return(H)=>{let Y=a0(H);return Y!==void 0&&Y<=G}}case"gte":{let G=z0($,X);return(H)=>q0(H)&&H>=G}case"lte":{let G=z0($,X);return(H)=>q0(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=vQ(X);return(H)=>H instanceof Blob&&H.type.startsWith(G)}case"fileSize":{let G=fQ(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: ${hQ.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 R0=new WeakMap;function $Q(Q){return typeof Q==="object"&&Q!==null&&R0.has(Q)}function V0(Q){let Z=R0.get(Q);if(!Z)throw Error("gemi/ai: expected a schema built with `s`, got a foreign object");return Z}function mQ(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=a($,Z);return Object.keys(Z.defs).length>0?{...X,$defs:Z.defs}:X}function a(Q,Z){let $=(Q.optional||Q.nullable)&&Q.node.kind!=="json",X=uQ(pQ(Q.node,Z),$),G=[Q.description,cQ(Q.node)].filter(Boolean).join(" ");if(G&&X.$ref!==void 0)X={anyOf:[X]};return G?{description:G,...X}:X}function cQ(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 pQ(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:a(Q.item,Z)};case"object":return{type:"object",properties:Object.fromEntries(Object.entries(Q.shape).map(([$,X])=>[$,a(X,Z)])),required:Object.keys(Q.shape),additionalProperties:!1};case"union":return{anyOf:Q.members.map(($)=>a($,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]=a(u($),Z);return{$ref:`#/$defs/${$.name}`}}}}function uQ(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 dQ(Q){if(Q===null)return"null";if(Array.isArray(Q))return"array";return typeof Q}function iQ(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 dQ(Z)}function XQ(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 XQ({...u(Z.cell),optional:!1,nullable:!1})}})();return Q.optional||Q.nullable?`${$} or null`:$}function lQ(Q){let Z="";for(let $ of Q)Z+=typeof $==="number"?`[${$}]`:Z?`.${$}`:$;return Z}function nQ(Q){let Z=lQ(Q);return Z?`${Z}: `:""}function w0(Q){return`${nQ(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 GQ($.cell,Z,()=>1,()=>B0(u($.cell),Z))}}function GQ(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:oQ(Q,Z,$,X)}}function oQ(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 ${XQ(Q)}, got ${iQ(G,Z)}`,params:M});return};switch(G.kind){case"string":if(typeof Z!=="string")return H();return QQ(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 sQ(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 QQ(G.checks,Z,$,X),Z;case"array":{if(!Array.isArray(Z))return H();let Y=Z.map((J,D)=>{let z=v(G.item,J,[...$,D],X);return z.drop?void 0:z.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 GQ(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 tQ(Q){let Z=0;for(let $ of Q)Z++;return Z}function QQ(Q,Z,$,X){if(!Q)return;let{minLength:G,maxLength:H,format:Y}=Q;if(G!==void 0||H!==void 0){let M=tQ(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 sQ(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 P0(Q)}function P0(Q){let Z={toJSONSchema:()=>mQ(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:($)=>P0({...Q,description:$}),optional:()=>P0({...Q,optional:!0}),nullable:()=>P0({...Q,nullable:!0,optional:!1})};return R0.set(Z,Q),Z}function x(Q){return{node:Q,optional:!1,nullable:!1}}var ZQ=["strip","error","passthrough"];class HQ 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 rQ=new Set(["title","$schema","$id","$comment","examples","default","deprecated","readOnly","writeOnly"]),r={string:["minLength","maxLength","format"],number:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],integer:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],boolean:[],object:["properties","required","additionalProperties"],array:["items","minItems","maxItems"]};function U0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function j0(Q,Z,$,X){let G=(W,V=$)=>{X.push(V?`${V}: ${W}`:W);return},H=(W)=>$?`${$}.${W}`:W;if(!U0(Q))return G("expected a schema object");let Y=new Set(Z.ignoreKeywords??[]),M=(W)=>rQ.has(W)||W.startsWith("x-")||Y.has(W),K=!1,J=Q.type;if(Array.isArray(J)){let W=J.filter((V)=>V!=="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 r)))return G(`type ${JSON.stringify(J)} is not supported; expected one of ${Object.keys(r).join(", ")}`,H("type"));let D=new Set(["type","description","enum","const","anyOf",...J?r[J]:[]]),z=!1;for(let W of Object.keys(Q)){if(D.has(W)||M(W))continue;z=!0;let V=Object.entries(r).find(([,U])=>U.includes(W));G(V&&V[0]!==J?`"${W}" applies to type ${V[0]}, and this schema is ${J?`type ${J}`:"untyped"}`:`"${W}" is not supported by s.fromJSONSchema`,H(W))}if(z)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=[],V=!1;if(Q.anyOf.forEach((U,P)=>{if(U0(U)&&U.type==="null"&&Object.keys(U).length===1){K=!0;return}let F=j0(U,Z,H(`anyOf[${P}]`),X);if(F)W.push(F);else V=!0}),V)return;if(W.length===0)return G("anyOf has only null in it",H("anyOf"));if(W.length===1){let U=W[0];return{...U,nullable:U.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 _;if(J==="string"){if(_=aQ(Q,Z,H,X),_===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((P)=>P!==null);if(W.length<Q.enum.length)K=!0;let V=W.find((P)=>!(typeof P==="string"||typeof P==="number"||typeof P==="boolean")||J!==void 0&&typeof P!==(J==="integer"?"number":J));if(V!==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(V)} is not`}`:"only strings, numbers and booleans are supported",H("enum"));if(W.every((P)=>typeof P==="string"))return B({kind:"enum",values:[...new Set(W)],..._?{checks:_}:{}});let U=[...new Set(W)];if(U.length===1)return B({kind:"literal",value:U[0]});return B({kind:"union",members:U.map((P)=>x({kind:"literal",value:P}))})}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",..._?{checks:_}:{}});case"number":case"integer":{let W=J==="integer"?{integer:!0}:{},V=!1;for(let U of r.number){let P=Q[U];if(P===void 0)continue;if(typeof P!=="number"||!Number.isFinite(P)){G("expected a number",H(U)),V=!0;continue}W[U]=P}if(V)return;return B({kind:"number",...Object.keys(W).length>0?{checks:W}:{}})}case"boolean":return B({kind:"boolean"});case"array":{if(!U0(Q.items))return G('an array needs "items" to be one schema (tuples are not supported)',H("items"));let W={},V=!1;for(let P of["minItems","maxItems"]){let F=Q[P];if(F===void 0)continue;if(typeof F!=="number"||!Number.isInteger(F)||F<0){G("expected a non-negative integer",H(P)),V=!0;continue}W[P]=F}let U=j0(Q.items,Z,H("items"),X);if(!U||V)return;return B({kind:"array",item:U,...Object.keys(W).length>0?{checks:W}:{}})}case"object":{let W=Q.properties??{};if(!U0(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 V=Q.required??[];if(!Array.isArray(V)||!V.every((A)=>typeof A==="string"))return G("expected an array of property names",H("required"));let U=V.filter((A)=>!Object.hasOwn(W,A));if(U.length>0)return G(`lists properties the schema doesn't have: ${U.join(", ")}`,H("required"));let P={},F=!1;for(let[A,C]of Object.entries(W)){let R=j0(C,Z,H(`properties.${A}`),X);if(!R){F=!0;continue}P[A]=V.includes(A)?R:{...R,optional:!0}}if(F)return;let I=Z.unknownKeys;return B({kind:"object",shape:P,...I==="error"||I==="passthrough"?{unknownKeys:I}:{}})}}return}function aQ(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:eQ(M)}}if(H)return null;return Object.keys(G).length>0?G:void 0}function eQ(Q){if(Q===!0)return()=>!0;if(Q instanceof RegExp)return(Z)=>{return Q.lastIndex=0,Q.test(Z)};return Q}var _1={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,V0($)]))})),array:(Q)=>E(x({kind:"array",item:V0(Q)})),union:(Q)=>E(x({kind:"union",members:Q.map(V0)})),json:()=>E(x({kind:"json"})),recursive:ZZ,fromJSONSchema:(Q,Z={})=>{let $=[];if(Z.unknownKeys!==void 0&&!ZQ.includes(Z.unknownKeys))throw Error(`gemi/ai: s.fromJSONSchema's unknownKeys option must be one of ${ZQ.map((G)=>JSON.stringify(G)).join(", ")}, got ${JSON.stringify(Z.unknownKeys)}`);let X=j0(Q,Z,"",$);if(!X||$.length>0)throw new HQ($.length>0?$:["unreadable schema"]);return E(X)}};function L1(Q){let Z=R0.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 QZ=/^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;function ZZ(Q,Z){if(typeof Q!=="string"||!QZ.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=V0(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 YQ(Q){if(typeof Q!=="string")return null;let[Z]=Q.split(";",1),$=Z.trim().toLowerCase();return $===""?null:$}function KQ(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 F1(Q,Z,$,X){$0.set(Q,{clientAddress:Z,...$?{grant:Object.freeze({...$,scopes:Object.freeze([...$.scopes])})}:{},...X?{progress:X}:{}})}function MQ(Q){return $0.get(Q)?.progress}function JQ(Q){return $0.get(Q)?.grant}function WQ(Q){return $0.has(Q)}function I1(Q){return $0.get(Q)?.clientAddress}var DQ=new WeakMap;function T1(Q,Z){DQ.set(Q,Z)}function zQ(Q){return DQ.get(Q)??null}var S0=new WeakMap;function N1(Q,Z){let $=S0.get(Q)??[];if(!$.includes(Z))S0.set(Q,[...$,Z])}function q1(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 UQ(Q){return typeof Q==="object"&&Q!==null&&!(Q instanceof Blob)}function $Z(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(UQ(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:UQ(Y)&&Object.hasOwn(Y,X)?Y[X]:void 0})}$=G}return $}function VQ(Q){return Q.join(".")}class XZ{kind;rawRequest;headers;cookies;search;schema={};routePath;params;domain;state;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,this.state=K.state??new x0}else this.params=Z,this.rawRequest=Q,this.routePath=X,this.kind=$??"api",this.domain=zQ(Q),this.state=new x0;this.headers=this.rawRequest.headers;let G=N0(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 WQ(this.rawRequest)}mcpGrant(){return JQ(this.rawRequest)??null}reportProgress(Q){let Z=MQ(this.rawRequest);if(!Z)return!1;return Z(Q),!0}get signal(){return this.rawRequest.signal}range(){return t0(this.rawRequest.headers.get("Range"))}refine(Q){return{}}async parseBody(){let Q=YQ(this.rawRequest.headers.get("Content-Type"));if(KQ(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 N)throw X;throw new N("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 N)throw $;throw new N("The request body could not be read.")}if(Q.trim()==="")return{};let Z;try{Z=JSON.parse(Q)}catch{throw new N("The request body is not valid JSON.")}if(Z===null||typeof Z!=="object")throw new N("The request body must be a JSON object.");return Z}validateInput(Q){if($Q(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 $Z(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 e0(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 GZ extends N{error;constructor(Q="Not authorized"){super(Q);this.name="AuthorizationError",this.error=Q,this.payload={api:{status:401,data:{error:L0("authorization",this.error,401)}},view:{}}}}class k0 extends N{static apiStatus=403;error;constructor(Q="Insufficient permissions"){super(Q);this.name="InsufficientPermissionsError",this.error=Q,this.payload={api:{status:k0.apiStatus,data:{error:L0("permission",this.error,k0.apiStatus)}},view:{status:403}}}}class g0 extends N{total;constructor(Q){super("Range not satisfiable");this.total=Q;this.name="RangeNotSatisfiableError",this.payload={api:{status:416,data:{error:_0("range_not_satisfiable","Range not satisfiable",416)},headers:{"Content-Range":r0(Q),"Accept-Ranges":"bytes","Cache-Control":"no-store"}},view:{}}}}class HZ extends N{constructor(Q="Not found"){super(Q);this.name="NotFoundError",this.payload={api:{status:404,data:{error:_0("not_found",Q,404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class h extends N{fileName;constructor(Q){super("File not found");this.fileName=Q;this.name="FileNotFoundError",this.payload={api:{status:404,data:{error:_0("not_found","Not found",404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class YZ extends N{constructor(Q={}){super("Authentication error");this.name="AuthenticationError";let Z=Q.redirectTo??"/auth/sign-in";this.payload={api:{status:401,data:{error:L0("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 BQ(this.getFacadeAccessor())}}import{Buffer as KZ}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:KZ.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 PQ(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 MZ,open as JZ,readdir as y0,rename as WZ,rmdir as DZ,stat as zZ,unlink as jQ}from"fs/promises";import{dirname as UZ,isAbsolute as b0,relative as H0,resolve as i,sep as f}from"path";class f0 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=i(this.folderPath),Y=i(H,Q),M=H0(H,Y);if(!M||M===".."||M.startsWith(`..${f}`)||b0(M))throw Error(`Refusing to write "${Q}": it is outside the storage folder`);await MZ(UZ(Y),{recursive:!0}),G=`${Y}.${Bun.randomUUIDv7()}.partial`;let K=await JZ(G,"wx");try{for(;;){$?.throwIfAborted();let{done:J,value:D}=await X.read();if(J)break;for(let z=0;z<D.byteLength;){let{bytesWritten:O}=await K.write(D,z);z+=O}}}finally{await K.close()}return $?.throwIfAborted(),await WZ(G,Y),Q}catch(H){if(await X.cancel(H).catch(()=>{}),G)await jQ(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=PQ(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?s0(X,H):null;if(X&&!Y)throw new g0(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 $=i(this.folderPath),X=i($,Z),G=H0($,X);if(!G||G===".."||G.startsWith(`..${f}`)||b0(G))throw Error(`Refusing to delete "${Z}": it is outside the storage folder`);try{await jQ(X)}catch(H){if(H?.code==="ENOENT")return;throw H}}resolvePrefix(Q){let Z=i(this.folderPath),$=Q.lastIndexOf("/"),X=$===-1?"":Q.slice(0,$),G=$===-1?Q:Q.slice($+1),H=i(Z,X),Y=H0(Z,H);if(Y===".."||Y.startsWith(`..${f}`)||b0(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 y0(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}`,z=H0($,D).split(f).join("/");if(J.isDirectory()){if(`${z}/`.startsWith(G)||G.startsWith(`${z}/`))await Y(D)}else if(J.isFile()&&z.startsWith(G))H.push(z)}};await Y(X),H.sort();for(let M of H){Z?.throwIfAborted();let K;try{K=await zZ(`${$}/${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 y0(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 DZ(G)}catch{}}async list(){return await y0(this.folderPath)}}function Y8(Q){return Q}function RQ(){return{driver:new f0}}class v0{static token="filesystem";driver;constructor(Q={}){this.driver=Q.driver??RQ().driver}}class q extends Error{code="safe-fetch";url;constructor(Q,Z,$){super(Q,$);this.name=new.target.name,this.url=Z}}class m extends q{reason;code="invalid-url";constructor(Q,Z,$){super($,Q);this.reason=Z}}class O0 extends q{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 l extends q{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 q{host;code="dns";constructor(Q,Z,$){super(`Couldn't resolve ${Z}.`,Q,{cause:$});this.host=Z}}class I0 extends q{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 A0 extends q{limit;code="too-large";constructor(Q,Z){super(`The response is larger than ${Z} bytes.`,Q);this.limit=Z}}class K0 extends q{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 h0 extends q{limit;code="too-many-redirects";constructor(Q,Z){super(`More than ${Z} redirects.`,Q);this.limit=Z}}class n extends q{code="network";constructor(Q,Z){super(`The request failed: ${Z instanceof Error?Z.message:String(Z)}`,Q,{cause:Z})}}class m0 extends q{status;code="http-status";constructor(Q,Z){super(`The server answered ${Z}.`,Q);this.status=Z}}function VZ(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=BZ(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 BZ(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 _Q(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 z=[],O=J.split(":");for(let B=0;B<O.length;B++){let _=O[B];if(D&&B===O.length-1&&_.includes(".")){if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(_))return null;let W=_.split(".").map(Number);if(W.some((V)=>V>255))return null;z.push(W[0]<<8|W[1],W[2]<<8|W[3]);continue}if(!/^[0-9a-f]{1,4}$/i.test(_))return null;z.push(parseInt(_,16))}return z},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 M0(Q){let Z=_Q(Q);if(Z)return{family:6,bytes:Z};let $=VZ(Q);if($)return{family:4,bytes:$};return null}function c(Q){if(Q.family===6&&PZ(Q.bytes))return{family:4,bytes:Q.bytes.slice(12)};return Q}function PZ(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($)?jZ($):_Q($);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 jZ(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 L=(Q,Z)=>({cidr:o(Q),kind:Z,text:Q}),RZ=[L("0.0.0.0/8","unspecified"),L("10.0.0.0/8","private"),L("100.64.0.0/10","shared"),L("127.0.0.0/8","loopback"),L("169.254.169.254/32","metadata"),L("169.254.0.0/16","link-local"),L("168.63.129.16/32","metadata"),L("172.16.0.0/12","private"),L("192.0.0.0/24","reserved"),L("192.0.2.0/24","documentation"),L("192.88.99.0/24","reserved"),L("192.168.0.0/16","private"),L("198.18.0.0/15","benchmarking"),L("198.51.100.0/24","documentation"),L("203.0.113.0/24","documentation"),L("224.0.0.0/4","multicast"),L("255.255.255.255/32","broadcast"),L("240.0.0.0/4","reserved")],_Z=[L("::/128","unspecified"),L("::1/128","loopback"),L("64:ff9b:1::/48","private"),L("::/8","reserved"),L("100::/64","reserved"),L("2001:db8::/32","documentation"),L("2001::/23","reserved"),L("3fff::/20","documentation"),L("fd00:ec2::254/128","metadata"),L("fc00::/7","unique-local"),L("fe80::/10","link-local"),L("fec0::/10","private"),L("ff00::/8","multicast")],LZ=o("64:ff9b::/96"),CZ=o("2002::/16"),OZ=o("2000::/3");function T0(Q){let Z=typeof Q==="string"?M0(Q):Q;if(!Z)return{kind:"reserved",range:"not an IP address"};let $=c(Z);if($.family===4){let G=RZ.find((H)=>g($,H.cidr));return G?{kind:G.kind,range:G.text}:null}if(g($,LZ))return T0({family:4,bytes:$.bytes.slice(12)});if(g($,CZ))return T0({family:4,bytes:$.bytes.slice(2,6)});let X=_Z.find((G)=>g($,G.cidr));if(X)return{kind:X.kind,range:X.text};return g($,OZ)?null:{kind:"reserved",range:"outside 2000::/3"}}function LQ(Q,Z){let $=c(Q),X=c(Z);return $.family===X.family&&$.bytes.every((G,H)=>G===X.bytes[H])}import{lookup as FZ}from"dns/promises";import*as IZ from"http";import*as AZ from"https";import*as t from"zlib";class c0 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]},TZ=new Set([301,302,303,307,308]),NZ=new Set([101,103,204,205,304]),qZ=["host","connection","content-length","transfer-encoding","keep-alive","upgrade"],wZ=["authorization","cookie","proxy-authorization"];async function FQ(Q,Z={}){let $=EZ(Z),X=Z.signal;X?.throwIfAborted();let G=new AbortController,H=G.signal,Y=String(Q),M=(z)=>{if(!H.aborted)G.abort(z)},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 z=OQ(Y,$),O=(Z.method??"GET").toUpperCase(),B=new Headers(Z.headers);for(let W of qZ)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 _=await gZ(O,Z.body,B);for(let W=0;;W++){Y=z.href;let{request:V,response:U,address:P}=await yZ(z,O,B,_,$,H),F=U.statusCode??0,I=U.headers.location;if(TZ.has(F)&&I&&Z.redirect!=="manual"){if(V.destroy(),W>=$.maxRedirects)throw new h0(z.href,$.maxRedirects);let A;try{A=new URL(I,z)}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",_=null;let C=[];B.forEach((R,j)=>{if(j.startsWith("content-"))C.push(j)});for(let R of C)B.delete(R)}if(A.origin!==z.origin)for(let C of wZ)B.delete(C);z=OQ(A.href,$);continue}return bZ({url:z,hop:W,method:O,request:V,response:U,address:P,policy:$,signal:H,release:D})}}catch(z){throw D(),H.aborted?H.reason:z}}function EZ(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(IQ(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??SZ}}async function SZ(Q){return(await FZ(Q,{all:!0,verbatim:!0})).map(($)=>$.address)}function IQ(Q){return Q.toLowerCase().replace(/\.$/,"")}function CQ(Q,Z){return Z.some(($)=>$.startsWith("*.")?Q.endsWith($.slice(1)):Q===$)}function OQ(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=AQ($);if(Z.ports!=="any"&&!Z.ports.includes(X))throw new m($.href,"port",`Port ${X} is not allowed.`);return $}function AQ(Q){return Q.port?Number(Q.port):Q.protocol==="https:"?443:80}async function xZ(Q,Z,$){let X=IQ(Q.hostname.replace(/^\[(.*)\]$/,"$1")),G=M0(X),H=G!==null&&(X.includes(":")||/^\d+\.\d+\.\d+\.\d+$/.test(X));if(!H&&CQ(X,Z.deny.hosts))throw new O0(Q.href,X,"denied");let Y=!H&&Z.allow!==null&&CQ(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 kZ(Z.resolve(X),$)}catch(J){if($.aborted)throw $.reason;throw new F0(Q.href,X,J)}if(M=K.map((J)=>M0(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((z)=>g(K,z)))throw new l(Q.href,X,J,"denied");if(Z.allow&&!Y&&!Z.allow.ranges.some((z)=>g(K,z)))throw new l(Q.href,X,J,"not-allowed");let D=T0(K);if(D&&Z.allowPrivate!==!0&&!Z.allowPrivate.some((z)=>g(K,z)))throw new l(Q.href,X,J,D.kind)}return{host:X,addresses:M,isLiteral:H}}function kZ(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 gZ(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 yZ(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:z}=await xZ(Q,G,K),O=Q.protocol==="https:",B={};if($.forEach((_,W)=>{B[W]=_}),X)B["content-length"]=String(X.byteLength);return await new Promise((_,W)=>{let V={method:Z,host:J,port:AQ(Q),path:`${Q.pathname}${Q.search}`,headers:B,agent:!1,lookup:(C,R,j)=>{let w=R?.family,T=D.filter((D0)=>!w||D0.family===w);if(T.length===0)j(Object.assign(Error(`No IPv${w} address for ${J}`),{code:"ENOTFOUND"}));else if(R?.all)j(null,T.map((D0)=>({address:J0(D0),family:D0.family})));else j(null,J0(T[0]),T[0].family)}};if(O&&!z)V.servername=J;let U=(O?AZ:IZ).request(V),P=null,F=(C)=>{K.removeEventListener("abort",I),U.destroy(),W(C)},I=()=>F(K.aborted?K.reason:H.reason);K.addEventListener("abort",I,{once:!0});let A=(C)=>{let R=C?.remoteAddress;if(!R||P!==null)return!0;let j=M0(R);if(!j||!D.some((w)=>LQ(w,j)))return F(new l(Q.href,J,R,"not-allowed")),!1;return P=J0(c(j)),!0};U.once("socket",(C)=>{let R=()=>{if(A(C)&&!O)clearTimeout(M)};if(C.connecting)C.once("connect",R);else R();if(O)C.once("secureConnect",()=>clearTimeout(M))}),U.once("response",(C)=>{if(clearTimeout(M),C.on("error",()=>{}),!A(C.socket))return;K.removeEventListener("abort",I),_({request:U,response:C,address:P})}),U.on("error",(C)=>{if(K.aborted)return F(K.reason);F(C instanceof q?C:new n(Q.href,C))}),U.end(X??void 0)})}finally{clearTimeout(M)}}function bZ({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,z=G.rawHeaders;for(let R=0;R<z.length;R+=2)D.append(z[R],z[R+1]);if(Y.contentTypes){let R=D.get("content-type")?.split(";")[0].trim().toLowerCase()??null;if(!R||!Y.contentTypes.some((j)=>fZ(R,j)))throw X.destroy(),new K0(Q.href,R,Y.contentTypes)}let O={url:Q.href,redirected:Z>0,address:H},B={status:J,statusText:G.statusMessage??"",headers:D};if($==="HEAD"||NZ.has(J))return X.destroy(),K(),new c0(null,B,O);let _=D.get("content-encoding")?.trim().toLowerCase(),W=_==="gzip"||_==="x-gzip"?t.createGunzip():_==="deflate"?t.createInflate():_==="br"?t.createBrotliDecompress():null,V=Number(D.get("content-length"));if(!W&&Number.isFinite(V)&&V>Y.maxSize)throw X.destroy(),new A0(Q.href,Y.maxSize);if(W)D.delete("content-encoding"),D.delete("content-length");let U=W?G.pipe(W):G,P=0,F=!1,I=()=>{},A=()=>{F=!0,M.removeEventListener("abort",I),K()},C=new ReadableStream({start(R){let j=(T)=>{if(F)return;if(A(),T===void 0)R.close();else X.destroy(),W?.destroy(),R.error(T)};if(I=()=>j(M.reason),M.addEventListener("abort",I,{once:!0}),M.aborted)return I();U.on("data",(T)=>{if(F)return;if(P+=T.byteLength,P>Y.maxSize)return j(new A0(Q.href,Y.maxSize));if(R.enqueue(new Uint8Array(T)),(R.desiredSize??1)<=0)U.pause()}),U.once("end",()=>j());let w=(T)=>j(T instanceof q?T:new n(Q.href,T));if(U.on("error",w),W)G.on("error",w);G.once("aborted",()=>j(new n(Q.href,Error("The response was cut off."))))},pull(){U.resume()},cancel(){if(F)return;A(),X.destroy(),W?.destroy()}});return new c0(C,B,O)}function fZ(Q,Z){let $=Z.toLowerCase();return $.endsWith("/*")?Q.startsWith($.slice(0,-1)):Q===$}function NQ(Q){return mZ(Q)??pZ(Q)??uZ(Q)}var p0=4096,vZ={"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 qQ(Q){return vZ[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 hZ={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 mZ(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 hZ[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 cZ=["!doctype html","html","head","script","iframe","h1","div","font","table","a","style","title","b","body","br","p","!--"];function pZ(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 cZ){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 uZ(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 dZ=new Set(["text/html","application/xhtml+xml","image/svg+xml","text/xml","application/xml","text/xsl","application/xslt+xml"]);function TQ(Q){let Z=Q.split(";")[0].trim().toLowerCase();return dZ.has(Z)||Z.endsWith("+xml")}function wQ(Q,Z){let $=Q.split(";")[0].trim().toLowerCase();return Z.some((X)=>{let G=X.split(";")[0].trim().toLowerCase();if(G==="*/*"||G==="*")return!TQ($);if(G.endsWith("/*"))return $.startsWith(G.slice(0,-1))&&!TQ($);return $===G})}import{Buffer as nZ}from"buffer";async function EQ(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 SQ(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 FQ(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 m0(D.url,D.status);let z=(D.body??new Response(new Uint8Array).body).getReader(),O=async(j)=>{throw await z.cancel(j).catch(()=>{}),j},B=[],_=0,W=!1;while(_<p0){let{done:j,value:w}=await z.read();if(j){W=!0;break}B.push(w),_+=w.byteLength}let V=lZ(B,_),U=NQ(V.subarray(0,Math.min(_,p0))),P=K?.length?K:["*/*"];if(!wQ(U,P))await O(new K0(D.url,U,P));let F=X??[(G??"").replace(/\/+$/,""),`${Bun.randomUUIDv7()}.${qQ(U)}`].filter(Boolean).join("/"),I=_,A=new ReadableStream({start(j){if(_>0)j.enqueue(V);if(W)j.close()},async pull(j){let{done:w,value:T}=await z.read();if(w){j.close();return}I+=T.byteLength,j.enqueue(T)},cancel(j){return z.cancel(j)}}),C={name:F,bucket:H,body:A,contentType:U},R;try{R=Q.putStream?await Q.putStream(C,{signal:J}):await G0.prototype.putStream.call(Q,C,{signal:J})}catch(j){throw await O(j),j}return{name:R,contentType:U,size:I,url:D.url}}function lZ(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 oZ extends X0{static getFacadeAccessor(){return v0}static async put(Q,Z={}){return this.getFacadeRoot().driver.put(Q,Z)}static async putFromUrl(Q,Z={}){return SQ(this.getFacadeRoot().driver,Q,Z)}static async metadata(Q){let Z=nZ.from(await Q.arrayBuffer()),$=await EQ("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 d0,readdir as aZ,access as eZ}from"fs/promises";var u0=["debug","info","notice","warning","error","critical","alert","emergency"],tZ=u0.indexOf("warning");function kQ(Q){if(!Q)return-1;if(Q===!0)return 0;let Z=u0.indexOf(Q);return Z===-1?0:Z}function sZ(){let Q=new WeakSet;return function(Z,$){if(typeof $==="bigint")return $.toString();if($ instanceof Error){let X={name:$.name,message:$.message,stack:$.stack};for(let G of Object.keys($))X[G]=$[G];if($.cause!==void 0)X.cause=$.cause;return X}if($!==null&&typeof $==="object"){if(Q.has($))return"[Circular]";Q.add($)}return $}}function xQ(Q){try{return JSON.stringify(Q,sZ())}catch{return'"[Unserializable]"'}}function rZ(Q,Z){if(Z==="json")return xQ({...Q.metadata,timestamp:Q.timestamp,level:Q.level,message:Q.message});let $=Object.keys(Q.metadata).length>0;return`${Q.timestamp} ${Q.level.toUpperCase()} ${Q.message}${$?` ${xQ(Q.metadata)}`:""}`}function gQ(Q,Z){let $=u0.indexOf(Q.level);if(Z.threshold===-1||$<Z.threshold)return;try{let X=rZ(Q,Z.format)+`
|
|
5
5
|
`;if($>=tZ)process.stderr.write(X);else process.stdout.write(X)}catch{}}async function i0(Q){try{return await eZ(Q),!0}catch{return!1}}class l0{config;static token="log";writer;isReady=!1;flushTimeout;fileSize=0;writerSize=0;isCreatingFile=!1;bootPromise=null;currentLogFilePath;get logsDirPath(){return`${Y0()}/storage/logs`}consoleThreshold;constructor(Q){this.config=Q;this.consoleThreshold=kQ(Q.console)}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 i0(Q))await d0(Q);if(!await i0(this.logsDirPath))await d0(this.logsDirPath);await this.newLogFile()}async newLogFile(){if(!await i0(this.logsDirPath))await d0(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 aZ(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(`
|
|
@@ -10,6 +10,6 @@ data: ${JSON.stringify(Q.event)}
|
|
|
10
10
|
`}var X1=5000,G1=`: keepalive
|
|
11
11
|
|
|
12
12
|
`;function H1(Q,Z=X1){let $=null,X=!1,G=()=>{if(X)return;if($!==null)clearTimeout($);$=setTimeout(()=>{if($=null,X)return;try{Q.enqueue(n0.encode(G1))}catch{H();return}G()},Z)},H=()=>{if(X=!0,$!==null)clearTimeout($);$=null};return G(),{touch:G,stop:H}}function Y1(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function m8(Q,Z=200){let $=Q[Symbol.asyncIterator](),X=-1,G,H=new ReadableStream({start(Y){G=H1(Y)},async pull(Y){try{let M=await $.next();if(M.done){G.stop(),Y.close();return}X=M.value.seq,Y.enqueue(n0.encode(yQ(M.value))),G.touch()}catch(M){let K={type:"error",error:M1(M)};G.stop(),Y.enqueue(n0.encode(yQ({seq:X+1,event:K}))),Y.close()}},cancel(Y){G.stop(),$.return?.(Y)}});return new Response(H,{status:Z,headers:Y1()})}var K1=new Set(["frame_cursor_evicted","live_run_not_found"]);function M1(Q){let Z=Q&&typeof Q==="object"?Q.code:void 0;if(Q instanceof Error&&typeof Z==="string"&&K1.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}}
|
|
13
|
-
export{o0 as
|
|
13
|
+
export{o0 as th,bQ as uh,W1 as vh,YQ as wh,F1 as xh,JQ as yh,I1 as zh,t0 as Ah,s0 as Bh,z1 as Ch,U1 as Dh,V1 as Eh,r0 as Fh,T1 as Gh,zQ as Hh,N1 as Ih,q1 as Jh,s as Kh,k as Lh,$Q as Mh,HQ as Nh,_1 as Oh,L1 as Ph,XZ as Qh,GZ as Rh,k0 as Sh,g0 as Th,HZ as Uh,h as Vh,YZ as Wh,X0 as Xh,EQ as Yh,C0 as Zh,G0 as _h,PQ as $h,f0 as ai,Y8 as bi,RQ as ci,v0 as di,q as ei,m as fi,O0 as gi,l as hi,F0 as ii,I0 as ji,A0 as ki,K0 as li,h0 as mi,n as ni,m0 as oi,T0 as pi,c0 as qi,FQ as ri,NQ as si,TQ as ti,oZ as ui,l0 as vi,Q1 as wi,Z1 as xi,G1 as yi,H1 as zi,Y1 as Ai,m8 as Bi};
|
|
14
14
|
|
|
15
|
-
//# debugId=
|
|
15
|
+
//# debugId=2A178AD9EF74C32F64756E2164756E21
|