gemi 0.235.0 → 0.236.1
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/client/conformance.d.ts +4 -2
- package/dist/ai/client/conformance.d.ts.map +1 -1
- package/dist/ai/client/index.js +72 -6
- package/dist/ai/client/index.js.map +1 -1
- package/dist/ai/client/reducer.d.ts.map +1 -1
- package/dist/ai/index.js +3 -3
- package/dist/ai/index.js.map +3 -3
- package/dist/ai/providers/call.d.ts +1 -1
- package/dist/ai/types.d.ts +5 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/useChat.d.ts +35 -0
- package/dist/ai/useChat.d.ts.map +1 -1
- package/dist/auth/AuthController.d.ts.map +1 -1
- package/dist/{chunk-adfkz2kf.js → chunk-0e5sq42y.js} +1 -1
- package/dist/chunk-4800w7qx.js.map +2 -2
- package/dist/{chunk-cb7mgx75.js → chunk-73541m4t.js} +6 -6
- package/dist/{chunk-cb7mgx75.js.map → chunk-73541m4t.js.map} +3 -3
- package/dist/{chunk-t5gbp0yr.js → chunk-dav7mv8t.js} +2 -2
- package/dist/{chunk-t5gbp0yr.js.map → chunk-dav7mv8t.js.map} +3 -3
- package/dist/{chunk-1yws1nvb.js → chunk-hy54f691.js} +2 -2
- package/dist/{chunk-1yws1nvb.js.map → chunk-hy54f691.js.map} +1 -1
- package/dist/{chunk-2hw8sr4d.js → chunk-wbj4jh1h.js} +1 -1
- package/dist/{chunk-2hw8sr4d.js.map → chunk-wbj4jh1h.js.map} +1 -1
- package/dist/{chunk-9359fg6r.js → chunk-yknc5rgh.js} +1 -1
- package/dist/{chunk-9359fg6r.js.map → chunk-yknc5rgh.js.map} +1 -1
- package/dist/chunks/{RealtimeClient-C5Zh3fD6.js → RealtimeClient-DRVodyn1.js} +2 -2
- package/dist/chunks/{RealtimeClient-C5Zh3fD6.js.map → RealtimeClient-DRVodyn1.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-bbbE-N3t.js → ThemeProvider-1WtAS7dH.js} +4 -4
- package/dist/chunks/{ThemeProvider-bbbE-N3t.js.map → ThemeProvider-1WtAS7dH.js.map} +1 -1
- package/dist/chunks/{fetchFileRequest-JXhnEi-R.js → fetchFileRequest-CVCelZqS.js} +2 -2
- package/dist/chunks/{fetchFileRequest-JXhnEi-R.js.map → fetchFileRequest-CVCelZqS.js.map} +1 -1
- package/dist/chunks/{live-CApTRvmK.js → live-twEh9Qwt.js} +3 -3
- package/dist/chunks/{live-CApTRvmK.js.map → live-twEh9Qwt.js.map} +1 -1
- package/dist/chunks/{mutationExtras-C2qSSZ2Q.js → mutationExtras-CM77Ur-9.js} +2 -2
- package/dist/chunks/{mutationExtras-C2qSSZ2Q.js.map → mutationExtras-CM77Ur-9.js.map} +1 -1
- package/dist/chunks/{subscriptionStream-DQLW7dTW.js → subscriptionStream-DQp1Krwi.js} +2 -2
- package/dist/chunks/{subscriptionStream-DQLW7dTW.js.map → subscriptionStream-DQp1Krwi.js.map} +1 -1
- package/dist/client/chunkLoadRecovery.d.ts +1 -1
- package/dist/client/index.js +4 -4
- package/dist/client/index.js.map +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/http/index.js +1 -1
- package/dist/i18n/index.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/orm/index.js.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/mcp/http/callers.d.ts +1 -1
- package/dist/testing/index.js +2 -2
- package/package.json +1 -1
- /package/dist/{chunk-adfkz2kf.js.map → chunk-0e5sq42y.js.map} +0 -0
package/dist/facades/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Jg as r,Kg as s,Lg as t,Mg as u,Qf as a,Tf as c,Uf as e,Vf as f,Wf as h,Xf as i,Yf as j,dg as k,eg as l,fg as m,gg as n,hg as o,ig as p,vh as v,yg as q}from"../chunk-
|
|
2
|
+
import{Jg as r,Kg as s,Lg as t,Mg as u,Qf as a,Tf as c,Uf as e,Vf as f,Wf as h,Xf as i,Yf as j,dg as k,eg as l,fg as m,gg as n,hg as o,ig as p,vh as v,yg as q}from"../chunk-73541m4t.js";import"../chunk-zm6b938z.js";import"../chunk-2kzysesp.js";import{yj as d}from"../chunk-fqndtpwm.js";import"../chunk-h1wmpa03.js";import{Jj as b,Nj as g}from"../chunk-t6x1r5n6.js";import"../chunk-naj8bmj5.js";import"../chunk-np6vee9d.js";import"../chunk-5exrgw07.js";import"../chunk-jssjfvsz.js";import"../chunk-a119av2z.js";import"../chunk-m3fbewhz.js";import"../chunk-x2dmgge8.js";import"../chunk-fs94x6ef.js";import"../chunk-8476xvk9.js";import"../chunk-kvtvx64t.js";import"../chunk-9jt5qj1b.js";import"../chunk-17ewxwga.js";import"../chunk-sv2mv2q2.js";import"../chunk-gt9ftnhn.js";import"../chunk-qvn0w2rt.js";import"../chunk-ka8dzc6q.js";import"../chunk-3y1h3ncf.js";import"../chunk-ts75gcfd.js";export{f as Url,d as Storage,r as Runs,j as Redis,a as Redirect,l as RateLimiter,e as Query,h as Meta,g as Log,m as Lock,c as Lang,s as Features,b as Facade,u as DB,n as Crypt,i as Cookie,o as Connections,t as ConnectionQueries,p as ChangeFeed,k as Cache,q as Broadcast,v as Auth};
|
|
3
3
|
|
|
4
4
|
//# debugId=7F8780ED1F134EFA64756E2164756E21
|
package/dist/http/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$e as E,Bh as ea,Ch as fa,Dh as ga,Eh as ha,Fh as ia,Gh as ja,Hh as ka,Ih as la,Jh as ma,Kh as na,Lh as oa,Mh as pa,Nh as qa,Of as K,Oh as ra,Pf as L,Ph as sa,Qh as ta,Rf as M,Rh as ua,Sf as N,Sh as va,Ug as aa,We as t,Xe as u,Ye as v,Ze as w,_e as x,ef as F,if as G,jf as H,kf as I,lf as J,wh as ba,xh as ca,yh as da}from"../chunk-
|
|
2
|
+
import{$e as E,Bh as ea,Ch as fa,Dh as ga,Eh as ha,Fh as ia,Gh as ja,Hh as ka,Ih as la,Jh as ma,Kh as na,Lh as oa,Mh as pa,Nh as qa,Of as K,Oh as ra,Pf as L,Ph as sa,Qh as ta,Rf as M,Rh as ua,Sf as N,Sh as va,Ug as aa,We as t,Xe as u,Ye as v,Ze as w,_e as x,ef as F,if as G,jf as H,kf as I,lf as J,wh as ba,xh as ca,yh as da}from"../chunk-73541m4t.js";import"../chunk-zm6b938z.js";import"../chunk-2kzysesp.js";import{Ai as h,Bi as i,Ci as j,Fi as n,Ki as o,Li as p,Mi as q,Ni as r,Si as s,Ui as y,Vi as z,Wi as A,Xi as B,Yi as C,Zi as D,hj as O,ij as P,jj as Q,kj as R,lj as S,mj as T,nj as U,oj as V,pj as W,qi as a,qj as X,ri as b,rj as Y,si as d,tj as Z,uj as _,vj as $,xi as e,yi as f,zi as g}from"../chunk-fqndtpwm.js";import{Cj as c}from"../chunk-h1wmpa03.js";import"../chunk-t6x1r5n6.js";import{Qj as k,Rj as l,Sj as m}from"../chunk-naj8bmj5.js";import"../chunk-np6vee9d.js";import"../chunk-5exrgw07.js";import"../chunk-jssjfvsz.js";import"../chunk-a119av2z.js";import"../chunk-m3fbewhz.js";import"../chunk-x2dmgge8.js";import"../chunk-fs94x6ef.js";import"../chunk-8476xvk9.js";import"../chunk-kvtvx64t.js";import"../chunk-9jt5qj1b.js";import"../chunk-17ewxwga.js";import"../chunk-sv2mv2q2.js";import"../chunk-gt9ftnhn.js";import"../chunk-qvn0w2rt.js";import"../chunk-ka8dzc6q.js";import"../chunk-3y1h3ncf.js";import"../chunk-ts75gcfd.js";export{g as toRangeHeaderValue,v as toMiddlewareList,k as stateKey,$ as safeFetch,f as resolveRange,e as parseRangeHeader,h as parseContentRange,r as parseByteSize,ja as middlewareConfigDefaults,u as httpError,d as getCookies,j as formatUnsatisfiedContentRange,i as formatContentRange,ra as defineResourcePolicy,ia as defineMiddlewareConfig,n as cspNonce,w as createUnsatisfiableResponse,x as createStreamResponse,M as createFileResponse,I as clientIp,J as clientAddress,Z as classifyAddress,da as authorizeChannel,N as ViewRouter,o as ValidationError,W as TooManyRedirectsError,U as TooLargeError,T as TimeoutError,sa as SitemapError,ta as Sitemap,L as SameSiteBounceMiddleware,_ as SafeResponse,O as SafeFetchError,K as SAME_SITE_BOUNCE_PARAM,ua as RobotsTxt,va as Robots,qa as ResourcePolicy,b as ResourceController,m as RequestState,c as RequestBreakerError,H as RateLimitMiddleware,F as RateLimitExceededError,A as RangeNotSatisfiableError,oa as PoliciesServiceProvider,pa as Policies,q as PayloadTooLargeError,B as NotFoundError,X as NetworkError,l as MissingRequestStateError,G as Middleware,ga as McpToolDeclaration,ha as McpRouter,fa as McpRouteDeclaration,ea as McpModelParam,p as InvalidValidationRuleError,P as InvalidUrlError,z as InsufficientPermissionsError,Y as HttpStatusError,t as HttpResponse,s as HttpRequest,C as FileNotFoundError,S as DnsError,ma as CorsMiddleware,a as Controller,V as ContentTypeError,ca as ChannelRouter,ba as ChannelDeclaration,la as CacheMiddleware,na as CSRFMiddleware,aa as BodyLimitMiddleware,Q as BlockedHostError,R as BlockedAddressError,y as AuthorizationError,ka as AuthenticationMiddleware,D as AuthenticationError,E as ApiRouter};
|
|
3
3
|
|
|
4
4
|
//# debugId=EEB068A0B304581064756E2164756E21
|
package/dist/i18n/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ra as T}from"../chunk-y2vayxcd.js";import"../chunk-hke4hzfm.js";import{pb as D}from"../chunk-0hy5dsbt.js";import{Te as b,Ue as w}from"../chunk-yahabnz4.js";import"../chunk-9kt24ctk.js";import{Tf as j}from"../chunk-
|
|
2
|
+
import{ra as T}from"../chunk-y2vayxcd.js";import"../chunk-hke4hzfm.js";import{pb as D}from"../chunk-0hy5dsbt.js";import{Te as b,Ue as w}from"../chunk-yahabnz4.js";import"../chunk-9kt24ctk.js";import{Tf as j}from"../chunk-73541m4t.js";import"../chunk-zm6b938z.js";import"../chunk-2kzysesp.js";import"../chunk-fqndtpwm.js";import"../chunk-h1wmpa03.js";import"../chunk-t6x1r5n6.js";import"../chunk-naj8bmj5.js";import"../chunk-np6vee9d.js";import"../chunk-5exrgw07.js";import"../chunk-jssjfvsz.js";import"../chunk-a119av2z.js";import"../chunk-m3fbewhz.js";import"../chunk-x2dmgge8.js";import"../chunk-fs94x6ef.js";import"../chunk-8476xvk9.js";import"../chunk-kvtvx64t.js";import{hm as V,im as X,jm as E,km as L,lm as R,mm as S}from"../chunk-9jt5qj1b.js";import"../chunk-17ewxwga.js";import"../chunk-sv2mv2q2.js";import"../chunk-gt9ftnhn.js";import"../chunk-qvn0w2rt.js";import"../chunk-ka8dzc6q.js";import"../chunk-3y1h3ncf.js";import"../chunk-ts75gcfd.js";import{createElement as J,Fragment as M,isValidElement as U}from"react";function $(q,B){let G=Object.values(B).some((z)=>typeof z==="function"&&U(z(""))),Q=/{{([^{}]+?)(?::([^{}\[\]]+?))?(?:\[(.*?)\])?}}/g;if(!G)return q.replace(Q,(W,O,_,Z)=>{let C=O.includes(":")?O.split(":")[0]:O,H=B[C];if(H===void 0)return W;if(typeof H==="function"){let K=H(Z!==void 0?Z:"");if(U(K))throw Error("JSX returned in string context");return String(K)}if(_)switch(_.toLowerCase()){case"number":return Number(H).toString();case"string":return String(H);case"boolean":return Boolean(H).toString();default:return String(H)}return String(H)});else{let z=[],W=0,O=null;while((O=Q.exec(q))!==null){let[_,Z,C,H]=O,F=O.index,K=Z.includes(":")?Z.split(":")[0]:Z;if(F>W)z.push(q.substring(W,F));let Y=B[K];if(Y===void 0)z.push(_);else if(typeof Y==="function"){let A=Y(H!==void 0?H:"");z.push(A)}else if(C)switch(C.toLowerCase()){case"number":z.push(Number(Y).toString());break;case"string":z.push(String(Y));break;case"boolean":z.push(Boolean(Y).toString());break;default:z.push(String(Y))}else z.push(String(Y));W=F+_.length}if(W<q.length)z.push(q.substring(W));return J(M,{},...z)}}class P{name;dictionary;constructor(q,B){this.name=q;this.dictionary=B}reference(q){if(typeof window<"u")throw Error("Cannot use reference in the browser");if(!this.dictionary?.[q])throw Error(`Translation not found for ${String(q)}`);return this.dictionary[q]}render(q,...B){let{locale:G=j.locale(),params:Q}={params:{},...B[0]};if(typeof window<"u")throw Error("Cannot use render in the browser");if(!this.dictionary?.[q]?.[G])throw Error(`Translation not found for ${String(q)} in ${String(G)}`);return $(this.dictionary[q][G],Q??{})}static create(q,B){return new P(q,B)}static text(q,...B){let{locale:G=j.locale(),params:Q}={params:{},...B?.[0]};if(!q?.[G])throw Error(`Translation not found for ${String(G)}`);return $(q[G],Q??{})}}async function N(q,B,...G){let{locale:Q=j.locale(),params:z}={params:{},...G[0]},O=(await q.load(String(Q)))[B];if(typeof O!=="string")throw Error(`Translation not found for "${B}" in "${String(Q)}" (dictionary ${q.id})`);return $(O,z??{})}export{w as translationConfigDefaults,N as translate,V as resolveLocale,X as negotiateLocale,L as isValidTimeZone,b as defineTranslationConfig,T as defineDictionary,R as createFormatter,S as Translator,D as TranslationServiceProvider,P as Dictionary,E as DEFAULT_TIME_ZONE};
|
|
3
3
|
|
|
4
4
|
//# debugId=1056A83173E7D75F64756E2164756E21
|
package/dist/kernel/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ta as E}from"../chunk-fbk79z21.js";import{ob as l}from"../chunk-t60krz4g.js";import{pb as H}from"../chunk-0hy5dsbt.js";import{$b as I,Cb as g,Db as W,Eb as _,Fb as p,Gb as P,Hb as u,Ib as $,Jb as V,Kb as q,Lb as B,Mb as K,Qb as L,Rb as Q,Sb as T,Wb as U,Xb as y,Yb as F,Zb as C,_b as D,dc as b,gc as f,hc as k,ic as m}from"../chunk-
|
|
2
|
+
import{Ta as E}from"../chunk-fbk79z21.js";import{ob as l}from"../chunk-t60krz4g.js";import{pb as H}from"../chunk-0hy5dsbt.js";import{$b as I,Cb as g,Db as W,Eb as _,Fb as p,Gb as P,Hb as u,Ib as $,Jb as V,Kb as q,Lb as B,Mb as K,Qb as L,Rb as Q,Sb as T,Wb as U,Xb as y,Yb as F,Zb as C,_b as D,dc as b,gc as f,hc as k,ic as m}from"../chunk-yknc5rgh.js";import"../chunk-dav7mv8t.js";import"../chunk-gvr7cwxn.js";import"../chunk-8mpptpn5.js";import"../chunk-g7hz0dmk.js";import{Ne as h}from"../chunk-x185900b.js";import"../chunk-yahabnz4.js";import"../chunk-9kt24ctk.js";import{Mf as n,Nf as v,lh as w,ph as A,qf as d,rf as s,th as R}from"../chunk-73541m4t.js";import"../chunk-zm6b938z.js";import"../chunk-2kzysesp.js";import"../chunk-fqndtpwm.js";import"../chunk-h1wmpa03.js";import"../chunk-t6x1r5n6.js";import"../chunk-naj8bmj5.js";import"../chunk-np6vee9d.js";import{ek as M}from"../chunk-5exrgw07.js";import"../chunk-jssjfvsz.js";import"../chunk-a119av2z.js";import"../chunk-m3fbewhz.js";import"../chunk-x2dmgge8.js";import"../chunk-fs94x6ef.js";import"../chunk-8476xvk9.js";import"../chunk-kvtvx64t.js";import"../chunk-1xz206e1.js";import"../chunk-9jt5qj1b.js";import{nm as O,pm as J}from"../chunk-17ewxwga.js";import"../chunk-sv2mv2q2.js";import"../chunk-gt9ftnhn.js";import"../chunk-qvn0w2rt.js";import"../chunk-ka8dzc6q.js";import"../chunk-3y1h3ncf.js";import"../chunk-ts75gcfd.js";var N=[C,I,E,T,L,k,B,Q,D,y,_,U,f,V,F,H,b,K,q,m,$];class S{config={};providers=[];services=[];serviceInstances=[];serviceTokens=new Set;servicesBooted=!1;models=[];app=new J;boot(){if(this.models.length>0)l(...this.models);else a();this.app.config.merge(this.config),J.setInstance(this.app),this.app.registerMany([...N,...this.providers]),this.registerServices()}registerServices(){let j=this.serviceTokens;this.serviceInstances=[],this.serviceTokens=new Set,this.servicesBooted=!1;let X=new Map;for(let z of this.services){let G=typeof z==="function"?new z:z,x=G.constructor;if(!x.token)throw Error(`Service [${x.name}] is listed in \`services\` but does not declare a \`static token\`.`);let Y=X.get(x.token);if(Y)throw Error(`Services [${Y}] and [${x.name}] both declare the token "${x.token}". Tokens are the container's keys, so they must be unique.`);X.set(x.token,x.name);let Z=x;if(!j.has(x.token)&&this.app.bound(Z))throw Error(`Service [${x.name}] declares the token "${x.token}", which is already bound in the container by the framework or a provider. Binding it would replace that service everywhere, so pick a token nothing else owns.`);this.app.instance(Z,G),this.serviceInstances.push(G),this.serviceTokens.add(x.token)}this.app.setShutdownHooks(this.serviceInstances.map((z)=>({name:`${z.constructor.name}.onShutdown`,shutdown:(G)=>z.onShutdown(G)})))}async waitForBoot(){await this.app.boot(),await this.bootServices(),p(this.app)}async bootServices(){if(this.servicesBooted)return;for(let j of this.serviceInstances)await j.boot();this.servicesBooted=!0}shutdown(j){return this.run(()=>this.app.shutdown(j))}run(j){return O.run(this.app,j)}resolve(j){return this.app.make(j)}apiRoutes(){return this.app.make(A)}viewRoutes(){return this.app.make(w)}domains(){return this.app.make(R)}queue(){return this.app.make(h)}mcpHttp(){return this.app.config.get("route.mcp.remote.enabled")===!0?this.app.make(g):null}sockets(){return this.app.config.get("route.channels")?this.app.make(u):null}globalMiddleware(j){return P(j)}destroy(){if(this.app.resolved(W))this.app.make(W).stop();if(this.app.flush(),J.getInstance()===this.app)J.setInstance(void 0);O.disable()}}function a(){if(Bun.env.NODE_ENV==="production")return;let j=M();if(j.length===0)return;console.warn(`[gemi] ${j.length} model${j.length===1?" is":"s are"} registered, but Kernel.models is empty.
|
|
3
3
|
Nested relation reads resolve a model by name, so a policy on a subclass that does not own its
|
|
4
4
|
`+" name is skipped inside every include \u2014 scoped at the root, "+`unscoped in an include, with nothing
|
|
5
5
|
to notice it. Declaring the modules registers each class under its own name and audits the set:
|
package/dist/orm/index.js.map
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"import type { SqlDialect } from \"../dialect\";\nimport {\n InvalidArgumentError,\n UnknownRelationError,\n UnsupportedQueryError,\n} from \"../errors\";\nimport type { ModelSchema, RelationSchema } from \"../schema\";\nimport { COUNT_KEY, countableRelations } from \"../relation-filters\";\nimport { type Fragment, concat, sql } from \"./fragment\";\nimport { correlate } from \"./correlate\";\nimport { compileWhere } from \"./where\";\n\n/**\n * `include: { _count: { select: { accounts: true } } }` -> a correlated\n * `count(*)` in the select list.\n *\n * The last item iteration 3 listed as out of scope and never rescheduled. It is\n * the same machinery relation filters use — a correlated subquery over the child,\n * aliased so a self-relation cannot shadow the outer table — projected instead of\n * predicated:\n *\n * select …, (select count(*) from \"Account\" as \"_c0\"\n * where \"_c0\".\"userId\" = \"User\".\"id\") as \"_count.accounts\"\n *\n * One statement, no extra round trip, and no row multiplication: a `group by`\n * against a to-many would fold the parents together and a join would duplicate\n * them, which is the same reason relation filters are `exists` rather than joins.\n */\n\nexport interface CountPlan {\n /** The relation being counted, as the caller named it. */\n as: string;\n /** The projected column, aliased so `shape` can find it in the raw row. */\n column: Fragment;\n /** The alias, which is also the raw row's key. */\n alias: string;\n}\n\n/**\n * Reads `_count` out of an `include` or a `select`.\n *\n * Returns an empty list when there is none, which is the overwhelmingly common\n * case and costs one property read.\n */\nexport function planRelationCounts(\n schema: ModelSchema,\n args: any,\n dialect: SqlDialect,\n operation: string,\n): CountPlan[] {\n const container = args?.include ?? args?.select;\n if (typeof container !== \"object\" || container === null) return [];\n\n const node = container[COUNT_KEY];\n if (node === undefined || node === false) return [];\n\n const selection = readCountSelection(schema, node, operation);\n const plans: CountPlan[] = [];\n\n // Sorted for the reason every walk here is: the plan cache canonicalises key\n // order, so two argument objects differing only in key order are one entry and\n // must produce one statement.\n for (const key of Object.keys(selection).sort()) {\n const value = selection[key];\n if (value === undefined || value === false) continue;\n\n const relation = schema.relations[key];\n if (!relation) {\n throw new UnknownRelationError(\n key,\n schema.name,\n Object.keys(schema.relations),\n );\n }\n\n // A malformed operand is refused rather than counted, and the reason is the\n // policy walk rather than tidiness. `scopeCounts` reaches for `value.where`\n // through the same `typeof value !== \"object\"` test and `continue`s past\n // anything that fails it, so an operand like `1` or `\"true\"` carries no\n // scope — while `countPlan` reads `node?.where` as `undefined` and emits a\n // perfectly good unscoped `count(*)`. That is the one disagreement between\n // the two walks that this file's arrangement is supposed to make impossible,\n // and what it leaks is a number over rows the caller cannot read.\n //\n // Refused *here* rather than taught to `scopeCounts`, because this is where\n // the same malformation on a relation node is already refused — `include:\n // { accounts: 1 }` raises rather than compiling — which is what makes the\n // identical `continue` in `applyNestedPolicies` safe.\n if (value !== true && (typeof value !== \"object\" || Array.isArray(value))) {\n throw new InvalidArgumentError(\n `_count.select.${key}`,\n schema.name,\n operation,\n \"Expected true or an object holding 'where'.\",\n );\n }\n\n plans.push(\n countPlan(schema, relation, value, dialect, operation, plans.length, args),\n );\n }\n\n // A `_count` that names no relation it will actually count — `select: {}`, or\n // every relation switched off with a flag. Refused for the same mechanical\n // reason the `_count: true` shorthand is refused on a model with nothing to\n // count, and this is the other route to that state: `resolveSelection` counts\n // `_count` as *something selected*, so an empty plan list still clears its \"at\n // least one field\" check and then projects no columns, emitting\n // `select from \"User\"` for the driver to reject with a syntax error.\n //\n // Only under `select`. An `include` carries the model's default columns, so\n // the statement stays valid and a count of nothing is merely nothing.\n if (plans.length === 0 && args?.select) {\n throw new InvalidArgumentError(\n \"_count.select\",\n schema.name,\n operation,\n \"No relations to count, and '_count' is the only thing selected. \" +\n \"Name at least one relation, or select a column beside it.\",\n );\n }\n\n return plans;\n}\n\nfunction countPlan(\n schema: ModelSchema,\n relation: RelationSchema,\n node: unknown,\n dialect: SqlDialect,\n operation: string,\n index: number,\n args: any,\n): CountPlan {\n const path = `_count.select.${relation.name}`;\n\n if (relation.kind !== \"many\") {\n // Prisma only counts to-many relations, and the reason is that the answer is\n // 0 or 1 — which the relation's own nullability already says.\n throw new UnsupportedQueryError(\n path,\n schema.name,\n operation,\n `${relation.name} is a to-one relation. Counting it can only ever ` +\n `return 0 or 1, which is what its nullability already tells you.`,\n );\n }\n\n const source = correlate(\n schema,\n relation,\n dialect,\n `_c${index}`,\n `${dialect.quoteIdent(schema.table)}.`,\n operation,\n );\n\n const where = node === true ? undefined : (node as any)?.where;\n const container = args?.include !== undefined ? \"include\" : \"select\";\n const locate = (a: any) =>\n a?.[container]?.[COUNT_KEY]?.select?.[relation.name]?.where;\n\n const filter = compileWhere(\n source.child,\n where,\n { dialect, operation, qualifier: source.qualifier },\n locate,\n );\n\n const parts: Fragment[] = [\n sql(`(select count(*) from ${source.source} where ${source.correlation}`),\n ];\n if (filter) parts.push(sql(\" and \"), filter);\n // The alias carries a dot on purpose: it cannot collide with a column, since\n // an identifier that needs quoting to contain one could not have come from the\n // schema, and it keeps the raw row self-describing when a query is logged.\n parts.push(sql(`) as ${dialect.quoteIdent(`_count.${relation.name}`)}`));\n\n return {\n as: relation.name,\n alias: `_count.${relation.name}`,\n column: concat(...parts),\n };\n}\n\n/**\n * `_count: { select: { … } }`, or the `_count: true` shorthand expanded into it.\n *\n * The shorthand was refused until #394, and the refusal gave two reasons. The\n * first — \"it names no relation, so a policy has nowhere to attach\" — was about\n * *where* the expansion happens rather than whether it can: expanded here and\n * nowhere else, the policy walk would still see `true`, `scopeCounts` would\n * return it untouched, and every count would be unscoped. So `policy.ts` expands\n * it too, through the same `countableRelations`, and this stays the compiler's\n * own total-function copy for the same reason `include: { accounts: true }`\n * compiles when the compiler is called directly: scoping is `$exec`'s job,\n * uniformly, and the compiler compiles what it is handed.\n *\n * The second reason — what it returns changes when the schema grows a relation —\n * is true, and is Prisma's semantics rather than a defect this could fix. It is\n * documented at the shorthand in `docs/orm.md` instead of being answered with a\n * refusal.\n */\nfunction readCountSelection(\n schema: ModelSchema,\n node: unknown,\n operation: string,\n): Record<string, unknown> {\n if (node === true) {\n const countable = countableRelations(schema);\n\n // A model with nothing to count. Refused rather than answered with `{}`,\n // and not only for tidiness: `select: { _count: true }` alone would then\n // project no columns at all — `resolveSelection` counts `_count` as\n // something selected, so an empty expansion passes its \"at least one field\"\n // check and emits `select from \"User\"`, which is not valid SQL.\n if (countable.length === 0) {\n throw new UnsupportedQueryError(\n \"_count\",\n schema.name,\n operation,\n `${schema.name} has no to-many relations, so there is nothing for ` +\n `'_count: true' to count.`,\n );\n }\n\n return Object.fromEntries(countable.map((name) => [name, true]));\n }\n\n if (typeof node !== \"object\" || node === null || Array.isArray(node)) {\n throw new InvalidArgumentError(\n \"_count\",\n schema.name,\n operation,\n \"Expected an object holding 'select'.\",\n );\n }\n\n const selection = (node as Record<string, unknown>).select;\n if (\n typeof selection !== \"object\" ||\n selection === null ||\n Array.isArray(selection)\n ) {\n throw new InvalidArgumentError(\n \"_count.select\",\n schema.name,\n operation,\n \"Expected an object naming the relations to count.\",\n );\n }\n\n return selection as Record<string, unknown>;\n}\n\n",
|
|
16
16
|
"import type { SqlDialect } from \"../dialect\";\nimport {\n InvalidArgumentError,\n UnknownFieldError,\n UnsupportedQueryError,\n} from \"../errors\";\nimport type { QueryPlan } from \"../plan\";\nimport type { FieldSchema, ModelSchema, ScalarType } from \"../schema\";\nimport {\n type Fragment,\n bindValues,\n concat,\n joinFragments,\n render,\n sql,\n} from \"./fragment\";\nimport { compileOrderBy, parseOrderBy } from \"./orderBy\";\nimport { pagination } from \"./paginate\";\nimport { compileWhere } from \"./where\";\n\n/**\n * `aggregate`, and the `select` form of `count`.\n *\n * The fourteenth operation, and the first read whose result is neither rows nor\n * a bare number. Its shape is Prisma's, verified against a generated client\n * rather than inferred from the docs — every claim in this file's comments is a\n * line of that probe's output.\n *\n * ## Why it is not just `count` with more functions\n *\n * Three things differ, and each one is a place a plausible implementation is\n * wrong:\n *\n * 1. **`_count` has two shapes.** `_count: true` returns a *number*;\n * `_count: { _all: true, email: true }` returns an object, and a per-field\n * count is `count(\"email\")` — the number of rows where that column is **not\n * null**, which is a different number from `count(*)` and is the whole point\n * of asking per field.\n * 2. **The empty set is not zeroes.** `_count` over no rows is `0`, but `_sum`,\n * `_avg`, `_min` and `_max` are all `null` — per field, inside their objects.\n * An implementation that coalesced to `0` would be wrong in the direction\n * nobody checks.\n * 3. **The driver's types are not the column's types.** `sum(integer)` is\n * `bigint` in Postgres and `avg(integer)` is `numeric`, and Bun hands both\n * back as *strings*. So the coercion cannot be `dialect.decode(value, field)`\n * — that decodes a value of the column's type, and an aggregate is not one.\n * See `coerce` below, where each rule is a measurement.\n *\n * ## Pagination\n *\n * `take` / `skip` describe the rows being aggregated, not the one row the\n * aggregate produces — exactly as they do for `count`, and for the same reason:\n * `limit` beside an aggregate caps the result, which is always one row. So a\n * paginated aggregate wraps its row query in a subquery, the same shape\n * `compileRead` uses. Verified against Prisma: `take: 2` with\n * `orderBy: { globalRole: \"asc\" }` over rows 0, 5, 10 sums to 5, not 15.\n */\n\n/** The aggregate functions Prisma exposes, in the order it returns them. */\nexport const KINDS = [\"_count\", \"_avg\", \"_sum\", \"_min\", \"_max\"] as const;\nexport type Kind = (typeof KINDS)[number];\n\nconst AGGREGATE_ARGS = new Set<string>([\n \"where\",\n \"orderBy\",\n \"take\",\n \"skip\",\n ...KINDS,\n]);\n\n/**\n * `_sum` and `_avg` need arithmetic, so Prisma restricts them to these.\n *\n * `Decimal` is listed for completeness and cannot occur: `emit.ts` refuses a\n * Decimal field at generation time, so no generated schema has one.\n */\nconst NUMERIC = new Set<ScalarType>([\"Int\", \"Float\", \"BigInt\", \"Decimal\"]);\n\n/**\n * `_min` / `_max` need an ordering. `Json` has none in either dialect, and\n * `Bytes` orders bytewise in a way Prisma does not expose — both are refused\n * rather than emitted and left to disagree.\n */\nconst UNORDERABLE = new Set<ScalarType>([\"Json\", \"Bytes\"]);\n\n/** The SQL function each kind compiles to. */\nexport const FUNCTION: Record<Kind, string> = {\n _count: \"count\",\n _avg: \"avg\",\n _sum: \"sum\",\n _min: \"min\",\n _max: \"max\",\n};\n\nexport interface Term {\n kind: Kind;\n /** Absent for `_count`'s `_all`, which is `count(*)`. */\n field?: FieldSchema;\n /** The key this term is written to inside its kind's object. */\n as: string;\n /** The column alias it comes back under. Positional, so it cannot collide. */\n alias: string;\n}\n\nexport function isAggregateOperation(op: string): boolean {\n return op === \"aggregate\";\n}\n\n/**\n * `aggregate`, and `count({ select })` — which is the same statement with a\n * flatter result.\n *\n * Prisma's `count({ select: { _all: true, email: true } })` returns\n * `{ _all: 3, email: 2 }`: no `_count` wrapper, because the operation already\n * says what the numbers are. It was refused here until now as \"aggregate\n * territory\", which was the right call while there was no aggregate to put it\n * beside; the two decisions belong together and this is the together.\n *\n * **No `ExecOptions`**, unlike every neighbouring read, and that is deliberate\n * rather than an omission: `strategy` chooses how an include tree loads and an\n * aggregate has no relations, `track` records where a row came from so `save`\n * can update it and an aggregate returns no rows. Accepting either and ignoring\n * it would be worse than not accepting it.\n */\nexport function compileAggregate(\n schema: ModelSchema,\n op: string,\n args: any,\n dialect: SqlDialect,\n): QueryPlan {\n const flat = op === \"count\";\n assertArgs(schema, op, args, flat);\n\n const terms = flat\n ? countSelectTerms(schema, op, args?.select)\n : aggregateTerms(schema, op, args);\n\n if (terms.length === 0) {\n throw new UnsupportedQueryError(\n op,\n schema.name,\n op,\n flat\n ? `A 'select' on a count must name at least one field, or '_all'.`\n : `An aggregate needs at least one of ${KINDS.join(\", \")}. Prisma ` +\n `rejects an empty one too.`,\n );\n }\n\n const where = compileWhere(\n schema,\n args?.where,\n { dialect, operation: op },\n (a) => a?.where,\n );\n const whereClause = where ? concat(sql(\" where \"), where) : sql(\"\");\n const from = sql(` from ${dialect.quoteIdent(schema.table)}`);\n\n const projection = joinFragments(\n terms.map((term) =>\n sql(\n `${FUNCTION[term.kind]}(${\n term.field ? dialect.quoteIdent(term.field.column) : \"*\"\n }) as ${dialect.quoteIdent(term.alias)}`,\n ),\n ),\n \", \",\n );\n\n // Parsed unconditionally, so that validation does not depend on whether a\n // *different* argument was also supplied — the same rule `count` follows.\n const parsed = parseOrderBy(schema, args?.orderBy, op, {\n dialect,\n locate: (a: any) => a?.orderBy,\n });\n const paginating = args?.take !== undefined || args?.skip !== undefined;\n\n let statement: Fragment;\n\n if (!paginating) {\n statement = concat(sql(\"select \"), projection, from, whereClause);\n } else {\n const { clause, terms: order } = pagination(\n schema,\n op,\n args,\n dialect,\n parsed,\n );\n const ordering = compileOrderBy(order, dialect);\n\n // The subquery selects every column an aggregate names — an `order by` may\n // reference columns beyond them, which is fine, since it is resolved\n // against the table rather than against the select list.\n //\n // With only `count(*)` there is no such column, so it selects the primary\n // key: the narrowest thing that keeps a row identity, which is what\n // `compileRead`'s paginated count does for the same reason.\n const columns = new Map<string, string>();\n for (const term of terms) {\n if (term.field) columns.set(term.field.column, term.field.column);\n }\n if (columns.size === 0) {\n const key = schema.primaryKey[0] ?? Object.keys(schema.fields)[0];\n const column = schema.fields[key]?.column ?? key;\n columns.set(column, column);\n }\n\n statement = concat(\n sql(\"select \"),\n projection,\n sql(\n ` from (select ${[...columns.values()]\n .map((column) => dialect.quoteIdent(column))\n .join(\", \")}`,\n ),\n from,\n whereClause,\n ordering ? concat(sql(\" order by \"), ordering) : sql(\"\"),\n clause,\n sql(`) as ${dialect.quoteIdent(\"sub\")}`),\n );\n }\n\n const { text, binders } = render(statement, dialect, {\n model: schema.name,\n operation: op,\n });\n\n return {\n text,\n bind: bindValues(binders),\n shape(rows) {\n const row = (rows as Record<string, unknown>[])[0] ?? {};\n\n if (flat) {\n const out: Record<string, unknown> = {};\n for (const term of terms)\n out[term.as] = coerce(term, row[term.alias], dialect);\n return out;\n }\n\n const out: Record<string, unknown> = {};\n for (const term of terms) {\n // `_count: true` is a number rather than an object, and it is the only\n // aggregate that can be either.\n if (term.kind === \"_count\" && term.as === BARE) {\n out._count = coerce(term, row[term.alias], dialect);\n continue;\n }\n const bucket = (out[term.kind] ??= {}) as Record<string, unknown>;\n bucket[term.as] = coerce(term, row[term.alias], dialect);\n }\n return out;\n },\n };\n}\n\n/** The `as` a bare `_count: true` carries, which no field name can be. */\nexport const BARE = \"\";\n\nexport function aggregateTerms(\n schema: ModelSchema,\n op: string,\n args: any,\n): Term[] {\n const terms: Term[] = [];\n\n for (const kind of KINDS) {\n const requested = args?.[kind];\n if (requested === undefined || requested === false) continue;\n\n if (kind === \"_count\" && requested === true) {\n terms.push({ kind, as: BARE, alias: alias(kind, terms.length) });\n continue;\n }\n\n if (\n typeof requested !== \"object\" ||\n requested === null ||\n Array.isArray(requested)\n ) {\n throw new InvalidArgumentError(\n kind,\n schema.name,\n op,\n kind === \"_count\"\n ? `Expected true or an object of fields.`\n : `Expected an object of fields.`,\n );\n }\n\n for (const key of Object.keys(requested).sort()) {\n const wanted = (requested as Record<string, unknown>)[key];\n if (wanted === undefined || wanted === false) continue;\n\n if (kind === \"_count\" && key === \"_all\") {\n terms.push({ kind, as: \"_all\", alias: alias(kind, terms.length) });\n continue;\n }\n\n const field = resolveField(schema, op, kind, key);\n assertAggregable(schema, op, kind, field);\n terms.push({ kind, field, as: key, alias: alias(kind, terms.length) });\n }\n }\n\n return terms;\n}\n\n/** `count({ select: { _all: true, email: true } })` — every term a `count`. */\nfunction countSelectTerms(\n schema: ModelSchema,\n op: string,\n select: any,\n): Term[] {\n if (typeof select !== \"object\" || select === null || Array.isArray(select)) {\n throw new InvalidArgumentError(\n \"select\",\n schema.name,\n op,\n `Expected an object of fields.`,\n );\n }\n\n const terms: Term[] = [];\n for (const key of Object.keys(select).sort()) {\n const wanted = select[key];\n if (wanted === undefined || wanted === false) continue;\n\n if (key === \"_all\") {\n terms.push({\n kind: \"_count\",\n as: \"_all\",\n alias: alias(\"_count\", terms.length),\n });\n continue;\n }\n\n const field = resolveField(schema, op, \"_count\", key);\n terms.push({\n kind: \"_count\",\n field,\n as: key,\n alias: alias(\"_count\", terms.length),\n });\n }\n return terms;\n}\n\n/**\n * Positional, so two terms can never collide however the model is named — a\n * field called `_all` would otherwise produce the same alias as `_count`'s own.\n * The kind stays in the name because a query log is read by a person.\n */\nconst alias = (kind: Kind, index: number) => `${kind}_${index}`;\n\nexport function resolveField(\n schema: ModelSchema,\n op: string,\n kind: Kind,\n name: string,\n): FieldSchema {\n const field = schema.fields[name];\n if (!field) {\n // A relation named here is a plausible mistake with an unhelpful default\n // message, so it gets its own.\n if (name in schema.relations) {\n throw new UnsupportedQueryError(\n `${kind}.${name}`,\n schema.name,\n op,\n `'${name}' is a relation. Aggregate its own model instead, or use ` +\n `'_count' inside an 'include' to count it per row.`,\n );\n }\n throw new UnknownFieldError(name, schema.name, Object.keys(schema.fields));\n }\n return field;\n}\n\nexport function assertAggregable(\n schema: ModelSchema,\n op: string,\n kind: Kind,\n field: FieldSchema,\n): void {\n if ((kind === \"_sum\" || kind === \"_avg\") && !NUMERIC.has(field.type)) {\n throw new UnsupportedQueryError(\n `${kind}.${field.name}`,\n schema.name,\n op,\n `'${field.name}' is a ${field.type}, and ${kind} needs a number. ` +\n `Prisma does not offer it on this field either.`,\n );\n }\n\n if ((kind === \"_min\" || kind === \"_max\") && UNORDERABLE.has(field.type)) {\n throw new UnsupportedQueryError(\n `${kind}.${field.name}`,\n schema.name,\n op,\n `'${field.name}' is a ${field.type}, which has no ordering the two ` +\n `dialects agree on.`,\n );\n }\n}\n\n/**\n * The driver's value for one aggregate, as the value Prisma returns.\n *\n * **Every line here is a measurement**, taken through Bun against Postgres 16\n * and SQLite, because the obvious rule — \"decode it as the column's type\" — is\n * wrong for three of the five kinds. What Postgres returns:\n *\n * count(*) \"2\" string\n * count(text) \"2\" string\n * sum(integer) \"4\" string <- bigint\n * sum(bigint) \"9007199254740995\" string\n * sum(double) 4 number\n * avg(integer) \"2.0000000000000000\" string <- numeric\n * avg(double) 2 number\n * min(integer) 1 number\n * max(text) \"b\" string\n * min(timestamp) Date object\n * max(bigint) \"9007199254740993\" string\n *\n * ...and over an empty set every one of them is `null` except the counts, which\n * are `\"0\"`.\n *\n * So:\n *\n * - **`_count` is always a number**, and always present. `Number(\"0\")` rather\n * than a coalesce, because the driver gives a string and `?? 0` would leave it\n * one.\n * - **`_avg` is always a number**, whatever the column is — Prisma returns a\n * float for the average of an `Int`, and Postgres hands back `numeric` text.\n * - **`_sum` keeps the column's type**, so it is the one kind where a `BigInt`\n * column matters: `sum(bigint)` crosses as an exact string, and `Number()` on\n * 9007199254740995 would silently drop the low bits. Same trap the lateral\n * strategy's `::text` cast exists for.\n * - **`_min` / `_max` are values of the column**, so here — and only here — the\n * dialect's own `decode` is exactly right. It is what turns SQLite's integer\n * milliseconds back into a `Date`.\n */\nexport function coerce(\n term: Term,\n value: unknown,\n dialect: SqlDialect,\n): unknown {\n if (term.kind === \"_count\") return Number(value ?? 0);\n\n // Every other aggregate is null over an empty set, and per field.\n if (value === null || value === undefined) return null;\n\n if (term.kind === \"_avg\") return Number(value);\n\n if (term.kind === \"_sum\") {\n const type = term.field?.type;\n if (type === \"BigInt\") return BigInt(String(value));\n // `Decimal` is **unreachable**, not merely untested: `emit.ts`'s\n // `UNSUPPORTED_SCALARS` refuses a Decimal field at generation time, so no\n // generated schema can carry one and neither this branch nor `Decimal`'s\n // membership of `NUMERIC` can be entered.\n //\n // Kept, and kept as a pass-through, because the day Decimal becomes\n // supported is the day this needs a real decision — Postgres returns\n // `sum(numeric)` as text, and whether that becomes a `Prisma.Decimal`, a\n // string or a number is the same question the generator declined to answer.\n // Silently `Number()`-ing it would answer it wrongly and lose exactly the\n // precision the type exists to keep.\n if (type === \"Decimal\") return value;\n return Number(value);\n }\n\n // `_min` / `_max` are values *of the column*, so here — and only here — the\n // dialect's own `decode` is exactly right. It is what turns SQLite's integer\n // milliseconds back into a `Date`, and Postgres's `bigint` text into a\n // `BigInt`. Without it a `_max: { createdAt: true }` comes back as\n // 1600000004000 where Prisma returns a `Date`, on SQLite only — which is the\n // shape of every bug this file's coercion table exists to prevent.\n return term.field ? dialect.decode(value, term.field) : value;\n}\n\nfunction assertArgs(\n schema: ModelSchema,\n op: string,\n args: any,\n flat: boolean,\n): void {\n if (args === undefined || args === null) {\n if (flat) return;\n throw new UnsupportedQueryError(\n op,\n schema.name,\n op,\n `An aggregate needs at least one of ${KINDS.join(\", \")}.`,\n );\n }\n\n if (typeof args !== \"object\" || Array.isArray(args)) {\n throw new InvalidArgumentError(\n String(args),\n schema.name,\n op,\n \"Expected an object.\",\n );\n }\n\n if (flat) return;\n\n for (const key of Object.keys(args).sort()) {\n if (args[key] === undefined) continue;\n if (AGGREGATE_ARGS.has(key)) continue;\n\n // `select` and `include` are the two a caller reaches for by habit, and\n // neither means anything here: an aggregate's shape is decided entirely by\n // which functions were asked for.\n if (key === \"select\" || key === \"include\") {\n throw new UnsupportedQueryError(\n key,\n schema.name,\n op,\n `An aggregate returns the functions it was given, so there is nothing ` +\n `to ${key === \"select\" ? \"select\" : \"include\"}. Prisma does not ` +\n `accept it either.`,\n );\n }\n\n throw new UnsupportedQueryError(\n key,\n schema.name,\n op,\n `${op} takes ${[...AGGREGATE_ARGS].sort().join(\", \")}.`,\n );\n }\n}\n",
|
|
17
17
|
"import { InvalidArgumentError } from \"../errors\";\nimport type { RowLockMode } from \"../types\";\n\n/**\n * A read's `lock` argument, validated and normalised: one strength and one\n * answer to \"what if another transaction holds the row\".\n *\n * The dialect turns this into SQL (`SqlDialect.rowLock`); the compiler never\n * spells a lock clause itself.\n */\nexport interface RowLockClause {\n mode: RowLockMode;\n /** `wait` blocks, `skipLocked` leaves the row out, `noWait` fails at once. */\n onLocked: \"wait\" | \"skipLocked\" | \"noWait\";\n}\n\nconst MODES = new Set<string>([\"update\", \"share\"]);\nconst OBJECT_KEYS = new Set([\"mode\", \"skipLocked\", \"noWait\"]);\n\nconst EXPECTED =\n `Expected \"update\", \"share\", or { mode: \"update\" | \"share\", ` +\n `skipLocked?: boolean, noWait?: boolean }.`;\n\n/**\n * Validates `lock` and returns what it asks for, or `undefined` for no lock.\n *\n * Strict for the reason every argument here is: a lock that is silently not\n * taken is a race that reads as fixed. So an unknown key, a misspelt mode or\n * both `skipLocked` and `noWait` at once raise rather than degrade to a plain\n * read.\n */\nexport function parseRowLock(\n lock: unknown,\n model: string,\n operation: string,\n): RowLockClause | undefined {\n if (lock === undefined) return undefined;\n\n if (typeof lock === \"string\") {\n if (MODES.has(lock)) {\n return { mode: lock as RowLockMode, onLocked: \"wait\" };\n }\n throw new InvalidArgumentError(\"lock\", model, operation, EXPECTED);\n }\n\n if (lock === null || typeof lock !== \"object\" || Array.isArray(lock)) {\n throw new InvalidArgumentError(\"lock\", model, operation, EXPECTED);\n }\n\n const record = lock as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (!OBJECT_KEYS.has(key)) {\n throw new InvalidArgumentError(\n `lock.${key}`,\n model,\n operation,\n `A lock takes mode, skipLocked and noWait.`,\n );\n }\n }\n\n if (typeof record.mode !== \"string\" || !MODES.has(record.mode)) {\n throw new InvalidArgumentError(\"lock.mode\", model, operation, EXPECTED);\n }\n\n for (const key of [\"skipLocked\", \"noWait\"] as const) {\n if (record[key] !== undefined && typeof record[key] !== \"boolean\") {\n throw new InvalidArgumentError(\n `lock.${key}`,\n model,\n operation,\n `Expected a boolean.`,\n );\n }\n }\n\n if (record.skipLocked === true && record.noWait === true) {\n throw new InvalidArgumentError(\n \"lock\",\n model,\n operation,\n `'skipLocked' and 'noWait' cannot both be set: a row another ` +\n `transaction holds is either left out of the result or fails the ` +\n `statement, not both.`,\n );\n }\n\n return {\n mode: record.mode as RowLockMode,\n onLocked:\n record.skipLocked === true\n ? \"skipLocked\"\n : record.noWait === true\n ? \"noWait\"\n : \"wait\",\n };\n}\n",
|
|
18
|
-
"import type { SqlDialect } from \"../dialect\";\nimport {\n InvalidArgumentError,\n UnsupportedByDesignError,\n UnsupportedQueryError,\n} from \"../errors\";\nimport type { Operation, QueryPlan } from \"../plan\";\nimport type { ModelSchema } from \"../schema\";\nimport { buildRowShaper } from \"../shape\";\nimport {\n type Fragment,\n bindValues,\n concat,\n joinFragments,\n render,\n sql,\n} from \"./fragment\";\nimport { compileOrderBy, parseOrderBy } from \"./orderBy\";\nimport {\n planRelations,\n strategiesOf,\n type RelationStrategy,\n} from \"./plan-relations\";\nimport { planRelationCounts } from \"./relation-count\";\nimport { resolveSelection, withKeyFields } from \"./select\";\nimport { assertUniqueWhere } from \"./unique\";\nimport { compileAggregate } from \"./aggregate\";\nimport { parseRowLock } from \"./lock\";\nimport { pagination } from \"./paginate\";\nimport { compileWhere } from \"./where\";\n\n/** Every read operation, and what each accepts. */\n//\n// `lock` is gemi's, not Prisma's: Prisma has no row locks, which is why folio\n// grew raw `select … for update` statements with hand-written row types (#627).\n// It changes only the statement's tail, so every other argument keeps its\n// Prisma meaning. See `compile/lock.ts`.\nexport const READ_ARGS: Record<string, Set<string>> = {\n findMany: new Set([\n \"where\",\n \"orderBy\",\n \"skip\",\n \"take\",\n \"select\",\n \"include\",\n \"omit\",\n \"lock\",\n ]),\n findFirst: new Set([\n \"where\",\n \"orderBy\",\n \"skip\",\n \"take\",\n \"select\",\n \"include\",\n \"omit\",\n \"lock\",\n ]),\n findFirstOrThrow: new Set([\n \"where\",\n \"orderBy\",\n \"skip\",\n \"take\",\n \"select\",\n \"include\",\n \"omit\",\n \"lock\",\n ]),\n findUnique: new Set([\"where\", \"select\", \"include\", \"omit\", \"lock\"]),\n findUniqueOrThrow: new Set([\"where\", \"select\", \"include\", \"omit\", \"lock\"]),\n // `select` on a count returns an object of per-field counts rather than a\n // number — `{ _all: 3, email: 2 }`. It was refused here while there was no\n // aggregate to put it beside; now there is, and `compileAggregate` owns it,\n // so this only has to let it through. No `omit`: it is `select`'s complement\n // over a *row*, and a count returns counts rather than rows.\n count: new Set([\"where\", \"orderBy\", \"skip\", \"take\", \"select\"]),\n};\n\n/**\n * The two read arguments that are **not coming**, and what to reach for.\n *\n * Both are decisions rather than gaps, and both were made against measurements\n * of what Prisma actually does rather than against its documentation.\n *\n * `docs/orm.md` says the same. An argument that says \"yet\" while the docs say\n * \"not in scope\" is the contradiction #68 exists to end — a caller cannot plan\n * around a refusal that might lift next release.\n */\nconst PERMANENTLY_REFUSED: Record<string, string> = {\n distinct:\n `Prisma's 'distinct' is applied **in memory**, not in SQL — its query log ` +\n `shows no DISTINCT at all, and 'take' therefore does not reduce the rows ` +\n `pulled or paginate by group. Reproducing that faithfully would mean ` +\n `reading the whole result set and deduplicating in JavaScript behind an ` +\n `argument that reads like a database operation. Implementing it as a real ` +\n `'DISTINCT ON' instead would be a silent divergence from Prisma. Write it ` +\n `as SQL instead, with 'sql' and 'DB.query' — where what runs is what you ` +\n `wrote, and 'distinct on' means what the database means by it.`,\n cursor:\n `'cursor' is only correct under a *total* ordering, which Prisma does not ` +\n `enforce — under a non-unique 'orderBy' it silently skips or repeats rows ` +\n `at the page boundary. For a stable page use 'take' with a 'where' on the ` +\n `last row's sort key, or compose the keyset comparison with 'sql' and ` +\n `'DB.query'.`,\n};\n\nexport function isReadOperation(op: Operation): boolean {\n return op in READ_ARGS;\n}\n\n/** The single-row operations, which pin `take` to 1 regardless of the args. */\nconst SINGLE_ROW = new Set([\n \"findFirst\",\n \"findFirstOrThrow\",\n \"findUnique\",\n \"findUniqueOrThrow\",\n]);\n\nexport function compileRead(\n schema: ModelSchema,\n op: Operation,\n args: any,\n dialect: SqlDialect,\n /**\n * Which relation strategy plans this query's include tree.\n *\n * Defaults to batched, which is what every caller passes today. Threaded rather\n * than resolved here because the compiler must not *choose* — selection depends\n * on the dialect and the tree, and iteration 9 deliverable 6 owns the rule.\n * Passing it keeps `compileRead` a pure function of its arguments, which is\n * also what lets a test drive it with a fake.\n */\n strategy?: RelationStrategy,\n): QueryPlan {\n assertArgs(schema, op, args);\n\n // A count with a `select` is an aggregate wearing a count's name: same\n // statement, flatter result. Routed rather than reimplemented, so the two\n // cannot disagree about what a per-field count means (rows where the column\n // is not null).\n if (op === \"count\" && args?.select !== undefined && args.select !== null) {\n return compileAggregate(schema, op, args, dialect);\n }\n\n // Relations are planned *before* the `where` is compiled, because whether any\n // strategy folds children into the root statement decides whether the root's\n // columns need qualifying — a lateral subquery puts a second table in scope and\n // a bare `\"id\"` becomes ambiguous. `count` never has relations, so it keeps the\n // unplanned path and pays nothing.\n const relations =\n op === \"count\"\n ? {\n plans: [] as ReturnType<typeof planRelations>[\"plans\"],\n keyFields: [],\n }\n : planRelations(schema, args, dialect, op, strategy);\n\n const folded = relations.plans.some((plan) => plan.root !== undefined);\n // The table's own name, not an invented alias: Postgres lets a lateral subquery\n // reference the outer table by name, so nothing has to be introduced into the\n // `from` clause. Undefined when nothing folds, which is what keeps existing\n // queries byte-identical.\n const qualifier = folded ? `${dialect.quoteIdent(schema.table)}.` : undefined;\n\n const context = { dialect, operation: op, qualifier };\n const where = compileWhere(schema, args?.where, context, (a) => a?.where);\n\n if (op === \"findUnique\" || op === \"findUniqueOrThrow\") {\n assertUniqueWhere(schema, args?.where, op);\n }\n\n const from = sql(` from ${dialect.quoteIdent(schema.table)}`);\n const whereClause = where ? concat(sql(\" where \"), where) : sql(\"\");\n\n // `count` needs no selection and no shaper, but `skip` / `take` still apply —\n // and they apply to the rows being counted, not to the single row the count\n // returns. Appending `limit` to the aggregate would cap the *result*, which\n // is always one row, and quietly report the unpaginated total. So when the\n // query paginates, the row query is wrapped in a subquery exactly the way\n // Prisma does it.\n if (op === \"count\") {\n const counted = sql(`select count(*) as ${dialect.quoteIdent(\"_count\")}`);\n const paginated = args?.take !== undefined || args?.skip !== undefined;\n\n // Parsed unconditionally, even though an unpaginated count discards the\n // terms: validation must not depend on whether a *different* argument was\n // also supplied, or `orderBy: { nonexistent: \"asc\" }` is an error with a\n // `take` and silently fine without one.\n const parsed = parseOrderBy(schema, args?.orderBy, op, {\n dialect,\n locate: (a: any) => a?.orderBy,\n });\n\n let statement: Fragment;\n if (!paginated) {\n statement = concat(counted, from, whereClause);\n } else {\n const { clause, terms } = pagination(\n schema,\n op,\n args,\n dialect,\n parsed,\n SINGLE_ROW.has(op),\n );\n const order = compileOrderBy(terms, dialect);\n // One column, not `*`: the subquery exists to be counted, so the narrowest\n // thing that keeps a row identity is right.\n const key = schema.primaryKey[0] ?? Object.keys(schema.fields)[0];\n statement = concat(\n counted,\n sql(` from (select ${dialect.quoteIdent(schema.fields[key].column)}`),\n from,\n whereClause,\n order ? concat(sql(\" order by \"), order) : sql(\"\"),\n clause,\n sql(`) as ${dialect.quoteIdent(\"sub\")}`),\n );\n }\n\n const { text, binders } = render(statement, dialect, {\n model: schema.name,\n operation: op,\n });\n return {\n text,\n bind: bindValues(binders),\n shape(rows) {\n const row = (rows as Record<string, unknown>[])[0];\n return Number(row?._count ?? 0);\n },\n };\n }\n\n const selection = resolveSelection(schema, args, op);\n const { plans, keyFields } = relations;\n const { fields, hidden } = withKeyFields(schema, selection, keyFields);\n\n // A folded relation's column comes from the strategy, appended after the\n // scalars so the shaped key order still matches schema order followed by\n // relations — which is what `buildRowShaper` produces and what the differential\n // harness compares.\n const contributed = plans.filter((plan) => plan.root !== undefined);\n\n // `_count` projects a correlated subquery per relation. It goes last for the\n // same reason a folded relation's column does: the shaper reads scalars by\n // position, and `_count` is attached afterwards from the raw row.\n const counts = planRelationCounts(schema, args, dialect, op);\n\n const columns = joinFragments(\n [\n ...fields.map((field) =>\n sql(`${qualifier ?? \"\"}${dialect.quoteIdent(field.column)}`),\n ),\n ...contributed.map((plan) => plan.root!.column),\n ...counts.map((count) => count.column),\n ],\n \", \",\n );\n\n const joins = concat(...contributed.map((plan) => plan.root!.join));\n\n const {\n clause: paginationClause,\n terms,\n reversed,\n } = pagination(\n schema,\n op,\n args,\n dialect,\n parseOrderBy(schema, args?.orderBy, op, {\n dialect,\n locate: (a: any) => a?.orderBy,\n }),\n SINGLE_ROW.has(op),\n );\n const order = compileOrderBy(terms, dialect, qualifier);\n\n // Last, after `limit`/`offset`, where Postgres requires it. Only the root\n // table is named, so a folded include's lateral subquery is not locked (and\n // could not be); a batched include's child queries carry no lock at all.\n const lock = parseRowLock(args?.lock, schema.name, op);\n\n const statement = concat(\n sql(\"select \"),\n columns,\n from,\n joins,\n whereClause,\n order ? concat(sql(\" order by \"), order) : sql(\"\"),\n paginationClause,\n lock ? dialect.rowLock(lock, schema.table) : sql(\"\"),\n );\n\n const { text, binders } = render(statement, dialect, {\n model: schema.name,\n operation: op,\n });\n const shaper = buildRowShaper(\n fields,\n dialect,\n plans.map((plan) => ({ key: plan.as, kind: plan.kind })),\n );\n const single = SINGLE_ROW.has(op);\n\n return {\n text,\n bind: bindValues(binders),\n relations: plans.length > 0 ? plans : undefined,\n strategies: plans.length > 0 ? strategiesOf(plans) : undefined,\n hidden,\n shape(rows) {\n const shaped = shaper(rows);\n\n // A folded relation's children arrived *in the row*, under the alias the\n // strategy chose. The shaper wrote the empty placeholder (`[]` / `null`)\n // because it knows nothing about strategies, so the decode replaces it.\n //\n // Per-row rather than once, and per-relation rather than in the shaper,\n // because `decode` is the strategy's — `json_agg` returns text, so this is\n // where dates stop being strings and an empty to-many becomes `[]`.\n // `_count` arrived as extra columns the shaper does not know about, under\n // aliases carrying a dot. Assembled into one object per row, because that\n // is the shape Prisma returns and the differential harness compares.\n if (counts.length > 0) {\n for (let i = 0; i < shaped.length; i++) {\n const raw = (rows[i] as Record<string, unknown>) ?? {};\n const totals: Record<string, number> = {};\n for (const count of counts) {\n totals[count.as] = Number(raw[count.alias] ?? 0);\n }\n shaped[i]._count = totals;\n }\n }\n\n if (contributed.length > 0) {\n for (let i = 0; i < shaped.length; i++) {\n const row = shaped[i];\n const raw = (rows[i] as Record<string, unknown>) ?? {};\n for (const plan of contributed) {\n row[plan.as] = plan.root!.decode(raw[plan.as]);\n }\n }\n }\n\n // A negative `take` means \"the last N\". The ordering terms were flipped\n // so the database returns the right *rows*, but the caller asked for them\n // in the order their `orderBy` describes — so the page is flipped back\n // here. Verified against Prisma: `take: -3, orderBy: { id: \"asc\" }`\n // returns c, d, e, not e, d, c.\n if (reversed) shaped.reverse();\n // Prisma returns the row or `null`, not a one-element array. The\n // *OrThrow* variants turn that `null` into an error in `Model.$exec`,\n // where the model's name is in scope for the message.\n return single ? (shaped[0] ?? null) : shaped;\n },\n };\n}\n\nfunction assertArgs(schema: ModelSchema, op: Operation, args: any): void {\n if (args === undefined || args === null) return;\n\n if (typeof args !== \"object\" || Array.isArray(args)) {\n throw new InvalidArgumentError(\n String(args),\n schema.name,\n op,\n \"Expected an object.\",\n );\n }\n\n // Checked before the per-key loop, so that passing both reports the thing\n // that is actually wrong rather than stopping at `include`.\n if (args.select !== undefined && args.include !== undefined) {\n throw new UnsupportedQueryError(\n \"select + include\",\n schema.name,\n op,\n \"Prisma allows only one of them on the same query.\",\n );\n }\n\n const allowed = READ_ARGS[op];\n for (const key of Object.keys(args).sort()) {\n if (args[key] === undefined) continue;\n if (allowed.has(key)) continue;\n\n const permanent = PERMANENTLY_REFUSED[key];\n if (permanent) {\n throw new UnsupportedByDesignError(key, schema.name, op, permanent);\n }\n\n throw new UnsupportedQueryError(\n key,\n schema.name,\n op,\n `${op} takes ${[...allowed].sort().join(\", \")}.`,\n );\n }\n}\n",
|
|
18
|
+
"import type { SqlDialect } from \"../dialect\";\nimport {\n InvalidArgumentError,\n UnsupportedByDesignError,\n UnsupportedQueryError,\n} from \"../errors\";\nimport type { Operation, QueryPlan } from \"../plan\";\nimport type { ModelSchema } from \"../schema\";\nimport { buildRowShaper } from \"../shape\";\nimport {\n type Fragment,\n bindValues,\n concat,\n joinFragments,\n render,\n sql,\n} from \"./fragment\";\nimport { compileOrderBy, parseOrderBy } from \"./orderBy\";\nimport {\n planRelations,\n strategiesOf,\n type RelationStrategy,\n} from \"./plan-relations\";\nimport { planRelationCounts } from \"./relation-count\";\nimport { resolveSelection, withKeyFields } from \"./select\";\nimport { assertUniqueWhere } from \"./unique\";\nimport { compileAggregate } from \"./aggregate\";\nimport { parseRowLock } from \"./lock\";\nimport { pagination } from \"./paginate\";\nimport { compileWhere } from \"./where\";\n\n/** Every read operation, and what each accepts. */\n//\n// `lock` is gemi's, not Prisma's: Prisma has no row locks, which is why an app\n// grew raw `select … for update` statements with hand-written row types (#627).\n// It changes only the statement's tail, so every other argument keeps its\n// Prisma meaning. See `compile/lock.ts`.\nexport const READ_ARGS: Record<string, Set<string>> = {\n findMany: new Set([\n \"where\",\n \"orderBy\",\n \"skip\",\n \"take\",\n \"select\",\n \"include\",\n \"omit\",\n \"lock\",\n ]),\n findFirst: new Set([\n \"where\",\n \"orderBy\",\n \"skip\",\n \"take\",\n \"select\",\n \"include\",\n \"omit\",\n \"lock\",\n ]),\n findFirstOrThrow: new Set([\n \"where\",\n \"orderBy\",\n \"skip\",\n \"take\",\n \"select\",\n \"include\",\n \"omit\",\n \"lock\",\n ]),\n findUnique: new Set([\"where\", \"select\", \"include\", \"omit\", \"lock\"]),\n findUniqueOrThrow: new Set([\"where\", \"select\", \"include\", \"omit\", \"lock\"]),\n // `select` on a count returns an object of per-field counts rather than a\n // number — `{ _all: 3, email: 2 }`. It was refused here while there was no\n // aggregate to put it beside; now there is, and `compileAggregate` owns it,\n // so this only has to let it through. No `omit`: it is `select`'s complement\n // over a *row*, and a count returns counts rather than rows.\n count: new Set([\"where\", \"orderBy\", \"skip\", \"take\", \"select\"]),\n};\n\n/**\n * The two read arguments that are **not coming**, and what to reach for.\n *\n * Both are decisions rather than gaps, and both were made against measurements\n * of what Prisma actually does rather than against its documentation.\n *\n * `docs/orm.md` says the same. An argument that says \"yet\" while the docs say\n * \"not in scope\" is the contradiction #68 exists to end — a caller cannot plan\n * around a refusal that might lift next release.\n */\nconst PERMANENTLY_REFUSED: Record<string, string> = {\n distinct:\n `Prisma's 'distinct' is applied **in memory**, not in SQL — its query log ` +\n `shows no DISTINCT at all, and 'take' therefore does not reduce the rows ` +\n `pulled or paginate by group. Reproducing that faithfully would mean ` +\n `reading the whole result set and deduplicating in JavaScript behind an ` +\n `argument that reads like a database operation. Implementing it as a real ` +\n `'DISTINCT ON' instead would be a silent divergence from Prisma. Write it ` +\n `as SQL instead, with 'sql' and 'DB.query' — where what runs is what you ` +\n `wrote, and 'distinct on' means what the database means by it.`,\n cursor:\n `'cursor' is only correct under a *total* ordering, which Prisma does not ` +\n `enforce — under a non-unique 'orderBy' it silently skips or repeats rows ` +\n `at the page boundary. For a stable page use 'take' with a 'where' on the ` +\n `last row's sort key, or compose the keyset comparison with 'sql' and ` +\n `'DB.query'.`,\n};\n\nexport function isReadOperation(op: Operation): boolean {\n return op in READ_ARGS;\n}\n\n/** The single-row operations, which pin `take` to 1 regardless of the args. */\nconst SINGLE_ROW = new Set([\n \"findFirst\",\n \"findFirstOrThrow\",\n \"findUnique\",\n \"findUniqueOrThrow\",\n]);\n\nexport function compileRead(\n schema: ModelSchema,\n op: Operation,\n args: any,\n dialect: SqlDialect,\n /**\n * Which relation strategy plans this query's include tree.\n *\n * Defaults to batched, which is what every caller passes today. Threaded rather\n * than resolved here because the compiler must not *choose* — selection depends\n * on the dialect and the tree, and iteration 9 deliverable 6 owns the rule.\n * Passing it keeps `compileRead` a pure function of its arguments, which is\n * also what lets a test drive it with a fake.\n */\n strategy?: RelationStrategy,\n): QueryPlan {\n assertArgs(schema, op, args);\n\n // A count with a `select` is an aggregate wearing a count's name: same\n // statement, flatter result. Routed rather than reimplemented, so the two\n // cannot disagree about what a per-field count means (rows where the column\n // is not null).\n if (op === \"count\" && args?.select !== undefined && args.select !== null) {\n return compileAggregate(schema, op, args, dialect);\n }\n\n // Relations are planned *before* the `where` is compiled, because whether any\n // strategy folds children into the root statement decides whether the root's\n // columns need qualifying — a lateral subquery puts a second table in scope and\n // a bare `\"id\"` becomes ambiguous. `count` never has relations, so it keeps the\n // unplanned path and pays nothing.\n const relations =\n op === \"count\"\n ? {\n plans: [] as ReturnType<typeof planRelations>[\"plans\"],\n keyFields: [],\n }\n : planRelations(schema, args, dialect, op, strategy);\n\n const folded = relations.plans.some((plan) => plan.root !== undefined);\n // The table's own name, not an invented alias: Postgres lets a lateral subquery\n // reference the outer table by name, so nothing has to be introduced into the\n // `from` clause. Undefined when nothing folds, which is what keeps existing\n // queries byte-identical.\n const qualifier = folded ? `${dialect.quoteIdent(schema.table)}.` : undefined;\n\n const context = { dialect, operation: op, qualifier };\n const where = compileWhere(schema, args?.where, context, (a) => a?.where);\n\n if (op === \"findUnique\" || op === \"findUniqueOrThrow\") {\n assertUniqueWhere(schema, args?.where, op);\n }\n\n const from = sql(` from ${dialect.quoteIdent(schema.table)}`);\n const whereClause = where ? concat(sql(\" where \"), where) : sql(\"\");\n\n // `count` needs no selection and no shaper, but `skip` / `take` still apply —\n // and they apply to the rows being counted, not to the single row the count\n // returns. Appending `limit` to the aggregate would cap the *result*, which\n // is always one row, and quietly report the unpaginated total. So when the\n // query paginates, the row query is wrapped in a subquery exactly the way\n // Prisma does it.\n if (op === \"count\") {\n const counted = sql(`select count(*) as ${dialect.quoteIdent(\"_count\")}`);\n const paginated = args?.take !== undefined || args?.skip !== undefined;\n\n // Parsed unconditionally, even though an unpaginated count discards the\n // terms: validation must not depend on whether a *different* argument was\n // also supplied, or `orderBy: { nonexistent: \"asc\" }` is an error with a\n // `take` and silently fine without one.\n const parsed = parseOrderBy(schema, args?.orderBy, op, {\n dialect,\n locate: (a: any) => a?.orderBy,\n });\n\n let statement: Fragment;\n if (!paginated) {\n statement = concat(counted, from, whereClause);\n } else {\n const { clause, terms } = pagination(\n schema,\n op,\n args,\n dialect,\n parsed,\n SINGLE_ROW.has(op),\n );\n const order = compileOrderBy(terms, dialect);\n // One column, not `*`: the subquery exists to be counted, so the narrowest\n // thing that keeps a row identity is right.\n const key = schema.primaryKey[0] ?? Object.keys(schema.fields)[0];\n statement = concat(\n counted,\n sql(` from (select ${dialect.quoteIdent(schema.fields[key].column)}`),\n from,\n whereClause,\n order ? concat(sql(\" order by \"), order) : sql(\"\"),\n clause,\n sql(`) as ${dialect.quoteIdent(\"sub\")}`),\n );\n }\n\n const { text, binders } = render(statement, dialect, {\n model: schema.name,\n operation: op,\n });\n return {\n text,\n bind: bindValues(binders),\n shape(rows) {\n const row = (rows as Record<string, unknown>[])[0];\n return Number(row?._count ?? 0);\n },\n };\n }\n\n const selection = resolveSelection(schema, args, op);\n const { plans, keyFields } = relations;\n const { fields, hidden } = withKeyFields(schema, selection, keyFields);\n\n // A folded relation's column comes from the strategy, appended after the\n // scalars so the shaped key order still matches schema order followed by\n // relations — which is what `buildRowShaper` produces and what the differential\n // harness compares.\n const contributed = plans.filter((plan) => plan.root !== undefined);\n\n // `_count` projects a correlated subquery per relation. It goes last for the\n // same reason a folded relation's column does: the shaper reads scalars by\n // position, and `_count` is attached afterwards from the raw row.\n const counts = planRelationCounts(schema, args, dialect, op);\n\n const columns = joinFragments(\n [\n ...fields.map((field) =>\n sql(`${qualifier ?? \"\"}${dialect.quoteIdent(field.column)}`),\n ),\n ...contributed.map((plan) => plan.root!.column),\n ...counts.map((count) => count.column),\n ],\n \", \",\n );\n\n const joins = concat(...contributed.map((plan) => plan.root!.join));\n\n const {\n clause: paginationClause,\n terms,\n reversed,\n } = pagination(\n schema,\n op,\n args,\n dialect,\n parseOrderBy(schema, args?.orderBy, op, {\n dialect,\n locate: (a: any) => a?.orderBy,\n }),\n SINGLE_ROW.has(op),\n );\n const order = compileOrderBy(terms, dialect, qualifier);\n\n // Last, after `limit`/`offset`, where Postgres requires it. Only the root\n // table is named, so a folded include's lateral subquery is not locked (and\n // could not be); a batched include's child queries carry no lock at all.\n const lock = parseRowLock(args?.lock, schema.name, op);\n\n const statement = concat(\n sql(\"select \"),\n columns,\n from,\n joins,\n whereClause,\n order ? concat(sql(\" order by \"), order) : sql(\"\"),\n paginationClause,\n lock ? dialect.rowLock(lock, schema.table) : sql(\"\"),\n );\n\n const { text, binders } = render(statement, dialect, {\n model: schema.name,\n operation: op,\n });\n const shaper = buildRowShaper(\n fields,\n dialect,\n plans.map((plan) => ({ key: plan.as, kind: plan.kind })),\n );\n const single = SINGLE_ROW.has(op);\n\n return {\n text,\n bind: bindValues(binders),\n relations: plans.length > 0 ? plans : undefined,\n strategies: plans.length > 0 ? strategiesOf(plans) : undefined,\n hidden,\n shape(rows) {\n const shaped = shaper(rows);\n\n // A folded relation's children arrived *in the row*, under the alias the\n // strategy chose. The shaper wrote the empty placeholder (`[]` / `null`)\n // because it knows nothing about strategies, so the decode replaces it.\n //\n // Per-row rather than once, and per-relation rather than in the shaper,\n // because `decode` is the strategy's — `json_agg` returns text, so this is\n // where dates stop being strings and an empty to-many becomes `[]`.\n // `_count` arrived as extra columns the shaper does not know about, under\n // aliases carrying a dot. Assembled into one object per row, because that\n // is the shape Prisma returns and the differential harness compares.\n if (counts.length > 0) {\n for (let i = 0; i < shaped.length; i++) {\n const raw = (rows[i] as Record<string, unknown>) ?? {};\n const totals: Record<string, number> = {};\n for (const count of counts) {\n totals[count.as] = Number(raw[count.alias] ?? 0);\n }\n shaped[i]._count = totals;\n }\n }\n\n if (contributed.length > 0) {\n for (let i = 0; i < shaped.length; i++) {\n const row = shaped[i];\n const raw = (rows[i] as Record<string, unknown>) ?? {};\n for (const plan of contributed) {\n row[plan.as] = plan.root!.decode(raw[plan.as]);\n }\n }\n }\n\n // A negative `take` means \"the last N\". The ordering terms were flipped\n // so the database returns the right *rows*, but the caller asked for them\n // in the order their `orderBy` describes — so the page is flipped back\n // here. Verified against Prisma: `take: -3, orderBy: { id: \"asc\" }`\n // returns c, d, e, not e, d, c.\n if (reversed) shaped.reverse();\n // Prisma returns the row or `null`, not a one-element array. The\n // *OrThrow* variants turn that `null` into an error in `Model.$exec`,\n // where the model's name is in scope for the message.\n return single ? (shaped[0] ?? null) : shaped;\n },\n };\n}\n\nfunction assertArgs(schema: ModelSchema, op: Operation, args: any): void {\n if (args === undefined || args === null) return;\n\n if (typeof args !== \"object\" || Array.isArray(args)) {\n throw new InvalidArgumentError(\n String(args),\n schema.name,\n op,\n \"Expected an object.\",\n );\n }\n\n // Checked before the per-key loop, so that passing both reports the thing\n // that is actually wrong rather than stopping at `include`.\n if (args.select !== undefined && args.include !== undefined) {\n throw new UnsupportedQueryError(\n \"select + include\",\n schema.name,\n op,\n \"Prisma allows only one of them on the same query.\",\n );\n }\n\n const allowed = READ_ARGS[op];\n for (const key of Object.keys(args).sort()) {\n if (args[key] === undefined) continue;\n if (allowed.has(key)) continue;\n\n const permanent = PERMANENTLY_REFUSED[key];\n if (permanent) {\n throw new UnsupportedByDesignError(key, schema.name, op, permanent);\n }\n\n throw new UnsupportedQueryError(\n key,\n schema.name,\n op,\n `${op} takes ${[...allowed].sort().join(\", \")}.`,\n );\n }\n}\n",
|
|
19
19
|
"import type { SqlDialect } from \"../dialect\";\nimport { COUNT_KEY } from \"../relation-filters\";\nimport type { FieldSchema, ModelSchema, RelationSchema } from \"../schema\";\nimport { type Binder, type Fragment, concat, sql } from \"./fragment\";\nimport {\n assertPaginable,\n batchedStrategy,\n type FoldedRelation,\n type Link,\n type RelationPlan,\n type RelationRequest,\n type RelationStrategy,\n relatedSchema,\n relationNodes,\n resolveLink,\n} from \"./plan-relations\";\nimport { resolveSelection } from \"./select\";\nimport { compileOrderBy, parseOrderBy, reverse, type OrderTerm } from \"./orderBy\";\nimport { compileWhere } from \"./where\";\n\n/**\n * `LATERAL` + `json_agg`: one round trip for a whole include *tree* instead of\n * one per node.\n *\n * Iteration 9. The measured case for it, from `plans/orm/benchmarks.md`: an include\n * costs one statement per node — 1, 2, 3 for no-include, depth-2, depth-3, counted\n * rather than timed — and on Postgres a round trip is the dominant cost of a small\n * query. Collapsing N statements into 1 removes `(N - 1)` round trips.\n *\n * ## What this version folds, and what it declines\n *\n * It **falls back to the batched plan** rather than emitting SQL it cannot get\n * right. Every decline is a correctness boundary, not a to-do:\n *\n * - **Not Postgres.** SQLite has `json_group_array`, but its round trips are\n * in-process and cost tens of microseconds; nothing measured asks for it, and the\n * plan says to build it only if something does.\n * - **An implicit many-to-many.** The join table needs a second lateral, and the\n * self-referential case cannot say which column is which end — see the note in\n * `plan-relations.ts`.\n * - **A self-relation**, where the child and the parent are the same table: the\n * correlation is written as `\"T\".\"fk\" = \"T\".\"pk\"`, which inside the subquery\n * refers to the subquery's own row rather than the outer one. Expressing it\n * needs an alias in the `from` clause, and the batched strategy already handles\n * it correctly.\n * - **A `_count` on a node.** It projects a correlated subquery that\n * `planRelationCounts` owns at the *root* of a statement, and a folded node has\n * no root of its own.\n *\n * A node whose subtree contains any of those declines as a whole, because half a\n * fold is not a thing: the children come back as JSON in the parent's row and\n * never enter the related model's `$exec`, so a descendant that cannot fold has\n * nowhere to be loaded from. Declining the node instead sends the *whole* subtree\n * back through `$exec`, where the strategy is applied again one level down — so a\n * decline costs one statement, not the subtree.\n *\n * Falling back per *node* rather than per query is what makes a mixed tree work:\n * `QueryPlan.strategies` then reports both names, which is why that field exists.\n *\n * ## Per-parent `take` / `skip`\n *\n * This is the strategy that can express them, and the only one. `json_agg` is an\n * aggregate, so a `limit` beside it would cap the aggregate's single row rather\n * than the children — the page has to happen *before* the aggregate, in a\n * subquery of its own. The ordering terms are carried out of that subquery as\n * `__ord_N` columns so the aggregate can re-apply them: aggregating over an\n * ordered subquery and hoping the order survives is not something Postgres\n * promises.\n *\n * ## Why the values are still parameters\n *\n * The subquery is built from `Fragment`s and its `where` goes through\n * `compileWhere`, so a node's filter binds exactly as a root filter does.\n * Invariant 2 applies to a strategy's SQL as much as to the compiler's own, and\n * this is the first strategy that emits any.\n */\nexport const lateralStrategy: RelationStrategy = {\n name: \"lateral\",\n\n plan(request: RelationRequest): RelationPlan {\n const declined = decline(\n request.parent,\n request.relation,\n request.as,\n request.node,\n request.dialect,\n request.operation,\n );\n\n if (declined) {\n // Raised here rather than left to the batched plan, because *why* this\n // node reached a strategy that cannot page it is the actionable half of\n // the message and only this function knows it.\n assertPaginable(request, `this node declined to fold (${declined})`);\n return batchedStrategy.plan(request);\n }\n\n const { dialect } = request;\n const child = relatedSchema(request.parent, request.relation, request.as);\n const link = resolveLink(\n request.parent,\n child,\n request.relation,\n request.operation,\n );\n\n const fold = foldNode({\n parent: request.parent,\n child,\n relation: request.relation,\n as: request.as,\n node: request.node,\n locate: request.locate,\n link,\n dialect,\n operation: request.operation,\n depth: 1,\n counter: { next: 0 },\n });\n\n return {\n as: request.as,\n model: request.relation.model,\n kind: request.relation.kind,\n parentFields: link.parentFields,\n strategy: \"lateral\",\n root: {\n column: concat(\n sql(`${fold.alias}.${dialect.quoteIdent(\"data\")} as `),\n sql(dialect.quoteIdent(request.as)),\n ),\n join: concat(\n sql(` left join lateral (`),\n fold.subquery,\n sql(`) as ${fold.alias} on true`),\n ),\n decode: fold.decode,\n folded: fold.folded,\n },\n // Unreachable: `attachRelations` skips a plan carrying `root`. Kept as a\n // loud failure rather than the batched loader, because reaching it would\n // mean the skip regressed and issuing the query would hide that.\n load: async () => {\n throw new Error(\n `${request.parent.name}.${request.as} was folded into the root ` +\n `statement, so it must not also be loaded. This means ` +\n `attachRelations stopped honouring RelationPlan.root.`,\n );\n },\n };\n },\n};\n\n/**\n * Why this node — or anything below it — cannot fold, or `undefined` if it can.\n *\n * Recursive, because folding is: a descendant that cannot be expressed has\n * nowhere to be loaded from once its ancestors are JSON in a parent row.\n */\nfunction decline(\n parent: ModelSchema,\n relation: RelationSchema,\n as: string,\n node: unknown,\n dialect: SqlDialect,\n operation: string,\n): string | undefined {\n if (dialect.name !== \"postgres\") return \"not postgres\";\n if (relation.joinTable) return \"implicit many-to-many\";\n\n const child = relatedSchema(parent, relation, as);\n // The correlation names both tables, so a relation onto the same table would\n // compare the subquery's own row against itself.\n if (child.table === parent.table) return \"self-relation\";\n\n const args = normalise(node);\n if (args === undefined) return undefined;\n\n // `_count` sits in the same container as the relation nodes and is skipped by\n // every walk over it, so a node carrying one would fold *without* it and\n // return rows missing a key the caller asked for.\n if (hasCount(args)) return \"_count on a folded node\";\n\n // `orderBy: { user: { email: \"asc\" } }` on a node compiles to a correlated\n // subquery, and `foldNode` parses the node's `orderBy` with no `OrderContext`\n // to build one with — so `parseOrderBy` raises rather than emitting anything.\n // Declining sends the node to the batched strategy, which compiles the\n // ordering as part of the child's own query and gets it right.\n //\n // It reads like the `_count` case above and is the same shape: a node that\n // would fold *without* something the caller asked for has to decline instead.\n // Supporting it properly means threading an `OrderContext` down through\n // `foldNode` so `order-relation.ts` can build the subquery against the child's\n // qualifier — a bigger change than this one, and one that owes the\n // differential harness its own coverage.\n if (ordersByRelation(child, args.orderBy)) {\n return \"relation ordering on a folded node\";\n }\n\n for (const nested of relationNodes(child, args, operation)) {\n const reason = decline(\n child,\n nested.relation,\n nested.as,\n nested.node,\n dialect,\n operation,\n );\n if (reason) return `${nested.as}: ${reason}`;\n }\n\n return undefined;\n}\n\n/**\n * Whether an `orderBy` sorts by a *relation* rather than by a column.\n *\n * Both of Prisma's relation-ordering forms name the relation as the key —\n * `{ organization: { name: \"asc\" } }` and `{ accounts: { _count: \"desc\" } }` —\n * so the check is the same one `parseOrderBy` makes, and both of its accepted\n * containers (one object, or an array of them) are walked.\n */\nfunction ordersByRelation(schema: ModelSchema, orderBy: unknown): boolean {\n if (orderBy === undefined || orderBy === null) return false;\n\n for (const entry of Array.isArray(orderBy) ? orderBy : [orderBy]) {\n if (typeof entry !== \"object\" || entry === null) continue;\n for (const [key, value] of Object.entries(entry)) {\n if (value === undefined) continue;\n if (key in schema.relations) return true;\n }\n }\n\n return false;\n}\n\nfunction hasCount(args: Record<string, unknown>): boolean {\n for (const container of [\"include\", \"select\"] as const) {\n const tree = args[container];\n if (typeof tree !== \"object\" || tree === null || Array.isArray(tree)) {\n continue;\n }\n const count = (tree as Record<string, unknown>)[COUNT_KEY];\n if (count !== undefined && count !== false) return true;\n }\n return false;\n}\n\ninterface FoldInput {\n /** The table the correlation compares against — one level out. */\n parent: ModelSchema;\n child: ModelSchema;\n relation: RelationSchema;\n as: string;\n node: unknown;\n /** Re-locates *this* node inside the whole call's argument tree. */\n locate: (args: any) => any;\n link: Link;\n dialect: SqlDialect;\n operation: string;\n depth: number;\n /**\n * Hands out one index per node in this subtree, so a nested alias cannot\n * shadow an ancestor's. Depth 1 keeps the bare `__lat_<relation>` form, which\n * is the one a query log is read with.\n */\n counter: { next: number };\n}\n\ninterface Fold {\n /** Quoted, and unique within the statement it is emitted into. */\n alias: string;\n subquery: Fragment;\n decode: (value: unknown) => unknown;\n folded: FoldedRelation[];\n}\n\n/**\n * One relation node as a correlated subquery, with everything below it folded in.\n */\nfunction foldNode(input: FoldInput): Fold {\n const { dialect, child, operation } = input;\n const node = normalise(input.node);\n const many = input.relation.kind === \"many\";\n\n const index = input.counter.next++;\n const alias = dialect.quoteIdent(suffixed(\"__lat_\", input.as, input.depth, index));\n const childTable = dialect.quoteIdent(child.table);\n const childQualifier = `${childTable}.`;\n\n const selected = resolveSelection(child, node, operation);\n\n // Everything below this node, folded into the same subquery. Their joins go\n // in this level's `from`, and their `data` columns into this level's object.\n const nested = relationNodes(child, node, operation).map((relationNode) => {\n const grandchild = relatedSchema(child, relationNode.relation, relationNode.as);\n return {\n as: relationNode.as,\n relation: relationNode.relation,\n fold: foldNode({\n parent: child,\n child: grandchild,\n relation: relationNode.relation,\n as: relationNode.as,\n node: relationNode.node,\n // Composed rather than captured: the plan is compiled once per argument\n // *shape*, so a nested `where`'s values are read from the call through\n // the whole chain of `locate`s.\n locate: (args: any) => relationNode.locate(input.locate(args)),\n link: resolveLink(child, grandchild, relationNode.relation, operation),\n dialect,\n operation,\n depth: input.depth + 1,\n counter: input.counter,\n }),\n };\n });\n\n const object = jsonObject(\n selected,\n childQualifier,\n dialect,\n nested.map((entry) => ({ key: entry.as, alias: entry.fold.alias })),\n );\n\n const joins = concat(\n ...nested.map((entry) =>\n concat(\n sql(` left join lateral (`),\n entry.fold.subquery,\n sql(`) as ${entry.fold.alias} on true`),\n ),\n ),\n );\n\n // The correlation: the child's foreign key against the *parent's* column.\n // This is the whole of \"lateral\" — the subquery references the outer row —\n // and one equality per joined field is the whole of composite support here.\n const correlation = sql(\n input.link.parentFields\n .map(\n (parentField, index) =>\n `${childQualifier}${dialect.quoteIdent(\n fieldOf(child, input.link.childFields[index]).column,\n )} = ${dialect.quoteIdent(input.parent.table)}.${dialect.quoteIdent(\n fieldOf(input.parent, parentField).column,\n )}`,\n )\n .join(\" and \"),\n );\n\n const filter = compileWhere(\n child,\n node?.where,\n { dialect, operation, qualifier: childQualifier },\n (args) => input.locate(args)?.where,\n );\n\n const scan = concat(\n sql(` from ${childTable}`),\n joins,\n sql(` where `),\n correlation,\n filter ? concat(sql(\" and \"), filter) : sql(\"\"),\n );\n\n const decode = buildDecoder(\n selected,\n dialect,\n many,\n nested.map((entry) => ({ key: entry.as, decode: entry.fold.decode })),\n );\n\n const folded: FoldedRelation[] = nested.map((entry) => ({\n as: entry.as,\n model: entry.relation.model,\n kind: entry.relation.kind,\n folded: entry.fold.folded,\n }));\n\n const terms = parseOrderBy(child, node?.orderBy, operation);\n\n if (!many) {\n // A to-one must not aggregate, and must not return two rows into a scalar\n // subquery position if the data violates the relation's cardinality. It\n // takes no `orderBy` — the planner refuses one — so there is nothing to\n // order by either.\n return {\n alias,\n folded,\n decode,\n subquery: concat(\n sql(`select `),\n object,\n sql(` as ${dialect.quoteIdent(\"data\")}`),\n scan,\n sql(\" limit 1\"),\n ),\n };\n }\n\n const page = pagination(input, node, terms, child);\n\n if (!page) {\n // `coalesce`, because `json_agg` over zero rows returns NULL and an empty\n // to-many must shape to `[]`. Getting this wrong is the single most likely\n // divergence in the whole strategy, and the differential harness compares\n // key presence, so it would be caught — but it is cheaper to be right.\n //\n // The ordering belongs to the aggregate — `json_agg(x order by y)` — not to\n // the subquery: a bare `order by` beside an aggregate orders the one row the\n // aggregate produces, and the children come back in whatever order the scan\n // found them.\n const ordering = compileOrderBy(terms, dialect, childQualifier);\n return {\n alias,\n folded,\n decode,\n subquery: concat(\n sql(`select coalesce(json_agg(`),\n object,\n ordering ? concat(sql(\" order by \"), ordering) : sql(\"\"),\n sql(`), '[]'::json) as ${dialect.quoteIdent(\"data\")}`),\n scan,\n ),\n };\n }\n\n // Paginated: the page has to be taken *before* the aggregate, so the scan goes\n // into a subquery of its own and the aggregate runs over its rows.\n const pageAlias = dialect.quoteIdent(\n suffixed(\"__page_\", input.as, input.depth, index),\n );\n\n // The ordering columns, carried out of the page so the aggregate can re-apply\n // them. Aliased rather than repeated, which also lets the inner `order by`\n // name them — Postgres resolves an `order by` against the select list.\n const carried = page.terms.map((term, position) =>\n sql(\n `, ${childQualifier}${dialect.quoteIdent(term.column)} as ` +\n `${dialect.quoteIdent(orderAlias(position))}`,\n ),\n );\n\n const inner = compileOrderBy(aliased(page.inner), dialect);\n const outer = compileOrderBy(aliased(page.terms), dialect, `${pageAlias}.`);\n\n return {\n alias,\n folded,\n decode,\n subquery: concat(\n sql(`select coalesce(json_agg(${pageAlias}.${dialect.quoteIdent(\"data\")}`),\n outer ? concat(sql(\" order by \"), outer) : sql(\"\"),\n sql(`), '[]'::json) as ${dialect.quoteIdent(\"data\")} from (select `),\n object,\n sql(` as ${dialect.quoteIdent(\"data\")}`),\n ...carried,\n scan,\n inner ? concat(sql(\" order by \"), inner) : sql(\"\"),\n page.clause,\n sql(`) as ${pageAlias}`),\n ),\n };\n}\n\n/**\n * The node's own `take` / `skip`, or `undefined` when it has neither.\n *\n * Mirrors the root's `pagination` in `read.ts`, including the two pieces of\n * Prisma behaviour that are invisible until you read the SQL it emits:\n *\n * - Paginating without an `orderBy` orders by the primary key. Without it,\n * \"the first ten\" is only meaningful if the scan happens to be stable.\n * - A *negative* `take` means \"the last N\": every ordering term is flipped and\n * `abs(take)` rows are taken. Here the page is put back into the caller's own\n * order by the aggregate rather than by reversing an array, since the\n * aggregate is already ordering — `inner` is the flipped order, `terms` is\n * the one the caller asked for.\n */\nfunction pagination(\n input: FoldInput,\n node: Record<string, any> | undefined,\n parsed: OrderTerm[],\n child: ModelSchema,\n): { clause: Fragment; terms: OrderTerm[]; inner: OrderTerm[] } | undefined {\n const take = node?.take;\n const skip = node?.skip;\n if (take === undefined && skip === undefined) return undefined;\n\n const terms =\n parsed.length > 0\n ? parsed\n : child.primaryKey.map((name) => ({\n column: child.fields[name]?.column ?? name,\n direction: \"asc\" as const,\n }));\n\n const takeBinder: Binder | null =\n take === undefined\n ? null\n : (args: any) => Math.abs(Number(input.locate(args)?.take));\n\n const skipBinder: Binder | null =\n skip === undefined ? null : (args: any) => Number(input.locate(args)?.skip);\n\n return {\n clause: input.dialect.paginate(takeBinder, skipBinder),\n terms,\n inner: typeof take === \"number\" && take < 0 ? reverse(terms) : terms,\n };\n}\n\nconst orderAlias = (position: number) => `__ord_${position}`;\n\n/**\n * The same terms, pointed at the carried `__ord_N` columns rather than at the\n * child's own. Position is what ties the two together, so this must be mapped\n * from the same array the columns were carried from.\n */\nfunction aliased(terms: OrderTerm[]): OrderTerm[] {\n return terms.map((term, position) => ({\n ...term,\n column: orderAlias(position),\n expression: undefined,\n }));\n}\n\n/**\n * An alias derived from the relation's key, so two relations on one query cannot\n * collide. Not user input: `as` is a key on the generated schema's `relations`,\n * so it is an identifier the same way a column is.\n *\n * Below the first level it carries the node's index too. Without it a tree that\n * reaches the same relation name twice — `accounts.user.accounts` — would emit\n * one alias inside another of the same name, where the inner silently shadows\n * the outer.\n */\nfunction suffixed(\n prefix: string,\n as: string,\n depth: number,\n index: number,\n): string {\n return depth === 1 ? `${prefix}${as}` : `${prefix}${as}_${index}`;\n}\n\nfunction normalise(node: unknown): any {\n if (node === true || node === undefined || node === null) return undefined;\n if (typeof node !== \"object\" || Array.isArray(node)) return undefined;\n return node;\n}\n\n/**\n * `json_build_object('id', \"Account\".\"id\", …)` over the child's selected columns,\n * followed by whatever relations folded below it.\n *\n * Keys are the *field* names, so the JSON arrives already shaped the way the\n * caller expects and the decoder does not have to map columns back. Both sides\n * come from the generated schema.\n */\nfunction jsonObject(\n fields: readonly FieldSchema[],\n qualifier: string,\n dialect: SqlDialect,\n nested: readonly { key: string; alias: string }[],\n): Fragment {\n const parts = fields.map((field) => {\n const column = `${qualifier}${dialect.quoteIdent(field.column)}`;\n // `::text` for BigInt, and this is a correctness fix rather than a\n // formality: JSON has no integer type, so `json_build_object` renders a\n // `bigint` as a JSON *number*, and `JSON.parse` turns that into a float64\n // before any decoder can see it. 9007199254740993 came back as\n // ...992 — the low bit gone, silently, in a value whose entire reason for\n // being a `BigInt` is that it does not fit a double.\n //\n // Casting in SQL means the value crosses as a string and `BigInt(string)` is\n // exact. Found by the all-scalars-through-a-relation fixture, which exists\n // because the template's schema has no BigInt behind a relation and the\n // differential matrix therefore cannot reach this.\n //\n // `::text[]` for a `BigInt[]`, and the measurement is the same one: a\n // `bigint[]` rendered into JSON is an array of JSON numbers, and\n // 9007199254740993 came back as ...992 element-wise. The array form of the\n // same trap, and it needs the array form of the same cast.\n const expression =\n field.type === \"BigInt\" ? `${column}::text${field.isList ? \"[]\" : \"\"}` : column;\n return `'${field.name}', ${expression}`;\n });\n\n // A folded relation is already JSON — an array from its own `json_agg`, or an\n // object from its own `json_build_object` — so it embeds as a value rather\n // than being re-encoded.\n for (const entry of nested) {\n parts.push(`'${entry.key}', ${entry.alias}.${dialect.quoteIdent(\"data\")}`);\n }\n\n return sql(`json_build_object(${parts.join(\", \")})`);\n}\n\n/**\n * Turns the subquery's JSON into the rows the caller gets.\n *\n * **This is where the strategy earns or loses its correctness.** JSON aggregation\n * flattens types: a `timestamp` becomes an ISO string, `bytea` becomes a\n * `\\\\x`-prefixed hex string, `bigint` becomes a number or a string depending on\n * magnitude. The batched path never sees any of that, because its children come\n * back through the driver's own type mapping — so a decoder here that merely\n * `JSON.parse`s would return strings where Prisma returns `Date`s, and the\n * differential harness would catch it only for the types the template's schema\n * happens to use.\n *\n * So the conversion is driven by the child's *schema*, per field, and it reuses the\n * dialect's own `decode` for anything the dialect already knows how to convert.\n * A folded relation arrived nested inside this one's JSON, so its own decoder\n * runs from here — the same recursion the SQL took, in the other direction.\n */\nfunction buildDecoder(\n fields: readonly FieldSchema[],\n dialect: SqlDialect,\n many: boolean,\n nested: readonly { key: string; decode: (value: unknown) => unknown }[],\n): (value: unknown) => unknown {\n const converters = fields\n .map((field) => ({ field, convert: jsonConverter(field) }))\n .filter((entry) => entry.convert !== undefined) as Array<{\n field: FieldSchema;\n convert: (value: unknown) => unknown;\n }>;\n\n const one = (row: unknown): unknown => {\n if (row === null || row === undefined || typeof row !== \"object\") return null;\n const record = row as Record<string, unknown>;\n for (const { field, convert } of converters) {\n record[field.name] = convert(record[field.name]);\n }\n for (const child of nested) {\n record[child.key] = child.decode(record[child.key]);\n }\n return record;\n };\n\n return (value: unknown) => {\n // `jsonb` arrives parsed on some driver versions and as text on others; the\n // same `typeof` check `PostgresDialect.decode` uses handles both without a\n // version test.\n const parsed =\n typeof value === \"string\" ? safeParse(value) : (value ?? null);\n\n if (many) {\n if (!Array.isArray(parsed)) return [];\n return parsed.map(one).filter((row) => row !== null);\n }\n\n return one(parsed);\n };\n}\n\n/**\n * How one field's JSON form becomes its JavaScript form, or `undefined` when JSON\n * already carries it faithfully (`Int`, `String`, `Boolean`, `Float`, `Json`).\n *\n * A **scalar list** is the element's own converter mapped over a JSON array,\n * which is exactly right and is worth saying because the alternative is\n * tempting: `PostgresDialect.decode` is *not* reusable here. Its whole job is\n * normalising the containers Bun's driver produces — an `Int32Array`, an\n * unparsed `{a,b}` literal — and none of them exist on this path. `json_agg`\n * hands over a JSON array whatever the element type, including for the enum\n * lists the driver refuses to parse. Two decoding sites, two container\n * problems, one shared per-element rule.\n */\nfunction jsonConverter(\n field: FieldSchema,\n): ((value: unknown) => unknown) | undefined {\n if (field.isList) {\n const element = elementConverter(field);\n if (!element) return undefined;\n return (value) => {\n if (value === null || value === undefined) return null;\n if (!Array.isArray(value)) return value;\n return value.map((item) =>\n item === null || item === undefined ? null : element(item),\n );\n };\n }\n\n return elementConverter(field);\n}\n\nfunction elementConverter(\n field: FieldSchema,\n): ((value: unknown) => unknown) | undefined {\n switch (field.type) {\n case \"DateTime\":\n // ISO text out of `json_build_object`, where the driver would have given a\n // `Date`. Prisma returns a `Date`, so this is not optional.\n return (value) =>\n value === null || value === undefined\n ? null\n : value instanceof Date\n ? value\n : new Date(String(value));\n\n case \"BigInt\":\n return (value) =>\n value === null || value === undefined ? null : BigInt(String(value));\n\n case \"Json\":\n // Nothing to do, for the same reason `PostgresDialect.decode` does\n // nothing: the value arrives already parsed. A `jsonb` column embedded in\n // `json_build_object` is a nested JSON value, and Bun parses the whole\n // `data` payload — so by the time it reaches here it is an object, an\n // array, a string, a number or null, exactly as stored.\n //\n // This used to re-parse anything that was a string, on the reasoning that\n // it might be raw JSON text. **A JS string is ambiguous** between \"text\n // nobody parsed\" and \"a JSON string value somebody did\", and here the\n // ambiguity is worse than on the batched path, because the value has been\n // through JSON *twice* — once for the column, once for `json_agg`. A\n // column holding the JSON string `\"42\"` came back as the number 42 from a\n // folded include and as `\"42\"` from a batched one: the same query, two\n // answers, decided by which strategy the dialect happened to pick.\n //\n // Caught by seeding a JSON string one relation down. Nothing reached it\n // before, because the template's schema had no `Json` column at all.\n return undefined;\n\n case \"Bytes\":\n // Postgres renders `bytea` into JSON as `\\x` followed by hex.\n //\n // **`Uint8Array`, not `Buffer`**, and the container matters as much as\n // the contents — see `PostgresDialect.decode`, which normalises the\n // driver's `Buffer` to the same thing for the batched path. Prisma 6\n // returns `Uint8Array` on every dialect; that is the contract, and\n // `Buffer.prototype.toString(\"hex\")` versus\n // `Uint8Array.prototype.toString(\"hex\")` is the observable difference.\n //\n // `Buffer.from(text, \"hex\")` for the parse — it is the parser the driver\n // would have used, and faster than a manual nibble loop — then a view\n // over the same bytes. No copy.\n return (value) => {\n if (value === null || value === undefined) return null;\n if (ArrayBuffer.isView(value)) {\n return Buffer.isBuffer(value)\n ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength)\n : value;\n }\n const buffer = Buffer.from(String(value).replace(/^\\\\?x/, \"\"), \"hex\");\n return new Uint8Array(\n buffer.buffer,\n buffer.byteOffset,\n buffer.byteLength,\n );\n };\n\n default:\n return undefined;\n }\n}\n\nfunction safeParse(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n}\n\nfunction fieldOf(schema: ModelSchema, name: string): FieldSchema {\n const field = schema.fields[name];\n if (!field) {\n throw new Error(\n `${schema.name} has no field '${name}', which the lateral strategy needs ` +\n `to correlate on. This means the generated artifact is stale.`,\n );\n }\n return field;\n}\n",
|
|
20
20
|
"import type { SqlDialect } from \"../dialect\";\nimport { UnsupportedQueryError } from \"../errors\";\nimport { lateralStrategy } from \"./lateral\";\nimport { batchedStrategy, type RelationStrategy } from \"./plan-relations\";\n\n/**\n * Choosing a relation strategy.\n *\n * Its own module, and not for tidiness: `lateral.ts` imports `plan-relations.ts`\n * for the batched plan it falls back to, so anything naming both has to sit above\n * them or the import graph is a cycle. That is also the honest layering — the\n * strategies do not know about each other, and selection is the only thing that\n * knows about both.\n */\n\n/**\n * **Lateral on Postgres, batched everywhere else.**\n *\n * The rule is the dialect and nothing more, which is as simple as the plan asked\n * for — and it is sufficient because the *strategy* declines per node for\n * everything it cannot fold. Selection does not need to know about tree depth or\n * row counts; it needs to know whether folding is possible at all, and that is a\n * property of the dialect.\n *\n * **What justifies Postgres defaulting to lateral**, since this changes what every\n * existing include does there:\n *\n * - It removes a round trip per include node, and on Postgres a round trip is the\n * dominant cost of a small query. The counts are in `plans/orm/benchmarks.md`,\n * measured rather than argued: 1, 2 and 3 statements for no-include, depth-2 and\n * depth-3.\n * - The **full** nested differential matrix runs against it — every relation case\n * in `differential.test.ts`, derived from the same table the batched run uses so\n * the two cannot drift — and matches Prisma. That is iteration 9's acceptance\n * criterion 2, and it is what this line was waiting for.\n * - Anything it cannot express falls back per node, so a tree it only half\n * understands is still correct.\n *\n * SQLite keeps batching: its round trips are in-process and cost tens of\n * microseconds, so `json_group_array` would be complexity bought with nothing. The\n * plan says build it only if a measurement asks, and none does.\n *\n * A caller can override either way with `ExecOptions.strategy`.\n */\nexport function defaultStrategy(dialect: SqlDialect): RelationStrategy {\n return dialect.name === \"postgres\" ? lateralStrategy : batchedStrategy;\n}\n\n/**\n * The named strategy, or the dialect's default.\n *\n * An unknown name raises rather than falling back: a typo that silently ran the\n * other strategy would be a performance mystery with no error attached, and the\n * set is two.\n */\nexport function resolveStrategy(\n named: string | undefined,\n dialect: SqlDialect,\n // Required, so the caller cannot fall back to a placeholder without saying\n // so. This used to report `\"Model\"` and `\"$exec\"` — a base class and\n // something that is not one of the operations — while `$exec`, its\n // only caller, had both in scope (#112).\n origin: { model: string; operation: string },\n): RelationStrategy {\n if (named === undefined) return defaultStrategy(dialect);\n if (named === \"batched\") return batchedStrategy;\n if (named === \"lateral\") return lateralStrategy;\n\n throw new UnsupportedQueryError(\n `strategy: ${JSON.stringify(named)}`,\n origin.model,\n origin.operation,\n `Unknown relation strategy. Expected \"batched\" or \"lateral\".`,\n );\n}\n",
|
|
21
21
|
"// Runtime model metadata: the shape the Prisma generator plugin emits into an\n// app's `app/models/generated/schema.ts`, and the only thing the compiler is\n// allowed to read identifiers from.\n//\n// Nothing here is discovered from the database at runtime. It is all generated,\n// which is what makes `compile` a pure function and what makes SQL injection\n// structurally impossible: every identifier the compiler emits is looked up in\n// one of these objects first (see the README's invariant 2).\n//\n// The generator deliberately emits *more* than the current iteration reads.\n// Regenerating an app's artifacts is free; changing the shape of the emitted\n// artifact after apps depend on it is not.\n\n/**\n * Bumped whenever the emitted artifact's shape changes in a way the runtime\n * cannot read. Generated `schema.ts` files carry their own literal copy, and\n * `assertSchemaArtifactVersion` compares the two at registration time so a stale\n * `app/models/generated` fails with \"run prisma generate\" rather than with a\n * `TypeError` five stack frames into the compiler.\n *\n * **`FieldSchema.isList` did not bump it**, and the argument given at the time\n * was that the generator is `bin/orm` and the runtime is `orm/`, both shipped\n * by the same `gemi` package at the same version — so a *new* artifact could\n * never be read by an *old* runtime.\n *\n * **That argument is wrong, and #350's review is what showed it.** The two\n * halves do not travel together. The artifact is committed to git; the runtime\n * is a version in a lockfile. A teammate who pulls a branch without installing,\n * or a deploy box a release behind, reads a freshly committed artifact with the\n * previous runtime — and because the version literal in that artifact was never\n * bumped, `assertSchemaArtifactVersion` sees `1 === 1` and says nothing.\n *\n * The consequence is worse than being unable to read the column, because\n * `isClientSideDefault` used to be a *denylist* — anything that was not\n * `autoincrement` or `dbgenerated` counted as gemi's. An old runtime meeting\n * `{ kind: \"nanoid\" }` therefore answered \"yes, gemi supplies this\", included\n * the column in the insert, asked `clientSideValue` for a value, got\n * `undefined` from its `default:` arm, and bound **NULL**. On a required column\n * that is a NOT NULL violation; on a nullable one it writes NULL into every row\n * forever, which is strictly harder to find than a column that was omitted.\n *\n * So this is now **2**, and `isClientSideDefault` is an allowlist. The bump is\n * the mechanism that catches the skew — both directions fail with \"run\n * `prisma generate`\" — and the allowlist is what makes the failure loud rather\n * than silent if one ever slips past it.\n */\nexport const SCHEMA_ARTIFACT_VERSION = 3;\n\n/**\n * Every artifact version this runtime reads. **3** added\n * `FieldSchema.encrypted`, and is the version emitted only for a schema that\n * uses it: a runtime that predates encrypted columns would ignore the flag and\n * write those columns in plaintext, which is exactly the silent skew this\n * version check exists to make loud. A schema without encrypted columns is\n * still emitted as **2** — it is the same artifact — so regenerating does not\n * force every teammate and deploy onto the new runtime for nothing.\n */\nexport const READABLE_ARTIFACT_VERSIONS: readonly number[] = [2, 3];\n\n/** The version a generated artifact for these schemas is stamped with. */\nexport function artifactVersionFor(schemas: readonly ModelSchema[]): number {\n const encrypted = schemas.some((schema) =>\n Object.values(schema.fields).some((field) => field.encrypted === true),\n );\n return encrypted ? 3 : 2;\n}\n\n/**\n * Prisma's scalar types, verbatim. Not SQL types — the mapping from these to a\n * column type is the dialect's business, and it differs (SQLite has no\n * `DateTime` and no `Boolean`).\n */\nexport type ScalarType =\n | \"Int\"\n | \"String\"\n | \"DateTime\"\n | \"Boolean\"\n | \"Float\"\n | \"BigInt\"\n | \"Decimal\"\n | \"Json\"\n | \"Bytes\";\n\n/**\n * Prisma 6.19.2's parser accepts seven default functions, and its client\n * registers client-side generators for **four** of them — `cuid`, `nanoid`,\n * `ulid` and `uuid`. All four produce a column whose DDL carries no `DEFAULT`,\n * so all four are gemi's to supply; that is the whole of #350, and `ulid` was\n * the last one still missing when its review was written.\n *\n * Read off the shipped artifacts rather than the docs: the parser's own string\n * table is `autoincrement ulid cuid dbgenerated nanoid now uuid`, and\n * `prisma migrate diff` on a schema using every one of them emits\n * `TEXT NOT NULL` with no default for each.\n */\nexport type DefaultKind =\n | \"autoincrement\"\n | \"cuid\"\n | \"uuid\"\n | \"nanoid\"\n | \"ulid\"\n | \"now\"\n | \"dbgenerated\"\n | \"value\";\n\n/** What `@default(nanoid())` means when written without an argument. */\nexport const NANOID_DEFAULT_LENGTH = 21;\n\nexport interface DefaultSpec {\n kind: DefaultKind;\n /** Present only for `kind: \"value\"` — the literal written in the schema. */\n value?: unknown;\n /**\n * Present only for `kind: \"nanoid\"` — the id's length in characters.\n *\n * Part of the default rather than a detail of it: `nanoid()` is 21 characters\n * and `nanoid(10)` is 10, and the column Prisma's migration emits is a plain\n * `TEXT` that constrains neither. So the length lives nowhere but the schema,\n * and if it does not survive into this artifact the runtime cannot mint the\n * same id the Prisma client would.\n */\n length?: number;\n /**\n * Present only for `kind: \"uuid\"` — `4` or `7`.\n *\n * The same reasoning as `length`, and it took the same bug to notice: `uuid()`\n * and `uuid(7)` are one `TEXT` column apart in the DDL and two different\n * *kinds* of identifier in practice. A v7 is time-ordered, which is the entire\n * reason a schema asks for one — order by it and rows come back in insertion\n * order, and a B-tree insert lands next to the last one. Minting a v4 where\n * the schema said 7 loses both, silently, in a column that still looks like a\n * UUID.\n *\n * Absent on an artifact generated before this existed. The runtime reads a\n * missing version as 4, which is what `uuid()` meant then and means now —\n * though `SCHEMA_ARTIFACT_VERSION` makes that pairing fail loudly first.\n *\n * `cuid` has a version argument too and does **not** get a field here: `cuid(2)`\n * is refused by the generator rather than recorded, so the only cuid that\n * reaches an artifact is v1. See `emit.ts`.\n */\n version?: number;\n}\n\nexport interface FieldSchema {\n /** The field name as an app author writes it: `organizationId`. */\n name: string;\n /** The column name in the database: `@map(...)` if present, else `name`. */\n column: string;\n type: ScalarType;\n nullable: boolean;\n isId: boolean;\n isUpdatedAt: boolean;\n /**\n * A Prisma **scalar list** — `tags String[]`. Postgres only; SQLite has no\n * array type and Prisma refuses the declaration there outright.\n *\n * **A flag beside `type` rather than a `ScalarType` constructor**, and the\n * choice reaches further than it looks. `type` keeps meaning the *element*\n * type, so every `switch (field.type)` already written — `encode`, `decode`,\n * `castParameter`, the lateral strategy's `jsonConverter`, `COMPOSITE_IN_TYPES`\n * — keeps reading correctly and only has to ask this one extra question where\n * a list genuinely differs. A `\"String[]\"` member of the union would have made\n * every one of those switches silently non-exhaustive instead: no compile\n * error, just a `default:` branch answering for a shape it had never seen.\n *\n * Absent rather than `false` on a non-list field, so an artifact generated\n * before this existed is byte-identical to one generated after it — see the\n * note on `SCHEMA_ARTIFACT_VERSION`, which is deliberately *not* bumped here.\n */\n isList?: boolean;\n /**\n * Set when the field is a Prisma enum. The enum's members are strings on the\n * wire, so `type` is `\"String\"` and this carries the name for later.\n */\n enum?: string;\n default?: DefaultSpec;\n /**\n * `/// @gemi.encrypted` on the field: stored as an encrypted envelope and\n * decrypted on every read (`orm/encryption.ts`). Only on a non-list `String`\n * that is not a key, has no default and is not a relation's foreign key —\n * the generator refuses the rest.\n *\n * Absent rather than `false`, so an artifact without encrypted columns is\n * byte-identical to one generated before this existed. An artifact *with*\n * one is emitted as version 3, which a runtime that predates this refuses —\n * see `SCHEMA_ARTIFACT_VERSION`.\n */\n encrypted?: true;\n /**\n * `/// @gemi.sensitive` on the field (#1065): a secret, such as a token or\n * a password hash, that a schema summary for a model (`describeSchema`)\n * marks or leaves out. Nothing else reads it: it changes no query.\n *\n * Absent rather than `false`, so an artifact without one is byte-identical\n * to one generated before this existed. A runtime that predates it ignores\n * it, which is harmless for a flag no query reads, so it does not bump\n * `SCHEMA_ARTIFACT_VERSION`.\n */\n sensitive?: true;\n}\n\nexport interface RelationSchema {\n /** The field name on the owning model: `accounts`. */\n name: string;\n /** The related model's *name*, resolved through the registry at call time. */\n model: string;\n kind: \"one\" | \"many\";\n /**\n * Prisma's relation name, shared by both sides. It is what lets the planner\n * find the other side of a relation whose `from`/`to` live on that side only.\n */\n relationName: string;\n /** Local fields. Empty on the side that does not hold the foreign key. */\n from: string[];\n /** Fields on the related model. Empty on the non-owning side, as above. */\n to: string[];\n nullable: boolean;\n /** Implicit many-to-many join table. Emitted now, unused until iteration 3. */\n joinTable?: {\n table: string;\n a: string;\n b: string;\n /**\n * Which column holds the owner of **this** relation field, for a\n * *self*-referential implicit m-n where `a === b` and the model names\n * cannot say.\n *\n * Prisma assigns the columns by **field name, alphabetically**: the\n * alphabetically-first of the relation's two fields has its owner in `A`.\n * Determined by experiment against a generated client, in both directions,\n * rather than from the docs — the two candidate rules (declaration order\n * and field-name order) disagree only when a schema declares the fields out\n * of alphabetical order, which is exactly the case that would have shipped\n * reversed.\n *\n * Absent for a non-self m-n, where comparing the model names answers it,\n * and absent in artifacts generated before this existed — which is why\n * reading it is optional rather than required. Such an artifact behaves\n * exactly as it did: a self-referential m-n is refused.\n */\n ownerColumn?: \"A\" | \"B\";\n };\n}\n\nexport interface ModelSchema {\n /** Registry key: `\"User\"`. */\n name: string;\n /** `@@map(...)` if present, else `name`. Never inferred or pluralised. */\n table: string;\n /** Insertion-ordered by schema declaration — this is the `select` order. */\n fields: Record<string, FieldSchema>;\n primaryKey: string[];\n /** Single-field `@unique` and composite `@@unique`, in declaration order. */\n uniques: string[][];\n relations: Record<string, RelationSchema>;\n}\n\nexport class StaleSchemaArtifactError extends Error {\n constructor(found: number) {\n super(\n `The generated model artifact is version ${found}, but this version of ` +\n `gemi reads version ${READABLE_ARTIFACT_VERSIONS.join(\" or \")}. Re-run ` +\n `\\`prisma generate\\` ` +\n `to refresh app/models/generated.`,\n );\n this.name = \"StaleSchemaArtifactError\";\n }\n}\n\n/**\n * Called by the generated `index.ts` with its own artifact version literal.\n */\nexport function assertSchemaArtifactVersion(version: number): void {\n if (!READABLE_ARTIFACT_VERSIONS.includes(version)) {\n throw new StaleSchemaArtifactError(version);\n }\n}\n",
|
package/dist/server/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ra as f}from"../chunk-ba1h9pm6.js";import{Sa as A}from"../chunk-4vn8gyzy.js";import{Bm as q,Cm as w,Fm as Z,Gm as P,Hm as y,Im as S,Jm as U,zm as Q}from"../chunk-qvn0w2rt.js";import{Nm as H}from"../chunk-ka8dzc6q.js";import"../chunk-3y1h3ncf.js";import{Vm as F}from"../chunk-ts75gcfd.js";var x="/__gemi__/health",$=Symbol.for("gemi.server.health");function V(){let z=globalThis;return z[$]??={lagMs:0,consecutiveBreaches:0,degraded:!1,timer:void 0},z[$]}function W(){let z=V(),B=Q();return{healthy:!B&&!z.degraded,shuttingDown:B,lagMs:z.lagMs,consecutiveBreaches:z.consecutiveBreaches}}function E(z,B){let I=V();I.lagMs=z,I.consecutiveBreaches=z>B.maxLagMs?I.consecutiveBreaches+1:0;let J=I.consecutiveBreaches>=B.breaches;if(J&&!I.degraded)console.warn(`[gemi] Health: degraded (event-loop lag ${Math.round(z)}ms, ${I.consecutiveBreaches} samples in a row over ${B.maxLagMs}ms).`);else if(!J&&I.degraded)console.log(`[gemi] Health: recovered (event-loop lag ${Math.round(z)}ms).`);I.degraded=J}function G(z){let B=V();if(B.timer)return;let I=performance.now()+z.intervalMs;B.timer=setInterval(()=>{let J=performance.now();E(Math.max(0,J-I),z),I=J+z.intervalMs},z.intervalMs),B.timer.unref?.()}function _(z=process.env){return{paths:D(z.GEMI_HEALTH_PATH),intervalMs:O("GEMI_HEALTH_INTERVAL_MS",z.GEMI_HEALTH_INTERVAL_MS,500),maxLagMs:O("GEMI_HEALTH_MAX_LAG_MS",z.GEMI_HEALTH_MAX_LAG_MS,1000),breaches:Math.ceil(O("GEMI_HEALTH_BREACHES",z.GEMI_HEALTH_BREACHES,3))}}function D(z){if(z===void 0||z.trim()==="")return[x];if(z.trim().toLowerCase()==="off")return[];let B=z.split(",").map((J)=>J.trim()).filter(Boolean);if(B.filter((J)=>!J.startsWith("/")).length>0)throw Error(`GEMI_HEALTH_PATH: expected comma-separated paths starting with "/", or "off"; got ${JSON.stringify(z)}.`);return B}function O(z,B,I){if(B===void 0||B.trim()==="")return I;let J=Number(B);if(Number.isFinite(J)&&J>0)return J;return console.warn(`[gemi] Ignoring ${z}="${B}": expected a positive number.`),I}function j(z,B){if(B.length===0)return z;let I=new Set(B);return async(J,K)=>{if(!B.some((b)=>J.url.includes(b))||!I.has(new URL(J.url).pathname))return z(J,K);return y(R(J.method))}}function R(z){let B={"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"};if(z!=="GET"&&z!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{...B,Allow:"GET, HEAD"}});let{healthy:I,shuttingDown:J}=W();return new Response(z==="HEAD"?null:I?"ok":J?"shutting down":"degraded",{status:I?200:503,headers:B})}var L=Symbol.for("gemi.server.devGeneration"),X={graceMs:1e4,providerTimeoutMs:5000};class Y{app;inFlight=0;waiters=new Set;constructor(z){this.app=z}track(z){return async(B,I)=>{this.inFlight++;try{return await z(B,I)}finally{if(this.inFlight--,this.inFlight===0)this.wake()}}}get pending(){return this.inFlight}async retire({graceMs:z,providerTimeoutMs:B}){try{await this.idle(z),await Promise.resolve().then(()=>this.app.shutdown({timeoutMs:B}))}catch(I){C(I)}}idle(z){if(this.inFlight===0)return Promise.resolve();return new Promise((B)=>{let I=()=>{clearTimeout(J),this.waiters.delete(I),B()},J=setTimeout(I,z);this.waiters.add(I)})}wake(){for(let z of this.waiters)z()}}function N(z,B=X){let I=globalThis,J=I[L];if(I[L]=z,!J||J===z||typeof J.retire!=="function")return Promise.resolve();let K=J.retire.bind(J);return Promise.resolve().then(()=>K(B)).catch(C)}function C(z){console.error("[gemi] Shutting down the application a reload replaced failed:",z)}class k{app;instrumentation;handleSignals;server;stopping;settings;constructor(z){this.app=new A({kernel:z.kernel}),this.handleSignals=z.handleSignals??!0,this.instrumentation=S(z.instrumentation??((B,I)=>I(B)))}async start(){process.env.ROOT_DIR=H();let z=Bun.env.NODE_ENV==="production",B=_();if(z)G(B);let I=j(this.instrumentation,B.paths);if(z){if(this.handleSignals)U(()=>this.stop());this.settings=Z()}try{await this.app.waitForBoot()}catch(J){if(!z)this.app.shutdown({timeoutMs:X.providerTimeoutMs});throw J}if(z){let{httpProd:J}=await import("../chunk-
|
|
2
|
+
import{Ra as f}from"../chunk-ba1h9pm6.js";import{Sa as A}from"../chunk-4vn8gyzy.js";import{Bm as q,Cm as w,Fm as Z,Gm as P,Hm as y,Im as S,Jm as U,zm as Q}from"../chunk-qvn0w2rt.js";import{Nm as H}from"../chunk-ka8dzc6q.js";import"../chunk-3y1h3ncf.js";import{Vm as F}from"../chunk-ts75gcfd.js";var x="/__gemi__/health",$=Symbol.for("gemi.server.health");function V(){let z=globalThis;return z[$]??={lagMs:0,consecutiveBreaches:0,degraded:!1,timer:void 0},z[$]}function W(){let z=V(),B=Q();return{healthy:!B&&!z.degraded,shuttingDown:B,lagMs:z.lagMs,consecutiveBreaches:z.consecutiveBreaches}}function E(z,B){let I=V();I.lagMs=z,I.consecutiveBreaches=z>B.maxLagMs?I.consecutiveBreaches+1:0;let J=I.consecutiveBreaches>=B.breaches;if(J&&!I.degraded)console.warn(`[gemi] Health: degraded (event-loop lag ${Math.round(z)}ms, ${I.consecutiveBreaches} samples in a row over ${B.maxLagMs}ms).`);else if(!J&&I.degraded)console.log(`[gemi] Health: recovered (event-loop lag ${Math.round(z)}ms).`);I.degraded=J}function G(z){let B=V();if(B.timer)return;let I=performance.now()+z.intervalMs;B.timer=setInterval(()=>{let J=performance.now();E(Math.max(0,J-I),z),I=J+z.intervalMs},z.intervalMs),B.timer.unref?.()}function _(z=process.env){return{paths:D(z.GEMI_HEALTH_PATH),intervalMs:O("GEMI_HEALTH_INTERVAL_MS",z.GEMI_HEALTH_INTERVAL_MS,500),maxLagMs:O("GEMI_HEALTH_MAX_LAG_MS",z.GEMI_HEALTH_MAX_LAG_MS,1000),breaches:Math.ceil(O("GEMI_HEALTH_BREACHES",z.GEMI_HEALTH_BREACHES,3))}}function D(z){if(z===void 0||z.trim()==="")return[x];if(z.trim().toLowerCase()==="off")return[];let B=z.split(",").map((J)=>J.trim()).filter(Boolean);if(B.filter((J)=>!J.startsWith("/")).length>0)throw Error(`GEMI_HEALTH_PATH: expected comma-separated paths starting with "/", or "off"; got ${JSON.stringify(z)}.`);return B}function O(z,B,I){if(B===void 0||B.trim()==="")return I;let J=Number(B);if(Number.isFinite(J)&&J>0)return J;return console.warn(`[gemi] Ignoring ${z}="${B}": expected a positive number.`),I}function j(z,B){if(B.length===0)return z;let I=new Set(B);return async(J,K)=>{if(!B.some((b)=>J.url.includes(b))||!I.has(new URL(J.url).pathname))return z(J,K);return y(R(J.method))}}function R(z){let B={"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"};if(z!=="GET"&&z!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{...B,Allow:"GET, HEAD"}});let{healthy:I,shuttingDown:J}=W();return new Response(z==="HEAD"?null:I?"ok":J?"shutting down":"degraded",{status:I?200:503,headers:B})}var L=Symbol.for("gemi.server.devGeneration"),X={graceMs:1e4,providerTimeoutMs:5000};class Y{app;inFlight=0;waiters=new Set;constructor(z){this.app=z}track(z){return async(B,I)=>{this.inFlight++;try{return await z(B,I)}finally{if(this.inFlight--,this.inFlight===0)this.wake()}}}get pending(){return this.inFlight}async retire({graceMs:z,providerTimeoutMs:B}){try{await this.idle(z),await Promise.resolve().then(()=>this.app.shutdown({timeoutMs:B}))}catch(I){C(I)}}idle(z){if(this.inFlight===0)return Promise.resolve();return new Promise((B)=>{let I=()=>{clearTimeout(J),this.waiters.delete(I),B()},J=setTimeout(I,z);this.waiters.add(I)})}wake(){for(let z of this.waiters)z()}}function N(z,B=X){let I=globalThis,J=I[L];if(I[L]=z,!J||J===z||typeof J.retire!=="function")return Promise.resolve();let K=J.retire.bind(J);return Promise.resolve().then(()=>K(B)).catch(C)}function C(z){console.error("[gemi] Shutting down the application a reload replaced failed:",z)}class k{app;instrumentation;handleSignals;server;stopping;settings;constructor(z){this.app=new A({kernel:z.kernel}),this.handleSignals=z.handleSignals??!0,this.instrumentation=S(z.instrumentation??((B,I)=>I(B)))}async start(){process.env.ROOT_DIR=H();let z=Bun.env.NODE_ENV==="production",B=_();if(z)G(B);let I=j(this.instrumentation,B.paths);if(z){if(this.handleSignals)U(()=>this.stop());this.settings=Z()}try{await this.app.waitForBoot()}catch(J){if(!z)this.app.shutdown({timeoutMs:X.providerTimeoutMs});throw J}if(z){let{httpProd:J}=await import("../chunk-wbj4jh1h.js");this.server=await J(this.app,I)}else{f();let{httpDev:J}=await import("../chunk-0e5sq42y.js"),K=new Y(this.app);this.server=await J(this.app,K.track(I)),N(K)}return this.server}stop(z={}){let B=this.app.sockets();return this.stopping??=P({server:this.server,closeSockets:B?()=>B.shutdown():void 0,shutdownProviders:(I)=>this.app.shutdown(I),settings:{...this.settings??Z(),...z}}),this.stopping}}export{q as shutdownSignal,W as liveness,Q as isShuttingDown,w as holdShutdown,k as Server};
|
|
3
3
|
|
|
4
4
|
//# debugId=E62905FC87416C0564756E2164756E21
|
package/dist/services/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{rb as z$}from"../chunk-g6tqje74.js";import{$b as t9,Ab as g4,Bb as s1,Cb as F9,Db as L9,Eb as v9,Ib as I9,Jb as f9,Kb as y9,Lb as A9,Mb as g9,Nb as m9,Ob as c9,Pb as u9,Qb as p9,Rb as d9,Sb as l9,Tb as n4,Ub as v6,Vb as h,Wb as n9,Xb as i9,Yb as s9,Zb as o9,_b as a9,ac as r9,bc as e9,cc as W$,dc as Z$,ec as $$,fc as Q$,gc as Y$,hc as K$,ic as J$,sb as z9,tb as G9,ub as X9,vb as B9,wb as j9,xb as u4,yb as M9,zb as E4}from"../chunk-9359fg6r.js";import{lc as d4}from"../chunk-t5gbp0yr.js";import"../chunk-gvr7cwxn.js";import{ee as D9,fe as H9,ge as N9,he as U9,ie as x9,je as R9,ke as O9,le as _9,me as V9,ne as k9,oe as C9,pe as T9,qe as P9,re as b9,se as w9,te as q9}from"../chunk-8mpptpn5.js";import{ue as S9}from"../chunk-g7hz0dmk.js";import{Ae as nZ,Be as iZ,Ce as sZ,De as oZ,Ee as aZ,Fe as tZ,Ge as rZ,He as eZ,Ie as W9,Je as Z9,Ke as $9,Le as Q9,Me as Y9,Ne as K9,Se as J9,ve as cZ,we as uZ,xe as pZ,ye as dZ,ze as lZ}from"../chunk-x185900b.js";import{Te as h9,Ue as E9}from"../chunk-yahabnz4.js";import"../chunk-9kt24ctk.js";import{$f as b8,Af as z8,Ag as BZ,Bf as G8,Bg as jZ,Cf as X8,Cg as MZ,Df as B8,Dg as FZ,Ef as j8,Eg as LZ,Ff as Y6,Fg as DZ,Fh as yZ,Gf as M8,Gg as HZ,Gh as AZ,Hf as F8,Hg as NZ,If as L8,Ig as UZ,Jf as D8,Kf as H8,Ng as R,Og as i,Pg as xZ,Qg as SZ,Rg as RZ,Sg as OZ,Tg as _Z,Vg as VZ,Wg as kZ,Xg as CZ,Yg as TZ,Zf as T8,_f as P8,_g as PZ,af as V6,ag as w8,bf as e5,bg as q8,bh as bZ,cf as W8,cg as v8,ch as wZ,df as Z8,dh as qZ,ff as $8,gh as vZ,jg as e8,kg as q6,lf as k6,lg as WZ,lh as IZ,mf as C4,nf as B6,of as T4,pf as P4,pg as ZZ,ph as fZ,qg as $Z,rg as YZ,tf as f6,th as i4,uf as y6,ug as KZ,uh as z1,vg as JZ,wf as Q8,wg as zZ,xf as Y8,xg as GZ,yf as K8,zf as J8,zg as XZ}from"../chunk-cb7mgx75.js";import"../chunk-zm6b938z.js";import"../chunk-2kzysesp.js";import{$i as _4,Ai as k1,Si as h4,Wi as j1,Yi as Y1,aj as C1,bj as p1,cj as N8,dj as U8,ej as x8,fj as S8,gj as R8,sj as mW,tj as cW,wj as O8,xj as _8,yi as k4,zi as O4,zj as d1}from"../chunk-fqndtpwm.js";import"../chunk-h1wmpa03.js";import{Kj as V8,Lj as k8,Mj as C8}from"../chunk-t6x1r5n6.js";import{Oj as q}from"../chunk-naj8bmj5.js";import{$j as u8,Wj as g8,Xj as m8,Yj as U,Zj as c8,_j as b,ak as p8}from"../chunk-np6vee9d.js";import{gk as A8,hk as h8,ik as E8}from"../chunk-5exrgw07.js";import"../chunk-jssjfvsz.js";import{Rk as QZ}from"../chunk-a119av2z.js";import{$k as o8,Tk as I8,Uk as f8,Vk as y8,Wk as d8,Xk as l8,Yk as n8,Zk as i8,_k as s8,el as a8,fl as t8,gl as r8}from"../chunk-m3fbewhz.js";import"../chunk-x2dmgge8.js";import"../chunk-fs94x6ef.js";import"../chunk-8476xvk9.js";import"../chunk-kvtvx64t.js";import{bm as w4,cm as hZ,dm as EZ,em as gZ,gm as mZ}from"../chunk-1xz206e1.js";import"../chunk-9jt5qj1b.js";import{qm as C}from"../chunk-17ewxwga.js";import"../chunk-sv2mv2q2.js";import"../chunk-gt9ftnhn.js";import"../chunk-qvn0w2rt.js";import"../chunk-ka8dzc6q.js";import"../chunk-3y1h3ncf.js";import{Vm as u1}from"../chunk-ts75gcfd.js";import{Buffer as K6}from"buffer";class J6 extends C1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-8gz07168.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket??K,Q=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);Q=Q||void 0;let J=$ instanceof K6?$:$ instanceof Blob||$ instanceof File?K6.from(await $.arrayBuffer()):"",{sdk:z,client:G}=await this.connect();return Z?.throwIfAborted(),await G.send(new z.PutObjectCommand({Bucket:K,Key:Y,Body:J,ContentType:Q}),{abortSignal:Z}),Y}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();try{await Y.send(new Q.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(K){if(K?.name==="NoSuchKey"||K?.$metadata?.httpStatusCode===404)return;throw K}}async*pages(W,{bucket:Z,signal:$}){let{sdk:Q,client:Y}=await this.connect(),K;do{$?.throwIfAborted();let J=await Y.send(new Q.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:K}),{abortSignal:$});yield(J.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),K=J.IsTruncated?J.NextContinuationToken:void 0}while(K)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){_4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect(),K=0;for await(let J of this.pages(W,{...Z,bucket:$})){if(J.length===0)continue;Z.signal?.throwIfAborted();let G=(await Y.send(new Q.DeleteObjectsCommand({Bucket:$,Delete:{Objects:J.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(G.length>0){let X=G[0];throw Error(`S3 could not delete ${G.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}K+=J.length}return K}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,Q;if(typeof W==="string")Q=W;else $=W.bucket??$,Q=W.name;if(!Q)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect();Z?.throwIfAborted();let J=await K.send(new Y.GetObjectCommand({Bucket:$,Key:Q}),{abortSignal:Z}),z=p1(J.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":J.ContentType,"Content-Length":J.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":J.LastModified?.toUTCString()||"",ETag:J.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:Q,range:Y=null}=Z;if(!Q)throw Error("Object name has to be specified");let{sdk:K,client:J}=await this.connect(),z;try{z=await J.send(new K.GetObjectCommand({Bucket:$,Key:Q,Range:Y?O4(Y):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new j1(await this.size({name:Q,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new Y1(Q);throw j}let G=k1(z.ContentRange),X=Boolean(G)&&z.$metadata?.httpStatusCode===206,B=G?.total??z.ContentLength??0;return{body:z.Body.transformToWebStream(),start:G?.start??0,end:G?.end??B-1,total:B,partial:X,type:z.ContentType??"application/octet-stream",etag:z.ETag||void 0,lastModified:z.LastModified,name:Q}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect();try{return(await Y.send(new Q.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(K){if(K?.name==="NotFound"||K?.$metadata?.httpStatusCode===404)throw new Y1(Z);throw K}}}import{Buffer as z6}from"buffer";import{Readable as dW}from"stream";function V4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function lW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class G6 extends C1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket,Q=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let J=$ instanceof z6?$:z6.from(await $.arrayBuffer()),z=await this.blob(Y,K);return Z?.throwIfAborted(),await z.uploadData(J,{blobHTTPHeaders:Q?{blobContentType:Q}:void 0,abortSignal:Z}),Y}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let Q=Z??this.config.container??process.env.BUCKET_NAME;if(!Q)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let K=(await this.serviceClient()).getContainerClient(Q);for await(let J of K.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:J.name,size:J.properties?.contentLength??0,lastModified:J.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,Q=(await this.serviceClient()).getContainerClient(Z),Y=[];for await(let K of Q.listBlobsFlat({prefix:W}))Y.push(K.name);return Y}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:Q,range:Y=null}=W,K=await this.blob($,Q);Z?.throwIfAborted();let J,z,G=Y?.kind==="suffix"||Y?.kind==="offset"&&Y.end===null&&Y.start===0;if(Y&&G){let V=await this.size({name:$,bucket:Q}),Q1=k4(Y,V);if(!Q1)throw new j1(V);J=Q1.start,z=Q1.length}else if(Y?.kind==="offset")J=Y.start,z=Y.end===null?void 0:Y.end-Y.start+1;let X;try{X=await K.download(J,z,Z?{abortSignal:Z}:void 0)}catch(V){if(lW(V))throw new j1(await this.size({name:$,bucket:Q}));if(V4(V))throw new Y1($);throw V}let B=k1(X.contentRange),j=Boolean(B),D=B?.total??X.contentLength??0,x=await nW(X);if(x instanceof ReadableStream)x=p1(x,Z);return Z?.throwIfAborted(),{body:x,start:B?.start??0,end:B?.end??D-1,total:D,partial:j,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{return(await Q.getProperties()).contentLength??0}catch(Y){if(V4(Y))throw new Y1(Z);throw Y}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{await Q.delete()}catch(Y){if(V4(Y))return;throw Y}}}async function nW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return dW.toWeb(W.readableStreamBody);return null}function iW(W){return W}class b4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class l1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var X6=1000,sW=60000,oW=`
|
|
2
|
+
import{rb as z$}from"../chunk-g6tqje74.js";import{$b as t9,Ab as g4,Bb as s1,Cb as F9,Db as L9,Eb as v9,Ib as I9,Jb as f9,Kb as y9,Lb as A9,Mb as g9,Nb as m9,Ob as c9,Pb as u9,Qb as p9,Rb as d9,Sb as l9,Tb as n4,Ub as v6,Vb as h,Wb as n9,Xb as i9,Yb as s9,Zb as o9,_b as a9,ac as r9,bc as e9,cc as W$,dc as Z$,ec as $$,fc as Q$,gc as Y$,hc as K$,ic as J$,sb as z9,tb as G9,ub as X9,vb as B9,wb as j9,xb as u4,yb as M9,zb as E4}from"../chunk-yknc5rgh.js";import{lc as d4}from"../chunk-dav7mv8t.js";import"../chunk-gvr7cwxn.js";import{ee as D9,fe as H9,ge as N9,he as U9,ie as x9,je as R9,ke as O9,le as _9,me as V9,ne as k9,oe as C9,pe as T9,qe as P9,re as b9,se as w9,te as q9}from"../chunk-8mpptpn5.js";import{ue as S9}from"../chunk-g7hz0dmk.js";import{Ae as nZ,Be as iZ,Ce as sZ,De as oZ,Ee as aZ,Fe as tZ,Ge as rZ,He as eZ,Ie as W9,Je as Z9,Ke as $9,Le as Q9,Me as Y9,Ne as K9,Se as J9,ve as cZ,we as uZ,xe as pZ,ye as dZ,ze as lZ}from"../chunk-x185900b.js";import{Te as h9,Ue as E9}from"../chunk-yahabnz4.js";import"../chunk-9kt24ctk.js";import{$f as b8,Af as z8,Ag as BZ,Bf as G8,Bg as jZ,Cf as X8,Cg as MZ,Df as B8,Dg as FZ,Ef as j8,Eg as LZ,Ff as Y6,Fg as DZ,Fh as yZ,Gf as M8,Gg as HZ,Gh as AZ,Hf as F8,Hg as NZ,If as L8,Ig as UZ,Jf as D8,Kf as H8,Ng as R,Og as i,Pg as xZ,Qg as SZ,Rg as RZ,Sg as OZ,Tg as _Z,Vg as VZ,Wg as kZ,Xg as CZ,Yg as TZ,Zf as T8,_f as P8,_g as PZ,af as V6,ag as w8,bf as e5,bg as q8,bh as bZ,cf as W8,cg as v8,ch as wZ,df as Z8,dh as qZ,ff as $8,gh as vZ,jg as e8,kg as q6,lf as k6,lg as WZ,lh as IZ,mf as C4,nf as B6,of as T4,pf as P4,pg as ZZ,ph as fZ,qg as $Z,rg as YZ,tf as f6,th as i4,uf as y6,ug as KZ,uh as z1,vg as JZ,wf as Q8,wg as zZ,xf as Y8,xg as GZ,yf as K8,zf as J8,zg as XZ}from"../chunk-73541m4t.js";import"../chunk-zm6b938z.js";import"../chunk-2kzysesp.js";import{$i as _4,Ai as k1,Si as h4,Wi as j1,Yi as Y1,aj as C1,bj as p1,cj as N8,dj as U8,ej as x8,fj as S8,gj as R8,sj as mW,tj as cW,wj as O8,xj as _8,yi as k4,zi as O4,zj as d1}from"../chunk-fqndtpwm.js";import"../chunk-h1wmpa03.js";import{Kj as V8,Lj as k8,Mj as C8}from"../chunk-t6x1r5n6.js";import{Oj as q}from"../chunk-naj8bmj5.js";import{$j as u8,Wj as g8,Xj as m8,Yj as U,Zj as c8,_j as b,ak as p8}from"../chunk-np6vee9d.js";import{gk as A8,hk as h8,ik as E8}from"../chunk-5exrgw07.js";import"../chunk-jssjfvsz.js";import{Rk as QZ}from"../chunk-a119av2z.js";import{$k as o8,Tk as I8,Uk as f8,Vk as y8,Wk as d8,Xk as l8,Yk as n8,Zk as i8,_k as s8,el as a8,fl as t8,gl as r8}from"../chunk-m3fbewhz.js";import"../chunk-x2dmgge8.js";import"../chunk-fs94x6ef.js";import"../chunk-8476xvk9.js";import"../chunk-kvtvx64t.js";import{bm as w4,cm as hZ,dm as EZ,em as gZ,gm as mZ}from"../chunk-1xz206e1.js";import"../chunk-9jt5qj1b.js";import{qm as C}from"../chunk-17ewxwga.js";import"../chunk-sv2mv2q2.js";import"../chunk-gt9ftnhn.js";import"../chunk-qvn0w2rt.js";import"../chunk-ka8dzc6q.js";import"../chunk-3y1h3ncf.js";import{Vm as u1}from"../chunk-ts75gcfd.js";import{Buffer as K6}from"buffer";class J6 extends C1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-8gz07168.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket??K,Q=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);Q=Q||void 0;let J=$ instanceof K6?$:$ instanceof Blob||$ instanceof File?K6.from(await $.arrayBuffer()):"",{sdk:z,client:G}=await this.connect();return Z?.throwIfAborted(),await G.send(new z.PutObjectCommand({Bucket:K,Key:Y,Body:J,ContentType:Q}),{abortSignal:Z}),Y}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();try{await Y.send(new Q.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(K){if(K?.name==="NoSuchKey"||K?.$metadata?.httpStatusCode===404)return;throw K}}async*pages(W,{bucket:Z,signal:$}){let{sdk:Q,client:Y}=await this.connect(),K;do{$?.throwIfAborted();let J=await Y.send(new Q.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:K}),{abortSignal:$});yield(J.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),K=J.IsTruncated?J.NextContinuationToken:void 0}while(K)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){_4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect(),K=0;for await(let J of this.pages(W,{...Z,bucket:$})){if(J.length===0)continue;Z.signal?.throwIfAborted();let G=(await Y.send(new Q.DeleteObjectsCommand({Bucket:$,Delete:{Objects:J.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(G.length>0){let X=G[0];throw Error(`S3 could not delete ${G.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}K+=J.length}return K}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,Q;if(typeof W==="string")Q=W;else $=W.bucket??$,Q=W.name;if(!Q)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect();Z?.throwIfAborted();let J=await K.send(new Y.GetObjectCommand({Bucket:$,Key:Q}),{abortSignal:Z}),z=p1(J.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":J.ContentType,"Content-Length":J.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":J.LastModified?.toUTCString()||"",ETag:J.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:Q,range:Y=null}=Z;if(!Q)throw Error("Object name has to be specified");let{sdk:K,client:J}=await this.connect(),z;try{z=await J.send(new K.GetObjectCommand({Bucket:$,Key:Q,Range:Y?O4(Y):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new j1(await this.size({name:Q,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new Y1(Q);throw j}let G=k1(z.ContentRange),X=Boolean(G)&&z.$metadata?.httpStatusCode===206,B=G?.total??z.ContentLength??0;return{body:z.Body.transformToWebStream(),start:G?.start??0,end:G?.end??B-1,total:B,partial:X,type:z.ContentType??"application/octet-stream",etag:z.ETag||void 0,lastModified:z.LastModified,name:Q}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect();try{return(await Y.send(new Q.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(K){if(K?.name==="NotFound"||K?.$metadata?.httpStatusCode===404)throw new Y1(Z);throw K}}}import{Buffer as z6}from"buffer";import{Readable as dW}from"stream";function V4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function lW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class G6 extends C1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket,Q=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let J=$ instanceof z6?$:z6.from(await $.arrayBuffer()),z=await this.blob(Y,K);return Z?.throwIfAborted(),await z.uploadData(J,{blobHTTPHeaders:Q?{blobContentType:Q}:void 0,abortSignal:Z}),Y}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let Q=Z??this.config.container??process.env.BUCKET_NAME;if(!Q)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let K=(await this.serviceClient()).getContainerClient(Q);for await(let J of K.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:J.name,size:J.properties?.contentLength??0,lastModified:J.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,Q=(await this.serviceClient()).getContainerClient(Z),Y=[];for await(let K of Q.listBlobsFlat({prefix:W}))Y.push(K.name);return Y}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:Q,range:Y=null}=W,K=await this.blob($,Q);Z?.throwIfAborted();let J,z,G=Y?.kind==="suffix"||Y?.kind==="offset"&&Y.end===null&&Y.start===0;if(Y&&G){let V=await this.size({name:$,bucket:Q}),Q1=k4(Y,V);if(!Q1)throw new j1(V);J=Q1.start,z=Q1.length}else if(Y?.kind==="offset")J=Y.start,z=Y.end===null?void 0:Y.end-Y.start+1;let X;try{X=await K.download(J,z,Z?{abortSignal:Z}:void 0)}catch(V){if(lW(V))throw new j1(await this.size({name:$,bucket:Q}));if(V4(V))throw new Y1($);throw V}let B=k1(X.contentRange),j=Boolean(B),D=B?.total??X.contentLength??0,x=await nW(X);if(x instanceof ReadableStream)x=p1(x,Z);return Z?.throwIfAborted(),{body:x,start:B?.start??0,end:B?.end??D-1,total:D,partial:j,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{return(await Q.getProperties()).contentLength??0}catch(Y){if(V4(Y))throw new Y1(Z);throw Y}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{await Q.delete()}catch(Y){if(V4(Y))return;throw Y}}}async function nW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return dW.toWeb(W.readableStreamBody);return null}function iW(W){return W}class b4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class l1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var X6=1000,sW=60000,oW=`
|
|
3
3
|
local currentKey = KEYS[1]
|
|
4
4
|
local previousKey = KEYS[2]
|
|
5
5
|
local limit = tonumber(ARGV[1])
|
|
@@ -80,7 +80,7 @@ export type McpApiKey = {
|
|
|
80
80
|
};
|
|
81
81
|
export type McpApiKeyResolverOptions = {
|
|
82
82
|
/**
|
|
83
|
-
* The prefix every key of this app starts with, like `"
|
|
83
|
+
* The prefix every key of this app starts with, like `"acme_mcp_"`.
|
|
84
84
|
* Required: a bearer token without it is left for the next resolver (an
|
|
85
85
|
* OAuth access token), and a key is never looked up by a resolver that did
|
|
86
86
|
* not issue it. Also what makes a leaked key recognisable to a secret
|
package/dist/testing/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { $ as toVariantKey, B as ProgressManager, Ct as Subject, G as RealtimeContext, J as liveModule, N as I18nProvider, P as ServerDataContext, c as ClientRouterContext, et as applyParams, i as RouteTransitionProvider, nt as QueryManagerContext, r as m, rt as QueryManagerProvider, t as ThemeProvider } from "../chunks/ThemeProvider-
|
|
1
|
+
import { $ as toVariantKey, B as ProgressManager, Ct as Subject, G as RealtimeContext, J as liveModule, N as I18nProvider, P as ServerDataContext, c as ClientRouterContext, et as applyParams, i as RouteTransitionProvider, nt as QueryManagerContext, r as m, rt as QueryManagerProvider, t as ThemeProvider } from "../chunks/ThemeProvider-1WtAS7dH.js";
|
|
2
2
|
import { r as RouteStateProvider } from "../chunks/useParams-BN3XXfmG.js";
|
|
3
3
|
import "../chunks/urlpattern-polyfill-Cc7YrzJf.js";
|
|
4
4
|
import { t as channelKey } from "../chunks/channelKey-CIhHpX6x.js";
|
|
5
|
-
import { t as followLive } from "../chunks/live-
|
|
5
|
+
import { t as followLive } from "../chunks/live-twEh9Qwt.js";
|
|
6
6
|
import { Suspense, createElement, useContext, useMemo, useRef, useState } from "react";
|
|
7
7
|
import { jsx } from "react/jsx-runtime";
|
|
8
8
|
import { hydrateRoot } from "react-dom/client";
|
package/package.json
CHANGED
|
File without changes
|