@m1212e/rumble 0.0.10 → 0.2.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/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  # rumble
2
- rumble is a combined ability and graphql builder built around [drizzle](https://orm.drizzle.team/docs/overview) and [pothos](https://pothos-graphql.dev/docs/plugins/drizzle), inspired by [CASL](https://casl.js.org/v6/en/). It takes much of the required configuration of your shoulders and makes creating a GraphQL server very easy!
2
+ rumble is a combined ability and graphql builder built around [drizzle](https://orm.drizzle.team/docs/overview) and [pothos](https://pothos-graphql.dev/docs/plugins/drizzle), inspired by [CASL](https://casl.js.org/v6/en/). It takes much of the required configuration off your shoulders and makes creating a GraphQL server very easy!
3
3
 
4
4
  > Please note that drizzle hasn't reached a full stable release yet and, as shown in the warning [here](https://pothos-graphql.dev/docs/plugins/drizzle), this is not stable yet.
5
5
 
@@ -25,7 +25,7 @@ export const db = drizzle(
25
25
  { schema }
26
26
  );
27
27
 
28
- const { abilityBuilder, schemaBuilder, yoga, implementDefaultObject } = rumble({ db });
28
+ const { abilityBuilder } = rumble({ db });
29
29
  ```
30
30
  > If the creation of a drizzle instance with the schema definition seems unfamiliar to you, please see their excellent [getting started guide](https://orm.drizzle.team/docs/get-started)
31
31
 
@@ -45,7 +45,7 @@ The `when` call accepts a variety of restrictions which have different effects.
45
45
  #### Dynamic abilities
46
46
  Most of the time we want to allow things based on who the user is. If they are logged in they should be able to change their username. But only theirs, not the ones of any other users. For this, abilities allow for conditions based on the call context of a request. To use this, we need to create a context callback when initiating rumble first:
47
47
  ```ts
48
- const { abilityBuilder, schemaBuilder, yoga, implementDefaultObject } =
48
+ const { abilityBuilder } =
49
49
  rumble({
50
50
  db,
51
51
  // the type of the request parameter may vary based on the HTTP library you are using.
@@ -85,124 +85,8 @@ const PostRef = schemaBuilder.drizzleObject("posts", {
85
85
  ```
86
86
  In the above object definition we tell pothos to expose the id and content so the fields will be just passed along from out database results and we define a relation to the posts author. We also restrict which author can be read. If the user which sends this request is not the author of a post, they cannot see the author and the request will fail. The `ctx.abilities.users.filter("read")` call simply injects the filter we defined in the abilities earlier and therefore restricts what can be returned.
87
87
 
88
- #### Automatic object implementation
89
- Since this can get a little extensive, especially for large models, rumble offers the `implementDefaultObject` helper. This does all of the above and will simply expose all fields and relations but with the ability restrictions applied.
90
- ```ts
91
- const UserRef = implementDefaultObject({
92
- name: "User",
93
- tableName: "users",
94
- });
95
- ```
96
-
97
- #### Automatic arg implementation
98
- rumble also supports automatically implementing basic filtering args. Those currently only allow for equality filtering for each field. E.g. the user can pass an email or an id and retrieve only results matching these for equality. Implementation works like this
99
- ```ts
100
- const {
101
- // the input arg type, here we rename it to UserWhere
102
- inputType: UserWhere,
103
- // since drizzle wants proper instantiated filter clauses with `eq` calls and references to each field
104
- // we need a transformer function which converts the object received from gql to a drizzle filter
105
- transformArgumentToQueryCondition: transformUserWhere,
106
- } = implementWhereArg({
107
- // for which table to implement this
108
- tableName: "users",
109
- });
110
- ```
111
- usage of the above argument type may look like this. This query will return all users which the currently logged in user, according to our defined abilities, is allowed to see AND which match the passed filter arguments.
112
- ```ts
113
- schemaBuilder.queryFields((t) => {
114
- return {
115
- findManyUsers: t.drizzleField({
116
- type: [UserRef],
117
- args: {
118
- // here we set our default type as type for the where argument
119
- where: t.arg({ type: UserWhere }),
120
- },
121
- resolve: (query, root, args, ctx, info) => {
122
- return db.query.users.findMany(
123
- query(
124
- ctx.abilities.users.filter("read",
125
- // this additional object offers temporarily injecting additional filters to our existing ability filters
126
- {
127
- // the inject field allows for temp, this time only filters to be added to our ability filters. They will only be applied for this specific call.
128
- inject: {
129
- // where conditions which are injected will be applied with an AND rather than an OR so the injected filter will further restrict the existing restrictions rather than expanding them
130
- where: transformUserWhere(args.where) },
131
- })
132
- )
133
- );
134
- },
135
- }),
136
- };
137
- });
138
- ```
139
-
140
- ### Defining queries and mutations
141
- Now we can define some things you can do. Again we use pothos for that. So please refer to [the docs](https://pothos-graphql.dev/docs/plugins/drizzle) if something is unclear.
142
- ```ts
143
- schemaBuilder.queryFields((t) => {
144
- return {
145
- findManyPosts: t.drizzleField({
146
- type: [PostRef],
147
- resolve: (query, root, args, ctx, info) => {
148
- return db.query.posts.findMany(
149
- query(ctx.abilities.posts.filter("read")),
150
- );
151
- },
152
- }),
153
- };
154
- });
155
-
156
- schemaBuilder.queryFields((t) => {
157
- return {
158
- findFirstUser: t.drizzleField({
159
- type: UserRef,
160
- resolve: (query, root, args, ctx, info) => {
161
- return (
162
- db.query.users
163
- .findFirst(
164
- query({
165
- where: ctx.abilities.users.filter("read").where,
166
- }),
167
- )
168
- // note that we need to manually raise an error if the value is not found
169
- // since there is a type mismatch between drizzle and pothos
170
- .then(assertFindFirstExists)
171
- );
172
- },
173
- }),
174
- };
175
- });
176
-
177
- // mutation to update the username
178
- schemaBuilder.mutationFields((t) => {
179
- return {
180
- updateUsername: t.drizzleField({
181
- type: UserRef,
182
- args: {
183
- userId: t.arg.int({ required: true }),
184
- newName: t.arg.string({ required: true }),
185
- },
186
- resolve: (query, root, args, ctx, info) => {
187
- return (
188
- db
189
- .update(schema.users)
190
- .set({
191
- name: args.newName,
192
- })
193
- .where(
194
- and(
195
- eq(schema.users.id, args.userId),
196
- ctx.abilities.users.filter("update").where,
197
- ),
198
- )
199
- .returning({ id: schema.users.id, name: schema.users.name })
200
- // note the different error mapper
201
- .then(assertFirstEntryExists)
202
- );
203
- },
204
- }),
205
- };
206
- });
88
+ ### Helpers
89
+ rumble offers a set of helpers which make it easy to implement your api. Please see the [full example code](./example/src/main.ts) for a more extensive demonstration of rumbles features.
207
90
 
208
- ```
91
+ ### Subscriptions
92
+ rumble supports subscriptions right out of the box. When using the rumble helpers, you basically get subscriptions for free, no additional work required!
package/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var P=require('@pothos/core'),j=require('@pothos/plugin-drizzle'),drizzleOrm=require('drizzle-orm'),graphqlYoga=require('graphql-yoga');require('console');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var P__default=/*#__PURE__*/_interopDefault(P);var j__default=/*#__PURE__*/_interopDefault(j);function E(r){return typeof r!="function"}function Q(r){return typeof r=="function"&&r.constructor.name!=="AsyncFunction"}var B=({db:r})=>{let l={},x={},D=f=>({allow:p=>{let y=x[f];y||(y={},x[f]=y);let i=Array.isArray(p)?p:[p];for(let C of i){let s=y[C];s||(s=[],y[C]=s);}return {when:C=>{for(let s of i)y[s].push(C);}}}});for(let f of Object.keys(r.query))l[f]=D(f);return {...l,registeredConditions:x,buildWithUserContext:f=>{let p={},y=i=>({filter:(C,s)=>{let c=x[i];if(!c)throw "TODO (No allowed entry found for this condition) #1";let d=c[C];if(!d)throw "TODO (No allowed entry found for this condition) #2";let T=d.filter(E),h=d.filter(Q).map(n=>n(f)),a=[...T,...h],o;for(let n of a)n.limit&&(o===void 0||n.limit>o)&&(o=n.limit);s?.inject?.limit&&o<s.inject.limit&&(o=s.inject.limit);let u;for(let n of [...a,s?.inject??{}])n.columns&&(u===void 0?u=n.columns:u={...u,...n.columns});let b=a.filter(n=>n.where).map(n=>n.where),t=b.length>0?drizzleOrm.or(...b):void 0;return s?.inject?.where&&(t=t?drizzleOrm.and(t,s.inject.where):s.inject.where),{where:t,columns:u,limit:o}}});for(let i of Object.keys(r.query))p[i]=y(i);return p}}};var m=class extends Error{constructor(l){super(l),this.name="RumbleError";}};var U=({db:r,nativeServerOptions:l,context:x,onlyQuery:D=!1,actions:f=["create","read","update","delete"]})=>{let p=B({db:r}),y=async c=>{let d=x?await x(c):{};return {...d,abilities:p.buildWithUserContext(d)}},i=new P__default.default({plugins:[j__default.default],drizzle:{client:r}});return i.queryType({}),D||i.mutationType({}),{abilityBuilder:p,schemaBuilder:i,yoga:()=>graphqlYoga.createYoga({...l,schema:i.toSchema(),context:y}),implementDefaultObject:({tableName:c,name:d,readAction:T="read"})=>{let h=r._.schema[c];return i.drizzleObject(c,{name:d,fields:a=>{let o=(t,e)=>{switch(t){case"serial":return a.exposeInt(e);case"int":return a.exposeInt(e);case"string":return a.exposeString(e);case"text":return a.exposeString(e);case"boolean":return a.exposeBoolean(e);default:throw new m(`Unknown SQL type: ${t}. Please open an issue so it can be added.`)}},u=Object.entries(h.columns).reduce((t,[e,n])=>(t[e]=o(n.getSQLType(),e),t),{}),b=Object.entries(h.relations).reduce((t,[e,n])=>(t[e]=a.relation(e,{query:(L,g)=>g.abilities[e].filter(T)}),t),{});return {...u,...b}}})},implementWhereArg:({tableName:c,name:d})=>{let T=r._.schema[c];return {inputType:i.inputType(d??`${String(c).charAt(0).toUpperCase()+String(c).slice(1)}WhereInputArgument`,{fields:o=>{let u=(t,e)=>{switch(t){case"serial":return o.int(e,{required:!1});case"int":return o.int(e,{required:!1});case"string":return o.string(e,{required:!1});case"text":return o.string(e,{required:!1});case"boolean":return o.boolean(e,{required:!1});default:throw new m(`Unknown SQL type: ${t} (input). Please open an issue so it can be added.`)}};return {...Object.entries(T.columns).reduce((t,[e,n])=>(t[e]=u(n.getSQLType(),e),t),{})}}}),transformArgumentToQueryCondition:o=>{if(!o)return;let u=t=>{let e=T.columns[t],n=o[t];if(n)return drizzleOrm.eq(e,n)},b=Object.keys(T.columns).map(u);return drizzleOrm.and(...b)}}}}};var z=r=>{if(!r)throw new m("Value not found but required (findFirst)");return r},q=r=>{let l=r.at(0);if(!l)throw new m("Value not found but required (firstEntry)");return l};exports.RumbleError=m;exports.assertFindFirstExists=z;exports.assertFirstEntryExists=q;exports.rumble=U;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var graphqlYoga=require('graphql-yoga'),drizzleOrm=require('drizzle-orm'),K=require('@pothos/core'),$=require('@pothos/plugin-drizzle'),M=require('@pothos/plugin-smart-subscriptions');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var K__default=/*#__PURE__*/_interopDefault(K);var $__default=/*#__PURE__*/_interopDefault($);var M__default=/*#__PURE__*/_interopDefault(M);var b=class extends Error{constructor(i){super(i),this.name="RumbleError";}};function O(e){return typeof e!="function"}function F(e){return typeof e=="function"&&e.constructor.name!=="AsyncFunction"}var I=({db:e})=>{let i=e._.schema,a={},t={},n=o=>({allow:d=>{let s=t[o];s||(s={},t[o]=s);let p=Array.isArray(d)?d:[d];for(let c of p){let r=s[c];r||(r=[],s[c]=r);}return {when:c=>{for(let r of p)s[r].push(c);}}}});for(let o of Object.keys(e.query))a[o]=n(o);return {...a,registeredConditions:t,buildWithUserContext:o=>{let d={},s=p=>({filter:(c,r)=>{let l=t[p];l||(l={});let u=l[c];if(!l||!u){let m=i[p].primaryKey.at(0);if(!m)throw new b(`No primary key found for entity ${p.toString()}`);u=[{where:drizzleOrm.and(drizzleOrm.eq(m,"1"),drizzleOrm.eq(m,"2"))}];}let y=u.filter(O),f=u.filter(F).map(m=>m(o)),x=[...y,...f],D;for(let m of x)m.limit&&(D===void 0||m.limit>D)&&(D=m.limit);r?.inject?.limit&&D<r.inject.limit&&(D=r.inject.limit);let T;for(let m of [...x,r?.inject??{}])m.columns&&(T===void 0?T=m.columns:T={...T,...m.columns});let C=x.filter(m=>m.where).map(m=>m.where),g=C.length>0?drizzleOrm.or(...C):void 0;return r?.inject?.where&&(g=g?drizzleOrm.and(g,r.inject.where):r.inject.where),{where:g,columns:T,limit:D}}});for(let p of Object.keys(e.query))d[p]=s(p);return d}}};var z=({context:e,abilityBuilder:i})=>async a=>{let t=e?await e(a):{};return {...t,abilities:i.buildWithUserContext(t)}};function B(e){if(["serial","int","integer"].includes(e))return "int";if(["string","text","varchar","char","text(256)"].includes(e))return "string";if(e==="boolean")return "boolean";throw new b(`Unknown SQL type: ${e}. Please open an issue so it can be added.`)}var N="RUMBLE_SUBSCRIPTION_NOTIFICATION",j="REMOVED",L="UPDATED",_="CREATED";function S({action:e,tableName:i,primaryKeyValue:a}){let t;switch(e){case "created":t=_;break;case "removed":t=j;break;case "updated":t=L;break;default:throw new Error(`Unknown action: ${e}`)}return `${N}/${i}${a?`/${a}`:""}/${t}`}var q=({subscriptions:e})=>{let i=e?graphqlYoga.createPubSub(...e):graphqlYoga.createPubSub();return {pubsub:i,makePubSubInstance:({tableName:t})=>({registerOnInstance({instance:n,action:o,primaryKeyValue:d}){let s=S({tableName:t.toString(),action:o,primaryKeyValue:d});n.register(s);},created(){let n=S({tableName:t.toString(),action:"created"});return i.publish(n)},removed(n){let o=S({tableName:t.toString(),action:"removed"});return i.publish(o)},updated(n){let o=S({tableName:t.toString(),action:"updated",primaryKeyValue:n});return i.publish(o)}})}};var P=({db:e,schemaBuilder:i,makePubSubInstance:a})=>({tableName:t,name:n,readAction:o="read"})=>{let d=e._.schema[t],s=d.primaryKey.at(0)?.name;s||console.warn(`Could not find primary key for ${t.toString()}. Cannot register subscriptions!`);let{registerOnInstance:p}=a({tableName:t});return i.drizzleObject(t,{name:n,subscribe:(c,r,l)=>{if(!s)return;let u=r[s];if(!u){console.warn(`Could not find primary key value for ${JSON.stringify(r)}. Cannot register subscription!`);return}p({instance:c,action:"updated",primaryKeyValue:u});},fields:c=>{let r=(y,f)=>{switch(B(y)){case "int":return c.exposeInt(f);case "string":return c.exposeString(f);case "boolean":return c.exposeBoolean(f);default:throw new b(`Unknown SQL type: ${y}. Please open an issue so it can be added.`)}},l=Object.entries(d.columns).reduce((y,[f,x])=>(y[f]=r(x.getSQLType(),f),y),{}),u=Object.entries(d.relations).reduce((y,[f,x])=>(y[f]=c.relation(f,{query:(D,T)=>T.abilities[x.referencedTableName].filter(o)}),y),{});return {...l,...u}}})};function R(e){return String(e).charAt(0).toUpperCase()+String(e).slice(1)}var h=e=>{if(!e)throw new b("Value not found but required (findFirst)");return e},G=e=>{let i=e.at(0);if(!i)throw new b("Value not found but required (firstEntry)");return i};var v=({db:e,schemaBuilder:i,argImplementer:a,makePubSubInstance:t})=>({tableName:n,readAction:o="read",listAction:d="read"})=>{e._.schema[n].primaryKey.at(0)?.name||console.warn(`Could not find primary key for ${n.toString()}. Cannot register subscriptions!`);let{inputType:c,transformArgumentToQueryCondition:r}=a({tableName:n,name:`${n.toString()}Where_DefaultRumbleQueryArgument`}),{registerOnInstance:l}=t({tableName:n});return i.queryFields(u=>({[`findMany${R(n.toString())}`]:u.drizzleField({type:[n],smartSubscription:true,subscribe:(y,f,x,D,T)=>{l({instance:y,action:"created"}),l({instance:y,action:"removed"});},args:{where:u.arg({type:c,required:false})},resolve:(y,f,x,D,T)=>{let C=D.abilities[n].filter(o,{inject:{where:r(x.where)}}),g=y(C);return C.columns&&(g.columns=C.columns),e.query[n].findMany(g)}}),[`findFirst${R(n.toString())}`]:u.drizzleField({type:n,smartSubscription:true,args:{where:u.arg({type:c,required:false})},resolve:(y,f,x,D,T)=>{let C=D.abilities[n].filter(o,{inject:{where:r(x.where)}}),g=y(C);return C.columns&&(g.columns=C.columns),e.query[n].findFirst(g).then(h)}})}))};var k=({db:e,disableDefaultObjects:i,pubsub:a})=>{let t=new K__default.default({plugins:[$__default.default,M__default.default],drizzle:{client:e},smartSubscriptions:{...M.subscribeOptionsFromIterator((n,o)=>a.subscribe(n))}});return i?.query||t.queryType({}),i?.subscription||t.subscriptionType({}),i?.mutation||t.mutationType({}),{schemaBuilder:t}};var w=({db:e,schemaBuilder:i})=>({tableName:a,name:t})=>{let n=e._.schema[a];return {inputType:i.inputType(t??`${R(a.toString())}WhereInputArgument`,{fields:s=>{let p=r=>{switch(B(r)){case "int":return s.int({required:false});case "string":return s.string({required:false});case "boolean":return s.boolean({required:false});default:throw new b(`Unknown SQL type: ${r} (input). Please open an issue so it can be added.`)}};return {...Object.entries(n.columns).reduce((r,[l,u])=>(r[l]=p(u.getSQLType()),r),{})}}}),transformArgumentToQueryCondition:s=>{if(!s)return;let p=r=>{let l=n.columns[r],u=s[r];if(u)return drizzleOrm.eq(l,u)},c=Object.keys(n.columns).map(p);return drizzleOrm.and(...c)}}};var Y=e=>{let i=I(e),a=z({...e,abilityBuilder:i}),{makePubSubInstance:t,pubsub:n}=q({...e}),{schemaBuilder:o}=k({...e,pubsub:n}),d=P({...e,schemaBuilder:o,makePubSubInstance:t}),s=w({...e,schemaBuilder:o}),p=v({...e,schemaBuilder:o,argImplementer:s,makePubSubInstance:t});return {abilityBuilder:i,schemaBuilder:o,yoga:()=>graphqlYoga.createYoga({...e.nativeServerOptions,schema:o.toSchema(),context:a}),object:d,arg:s,query:p,pubsub:t}};exports.RumbleError=b;exports.assertFindFirstExists=h;exports.assertFirstEntryExists=G;exports.rumble=Y;//# sourceMappingURL=index.cjs.map
2
2
  //# sourceMappingURL=index.cjs.map
package/index.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../lib/abilities/builder.ts","../lib/helpers/rumbleError.ts","../lib/gql/builder.ts","../lib/helpers/helper.ts"],"names":["isSimpleCondition","condition","isSyncFunctionCondition","createAbilityBuilder","db","builder","registeredConditions","createEntityObject","entityKey","action","conditionsPerEntity","actions","conditionsPerEntityAndAction","userContext","options","simpleConditions","syncFunctionConditions","allConditionObjects","highestLimit","conditionObject","combinedAllowedColumns","accumulatedWhereConditions","o","combinedWhere","or","and","RumbleError","message","rumble","nativeServerOptions","makeUserContext","onlyQuery","abilityBuilder","makeContext","req","nativeBuilder","SchemaBuilder","DrizzlePlugin","createYoga","tableName","name","readAction","schema","t","mapSQLTypeStringToExposedPothosType","sqlType","columnName","fields","acc","key","value","relations","_args","ctx","mapSQLTypeStringToInputPothosType","arg","mapColumnToQueryCondition","columnname","column","filterValue","eq","conditions","assertFindFirstExists","assertFirstEntryExists","v"],"mappings":"uUAuBA,SAASA,CACRC,CAAAA,CAAAA,CAC6C,CAC7C,OAAO,OAAOA,GAAc,UAC7B,CAEA,SAASC,CAAAA,CACRD,CACgE,CAAA,CAChE,OACC,OAAOA,CAAAA,EAAc,YACrBA,CAAU,CAAA,WAAA,CAAY,OAAS,eAEjC,CAWO,IAAME,CAAAA,CAAuB,CAIlC,CACD,GAAAC,CACD,CAAA,GAEM,CAIL,IAAMC,CAAAA,CAEF,EAEEC,CAAAA,CAAAA,CAQF,EAAC,CAECC,CAAsBC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,CAAE,QAAU,CAAA,CAAA,CAAM,CAAC,CACjD,CAAA,QACC,MAAM,IAAIpB,CAAAA,CACT,CAAqBmB,kBAAAA,EAAAA,CAAO,CAC7B,kDAAA,CAAA,CACF,CACD,CA8BA,CAAA,OAAO,CACN,GA7Bc,MAAA,CAAO,QAAQH,CAAO,CAAA,OAAO,CAAE,CAAA,MAAA,CAC7C,CAACM,CAAAA,CAAK,CAACC,CAAKC,CAAAA,CAAK,KAChBF,CAAIC,CAAAA,CAAG,EAAIK,CACVJ,CAAAA,CAAAA,CAAM,UAAW,EAAA,CACjBD,CACD,CAAA,CACOD,GAER,EAID,CAmBA,CACD,CACD,CACD,CA0BoB,CAAA,iCAAA,CArBnBO,CACI,EAAA,CACJ,GAAI,CAACA,EAAK,OACV,IAAMC,EAGLC,CACI,EAAA,CACJ,IAAMC,CAAShB,CAAAA,CAAAA,CAAO,OAAQe,CAAAA,CAAU,CAClCE,CAAAA,CAAAA,CAAcJ,EAAIE,CAAU,CAAA,CAClC,GAAKE,CAEL,CAAA,OAAOC,cAAGF,CAAQC,CAAAA,CAAW,CAC9B,CAAA,CAEME,CAAa,CAAA,MAAA,CAAO,KAAKnB,CAAO,CAAA,OAAO,EAAE,GAC9Cc,CAAAA,CACD,EACA,OAAO/B,cAAAA,CAAI,GAAGoC,CAAU,CACzB,CAEsD,CACvD,CAmDA,CACD,EClTaC,IAAAA,CAAAA,CAA4BZ,GAA4B,CACpE,GAAI,CAACA,CAAAA,CAAO,MAAM,IAAIxB,EAAY,0CAA0C,CAAA,CAC5E,OAAOwB,CACR,CAAA,CAyCaa,EAA6Bb,CAAkB,EAAA,CAC3D,IAAMc,CAAAA,CAAId,CAAM,CAAA,EAAA,CAAG,CAAC,CACpB,CAAA,GAAI,CAACc,CAAG,CAAA,MAAM,IAAItC,CAAY,CAAA,2CAA2C,CACzE,CAAA,OAAOsC,CACR","file":"index.cjs","sourcesContent":["import { log } from \"node:console\";\nimport { and, or } from \"drizzle-orm\";\nimport type {\n\tGenericDrizzleDbTypeConstraints,\n\tQueryConditionObject,\n} from \"../types/genericDrizzleDbType\";\n\nexport type AbilityBuilder = ReturnType<typeof createAbilityBuilder>;\n\ntype Condition<DBParameters, UserContext> =\n\t| SimpleCondition<DBParameters>\n\t| SyncFunctionCondition<DBParameters, UserContext>;\n// | AsyncFunctionCondition<DBParameters, UserContext>;\n\ntype SimpleCondition<DBParameters> = DBParameters;\ntype SyncFunctionCondition<DBParameters, UserContext> = (\n\tcontext: UserContext,\n) => DBParameters;\n// type AsyncFunctionCondition<DBParameters, UserContext> = (\n// \tcontext: UserContext,\n// ) => Promise<DBParameters>;\n\n// type guards for the condition types\nfunction isSimpleCondition<DBParameters, UserContext>(\n\tcondition: Condition<DBParameters, UserContext>,\n): condition is SimpleCondition<DBParameters> {\n\treturn typeof condition !== \"function\";\n}\n\nfunction isSyncFunctionCondition<DBParameters, UserContext>(\n\tcondition: Condition<DBParameters, UserContext>,\n): condition is SyncFunctionCondition<DBParameters, UserContext> {\n\treturn (\n\t\ttypeof condition === \"function\" &&\n\t\tcondition.constructor.name !== \"AsyncFunction\"\n\t);\n}\n\n// function isAsyncFunctionCondition<DBParameters, UserContext>(\n// \tcondition: Condition<DBParameters, UserContext>,\n// ): condition is AsyncFunctionCondition<DBParameters, UserContext> {\n// \treturn (\n// \t\ttypeof condition === \"function\" &&\n// \t\tcondition.constructor.name === \"AsyncFunction\"\n// \t);\n// }\n\nexport const createAbilityBuilder = <\n\tUserContext extends Record<string, any>,\n\tDB extends GenericDrizzleDbTypeConstraints,\n\tAction extends string,\n>({\n\tdb,\n}: {\n\tdb: DB;\n}) => {\n\ttype DBQueryKey = keyof DB[\"query\"];\n\ttype DBParameters = Parameters<DB[\"query\"][DBQueryKey][\"findMany\"]>[0];\n\n\tconst builder: {\n\t\t[key in DBQueryKey]: ReturnType<typeof createEntityObject>;\n\t} = {} as any;\n\n\tconst registeredConditions: {\n\t\t[key in DBQueryKey]: {\n\t\t\t[key in Action[number]]: (\n\t\t\t\t| QueryConditionObject\n\t\t\t\t| ((context: UserContext) => QueryConditionObject)\n\t\t\t)[];\n\t\t\t// | ((context: UserContext) => Promise<QueryConditionObject>)\n\t\t};\n\t} = {} as any;\n\n\tconst createEntityObject = (entityKey: DBQueryKey) => ({\n\t\tallow: (action: Action | Action[]) => {\n\t\t\tlet conditionsPerEntity = registeredConditions[entityKey];\n\t\t\tif (!conditionsPerEntity) {\n\t\t\t\tconditionsPerEntity = {} as any;\n\t\t\t\tregisteredConditions[entityKey] = conditionsPerEntity;\n\t\t\t}\n\n\t\t\tconst actions = Array.isArray(action) ? action : [action];\n\t\t\tfor (const action of actions) {\n\t\t\t\tlet conditionsPerEntityAndAction = conditionsPerEntity[action];\n\t\t\t\tif (!conditionsPerEntityAndAction) {\n\t\t\t\t\tconditionsPerEntityAndAction = [];\n\t\t\t\t\tconditionsPerEntity[action] = conditionsPerEntityAndAction;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\twhen: (condition: Condition<DBParameters, UserContext>) => {\n\t\t\t\t\tfor (const action of actions) {\n\t\t\t\t\t\tconst conditionsPerEntityAndAction = conditionsPerEntity[action];\n\t\t\t\t\t\tconditionsPerEntityAndAction.push(condition);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t});\n\n\tfor (const entityKey of Object.keys(db.query) as DBQueryKey[]) {\n\t\tbuilder[entityKey] = createEntityObject(entityKey);\n\t}\n\treturn {\n\t\t...builder,\n\t\tregisteredConditions,\n\t\tbuildWithUserContext: (userContext: UserContext) => {\n\t\t\tconst builder: {\n\t\t\t\t[key in DBQueryKey]: ReturnType<typeof createEntityObject>;\n\t\t\t} = {} as any;\n\n\t\t\tconst createEntityObject = (entityKey: DBQueryKey) => ({\n\t\t\t\tfilter: (\n\t\t\t\t\taction: Action,\n\t\t\t\t\toptions?: {\n\t\t\t\t\t\t/**\n\t\t\t\t\t\t * Additional conditions applied only for this call. Useful for injecting one time additional filters\n\t\t\t\t\t\t * for e.g. user args in a handler.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tinject?: QueryConditionObject;\n\t\t\t\t\t},\n\t\t\t\t) => {\n\t\t\t\t\tconst conditionsPerEntity = registeredConditions[entityKey];\n\t\t\t\t\tif (!conditionsPerEntity) {\n\t\t\t\t\t\tthrow \"TODO (No allowed entry found for this condition) #1\";\n\t\t\t\t\t}\n\n\t\t\t\t\tconst conditionsPerEntityAndAction = conditionsPerEntity[action];\n\t\t\t\t\tif (!conditionsPerEntityAndAction) {\n\t\t\t\t\t\tthrow \"TODO (No allowed entry found for this condition) #2\";\n\t\t\t\t\t}\n\n\t\t\t\t\tconst simpleConditions =\n\t\t\t\t\t\tconditionsPerEntityAndAction.filter(isSimpleCondition);\n\n\t\t\t\t\tconst syncFunctionConditions = conditionsPerEntityAndAction\n\t\t\t\t\t\t.filter(isSyncFunctionCondition)\n\t\t\t\t\t\t.map((condition) => condition(userContext));\n\n\t\t\t\t\t// const asyncFunctionConditions = await Promise.all(\n\t\t\t\t\t// \tconditionsPerEntityAndAction\n\t\t\t\t\t// \t\t.filter(isAsyncFunctionCondition)\n\t\t\t\t\t// \t\t.map((condition) => condition(userContext)),\n\t\t\t\t\t// );\n\n\t\t\t\t\tconst allConditionObjects = [\n\t\t\t\t\t\t...simpleConditions,\n\t\t\t\t\t\t...syncFunctionConditions,\n\t\t\t\t\t\t// ...asyncFunctionConditions,\n\t\t\t\t\t];\n\n\t\t\t\t\tlet highestLimit = undefined;\n\t\t\t\t\tfor (const conditionObject of allConditionObjects) {\n\t\t\t\t\t\tif (conditionObject.limit) {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\thighestLimit === undefined ||\n\t\t\t\t\t\t\t\tconditionObject.limit > highestLimit\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\thighestLimit = conditionObject.limit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (options?.inject?.limit && highestLimit < options.inject.limit) {\n\t\t\t\t\t\thighestLimit = options.inject.limit;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet combinedAllowedColumns: Record<string, any> | undefined =\n\t\t\t\t\t\tundefined;\n\t\t\t\t\tfor (const conditionObject of [\n\t\t\t\t\t\t...allConditionObjects,\n\t\t\t\t\t\toptions?.inject ?? {},\n\t\t\t\t\t]) {\n\t\t\t\t\t\tif (conditionObject.columns) {\n\t\t\t\t\t\t\tif (combinedAllowedColumns === undefined) {\n\t\t\t\t\t\t\t\tcombinedAllowedColumns = conditionObject.columns;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcombinedAllowedColumns = {\n\t\t\t\t\t\t\t\t\t...combinedAllowedColumns,\n\t\t\t\t\t\t\t\t\t...conditionObject.columns,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst accumulatedWhereConditions = allConditionObjects\n\t\t\t\t\t\t.filter((o) => o.where)\n\t\t\t\t\t\t.map((o) => o.where);\n\n\t\t\t\t\tlet combinedWhere =\n\t\t\t\t\t\taccumulatedWhereConditions.length > 0\n\t\t\t\t\t\t\t? or(...accumulatedWhereConditions)\n\t\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\tif (options?.inject?.where) {\n\t\t\t\t\t\tcombinedWhere = combinedWhere\n\t\t\t\t\t\t\t? and(combinedWhere, options.inject.where)\n\t\t\t\t\t\t\t: options.inject.where;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst ret = {\n\t\t\t\t\t\twhere: combinedWhere,\n\t\t\t\t\t\tcolumns: combinedAllowedColumns,\n\t\t\t\t\t\tlimit: highestLimit,\n\t\t\t\t\t};\n\n\t\t\t\t\t//TODO make this typesafe per actual entity\n\t\t\t\t\treturn ret;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tfor (const entityKey of Object.keys(db.query) as DBQueryKey[]) {\n\t\t\t\tbuilder[entityKey] = createEntityObject(entityKey);\n\t\t\t}\n\n\t\t\treturn builder;\n\t\t},\n\t};\n};\n","export class RumbleError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"RumbleError\";\n\t}\n}\n","import SchemaBuilder from \"@pothos/core\";\nimport DrizzlePlugin from \"@pothos/plugin-drizzle\";\nimport { and, eq } from \"drizzle-orm\";\nimport { type YogaServerOptions, createYoga } from \"graphql-yoga\";\nimport { createAbilityBuilder } from \"../abilities/builder\";\nimport { RumbleError } from \"../helpers/rumbleError\";\nimport type {\n\tGenericDrizzleDbTypeConstraints,\n\tQueryConditionObject,\n} from \"../types/genericDrizzleDbType\";\n\nexport const rumble = <\n\tUserContext extends Record<string, any>,\n\tDB extends GenericDrizzleDbTypeConstraints,\n\tRequestEvent extends Record<string, any>,\n\tAction extends string = \"create\" | \"read\" | \"update\" | \"delete\",\n>({\n\tdb,\n\tnativeServerOptions,\n\tcontext: makeUserContext,\n\tonlyQuery = false,\n\tactions = [\"create\", \"read\", \"update\", \"delete\"] as Action[],\n}: {\n\t/**\n\t * Your drizzle database instance\n\t */\n\tdb: DB;\n\t/**\n\t * Optional options for the native GraphQL Yoga server\n\t */\n\tnativeServerOptions?:\n\t\t| Omit<YogaServerOptions<RequestEvent, any>, \"schema\" | \"context\">\n\t\t| undefined;\n\t/**\n\t * A function for providing context for each request based on the incoming HTTP Request.\n\t * The type of the parameter equals the HTTPRequest type of your chosen server.\n\t */\n\tcontext?:\n\t\t| ((event: RequestEvent) => Promise<UserContext> | UserContext)\n\t\t| undefined;\n\t/**\n\t * If you only want to create queries and do not need mutations, enable this\n\t */\n\tonlyQuery?: boolean;\n\t/**\n\t * The actions that are available\n\t */\n\tactions?: Action[];\n}) => {\n\tconst abilityBuilder = createAbilityBuilder<UserContext, DB, Action>({\n\t\tdb,\n\t});\n\n\tconst makeContext = async (req: RequestEvent) => {\n\t\tconst userContext = makeUserContext\n\t\t\t? await makeUserContext(req)\n\t\t\t: ({} as UserContext);\n\t\treturn {\n\t\t\t...userContext,\n\t\t\tabilities: abilityBuilder.buildWithUserContext(userContext),\n\t\t};\n\t};\n\n\tconst nativeBuilder = new SchemaBuilder<{\n\t\tContext: Awaited<ReturnType<typeof makeContext>>;\n\t\t// Scalars: Scalars<Prisma.Decimal, Prisma.InputJsonValue | null, Prisma.InputJsonValue> & {\n\t\t// \tFile: {\n\t\t// \t\tInput: File;\n\t\t// \t\tOutput: never;\n\t\t// \t};\n\t\t// \tJSONObject: {\n\t\t// \t\tInput: any;\n\t\t// \t\tOutput: any;\n\t\t// \t};\n\t\t// };\n\t\tDrizzleSchema: DB[\"_\"][\"fullSchema\"];\n\t}>({\n\t\tplugins: [DrizzlePlugin],\n\t\tdrizzle: {\n\t\t\tclient: db,\n\t\t},\n\t});\n\n\tnativeBuilder.queryType({});\n\n\tif (!onlyQuery) {\n\t\tnativeBuilder.mutationType({});\n\t}\n\n\tconst implementDefaultObject = <\n\t\tExplicitTableName extends keyof NonNullable<DB[\"_\"][\"schema\"]>,\n\t\tRefName extends string,\n\t>({\n\t\ttableName,\n\t\tname,\n\t\treadAction = \"read\" as Action,\n\t}: {\n\t\ttableName: ExplicitTableName;\n\t\tname: RefName;\n\t\treadAction?: Action;\n\t}) => {\n\t\tconst schema = (db._.schema as NonNullable<DB[\"_\"][\"schema\"]>)[tableName];\n\n\t\treturn nativeBuilder.drizzleObject(tableName, {\n\t\t\tname,\n\t\t\tfields: (t) => {\n\t\t\t\tconst mapSQLTypeStringToExposedPothosType = <\n\t\t\t\t\tColumn extends keyof typeof schema.columns,\n\t\t\t\t\tSQLType extends ReturnType<\n\t\t\t\t\t\t(typeof schema.columns)[Column][\"getSQLType\"]\n\t\t\t\t\t>,\n\t\t\t\t>(\n\t\t\t\t\tsqlType: SQLType,\n\t\t\t\t\tcolumnName: Column,\n\t\t\t\t) => {\n\t\t\t\t\tswitch (sqlType) {\n\t\t\t\t\t\tcase \"serial\":\n\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\treturn t.exposeInt(columnName);\n\t\t\t\t\t\tcase \"int\":\n\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\treturn t.exposeInt(columnName);\n\t\t\t\t\t\tcase \"string\":\n\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\treturn t.exposeString(columnName);\n\t\t\t\t\t\tcase \"text\":\n\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\treturn t.exposeString(columnName);\n\t\t\t\t\t\tcase \"boolean\":\n\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\treturn t.exposeBoolean(columnName);\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tthrow new RumbleError(\n\t\t\t\t\t\t\t\t`Unknown SQL type: ${sqlType}. Please open an issue so it can be added.`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tconst fields = Object.entries(schema.columns).reduce(\n\t\t\t\t\t(acc, [key, value]) => {\n\t\t\t\t\t\tacc[key] = mapSQLTypeStringToExposedPothosType(\n\t\t\t\t\t\t\tvalue.getSQLType(),\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn acc;\n\t\t\t\t\t},\n\t\t\t\t\t{} as Record<\n\t\t\t\t\t\tkeyof typeof schema.columns,\n\t\t\t\t\t\tReturnType<typeof mapSQLTypeStringToExposedPothosType>\n\t\t\t\t\t>,\n\t\t\t\t);\n\n\t\t\t\tconst relations = Object.entries(schema.relations).reduce(\n\t\t\t\t\t(acc, [key, value]) => {\n\t\t\t\t\t\tacc[key] = t.relation(key, {\n\t\t\t\t\t\t\tquery: (_args: any, ctx: any) =>\n\t\t\t\t\t\t\t\tctx.abilities[key].filter(readAction),\n\t\t\t\t\t\t} as any) as any;\n\t\t\t\t\t\treturn acc;\n\t\t\t\t\t},\n\t\t\t\t\t{} as Record<\n\t\t\t\t\t\tkeyof typeof schema.relations,\n\t\t\t\t\t\tReturnType<typeof mapSQLTypeStringToExposedPothosType>\n\t\t\t\t\t>,\n\t\t\t\t);\n\n\t\t\t\treturn {\n\t\t\t\t\t...fields,\n\t\t\t\t\t...relations,\n\t\t\t\t};\n\t\t\t},\n\t\t});\n\t};\n\n\tconst implementWhereArgType = <\n\t\tExplicitTableName extends keyof NonNullable<DB[\"_\"][\"schema\"]>,\n\t\tRefName extends string,\n\t>({\n\t\ttableName,\n\t\tname,\n\t}: {\n\t\ttableName: ExplicitTableName;\n\t\tname?: RefName | undefined;\n\t}) => {\n\t\tconst schema = (db._.schema as NonNullable<DB[\"_\"][\"schema\"]>)[tableName];\n\n\t\tconst inputType = nativeBuilder.inputType(\n\t\t\tname ??\n\t\t\t\t`${\n\t\t\t\t\tString(tableName).charAt(0).toUpperCase() + String(tableName).slice(1)\n\t\t\t\t}WhereInputArgument`,\n\t\t\t{\n\t\t\t\tfields: (t) => {\n\t\t\t\t\tconst mapSQLTypeStringToInputPothosType = <\n\t\t\t\t\t\tColumn extends keyof typeof schema.columns,\n\t\t\t\t\t\tSQLType extends ReturnType<\n\t\t\t\t\t\t\t(typeof schema.columns)[Column][\"getSQLType\"]\n\t\t\t\t\t\t>,\n\t\t\t\t\t>(\n\t\t\t\t\t\tsqlType: SQLType,\n\t\t\t\t\t\tcolumnName: Column,\n\t\t\t\t\t) => {\n\t\t\t\t\t\tswitch (sqlType) {\n\t\t\t\t\t\t\tcase \"serial\":\n\t\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\t\treturn t.int(columnName, { required: false });\n\t\t\t\t\t\t\tcase \"int\":\n\t\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\t\treturn t.int(columnName, { required: false });\n\t\t\t\t\t\t\tcase \"string\":\n\t\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\t\treturn t.string(columnName, { required: false });\n\t\t\t\t\t\t\tcase \"text\":\n\t\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\t\treturn t.string(columnName, { required: false });\n\t\t\t\t\t\t\tcase \"boolean\":\n\t\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\t\treturn t.boolean(columnName, { required: false });\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tthrow new RumbleError(\n\t\t\t\t\t\t\t\t\t`Unknown SQL type: ${sqlType} (input). Please open an issue so it can be added.`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\tconst fields = Object.entries(schema.columns).reduce(\n\t\t\t\t\t\t(acc, [key, value]) => {\n\t\t\t\t\t\t\tacc[key] = mapSQLTypeStringToInputPothosType(\n\t\t\t\t\t\t\t\tvalue.getSQLType(),\n\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn acc;\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{} as Record<\n\t\t\t\t\t\t\tkeyof typeof schema.columns,\n\t\t\t\t\t\t\tReturnType<typeof mapSQLTypeStringToInputPothosType>\n\t\t\t\t\t\t>,\n\t\t\t\t\t);\n\n\t\t\t\t\t// const relations = Object.entries(schema.relations).reduce(\n\t\t\t\t\t// (acc, [key, value]) => {\n\t\t\t\t\t// acc[key] = t.relation(key, {\n\t\t\t\t\t// query: (_args: any, ctx: any) =>\n\t\t\t\t\t// ctx.abilities[tableName].filter(readAction),\n\t\t\t\t\t// } as any) as any;\n\t\t\t\t\t// return acc;\n\t\t\t\t\t// },\n\t\t\t\t\t// {} as Record<\n\t\t\t\t\t// keyof typeof schema.relations,\n\t\t\t\t\t// ReturnType<typeof mapSQLTypeStringToExposedPothosType>\n\t\t\t\t\t// >\n\t\t\t\t\t// );\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...fields,\n\t\t\t\t\t\t// ...relations,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tconst transformArgumentToQueryCondition = <\n\t\t\tT extends typeof inputType.$inferInput,\n\t\t>(\n\t\t\targ: T | null | undefined,\n\t\t) => {\n\t\t\tif (!arg) return undefined;\n\t\t\tconst mapColumnToQueryCondition = <\n\t\t\t\tColumnName extends keyof typeof schema.columns,\n\t\t\t>(\n\t\t\t\tcolumnname: ColumnName,\n\t\t\t) => {\n\t\t\t\tconst column = schema.columns[columnname];\n\t\t\t\tconst filterValue = arg[columnname];\n\t\t\t\tif (!filterValue) return;\n\n\t\t\t\treturn eq(column, filterValue);\n\t\t\t};\n\n\t\t\tconst conditions = Object.keys(schema.columns).map(\n\t\t\t\tmapColumnToQueryCondition,\n\t\t\t);\n\t\t\treturn and(...conditions);\n\t\t};\n\n\t\treturn { inputType, transformArgumentToQueryCondition };\n\t};\n\n\treturn {\n\t\t/**\n * The ability builder. Use it to declare whats allowed for each entity in your DB.\n * \n * @example\n * \n * ```ts\n * // users can edit themselves\n abilityBuilder.users\n .allow([\"read\", \"update\", \"delete\"])\n .when(({ userId }) => ({ where: eq(schema.users.id, userId) }));\n \n // everyone can read posts\n abilityBuilder.posts.allow(\"read\");\n * \n * ```\n */\n\t\tabilityBuilder,\n\t\t/**\n\t\t * The pothos schema builder. See https://pothos-graphql.dev/docs/plugins/drizzle\n\t\t */\n\t\tschemaBuilder: nativeBuilder,\n\t\t/**\n * The native yoga instance. Can be used to run an actual HTTP server.\n * \n * @example\n * \n * ```ts\n import { createServer } from \"node:http\";\n * const server = createServer(yoga());\n server.listen(3000, () => {\n console.log(\"Visit http://localhost:3000/graphql\");\n });\n * ```\n */\n\t\tyoga: () =>\n\t\t\tcreateYoga<RequestEvent>({\n\t\t\t\t...nativeServerOptions,\n\t\t\t\tschema: nativeBuilder.toSchema(),\n\t\t\t\tcontext: makeContext,\n\t\t\t}),\n\t\t/**\n\t\t * A function for creating default objects for your schema\n\t\t */\n\t\timplementDefaultObject,\n\t\t/**\n\t\t * A function for creating where args to filter entities\n\t\t */\n\t\timplementWhereArg: implementWhereArgType,\n\t};\n};\n","import { RumbleError } from \"./rumbleError\";\n\n/**\n * \n * Helper function to map a drizzle findFirst query result,\n * which may be optional, to a correct drizzle type.\n * \n * @throws RumbleError\n * \n * @example\n * \n * ```ts\n * schemaBuilder.queryFields((t) => {\n return {\n findFirstUser: t.drizzleField({\n type: UserRef,\n resolve: (query, root, args, ctx, info) => {\n return (\n db.query.users\n .findFirst({\n ...query,\n where: ctx.abilities.users.filter(\"read\").where,\n })\n // note that we need to manually raise an error if the value is not found\n .then(assertFindFirstExists)\n );\n },\n }),\n };\n });\n * ```\n */\nexport const assertFindFirstExists = <T>(value: T | undefined): T => {\n\tif (!value) throw new RumbleError(\"Value not found but required (findFirst)\");\n\treturn value;\n};\n\n/**\n * \n * Helper function to map a drizzle findFirst query result,\n * which may be optional, to a correct drizzle type.\n * \n * @throws RumbleError\n * \n * @example\n * \n * ```ts\n schemaBuilder.mutationFields((t) => {\n return {\n updateUsername: t.drizzleField({\n type: UserRef,\n args: {\n userId: t.arg.int({ required: true }),\n newName: t.arg.string({ required: true }),\n },\n resolve: (query, root, args, ctx, info) => {\n return db\n .update(schema.users)\n .set({\n name: args.newName,\n })\n .where(\n and(\n eq(schema.users.id, args.userId),\n ctx.abilities.users.filter(\"update\").where\n )\n )\n .returning({ id: schema.users.id, name: schema.users.name })\n // note that we need to manually raise an error if the value is not found\n .then(assertFirstEntryExists);\n },\n }),\n };\n });\n * ```\n */\nexport const assertFirstEntryExists = <T>(value: T[]): T => {\n\tconst v = value.at(0);\n\tif (!v) throw new RumbleError(\"Value not found but required (firstEntry)\");\n\treturn v;\n};\n"]}
1
+ {"version":3,"sources":["../lib/types/rumbleError.ts","../lib/abilityBuilder.ts","../lib/context.ts","../lib/helpers/mapSQLTypeToTSType.ts","../lib/pubsub.ts","../lib/object.ts","../lib/helpers/capitalize.ts","../lib/helpers/helper.ts","../lib/query.ts","../lib/schemaBuilder.ts","../lib/whereArg.ts","../lib/rumble.ts"],"names":["RumbleError","message","isSimpleCondition","condition","isSyncFunctionCondition","createAbilityBuilder","db","schema","builder","registeredConditions","createEntityObject","entityKey","action","conditionsPerEntity","actions","conditionsPerEntityAndAction","userContext","options","primaryKeyField","and","eq","simpleConditions","syncFunctionConditions","allConditionObjects","highestLimit","conditionObject","combinedAllowedColumns","accumulatedWhereConditions","o","combinedWhere","or","createContextFunction","makeUserContext","abilityBuilder","req","mapSQLTypeToTSType","sqlType","SUBSCRIPTION_NOTIFIER_RUMBLE_PREFIX","SUBSCRIPTION_NOTIFIER_REMOVED","SUBSCRIPTION_NOTIFIER_UPDATED","SUBSCRIPTION_NOTIFIER_CREATED","makePubSubKey","tableName","primaryKeyValue","actionKey","createPubSubInstance","subscriptions","pubsub","createPubSub","instance","key","createObjectImplementer","schemaBuilder","makePubSubInstance","name","readAction","primaryKey","registerOnInstance","element","context","t","mapSQLTypeStringToExposedPothosType","columnName","fields","acc","value","relations","_args","ctx","capitalizeFirstLetter","val","assertFindFirstExists","assertFirstEntryExists","v","createQueryImplementer","argImplementer","listAction","WhereArg","transformWhere","root","args","info","query","filter","queryInstance","createSchemaBuilder","disableDefaultObjects","SchemaBuilder","DrizzlePlugin","SmartSubscriptionsPlugin","subscribeOptionsFromIterator","createArgImplementer","mapSQLTypeStringToInputPothosType","arg","mapColumnToQueryCondition","columnname","column","filterValue","conditions","rumble","rumbleInput","object","createYoga"],"mappings":"mZAAO,IAAMA,EAAN,cAA0B,KAAM,CACtC,WAAYC,CAAAA,CAAAA,CAAiB,CAC5B,KAAMA,CAAAA,CAAO,EACb,IAAK,CAAA,IAAA,CAAO,cACb,CACD,EC0BA,SAASC,CACRC,CAAAA,CAAAA,CAC6C,CAC7C,OAAO,OAAOA,GAAc,UAC7B,CAEA,SAASC,CACRD,CAAAA,CAAAA,CACgE,CAChE,OACC,OAAOA,GAAc,UACrBA,EAAAA,CAAAA,CAAU,YAAY,IAAS,GAAA,eAEjC,CAWO,IAAME,CAAAA,CAAuB,CAKlC,CACD,EAAA,CAAAC,CACD,CAA0D,GAAA,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AAMC,EAMZC,CACI,EAAA,CACJ,IAAMnE,CAAiB5B,CAAAA,CAAAA,CAKrB+F,CAAW,CAEPzC,CAAAA,CAAAA,CAAU5B,EAMd,CACD,GAAGqE,EACH,cAAAnE,CAAAA,CACD,CAAC,CAEK,CAAA,CAAE,mBAAAoB,CAAoB,CAAA,MAAA,CAAAN,CAAO,CAAIF,CAAAA,CAAAA,CAKrC,CACD,GAAGuD,CACJ,CAAC,CAEK,CAAA,CAAE,cAAAhD,CAAc,CAAA,CAAIiC,EAKxB,CAAE,GAAGe,EAAa,MAAArD,CAAAA,CAAO,CAAC,CAEtBsD,CAAAA,CAAAA,CAASlD,EAOb,CACD,GAAGiD,EACH,aAAAhD,CAAAA,CAAAA,CACA,mBAAAC,CACD,CAAC,EACKwC,CAAMF,CAAAA,CAAAA,CAMV,CACD,GAAGS,CAAAA,CACH,cAAAhD,CACD,CAAC,EACK8B,CAAQR,CAAAA,CAAAA,CAQZ,CACD,GAAG0B,CAAAA,CACH,cAAAhD,CACA,CAAA,cAAA,CAAgByC,EAChB,kBAAAxC,CAAAA,CACD,CAAC,CASD,CAAA,OAAO,CAiBN,cAAApB,CAAAA,CAAAA,CAIA,cAAAmB,CAcA,CAAA,IAAA,CA1CY,IACZkD,sBAAyB,CAAA,CACxB,GAAGF,CAAY,CAAA,mBAAA,CACf,OAAQhD,CAAc,CAAA,QAAA,GACtB,OAAAO,CAAAA,CACD,CAAC,CAyCD,CAAA,MAAA,CAAA0C,EAIA,GAAAR,CAAAA,CAAAA,CAKA,MAAAX,CAIA,CAAA,MAAA,CAAQ7B,CACT,CACD","file":"index.cjs","sourcesContent":["export class RumbleError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"RumbleError\";\n\t}\n}\n","import { and, eq, or } from \"drizzle-orm\";\nimport type {\n\tGenericDrizzleDbTypeConstraints,\n\tQueryConditionObject,\n} from \"./types/genericDrizzleDbType\";\nimport { RumbleError } from \"./types/rumbleError\";\nimport type { RumbleInput } from \"./types/rumbleInput\";\n\nexport type AbilityBuilderType<\n\tUserContext extends Record<string, any>,\n\tDB extends GenericDrizzleDbTypeConstraints,\n\tRequestEvent extends Record<string, any>,\n\tAction extends string,\n> = ReturnType<\n\ttypeof createAbilityBuilder<UserContext, DB, RequestEvent, Action>\n>;\n\ntype Condition<DBParameters, UserContext> =\n\t| SimpleCondition<DBParameters>\n\t| SyncFunctionCondition<DBParameters, UserContext>;\n// | AsyncFunctionCondition<DBParameters, UserContext>;\n\ntype SimpleCondition<DBParameters> = DBParameters;\ntype SyncFunctionCondition<DBParameters, UserContext> = (\n\tcontext: UserContext,\n) => DBParameters;\n// type AsyncFunctionCondition<DBParameters, UserContext> = (\n// \tcontext: UserContext,\n// ) => Promise<DBParameters>;\n\n// type guards for the condition types\nfunction isSimpleCondition<DBParameters, UserContext>(\n\tcondition: Condition<DBParameters, UserContext>,\n): condition is SimpleCondition<DBParameters> {\n\treturn typeof condition !== \"function\";\n}\n\nfunction isSyncFunctionCondition<DBParameters, UserContext>(\n\tcondition: Condition<DBParameters, UserContext>,\n): condition is SyncFunctionCondition<DBParameters, UserContext> {\n\treturn (\n\t\ttypeof condition === \"function\" &&\n\t\tcondition.constructor.name !== \"AsyncFunction\"\n\t);\n}\n\n// function isAsyncFunctionCondition<DBParameters, UserContext>(\n// \tcondition: Condition<DBParameters, UserContext>,\n// ): condition is AsyncFunctionCondition<DBParameters, UserContext> {\n// \treturn (\n// \t\ttypeof condition === \"function\" &&\n// \t\tcondition.constructor.name === \"AsyncFunction\"\n// \t);\n// }\n\nexport const createAbilityBuilder = <\n\tUserContext extends Record<string, any>,\n\tDB extends GenericDrizzleDbTypeConstraints,\n\tRequestEvent extends Record<string, any>,\n\tAction extends string,\n>({\n\tdb,\n}: RumbleInput<UserContext, DB, RequestEvent, Action>) => {\n\ttype DBQueryKey = keyof DB[\"query\"];\n\ttype DBParameters = Parameters<DB[\"query\"][DBQueryKey][\"findMany\"]>[0];\n\n\tconst schema = db._.schema as NonNullable<DB[\"_\"][\"schema\"]>;\n\n\tconst builder: {\n\t\t[key in DBQueryKey]: ReturnType<typeof createEntityObject>;\n\t} = {} as any;\n\n\tconst registeredConditions: {\n\t\t[key in DBQueryKey]: {\n\t\t\t[key in Action[number]]: (\n\t\t\t\t| QueryConditionObject\n\t\t\t\t| ((context: UserContext) => QueryConditionObject)\n\t\t\t)[];\n\t\t\t// | ((context: UserContext) => Promise<QueryConditionObject>)\n\t\t};\n\t} = {} as any;\n\n\tconst createEntityObject = (entityKey: DBQueryKey) => ({\n\t\tallow: (action: Action | Action[]) => {\n\t\t\tlet conditionsPerEntity = registeredConditions[entityKey];\n\t\t\tif (!conditionsPerEntity) {\n\t\t\t\tconditionsPerEntity = {} as any;\n\t\t\t\tregisteredConditions[entityKey] = conditionsPerEntity;\n\t\t\t}\n\n\t\t\tconst actions = Array.isArray(action) ? action : [action];\n\t\t\tfor (const action of actions) {\n\t\t\t\tlet conditionsPerEntityAndAction = conditionsPerEntity[action];\n\t\t\t\tif (!conditionsPerEntityAndAction) {\n\t\t\t\t\tconditionsPerEntityAndAction = [];\n\t\t\t\t\tconditionsPerEntity[action] = conditionsPerEntityAndAction;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\twhen: (condition: Condition<DBParameters, UserContext>) => {\n\t\t\t\t\tfor (const action of actions) {\n\t\t\t\t\t\tconst conditionsPerEntityAndAction = conditionsPerEntity[action];\n\t\t\t\t\t\tconditionsPerEntityAndAction.push(condition);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t});\n\n\tfor (const entityKey of Object.keys(db.query) as DBQueryKey[]) {\n\t\tbuilder[entityKey] = createEntityObject(entityKey);\n\t}\n\treturn {\n\t\t...builder,\n\t\tregisteredConditions,\n\t\tbuildWithUserContext: (userContext: UserContext) => {\n\t\t\tconst builder: {\n\t\t\t\t[key in DBQueryKey]: ReturnType<typeof createEntityObject>;\n\t\t\t} = {} as any;\n\n\t\t\tconst createEntityObject = (entityKey: DBQueryKey) => ({\n\t\t\t\tfilter: (\n\t\t\t\t\taction: Action,\n\t\t\t\t\toptions?: {\n\t\t\t\t\t\t/**\n\t\t\t\t\t\t * Additional conditions applied only for this call. Useful for injecting one time additional filters\n\t\t\t\t\t\t * for e.g. user args in a handler.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tinject?: QueryConditionObject;\n\t\t\t\t\t},\n\t\t\t\t) => {\n\t\t\t\t\tlet conditionsPerEntity = registeredConditions[entityKey];\n\t\t\t\t\tif (!conditionsPerEntity) {\n\t\t\t\t\t\tconditionsPerEntity = {} as any;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet conditionsPerEntityAndAction = conditionsPerEntity[action];\n\n\t\t\t\t\tif (!conditionsPerEntity || !conditionsPerEntityAndAction) {\n\t\t\t\t\t\tconst primaryKeyField = schema[entityKey].primaryKey.at(0);\n\t\t\t\t\t\tif (!primaryKeyField) {\n\t\t\t\t\t\t\tthrow new RumbleError(\n\t\t\t\t\t\t\t\t`No primary key found for entity ${entityKey.toString()}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconditionsPerEntityAndAction = [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\twhere: and(eq(primaryKeyField, \"1\"), eq(primaryKeyField, \"2\")),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t];\n\t\t\t\t\t}\n\n\t\t\t\t\tconst simpleConditions =\n\t\t\t\t\t\tconditionsPerEntityAndAction.filter(isSimpleCondition);\n\n\t\t\t\t\tconst syncFunctionConditions = conditionsPerEntityAndAction\n\t\t\t\t\t\t.filter(isSyncFunctionCondition)\n\t\t\t\t\t\t.map((condition) => condition(userContext));\n\n\t\t\t\t\t// const asyncFunctionConditions = await Promise.all(\n\t\t\t\t\t// \tconditionsPerEntityAndAction\n\t\t\t\t\t// \t\t.filter(isAsyncFunctionCondition)\n\t\t\t\t\t// \t\t.map((condition) => condition(userContext)),\n\t\t\t\t\t// );\n\n\t\t\t\t\tconst allConditionObjects = [\n\t\t\t\t\t\t...simpleConditions,\n\t\t\t\t\t\t...syncFunctionConditions,\n\t\t\t\t\t\t// ...asyncFunctionConditions,\n\t\t\t\t\t];\n\n\t\t\t\t\tlet highestLimit = undefined;\n\t\t\t\t\tfor (const conditionObject of allConditionObjects) {\n\t\t\t\t\t\tif (conditionObject.limit) {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\thighestLimit === undefined ||\n\t\t\t\t\t\t\t\tconditionObject.limit > highestLimit\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\thighestLimit = conditionObject.limit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (options?.inject?.limit && highestLimit < options.inject.limit) {\n\t\t\t\t\t\thighestLimit = options.inject.limit;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet combinedAllowedColumns: Record<string, any> | undefined =\n\t\t\t\t\t\tundefined;\n\t\t\t\t\tfor (const conditionObject of [\n\t\t\t\t\t\t...allConditionObjects,\n\t\t\t\t\t\toptions?.inject ?? {},\n\t\t\t\t\t]) {\n\t\t\t\t\t\tif (conditionObject.columns) {\n\t\t\t\t\t\t\tif (combinedAllowedColumns === undefined) {\n\t\t\t\t\t\t\t\tcombinedAllowedColumns = conditionObject.columns;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcombinedAllowedColumns = {\n\t\t\t\t\t\t\t\t\t...combinedAllowedColumns,\n\t\t\t\t\t\t\t\t\t...conditionObject.columns,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst accumulatedWhereConditions = allConditionObjects\n\t\t\t\t\t\t.filter((o) => o.where)\n\t\t\t\t\t\t.map((o) => o.where);\n\n\t\t\t\t\tlet combinedWhere =\n\t\t\t\t\t\taccumulatedWhereConditions.length > 0\n\t\t\t\t\t\t\t? or(...accumulatedWhereConditions)\n\t\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\tif (options?.inject?.where) {\n\t\t\t\t\t\tcombinedWhere = combinedWhere\n\t\t\t\t\t\t\t? and(combinedWhere, options.inject.where)\n\t\t\t\t\t\t\t: options.inject.where;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst ret = {\n\t\t\t\t\t\twhere: combinedWhere,\n\t\t\t\t\t\tcolumns: combinedAllowedColumns,\n\t\t\t\t\t\tlimit: highestLimit,\n\t\t\t\t\t};\n\n\t\t\t\t\t//TODO make this typesafe per actual entity\n\t\t\t\t\treturn ret;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tfor (const entityKey of Object.keys(db.query) as DBQueryKey[]) {\n\t\t\t\tbuilder[entityKey] = createEntityObject(entityKey);\n\t\t\t}\n\n\t\t\treturn builder;\n\t\t},\n\t};\n};\n","import type {\n\tAbilityBuilderType,\n\tcreateAbilityBuilder,\n} from \"./abilityBuilder\";\nimport type { GenericDrizzleDbTypeConstraints } from \"./types/genericDrizzleDbType\";\nimport type { RumbleInput } from \"./types/rumbleInput\";\n\nexport type ContextFunctionType<\n\tUserContext extends Record<string, any>,\n\tDB extends GenericDrizzleDbTypeConstraints,\n\tRequestEvent extends Record<string, any>,\n\tAction extends string,\n> = ReturnType<\n\ttypeof createContextFunction<\n\t\tUserContext,\n\t\tDB,\n\t\tRequestEvent,\n\t\tAction,\n\t\tAbilityBuilderType<UserContext, DB, RequestEvent, Action>\n\t>\n>;\n\nexport type ContextType<\n\tUserContext extends Record<string, any>,\n\tDB extends GenericDrizzleDbTypeConstraints,\n\tRequestEvent extends Record<string, any>,\n\tAction extends string,\n> = Awaited<\n\tReturnType<ContextFunctionType<UserContext, DB, RequestEvent, Action>>\n>;\n\nexport const createContextFunction = <\n\tUserContext extends Record<string, any>,\n\tDB extends GenericDrizzleDbTypeConstraints,\n\tRequestEvent extends Record<string, any>,\n\tAction extends string,\n\tAbilityBuilder extends ReturnType<\n\t\ttypeof createAbilityBuilder<UserContext, DB, RequestEvent, Action>\n\t>,\n>({\n\tcontext: makeUserContext,\n\tabilityBuilder,\n}: RumbleInput<UserContext, DB, RequestEvent, Action> & {\n\tabilityBuilder: AbilityBuilder;\n}) => {\n\treturn async (req: RequestEvent) => {\n\t\tconst userContext = makeUserContext\n\t\t\t? await makeUserContext(req)\n\t\t\t: ({} as UserContext);\n\t\treturn {\n\t\t\t...userContext,\n\t\t\tabilities: abilityBuilder.buildWithUserContext(userContext),\n\t\t};\n\t};\n};\n","import { RumbleError } from \"../types/rumbleError\";\n\ntype GraphQLType = \"int\" | \"string\" | \"boolean\";\n\nexport function mapSQLTypeToTSType(sqlType: string): GraphQLType {\n\tif ([\"serial\", \"int\", \"integer\"].includes(sqlType)) {\n\t\treturn \"int\";\n\t}\n\n\tif ([\"string\", \"text\", \"varchar\", \"char\", \"text(256)\"].includes(sqlType)) {\n\t\treturn \"string\";\n\t}\n\n\tif (sqlType === \"boolean\") {\n\t\treturn \"boolean\";\n\t}\n\n\tthrow new RumbleError(\n\t\t`Unknown SQL type: ${sqlType}. Please open an issue so it can be added.`,\n\t);\n}\n","import { createPubSub } from \"graphql-yoga\";\nimport type { GenericDrizzleDbTypeConstraints } from \"./types/genericDrizzleDbType\";\nimport type { RumbleInput } from \"./types/rumbleInput\";\n\ntype PubSubAction = \"created\" | \"removed\" | \"updated\";\n\nconst SUBSCRIPTION_NOTIFIER_RUMBLE_PREFIX = \"RUMBLE_SUBSCRIPTION_NOTIFICATION\";\nconst SUBSCRIPTION_NOTIFIER_REMOVED = \"REMOVED\";\nconst SUBSCRIPTION_NOTIFIER_UPDATED = \"UPDATED\";\nconst SUBSCRIPTION_NOTIFIER_CREATED = \"CREATED\";\n\nfunction makePubSubKey({\n\taction,\n\ttableName,\n\tprimaryKeyValue,\n}: {\n\ttableName: string;\n\taction: PubSubAction;\n\tprimaryKeyValue?: string;\n}) {\n\tlet actionKey: string;\n\n\tswitch (action) {\n\t\tcase \"created\":\n\t\t\tactionKey = SUBSCRIPTION_NOTIFIER_CREATED;\n\t\t\tbreak;\n\t\tcase \"removed\":\n\t\t\tactionKey = SUBSCRIPTION_NOTIFIER_REMOVED;\n\t\t\tbreak;\n\t\tcase \"updated\":\n\t\t\tactionKey = SUBSCRIPTION_NOTIFIER_UPDATED;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown action: ${action}`);\n\t}\n\n\treturn `${SUBSCRIPTION_NOTIFIER_RUMBLE_PREFIX}/${tableName}${\n\t\tprimaryKeyValue ? `/${primaryKeyValue}` : \"\"\n\t}/${actionKey}`;\n}\n\nexport type MakePubSubInstanceType<\n\tUserContext extends Record<string, any>,\n\tDB extends GenericDrizzleDbTypeConstraints,\n\tRequestEvent extends Record<string, any>,\n\tAction extends string,\n> = ReturnType<\n\ttypeof createPubSubInstance<UserContext, DB, RequestEvent, Action>\n>[\"makePubSubInstance\"];\n\nexport const createPubSubInstance = <\n\tUserContext extends Record<string, any>,\n\tDB extends GenericDrizzleDbTypeConstraints,\n\tRequestEvent extends Record<string, any>,\n\tAction extends string,\n>({\n\tsubscriptions,\n}: RumbleInput<UserContext, DB, RequestEvent, Action> & {}) => {\n\tconst pubsub = subscriptions\n\t\t? createPubSub(...subscriptions)\n\t\t: createPubSub();\n\n\tconst makePubSubInstance = <\n\t\tExplicitTableName extends keyof NonNullable<DB[\"_\"][\"schema\"]>,\n\t>({\n\t\ttableName,\n\t}: {\n\t\ttableName: ExplicitTableName;\n\t}) => ({\n\t\t/**\n\t\t * Call this when you want to register a subscription on an instance to this table\n\t\t */\n\t\tregisterOnInstance({\n\t\t\tinstance,\n\t\t\taction,\n\t\t\tprimaryKeyValue,\n\t\t}: {\n\t\t\tinstance: { register: (id: string) => void };\n\t\t\taction: PubSubAction;\n\t\t\tprimaryKeyValue?: string;\n\t\t}) {\n\t\t\tconst key = makePubSubKey({\n\t\t\t\ttableName: tableName.toString(),\n\t\t\t\taction,\n\t\t\t\tprimaryKeyValue,\n\t\t\t});\n\t\t\tinstance.register(key);\n\t\t},\n\t\t/**\n\t\t * Call this when you created an entity of this table\n\t\t */\n\t\tcreated() {\n\t\t\tconst key = makePubSubKey({\n\t\t\t\ttableName: tableName.toString(),\n\t\t\t\taction: \"created\",\n\t\t\t});\n\t\t\treturn pubsub.publish(key);\n\t\t},\n\t\t/**\n\t\t * Call this when you removed an entity of this table\n\t\t */\n\t\tremoved(primaryKeyValue?: any) {\n\t\t\tconst key = makePubSubKey({\n\t\t\t\ttableName: tableName.toString(),\n\t\t\t\taction: \"removed\",\n\t\t\t\t// primaryKeyValue,\n\t\t\t});\n\t\t\treturn pubsub.publish(key);\n\t\t},\n\t\t/**\n\t\t * Call this when you updated an entity of this table\n\t\t */\n\t\tupdated(primaryKeyValue?: any) {\n\t\t\tconst key = makePubSubKey({\n\t\t\t\ttableName: tableName.toString(),\n\t\t\t\taction: \"updated\",\n\t\t\t\tprimaryKeyValue,\n\t\t\t});\n\t\t\treturn pubsub.publish(key);\n\t\t},\n\t});\n\n\treturn {\n\t\tpubsub,\n\t\tmakePubSubInstance,\n\t};\n};\n","import { mapSQLTypeToTSType } from \"./helpers/mapSQLTypeToTSType\";\nimport { type MakePubSubInstanceType, createPubSubInstance } from \"./pubsub\";\nimport type { SchemaBuilderType } from \"./schemaBuilder\";\nimport type { GenericDrizzleDbTypeConstraints } from \"./types/genericDrizzleDbType\";\nimport { RumbleError } from \"./types/rumbleError\";\nimport type { RumbleInput } from \"./types/rumbleInput\";\n\nexport const createObjectImplementer = <\n\tUserContext extends Record<string, any>,\n\tDB extends GenericDrizzleDbTypeConstraints,\n\tRequestEvent extends Record<string, any>,\n\tAction extends string,\n\tSchemaBuilder extends SchemaBuilderType<\n\t\tUserContext,\n\t\tDB,\n\t\tRequestEvent,\n\t\tAction\n\t>,\n\tMakePubSubInstance extends MakePubSubInstanceType<\n\t\tUserContext,\n\t\tDB,\n\t\tRequestEvent,\n\t\tAction\n\t>,\n>({\n\tdb,\n\tschemaBuilder,\n\tmakePubSubInstance,\n}: RumbleInput<UserContext, DB, RequestEvent, Action> & {\n\tschemaBuilder: SchemaBuilder;\n\tmakePubSubInstance: MakePubSubInstance;\n}) => {\n\treturn <\n\t\tExplicitTableName extends keyof NonNullable<DB[\"_\"][\"schema\"]>,\n\t\tRefName extends string,\n\t>({\n\t\ttableName,\n\t\tname,\n\t\treadAction = \"read\" as Action,\n\t}: {\n\t\ttableName: ExplicitTableName;\n\t\tname: RefName;\n\t\treadAction?: Action;\n\t}) => {\n\t\tconst schema = (db._.schema as NonNullable<DB[\"_\"][\"schema\"]>)[tableName];\n\t\tconst primaryKey = schema.primaryKey.at(0)?.name;\n\t\tif (!primaryKey)\n\t\t\tconsole.warn(\n\t\t\t\t`Could not find primary key for ${tableName.toString()}. Cannot register subscriptions!`,\n\t\t\t);\n\n\t\tconst { registerOnInstance } = makePubSubInstance({ tableName });\n\n\t\treturn schemaBuilder.drizzleObject(tableName, {\n\t\t\tname,\n\t\t\tsubscribe: (subscriptions, element, context) => {\n\t\t\t\tif (!primaryKey) return;\n\t\t\t\tconst primaryKeyValue = (element as any)[primaryKey];\n\t\t\t\tif (!primaryKeyValue) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`Could not find primary key value for ${JSON.stringify(\n\t\t\t\t\t\t\telement,\n\t\t\t\t\t\t)}. Cannot register subscription!`,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tregisterOnInstance({\n\t\t\t\t\tinstance: subscriptions,\n\t\t\t\t\taction: \"updated\",\n\t\t\t\t\tprimaryKeyValue: primaryKeyValue,\n\t\t\t\t});\n\t\t\t},\n\t\t\tfields: (t) => {\n\t\t\t\tconst mapSQLTypeStringToExposedPothosType = <\n\t\t\t\t\tColumn extends keyof typeof schema.columns,\n\t\t\t\t\tSQLType extends ReturnType<\n\t\t\t\t\t\t(typeof schema.columns)[Column][\"getSQLType\"]\n\t\t\t\t\t>,\n\t\t\t\t>(\n\t\t\t\t\tsqlType: SQLType,\n\t\t\t\t\tcolumnName: Column,\n\t\t\t\t) => {\n\t\t\t\t\tconst gqlType = mapSQLTypeToTSType(sqlType);\n\t\t\t\t\tswitch (gqlType) {\n\t\t\t\t\t\tcase \"int\":\n\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\treturn t.exposeInt(columnName);\n\t\t\t\t\t\tcase \"string\":\n\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\treturn t.exposeString(columnName);\n\t\t\t\t\t\tcase \"boolean\":\n\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\treturn t.exposeBoolean(columnName);\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tthrow new RumbleError(\n\t\t\t\t\t\t\t\t`Unknown SQL type: ${sqlType}. Please open an issue so it can be added.`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tconst fields = Object.entries(schema.columns).reduce(\n\t\t\t\t\t(acc, [key, value]) => {\n\t\t\t\t\t\tacc[key] = mapSQLTypeStringToExposedPothosType(\n\t\t\t\t\t\t\tvalue.getSQLType(),\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn acc;\n\t\t\t\t\t},\n\t\t\t\t\t{} as Record<\n\t\t\t\t\t\tkeyof typeof schema.columns,\n\t\t\t\t\t\tReturnType<typeof mapSQLTypeStringToExposedPothosType>\n\t\t\t\t\t>,\n\t\t\t\t);\n\n\t\t\t\tconst relations = Object.entries(schema.relations).reduce(\n\t\t\t\t\t(acc, [key, value]) => {\n\t\t\t\t\t\tacc[key] = t.relation(key, {\n\t\t\t\t\t\t\tquery: (_args: any, ctx: any) => {\n\t\t\t\t\t\t\t\treturn ctx.abilities[value.referencedTableName].filter(\n\t\t\t\t\t\t\t\t\treadAction,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} as any) as any;\n\t\t\t\t\t\treturn acc;\n\t\t\t\t\t},\n\t\t\t\t\t{} as Record<\n\t\t\t\t\t\tkeyof typeof schema.relations,\n\t\t\t\t\t\tReturnType<typeof mapSQLTypeStringToExposedPothosType>\n\t\t\t\t\t>,\n\t\t\t\t);\n\n\t\t\t\treturn {\n\t\t\t\t\t...fields,\n\t\t\t\t\t...relations,\n\t\t\t\t};\n\t\t\t},\n\t\t});\n\t};\n};\n","// https://stackoverflow.com/a/1026087/11988368\nexport function capitalizeFirstLetter(val: string) {\n\treturn String(val).charAt(0).toUpperCase() + String(val).slice(1);\n}\n","import { RumbleError } from \"../types/rumbleError\";\n\n/**\n * \n * Helper function to map a drizzle findFirst query result,\n * which may be optional, to a correct drizzle type.\n * \n * @throws RumbleError\n * \n * @example\n * \n * ```ts\n * schemaBuilder.queryFields((t) => {\n return {\n findFirstUser: t.drizzleField({\n type: UserRef,\n resolve: (query, root, args, ctx, info) => {\n return (\n db.query.users\n .findFirst({\n ...query,\n where: ctx.abilities.users.filter(\"read\").where,\n })\n // note that we need to manually raise an error if the value is not found\n .then(assertFindFirstExists)\n );\n },\n }),\n };\n });\n * ```\n */\nexport const assertFindFirstExists = <T>(value: T | undefined): T => {\n\tif (!value) throw new RumbleError(\"Value not found but required (findFirst)\");\n\treturn value;\n};\n\n/**\n * \n * Helper function to map a drizzle findFirst query result,\n * which may be optional, to a correct drizzle type.\n * \n * @throws RumbleError\n * \n * @example\n * \n * ```ts\n schemaBuilder.mutationFields((t) => {\n return {\n updateUsername: t.drizzleField({\n type: UserRef,\n args: {\n userId: t.arg.int({ required: true }),\n newName: t.arg.string({ required: true }),\n },\n resolve: (query, root, args, ctx, info) => {\n return db\n .update(schema.users)\n .set({\n name: args.newName,\n })\n .where(\n and(\n eq(schema.users.id, args.userId),\n ctx.abilities.users.filter(\"update\").where\n )\n )\n .returning({ id: schema.users.id, name: schema.users.name })\n // note that we need to manually raise an error if the value is not found\n .then(assertFirstEntryExists);\n },\n }),\n };\n });\n * ```\n */\nexport const assertFirstEntryExists = <T>(value: T[]): T => {\n\tconst v = value.at(0);\n\tif (!v) throw new RumbleError(\"Value not found but required (firstEntry)\");\n\treturn v;\n};\n","import { capitalizeFirstLetter } from \"./helpers/capitalize\";\nimport { assertFindFirstExists } from \"./helpers/helper\";\nimport type { MakePubSubInstanceType } from \"./pubsub\";\nimport type { SchemaBuilderType } from \"./schemaBuilder\";\nimport type { GenericDrizzleDbTypeConstraints } from \"./types/genericDrizzleDbType\";\nimport type { RumbleInput } from \"./types/rumbleInput\";\nimport type { ArgImplementerType } from \"./whereArg\";\n\nexport const createQueryImplementer = <\n\tUserContext extends Record<string, any>,\n\tDB extends GenericDrizzleDbTypeConstraints,\n\tRequestEvent extends Record<string, any>,\n\tAction extends string,\n\tSchemaBuilder extends SchemaBuilderType<\n\t\tUserContext,\n\t\tDB,\n\t\tRequestEvent,\n\t\tAction\n\t>,\n\tArgImplementer extends ArgImplementerType<\n\t\tUserContext,\n\t\tDB,\n\t\tRequestEvent,\n\t\tAction\n\t>,\n\tMakePubSubInstance extends MakePubSubInstanceType<\n\t\tUserContext,\n\t\tDB,\n\t\tRequestEvent,\n\t\tAction\n\t>,\n>({\n\tdb,\n\tschemaBuilder,\n\targImplementer,\n\tmakePubSubInstance,\n}: RumbleInput<UserContext, DB, RequestEvent, Action> & {\n\tschemaBuilder: SchemaBuilder;\n\targImplementer: ArgImplementer;\n\tmakePubSubInstance: MakePubSubInstance;\n}) => {\n\treturn <ExplicitTableName extends keyof NonNullable<DB[\"_\"][\"schema\"]>>({\n\t\ttableName,\n\t\treadAction = \"read\" as Action,\n\t\tlistAction = \"read\" as Action,\n\t}: {\n\t\t/**\n\t\t * The table for which to implement the query\n\t\t */\n\t\ttableName: ExplicitTableName;\n\t\t/**\n\t\t * Which action should be used for reading single entities\n\t\t * @default \"read\"\n\t\t */\n\t\treadAction?: Action;\n\t\t/**\n\t\t * Which action should be used for listing many entities\n\t\t * @default \"read\"\n\t\t */\n\t\tlistAction?: Action;\n\t}) => {\n\t\tconst schema = (db._.schema as NonNullable<DB[\"_\"][\"schema\"]>)[tableName];\n\t\tconst primaryKey = schema.primaryKey.at(0)?.name;\n\t\tif (!primaryKey)\n\t\t\tconsole.warn(\n\t\t\t\t`Could not find primary key for ${tableName.toString()}. Cannot register subscriptions!`,\n\t\t\t);\n\n\t\tconst {\n\t\t\tinputType: WhereArg,\n\t\t\ttransformArgumentToQueryCondition: transformWhere,\n\t\t} = argImplementer({\n\t\t\ttableName: tableName,\n\t\t\tname: `${tableName.toString()}Where_DefaultRumbleQueryArgument`,\n\t\t});\n\n\t\tconst { registerOnInstance } = makePubSubInstance({ tableName });\n\n\t\treturn schemaBuilder.queryFields((t) => {\n\t\t\treturn {\n\t\t\t\t[`findMany${capitalizeFirstLetter(tableName.toString())}`]:\n\t\t\t\t\tt.drizzleField({\n\t\t\t\t\t\ttype: [tableName],\n\t\t\t\t\t\tsmartSubscription: true,\n\t\t\t\t\t\tsubscribe: (subscriptions, root, args, ctx, info) => {\n\t\t\t\t\t\t\tregisterOnInstance({\n\t\t\t\t\t\t\t\tinstance: subscriptions,\n\t\t\t\t\t\t\t\taction: \"created\",\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tregisterOnInstance({\n\t\t\t\t\t\t\t\tinstance: subscriptions,\n\t\t\t\t\t\t\t\taction: \"removed\",\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t},\n\t\t\t\t\t\targs: {\n\t\t\t\t\t\t\twhere: t.arg({ type: WhereArg, required: false }),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tresolve: (query, root, args, ctx, info) => {\n\t\t\t\t\t\t\tconst filter = ctx.abilities[tableName as any].filter(\n\t\t\t\t\t\t\t\treadAction,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tinject: { where: transformWhere(args.where) },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\tconst queryInstance = query(filter as any);\n\n\t\t\t\t\t\t\tif (filter.columns) {\n\t\t\t\t\t\t\t\tqueryInstance.columns = filter.columns;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn db.query[tableName as any].findMany(queryInstance);\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t[`findFirst${capitalizeFirstLetter(tableName.toString())}`]:\n\t\t\t\t\tt.drizzleField({\n\t\t\t\t\t\ttype: tableName,\n\t\t\t\t\t\tsmartSubscription: true,\n\t\t\t\t\t\targs: {\n\t\t\t\t\t\t\twhere: t.arg({ type: WhereArg, required: false }),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tresolve: (query, root, args, ctx, info) => {\n\t\t\t\t\t\t\tconst filter = ctx.abilities[tableName as any].filter(\n\t\t\t\t\t\t\t\treadAction,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tinject: { where: transformWhere(args.where) },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\tconst queryInstance = query(filter as any);\n\n\t\t\t\t\t\t\tif (filter.columns) {\n\t\t\t\t\t\t\t\tqueryInstance.columns = filter.columns;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn db.query[tableName as any]\n\t\t\t\t\t\t\t\t.findFirst(queryInstance)\n\t\t\t\t\t\t\t\t.then(assertFindFirstExists);\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t};\n\t\t});\n\t};\n};\n","import SchemaBuilder from \"@pothos/core\";\nimport DrizzlePlugin from \"@pothos/plugin-drizzle\";\nimport SmartSubscriptionsPlugin, {\n\tsubscribeOptionsFromIterator,\n} from \"@pothos/plugin-smart-subscriptions\";\nimport type { createPubSub } from \"graphql-yoga\";\nimport type { ContextType } from \"./context\";\nimport type { GenericDrizzleDbTypeConstraints } from \"./types/genericDrizzleDbType\";\nimport type { RumbleInput } from \"./types/rumbleInput\";\n\nexport type SchemaBuilderType<\n\tUserContext extends Record<string, any>,\n\tDB extends GenericDrizzleDbTypeConstraints,\n\tRequestEvent extends Record<string, any>,\n\tAction extends string,\n> = ReturnType<\n\ttypeof createSchemaBuilder<UserContext, DB, RequestEvent, Action>\n>[\"schemaBuilder\"];\n\nexport const createSchemaBuilder = <\n\tUserContext extends Record<string, any>,\n\tDB extends GenericDrizzleDbTypeConstraints,\n\tRequestEvent extends Record<string, any>,\n\tAction extends string,\n>({\n\tdb,\n\tdisableDefaultObjects,\n\tpubsub,\n}: RumbleInput<UserContext, DB, RequestEvent, Action> & {\n\tpubsub: ReturnType<typeof createPubSub>;\n}) => {\n\tconst schemaBuilder = new SchemaBuilder<{\n\t\tContext: ContextType<UserContext, DB, RequestEvent, Action>;\n\t\t//TODO set sensible defaults here\n\t\t// Scalars: Scalars<Prisma.Decimal, Prisma.InputJsonValue | null, Prisma.InputJsonValue> & {\n\t\t// \tFile: {\n\t\t// \t\tInput: File;\n\t\t// \t\tOutput: never;\n\t\t// \t};\n\t\t// \tJSONObject: {\n\t\t// \t\tInput: any;\n\t\t// \t\tOutput: any;\n\t\t// \t};\n\t\t// };\n\t\tDrizzleSchema: DB[\"_\"][\"fullSchema\"];\n\t}>({\n\t\tplugins: [DrizzlePlugin, SmartSubscriptionsPlugin],\n\t\tdrizzle: {\n\t\t\tclient: db,\n\t\t},\n\t\tsmartSubscriptions: {\n\t\t\t...subscribeOptionsFromIterator((name, context) => {\n\t\t\t\treturn pubsub.subscribe(name);\n\t\t\t}),\n\t\t},\n\t});\n\n\tif (!disableDefaultObjects?.query) {\n\t\tschemaBuilder.queryType({});\n\t}\n\n\tif (!disableDefaultObjects?.subscription) {\n\t\tschemaBuilder.subscriptionType({});\n\t}\n\n\tif (!disableDefaultObjects?.mutation) {\n\t\tschemaBuilder.mutationType({});\n\t}\n\n\treturn { schemaBuilder };\n};\n","import { and, eq } from \"drizzle-orm\";\nimport { capitalizeFirstLetter } from \"./helpers/capitalize\";\nimport { mapSQLTypeToTSType } from \"./helpers/mapSQLTypeToTSType\";\nimport type { SchemaBuilderType } from \"./schemaBuilder\";\nimport type { GenericDrizzleDbTypeConstraints } from \"./types/genericDrizzleDbType\";\nimport { RumbleError } from \"./types/rumbleError\";\nimport type { RumbleInput } from \"./types/rumbleInput\";\n\nexport type ArgImplementerType<\n\tUserContext extends Record<string, any>,\n\tDB extends GenericDrizzleDbTypeConstraints,\n\tRequestEvent extends Record<string, any>,\n\tAction extends string,\n> = ReturnType<\n\ttypeof createArgImplementer<\n\t\tUserContext,\n\t\tDB,\n\t\tRequestEvent,\n\t\tAction,\n\t\tSchemaBuilderType<UserContext, DB, RequestEvent, Action>\n\t>\n>;\n\nexport const createArgImplementer = <\n\tUserContext extends Record<string, any>,\n\tDB extends GenericDrizzleDbTypeConstraints,\n\tRequestEvent extends Record<string, any>,\n\tAction extends string,\n\tSchemaBuilder extends SchemaBuilderType<\n\t\tUserContext,\n\t\tDB,\n\t\tRequestEvent,\n\t\tAction\n\t>,\n>({\n\tdb,\n\tschemaBuilder,\n}: RumbleInput<UserContext, DB, RequestEvent, Action> & {\n\tschemaBuilder: SchemaBuilder;\n}) => {\n\treturn <\n\t\tExplicitTableName extends keyof NonNullable<DB[\"_\"][\"schema\"]>,\n\t\tRefName extends string,\n\t>({\n\t\ttableName,\n\t\tname,\n\t}: {\n\t\ttableName: ExplicitTableName;\n\t\tname?: RefName | undefined;\n\t}) => {\n\t\tconst schema = (db._.schema as NonNullable<DB[\"_\"][\"schema\"]>)[tableName];\n\t\tconst inputType = schemaBuilder.inputType(\n\t\t\tname ??\n\t\t\t\t`${capitalizeFirstLetter(tableName.toString())}WhereInputArgument`,\n\t\t\t{\n\t\t\t\tfields: (t) => {\n\t\t\t\t\tconst mapSQLTypeStringToInputPothosType = <\n\t\t\t\t\t\tColumn extends keyof typeof schema.columns,\n\t\t\t\t\t\tSQLType extends ReturnType<\n\t\t\t\t\t\t\t(typeof schema.columns)[Column][\"getSQLType\"]\n\t\t\t\t\t\t>,\n\t\t\t\t\t>(\n\t\t\t\t\t\tsqlType: SQLType,\n\t\t\t\t\t) => {\n\t\t\t\t\t\tconst gqlType = mapSQLTypeToTSType(sqlType);\n\t\t\t\t\t\tswitch (gqlType) {\n\t\t\t\t\t\t\tcase \"int\":\n\t\t\t\t\t\t\t\treturn t.int({ required: false });\n\t\t\t\t\t\t\tcase \"string\":\n\t\t\t\t\t\t\t\treturn t.string({ required: false });\n\t\t\t\t\t\t\tcase \"boolean\":\n\t\t\t\t\t\t\t\treturn t.boolean({ required: false });\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tthrow new RumbleError(\n\t\t\t\t\t\t\t\t\t`Unknown SQL type: ${sqlType} (input). Please open an issue so it can be added.`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\tconst fields = Object.entries(schema.columns).reduce(\n\t\t\t\t\t\t(acc, [key, value]) => {\n\t\t\t\t\t\t\tacc[key] = mapSQLTypeStringToInputPothosType(value.getSQLType());\n\t\t\t\t\t\t\treturn acc;\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{} as Record<\n\t\t\t\t\t\t\tkeyof typeof schema.columns,\n\t\t\t\t\t\t\tReturnType<typeof mapSQLTypeStringToInputPothosType>\n\t\t\t\t\t\t>,\n\t\t\t\t\t);\n\t\t\t\t\t// const relations = Object.entries(schema.relations).reduce(\n\t\t\t\t\t// (acc, [key, value]) => {\n\t\t\t\t\t// acc[key] = t.relation(key, {\n\t\t\t\t\t// query: (_args: any, ctx: any) =>\n\t\t\t\t\t// ctx.abilities[tableName].filter(readAction),\n\t\t\t\t\t// } as any) as any;\n\t\t\t\t\t// return acc;\n\t\t\t\t\t// },\n\t\t\t\t\t// {} as Record<\n\t\t\t\t\t// keyof typeof schema.relations,\n\t\t\t\t\t// ReturnType<typeof mapSQLTypeStringToExposedPothosType>\n\t\t\t\t\t// >\n\t\t\t\t\t// );\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...fields,\n\t\t\t\t\t\t// ...relations,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tconst transformArgumentToQueryCondition = <\n\t\t\tT extends typeof inputType.$inferInput,\n\t\t>(\n\t\t\targ: T | null | undefined,\n\t\t) => {\n\t\t\tif (!arg) return undefined;\n\t\t\tconst mapColumnToQueryCondition = <\n\t\t\t\tColumnName extends keyof typeof schema.columns,\n\t\t\t>(\n\t\t\t\tcolumnname: ColumnName,\n\t\t\t) => {\n\t\t\t\tconst column = schema.columns[columnname];\n\t\t\t\tconst filterValue = arg[columnname];\n\t\t\t\tif (!filterValue) return;\n\t\t\t\treturn eq(column, filterValue);\n\t\t\t};\n\t\t\tconst conditions = Object.keys(schema.columns).map(\n\t\t\t\tmapColumnToQueryCondition,\n\t\t\t);\n\t\t\treturn and(...conditions);\n\t\t};\n\n\t\treturn {\n\t\t\t/**\n\t\t\t * The input type used to pass arguments to resolvers\n\t\t\t */\n\t\t\tinputType,\n\t\t\t/**\n\t\t\t * Performs a conversion of an input argument passed to a resolver to a drizzle filter.\n\t\t\t * Make sure you use the correct converter for the input type.\n\t\t\t */\n\t\t\ttransformArgumentToQueryCondition,\n\t\t};\n\t};\n};\n","import { createYoga } from \"graphql-yoga\";\nimport { createAbilityBuilder } from \"./abilityBuilder\";\nimport { createContextFunction } from \"./context\";\nimport { createObjectImplementer } from \"./object\";\nimport { createPubSubInstance } from \"./pubsub\";\nimport { createQueryImplementer } from \"./query\";\nimport { createSchemaBuilder } from \"./schemaBuilder\";\nimport type { GenericDrizzleDbTypeConstraints } from \"./types/genericDrizzleDbType\";\nimport type { RumbleInput } from \"./types/rumbleInput\";\nimport { createArgImplementer } from \"./whereArg\";\n\nexport const rumble = <\n\tUserContext extends Record<string, any>,\n\tDB extends GenericDrizzleDbTypeConstraints,\n\tRequestEvent extends Record<string, any>,\n\tAction extends string = \"read\" | \"update\" | \"delete\",\n>(\n\trumbleInput: RumbleInput<UserContext, DB, RequestEvent, Action>,\n) => {\n\tconst abilityBuilder = createAbilityBuilder<\n\t\tUserContext,\n\t\tDB,\n\t\tRequestEvent,\n\t\tAction\n\t>(rumbleInput);\n\n\tconst context = createContextFunction<\n\t\tUserContext,\n\t\tDB,\n\t\tRequestEvent,\n\t\tAction,\n\t\ttypeof abilityBuilder\n\t>({\n\t\t...rumbleInput,\n\t\tabilityBuilder,\n\t});\n\n\tconst { makePubSubInstance, pubsub } = createPubSubInstance<\n\t\tUserContext,\n\t\tDB,\n\t\tRequestEvent,\n\t\tAction\n\t>({\n\t\t...rumbleInput,\n\t});\n\n\tconst { schemaBuilder } = createSchemaBuilder<\n\t\tUserContext,\n\t\tDB,\n\t\tRequestEvent,\n\t\tAction\n\t>({ ...rumbleInput, pubsub });\n\n\tconst object = createObjectImplementer<\n\t\tUserContext,\n\t\tDB,\n\t\tRequestEvent,\n\t\tAction,\n\t\ttypeof schemaBuilder,\n\t\ttypeof makePubSubInstance\n\t>({\n\t\t...rumbleInput,\n\t\tschemaBuilder,\n\t\tmakePubSubInstance,\n\t});\n\tconst arg = createArgImplementer<\n\t\tUserContext,\n\t\tDB,\n\t\tRequestEvent,\n\t\tAction,\n\t\ttypeof schemaBuilder\n\t>({\n\t\t...rumbleInput,\n\t\tschemaBuilder,\n\t});\n\tconst query = createQueryImplementer<\n\t\tUserContext,\n\t\tDB,\n\t\tRequestEvent,\n\t\tAction,\n\t\ttypeof schemaBuilder,\n\t\ttypeof arg,\n\t\ttypeof makePubSubInstance\n\t>({\n\t\t...rumbleInput,\n\t\tschemaBuilder,\n\t\targImplementer: arg,\n\t\tmakePubSubInstance,\n\t});\n\n\tconst yoga = () =>\n\t\tcreateYoga<RequestEvent>({\n\t\t\t...rumbleInput.nativeServerOptions,\n\t\t\tschema: schemaBuilder.toSchema(),\n\t\t\tcontext,\n\t\t});\n\n\treturn {\n\t\t/**\n * The ability builder. Use it to declare whats allowed for each entity in your DB.\n * \n * @example\n * \n * ```ts\n * // users can edit themselves\n abilityBuilder.users\n .allow([\"read\", \"update\", \"delete\"])\n .when(({ userId }) => ({ where: eq(schema.users.id, userId) }));\n \n // everyone can read posts\n abilityBuilder.posts.allow(\"read\");\n * \n * ```\n */\n\t\tabilityBuilder,\n\t\t/**\n\t\t * The pothos schema builder. See https://pothos-graphql.dev/docs/plugins/drizzle\n\t\t */\n\t\tschemaBuilder,\n\t\t/**\n * The native yoga instance. Can be used to run an actual HTTP server.\n * \n * @example\n * \n * ```ts\n import { createServer } from \"node:http\";\n * const server = createServer(yoga());\n server.listen(3000, () => {\n console.info(\"Visit http://localhost:3000/graphql\");\n });\n * ```\n */\n\t\tyoga,\n\t\t/**\n\t\t * A function for creating default objects for your schema\n\t\t */\n\t\tobject,\n\t\t/**\n\t\t * A function for creating where args to filter entities\n\t\t */\n\t\targ,\n\t\t/**\n\t\t * A function for creating default READ queries.\n\t\t * Make sure the objects for the table you are creating the queries for are implemented\n\t\t */\n\t\tquery,\n\t\t/**\n\t\t * A function for creating a pubsub instance for a table. Use this to publish or subscribe events\n\t\t */\n\t\tpubsub: makePubSubInstance,\n\t};\n};\n"]}