@m1212e/rumble 0.10.2 → 0.10.3
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/index.cjs +5 -5
- package/index.cjs.map +1 -1
- package/index.js +5 -5
- package/index.js.map +1 -1
- package/package.json +1 -1
package/index.js
CHANGED
@@ -1,9 +1,9 @@
|
|
1
|
-
import {createYoga,createPubSub}from'graphql-yoga';import {useSofa}from'sofa-api';import {One,relationsFilterToSQL}from'drizzle-orm';import {toCamelCase}from'drizzle-orm/casing';import {PgEnumColumn}from'drizzle-orm/pg-core';import {singular,plural}from'pluralize';import
|
2
|
-
`,
|
3
|
-
`)}function
|
1
|
+
import {createYoga,createPubSub}from'graphql-yoga';import {useSofa}from'sofa-api';import {One,relationsFilterToSQL}from'drizzle-orm';import {toCamelCase}from'drizzle-orm/casing';import {PgEnumColumn}from'drizzle-orm/pg-core';import {singular,plural}from'pluralize';import Ue,{BasePlugin}from'@pothos/core';import Ke from'@pothos/plugin-drizzle';import _e,{subscribeOptionsFromIterator}from'@pothos/plugin-smart-subscriptions';import {JSONResolver,DateResolver,DateTimeISOResolver}from'graphql-scalars';function J(t){return typeof t=="object"&&t!==null}function H(t,n){throw new Error("Unexpected invariant triggered.")}var he=/\r\n|[\n\r]/g;function U(t,n){let r=0,p=1;for(let i of t.body.matchAll(he)){if(typeof i.index=="number"||H(),i.index>=n)break;r=i.index+i[0].length,p+=1;}return {line:p,column:n+1-r}}function X(t){return _(t.source,U(t.source,t.start))}function _(t,n){let r=t.locationOffset.column-1,p="".padStart(r)+t.body,i=n.line-1,e=t.locationOffset.line-1,y=n.line+e,l=n.line===1?r:0,u=n.column+l,m=`${t.name}:${y}:${u}
|
2
|
+
`,a=p.split(/\r\n|[\n\r]/g),f=a[i];if(f.length>120){let s=Math.floor(u/80),h=u%80,o=[];for(let b=0;b<f.length;b+=80)o.push(f.slice(b,b+80));return m+Y([[`${y} |`,o[0]],...o.slice(1,s+1).map(b=>["|",b]),["|","^".padStart(h)],["|",o[s+1]]])}return m+Y([[`${y-1} |`,a[i-1]],[`${y} |`,f],["|","^".padStart(u)],[`${y+1} |`,a[i+1]]])}function Y(t){let n=t.filter(([p,i])=>i!==void 0),r=Math.max(...n.map(([p])=>p.length));return n.map(([p,i])=>p.padStart(r)+(i?" "+i:"")).join(`
|
3
|
+
`)}function Te(t){let n=t[0];return n==null||"kind"in n||"length"in n?{nodes:n,source:t[1],positions:t[2],path:t[3],originalError:t[4],extensions:t[5]}:n}var L=class t extends Error{constructor(n,...r){var p,i,e;let{nodes:y,source:l,positions:u,path:m,originalError:a,extensions:f}=Te(r);super(n),this.name="GraphQLError",this.path=m??void 0,this.originalError=a??void 0,this.nodes=Z(Array.isArray(y)?y:y?[y]:void 0);let s=Z((p=this.nodes)===null||p===void 0?void 0:p.map(o=>o.loc).filter(o=>o!=null));this.source=l??(s==null||(i=s[0])===null||i===void 0?void 0:i.source),this.positions=u??s?.map(o=>o.start),this.locations=u&&l?u.map(o=>U(l,o)):s?.map(o=>U(o.source,o.start));let h=J(a?.extensions)?a?.extensions:void 0;this.extensions=(e=f??h)!==null&&e!==void 0?e:Object.create(null),Object.defineProperties(this,{message:{writable:true,enumerable:true},name:{enumerable:false},nodes:{enumerable:false},source:{enumerable:false},positions:{enumerable:false},originalError:{enumerable:false}}),a!=null&&a.stack?Object.defineProperty(this,"stack",{value:a.stack,writable:true,configurable:true}):Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:Error().stack,writable:true,configurable:true});}get[Symbol.toStringTag](){return "GraphQLError"}toString(){let n=this.message;if(this.nodes)for(let r of this.nodes)r.loc&&(n+=`
|
4
4
|
|
5
5
|
`+X(r.loc));else if(this.source&&this.locations)for(let r of this.locations)n+=`
|
6
6
|
|
7
|
-
`+_(this.source,r);return n}toJSON(){let n={message:this.message};return this.locations!=null&&(n.locations=this.locations),this.path!=null&&(n.path=this.path),this.extensions!=null&&Object.keys(this.extensions).length>0&&(n.extensions=this.extensions),n}};function Z(t){return t===void 0||t.length===0?void 0:t}var I=class extends Error{constructor(n){super(n),this.name="RumbleError";}},k=class extends L{};var V=t=>{if(!t)throw new k("Value not found but required (findFirst)");return t},
|
8
|
-
Please ensure that you use the enum at least once as a column of a table!`);u=h.enumValues;}else if(e){let a=Object.entries(t._.relations.schema).find(([h,o])=>o===e.config.enum);if(!a)throw new I(`Could not find enum in schema for ${e.name}!`);l=a[0],u=e.enumValues;}if(!l||!u)throw new I("Could not determine enum structure!");let y=c??`${z(toCamelCase(l))}Enum`,s=r.get(y);return s||(s=n.enumType(y,{values:u}),r.set(y,s),s)}};var se={paths:{"/webhook":{post:{operationId:"webhook_create",description:"Creates a webhook subscription.",tags:[],parameters:[],requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookCreateBody"}}}},responses:{200:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}}},"/webhook/{id}":{post:{operationId:"webhook_update",description:"Updates a webhook subscription.",parameters:[{name:"id",in:"path",description:"The ID of the webhook to update",required:true,schema:{type:"string"}}],requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookCreateBody"}}}},responses:{200:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}},delete:{operationId:"webhook_delete",description:"Removes a webhook subscription.",tags:[],parameters:[{name:"id",in:"path",description:"The ID of the webhook to delete",required:true,schema:{type:"string"}}],responses:{200:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}}}},components:{schemas:{WebhookCreateBody:{type:"object",properties:{subscription:{description:"The subscription to subscribe to. In many cases, these match the available query IDs without the '_query' suffix. E.g., 'findFirstUser_query' -> 'findFirstUser'. See the graphql schema for more details on what subscriptions are available.",type:"string"},variables:{description:"The variables to pass to the subscription.",type:"object"},url:{description:"The URL to send the webhook to.",type:"string"}}},WebhookDetailResponse:{type:"object",properties:{id:{description:"The ID of the webhook. Can be used as reference in update or delete calls.",type:"string"}}}}}};function K({sqlType:t,fieldName:n}){let r;if(["serial","int","integer","tinyint","smallint","mediumint"].includes(t)&&(r="Int"),["real","decimal","double","float"].includes(t)&&(r="Float"),["string","text","varchar","char","text(256)"].includes(t)&&(n&&(n.toLowerCase().endsWith("_id")||n.toLowerCase().endsWith("id"))?r="ID":r="String"),["uuid"].includes(t)&&(r="ID"),["boolean"].includes(t)&&(r="Boolean"),["timestamp","datetime"].includes(t)&&(r="DateTime"),["date"].includes(t)&&(r="Date"),["json"].includes(t)&&(r="JSON"),r!==void 0)return r;throw G(t,"SQL to GQL")}var Ne=t=>typeof t!="object"?false:!!Object.keys(t).some(n=>["args","nullable","query","subscribe","description","type","resolve"].find(r=>r===n)),ae=({db:t,schemaBuilder:n,makePubSubInstance:r,whereArgImplementer:p,orderArgImplementer:i,enumImplementer:e,abilityBuilder:c})=>({table:l,refName:u,readAction:y="read",adjust:s})=>{let d=B({db:t,tsName:l});Object.keys(d.primaryColumns).length===0&&console.warn(`Could not find primary key for ${l.toString()}. Cannot register subscriptions!`);let a=Object.values(d.primaryColumns)[0],{registerOnInstance:h}=r({table:l});return n.drizzleObject(l,{name:u??z(l.toString()),subscribe:(o,b,f)=>{if(!a)return;let T=b[a.name];if(!T){console.warn(`Could not find primary key value for ${JSON.stringify(b)}. Cannot register subscription!`);return}h({instance:o,action:"updated",primaryKeyValue:T});},applyFilters:c?.registeredFilters?.[l]?.[y],fields:o=>{let b=d.columns,f=(S,g,x)=>{let m=K({sqlType:S,fieldName:g});switch(m){case "Int":return o.exposeInt(g,{nullable:x});case "String":return o.exposeString(g,{nullable:x});case "Boolean":return o.exposeBoolean(g,{nullable:x});case "Date":return o.field({type:"Date",resolve:R=>R[g],nullable:x});case "DateTime":return o.field({type:"DateTime",resolve:R=>R[g],nullable:x});case "Float":return o.exposeFloat(g,{nullable:x});case "ID":return o.exposeID(g,{nullable:x});case "JSON":return o.field({type:"JSON",resolve:R=>R[g],nullable:x});default:throw new I(`Unsupported object type ${m} for column ${g}`)}},T=new Map,C=s?.(new Proxy(o,{get:(S,g)=>typeof S[g]=="function"?(...x)=>{let m=S[g](...x),R=x.find(Ne);if(!R)throw new I("Expected config object to be passed to adjust field");return T.set(m,{params:x,creatorFunction:S[g],configObject:R}),m}:S[g]}))??{},D=Object.entries(b).reduce((S,[g,x])=>{if(C[g]){let{params:m,creatorFunction:R,configObject:P}=T.get(C[g]);return typeof P.nullable!="boolean"&&(P.nullable=!x.notNull),C[g]=R.bind(o)(...m),S}if(W(x)){let m=e({enumColumn:x});S[g]=o.field({type:m,resolve:R=>R[g],nullable:!x.notNull});}else S[g]=f(x.getSQLType(),g,!x.notNull);return S},{}),A=Object.entries(d.relations??{}).reduce((S,[g,x])=>{let m=B({db:t,table:x.targetTable}),R=p({dbName:m.dbName}),P=i({dbName:m.dbName}),w=r({table:m.tsName}),F=false,q=true,E="many";x instanceof One&&(q=false,F=x.optional,E="single");let Q=(N,j)=>{w.registerOnInstance({instance:N,action:"created"}),w.registerOnInstance({instance:N,action:"removed"});};if(C[g]){let{params:N,creatorFunction:j,configObject:O}=T.get(C[g]);return typeof O.nullable!="boolean"&&(O.nullable=F),typeof O.subscribe!="function"&&(O.subscribe=Q),C[g]=j.bind(o)(...N),S}return S[g]=o.relation(g,{args:{where:o.arg({type:R,required:false}),orderBy:o.arg({type:P,required:false}),...q?{offset:o.arg.int({required:false}),limit:o.arg.int({required:false})}:{}},subscribe:Q,nullable:F,query:(N,j)=>{N=JSON.parse(JSON.stringify(N));let O=j.abilities[m.tsName].filter(y,{inject:{where:N.where,limit:N.limit}}).query[E];return N.offset&&(O.offset=N.offset),N.orderBy&&(O.orderBy=N.orderBy),O}}),S},{});return {...D,...A,...C}}})};var ve=t=>`${z(toCamelCase(t.toString()))}OrderInputArgument`,le=({db:t,schemaBuilder:n})=>{let r=new Map,p=v(()=>n.enumType("SortingParameter",{values:["asc","desc"]})),i=({table:e,refName:c,dbName:l})=>{let u=B({db:t,dbName:l,tsName:e}),y=c??ve(u.tsName),s=r.get(y);return s||(s=n.inputType(y,{fields:a=>{let h=Object.entries(u.columns).reduce((b,[f,T])=>(b[f]=a.field({type:p(),required:false}),b),{}),o=Object.entries(u.relations??{}).reduce((b,[f,T])=>{let C=B({db:t,table:T.targetTable}),D=i({dbName:C.dbName});return b[f]=a.field({type:D,required:false}),b},{});return {...h,...o}}}),r.set(y,s),s)};return i};var Fe="RUMBLE_SUBSCRIPTION_NOTIFICATION",Oe="REMOVED",ze="UPDATED",qe="CREATED",pe=({subscriptions:t,db:n})=>{let r=t?createPubSub(...t):createPubSub();return {pubsub:r,makePubSubInstance:({table:i})=>{function e({action:c,tableName:l,primaryKeyValue:u}){let y;switch(c){case "created":y=qe;break;case "removed":y=Oe;break;case "updated":y=ze;break;default:throw new Error(`Unknown action: ${c}`)}return `${Fe}/${l}${u?`/${u}`:""}/${y}`}return {registerOnInstance({instance:c,action:l,primaryKeyValue:u}){let y=e({tableName:i.toString(),action:l,primaryKeyValue:u});c.register(y);},created(){let c=e({tableName:i.toString(),action:"created"});return r.publish(c)},removed(c){let l=e({tableName:i.toString(),action:"removed"});return r.publish(l)},updated(c){let u=(Array.isArray(c)?c:[c]).map(s=>e({tableName:i.toString(),action:"updated",primaryKeyValue:s})),y=Array.from(new Set(u));for(let s of y)r.publish(s);}}}}};var me=({db:t,schemaBuilder:n,whereArgImplementer:r,orderArgImplementer:p,makePubSubInstance:i})=>({table:e,readAction:c="read",listAction:l="read"})=>{let u=r({table:e}),y=p({table:e}),s=B({db:t,tsName:e}),d=Object.values(s.primaryColumns)[0],{registerOnInstance:a}=i({table:e});return n.queryFields(h=>({[plural(e.toString())]:h.drizzleField({type:[e],nullable:false,smartSubscription:true,subscribe:(o,b,f,T,C)=>{a({instance:o,action:"created"}),a({instance:o,action:"removed"});},args:{where:h.arg({type:u,required:false}),orderBy:h.arg({type:y,required:false}),limit:h.arg.int({required:false}),offset:h.arg.int({required:false})},resolve:(o,b,f,T,C)=>{f=JSON.parse(JSON.stringify(f));let D=T.abilities[e].filter(l,f.where||f.limit||f.offset?{inject:{where:f.where,limit:f.limit}}:void 0).query.many;f.offset&&(D.offset=f.offset),f.orderBy&&(D.orderBy=f.orderBy);let A=o(D);return D.columns&&(A.columns=D.columns),t.query[e].findMany(A)}}),[singular(e.toString())]:h.drizzleField({type:e,nullable:false,smartSubscription:true,args:{id:h.arg.id({required:true})},resolve:(o,b,f,T,C)=>{f=JSON.parse(JSON.stringify(f));let D=T.abilities[e].filter(c,{inject:{where:{[d.name]:f.id}}}).query.single,A=o(D);return D.columns&&(A.columns=D.columns),t.query[e].findFirst(A).then(V)}})}))};var ce="ManualFiltersPlugin",ye=ce,Qe="applyFilters",$=class extends BasePlugin{wrapResolve(n,r){return async(p,i,e,c)=>{let l=(r?.type).type?.ref.currentConfig.pothosOptions[Qe];if(!l||!Array.isArray(l)||l.length===0)return n(p,i,e,c);let u=await n(p,i,e,c),y=Array.isArray(u)?u:[u],s=Array.isArray(l)?l:[l],d=await ee({filters:s,entities:y,context:e});return Array.isArray(u)?d:d[0]??null}}};we.registerPlugin(ce,$);var Ge=t=>`${z(toCamelCase(t.toString()))}WhereInputArgument`,de=({db:t,schemaBuilder:n,enumImplementer:r})=>{let p=new Map,i=({table:e,refName:c,dbName:l})=>{let u=B({db:t,dbName:l,tsName:e}),y=c??Ge(u.tsName),s=p.get(y);return s||(s=n.inputType(y,{fields:a=>{let h=(f,T)=>{let C=K({sqlType:f,fieldName:T});switch(C){case "Int":return a.field({type:"IntWhereInputArgument"});case "String":return a.field({type:"StringWhereInputArgument"});case "Boolean":return a.boolean({required:false});case "Date":return a.field({type:"DateWhereInputArgument"});case "DateTime":return a.field({type:"DateWhereInputArgument"});case "Float":return a.field({type:"FloatWhereInputArgument"});case "ID":return a.id({required:false});case "JSON":return a.field({type:"JSON",required:false});default:throw new I(`Unsupported argument type ${C} for column ${f}`)}},o=Object.entries(u.columns).reduce((f,[T,C])=>{if(W(C)){let D=r({enumColumn:C});f[T]=a.field({type:D,required:false});}else f[T]=h(C.getSQLType(),T);return f},{}),b=Object.entries(u.relations??{}).reduce((f,[T,C])=>{let D=B({db:t,table:C.targetTable}),A=i({dbName:D.dbName});return f[T]=a.field({type:A,required:false}),f},{});return {...o,...b}}}),p.set(y,s),s)};return i};function fe(t){let n=t.inputRef("IntWhereInputArgument").implement({fields:e=>({eq:e.int(),ne:e.int(),gt:e.int(),gte:e.int(),lt:e.int(),lte:e.int(),in:e.intList(),notIn:e.intList(),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.intList(),arrayContained:e.intList(),arrayContains:e.intList(),AND:e.field({type:[n]}),OR:e.field({type:[n]}),NOT:e.field({type:n})})}),r=t.inputRef("FloatWhereInputArgument").implement({fields:e=>({eq:e.float(),ne:e.float(),gt:e.float(),gte:e.float(),lt:e.float(),lte:e.float(),in:e.floatList(),notIn:e.floatList(),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.floatList(),arrayContained:e.floatList(),arrayContains:e.floatList(),AND:e.field({type:[r]}),OR:e.field({type:[r]}),NOT:e.field({type:r})})}),p=t.inputRef("StringWhereInputArgument").implement({fields:e=>({eq:e.string(),ne:e.string(),gt:e.string(),gte:e.string(),lt:e.string(),lte:e.string(),in:e.stringList(),notIn:e.stringList(),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.stringList(),arrayContained:e.stringList(),arrayContains:e.stringList(),AND:e.field({type:[p]}),OR:e.field({type:[p]}),NOT:e.field({type:p})})}),i=t.inputRef("DateWhereInputArgument").implement({fields:e=>({eq:e.field({type:"Date"}),ne:e.field({type:"Date"}),gt:e.field({type:"Date"}),gte:e.field({type:"Date"}),lt:e.field({type:"Date"}),lte:e.field({type:"Date"}),in:e.field({type:["Date"]}),notIn:e.field({type:["Date"]}),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.field({type:["Date"]}),arrayContained:e.field({type:["Date"]}),arrayContains:e.field({type:["Date"]}),AND:e.field({type:[i]}),OR:e.field({type:[i]}),NOT:e.field({type:i})})});}var ge=({db:t,disableDefaultObjects:n,pubsub:r,pothosConfig:p})=>{let i=new we({...p,plugins:[ye,Ke,_e,...p?.plugins??[]],drizzle:{client:t,relations:t._.relations,getTableConfig(e){return {columns:Object.values(e[Symbol.for("drizzle:Columns")]),primaryKeys:Object.values(e[Symbol.for("drizzle:Columns")]).filter(c=>c.primary)}}},smartSubscriptions:{...subscribeOptionsFromIterator((e,c)=>r.subscribe(e))}});return i.addScalarType("JSON",JSONResolver),i.addScalarType("Date",DateResolver),i.addScalarType("DateTime",DateTimeISOResolver),fe(i),n?.query||i.queryType({}),n?.subscription||i.subscriptionType({}),n?.mutation||i.mutationType({}),{schemaBuilder:i}};var Xe=t=>{t.actions||(t.actions=["read","update","delete"]),t.defaultLimit===void 0&&(t.defaultLimit=100);let n=re(t),r=ie({...t,abilityBuilder:n}),{makePubSubInstance:p,pubsub:i}=pe({...t}),{schemaBuilder:e}=ge({...t,pubsub:i}),c=oe({...t,schemaBuilder:e}),l=de({...t,schemaBuilder:e,enumImplementer:c}),u=le({...t,schemaBuilder:e}),y=ae({...t,schemaBuilder:e,makePubSubInstance:p,whereArgImplementer:l,orderArgImplementer:u,enumImplementer:c,abilityBuilder:n}),s=me({...t,schemaBuilder:e,whereArgImplementer:l,orderArgImplementer:u,makePubSubInstance:p}),d=v(()=>e.toSchema());return {abilityBuilder:n,schemaBuilder:e,createYoga:o=>createYoga({...o,schema:d(),context:r}),createSofa:o=>(o.openAPI&&(o.openAPI={...se,...o.openAPI}),useSofa({...o,schema:d(),context:r})),object:y,whereArg:l,orderArg:u,query:s,pubsub:p,enum_:c}};export{I as RumbleError,k as RumbleErrorSafe,V as assertFindFirstExists,Ce as assertFirstEntryExists,De as mapNullFieldsToUndefined,Xe as rumble};//# sourceMappingURL=index.js.map
|
7
|
+
`+_(this.source,r);return n}toJSON(){let n={message:this.message};return this.locations!=null&&(n.locations=this.locations),this.path!=null&&(n.path=this.path),this.extensions!=null&&Object.keys(this.extensions).length>0&&(n.extensions=this.extensions),n}};function Z(t){return t===void 0||t.length===0?void 0:t}var I=class extends Error{constructor(n){super(n),this.name="RumbleError";}},k=class extends L{};var V=t=>{if(!t)throw new k("Value not found but required (findFirst)");return t},De=t=>{let n=t.at(0);if(!n)throw new k("Value not found but required (firstEntry)");return n},ee=async({filters:t,entities:n,context:r})=>(await Promise.all(t.map(p=>p({context:r,entities:n})))).reduce((p,i)=>(p.push(...i),p),[]);function Re(t){return Object.fromEntries(Object.entries(t).map(([n,r])=>[n,r===null?void 0:r]))}function v(t){let n,r=false;return ()=>(r||(n=t(),r=true),n)}var G=(t,n)=>new I(`RumbleError: Unknown SQL type '${t}'. Please open an issue (https://github.com/m1212e/rumble/issues) so it can be added. (${n})`);function te(t){if(["serial","int","integer","tinyint","smallint","mediumint"].includes(t))return {value1:1,value2:2};if(["real","decimal","double","float"].includes(t))return {value1:1.1,value2:2.2};if(["string","text","varchar","char","text(256)"].includes(t))return {value1:"a",value2:"b"};if(["uuid"].includes(t))return {value1:"fba31870-5528-42d7-b27e-2e5ee657aea5",value2:"fc65db81-c2d1-483d-8a25-a30e2cf6e02d"};if(["boolean"].includes(t))return {value1:true,value2:false};if(["timestamp","datetime"].includes(t))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(["date"].includes(t))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(["json"].includes(t))return {value1:{a:1},value2:{b:2}};throw G(t,"Distinct")}var M=Symbol.for("drizzle:Name"),ne=Symbol.for("drizzle:Columns");function B({dbName:t,tsName:n,table:r,db:p}){let i=r;if(n&&(i=p._.relations.schema[n]),t&&(i=Object.values(p._.relations.schema).find(e=>e[M]===t)),!i)throw new I(`Could not find schema for ${JSON.stringify({tsName:n,dbName:t,table:r?.[M]}).toString()}`);return {tableSchema:i,columns:i[ne],get primaryColumns(){return Object.entries(i[ne]).filter(([e,y])=>y.primary).reduce((e,[y,l])=>(e[y]=l,e),{})},relations:p._.relations.config[n],dbName:i[M],get tsName(){return Object.entries(p._.relations.schema).find(([e,y])=>y===i).at(0)}}}function Ie(t){return typeof t!="function"}function Ae(t){return typeof t=="function"&&t.constructor.name!=="AsyncFunction"}var re=({db:t,actions:n,defaultLimit:r})=>{let p={},i={},e={},y=l=>{for(let u of n)e[l]||(e[l]={}),e[l][u]||(e[l][u]=[]);return {allow:u=>{let m=i[l];m||(m={},i[l]=m);let a=Array.isArray(u)?u:[u];for(let f of a){let s=m[f];s||(s="unspecified",m[f]=s);}return {when:f=>{for(let s of a)m[s]==="unspecified"&&(m[s]=[]),m[s].push(f);}}},filter:u=>{let m=Array.isArray(u)?u:[u];return {by:a=>{for(let f of m)e[l][f].push(a);}}}}};for(let l of Object.keys(t.query))p[l]=y(l);return {...p,registeredQueryFilters:i,registeredFilters:e,buildWithUserContext:l=>{let u={},m=a=>({filter:(f,s)=>{let h=c=>{let R=v(()=>{if(!(!c?.where&&!s?.inject?.where)){if(s?.inject?.where&&c?.where)return {AND:[c?.where,s?.inject?.where]};if(s?.inject?.where&&!c?.where)return s?.inject?.where;if(!s?.inject?.where&&c?.where)return c?.where;!s?.inject?.where&&c?.where;}}),P=v(()=>{let E=R();if(!E)return;let Q=B({tsName:a,db:t});return relationsFilterToSQL(Q.tableSchema,E)}),w=v(()=>{let E=c?.limit??r;return s?.inject?.limit&&(!E||E>s.inject.limit)&&(E=s.inject.limit),c?.limit&&(!E||c.limit>E)&&(E=c.limit),E??void 0}),F=v(()=>{if(!(!c?.columns&&!s?.inject?.columns))return {...c?.columns,...s?.inject?.columns}}),q={query:{single:{get where(){return R()},columns:F()},many:{get where(){return R()},columns:F(),get limit(){return w()}}},sql:{get where(){return P()},columns:F(),get limit(){return w()}}};return F()||(delete q.sql.columns,delete q.query.many.columns,delete q.query.single.columns),q},o=()=>{let c=B({db:t,tsName:a});if(Object.keys(c.primaryColumns).length===0)throw new I(`No primary key found for entity ${a.toString()}`);let R=Object.values(c.primaryColumns)[0],P=te(R.getSQLType());return {where:{AND:[{[R.name]:P.value1},{[R.name]:P.value2}]}}},b=i?.[a]?.[f];if(b==="unspecified")return h();b||(b=[o()]);let d=b.filter(Ie),T=b.filter(Ae).map(c=>c(l)),C=T.some(c=>c==="allow"),D=[...d,...T].filter(c=>c!==void 0).filter(c=>c!=="allow");!C&&D.length===0&&(D=[o()]);let A;for(let c of D)c?.limit&&(A===void 0||c.limit>A)&&(A=c.limit);let S;for(let c of [...D,s?.inject])c?.columns&&(S===void 0?S=c.columns:S={...S,...c.columns});let g=C?[]:D.filter(c=>c?.where).map(c=>c.where),x=g.length>0?{OR:g}:void 0;return h({where:x,columns:S,limit:A})},explicitFilters:f=>e[a][f]});for(let a of Object.keys(t.query))u[a]=m(a);return u}}};var ie=({context:t,abilityBuilder:n})=>async r=>{let p=t?await t(r):{};return {...p,abilities:n.buildWithUserContext(p)}};function z(t){return String(t).charAt(0).toUpperCase()+String(t).slice(1)}function W(t){return t instanceof PgEnumColumn}var oe=({db:t,schemaBuilder:n})=>{let r=new Map;return ({tsName:i,enumColumn:e,refName:y})=>{let l,u;if(i){let s=t._.relations.schema[i];l=i.toString();let h=Object.values(t._.relations.schema).filter(o=>typeof o=="object").map(o=>Object.values(o[Symbol.for("drizzle:Columns")])).flat(2).find(o=>o.config?.enum===s);if(!h)throw new I(`Could not find applied enum column for ${i.toString()}.
|
8
|
+
Please ensure that you use the enum at least once as a column of a table!`);u=h.enumValues;}else if(e){let s=Object.entries(t._.relations.schema).find(([h,o])=>o===e.config.enum);if(!s)throw new I(`Could not find enum in schema for ${e.name}!`);l=s[0],u=e.enumValues;}if(!l||!u)throw new I("Could not determine enum structure!");let m=y??`${z(toCamelCase(l))}Enum`,a=r.get(m);return a||(a=n.enumType(m,{values:u}),r.set(m,a),a)}};var se={paths:{"/webhook":{post:{operationId:"webhook_create",description:"Creates a webhook subscription.",tags:[],parameters:[],requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookCreateBody"}}}},responses:{200:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}}},"/webhook/{id}":{post:{operationId:"webhook_update",description:"Updates a webhook subscription.",parameters:[{name:"id",in:"path",description:"The ID of the webhook to update",required:true,schema:{type:"string"}}],requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookCreateBody"}}}},responses:{200:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}},delete:{operationId:"webhook_delete",description:"Removes a webhook subscription.",tags:[],parameters:[{name:"id",in:"path",description:"The ID of the webhook to delete",required:true,schema:{type:"string"}}],responses:{200:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}}}},components:{schemas:{WebhookCreateBody:{type:"object",properties:{subscription:{description:"The subscription to subscribe to. In many cases, these match the available query IDs without the '_query' suffix. E.g., 'findFirstUser_query' -> 'findFirstUser'. See the graphql schema for more details on what subscriptions are available.",type:"string"},variables:{description:"The variables to pass to the subscription.",type:"object"},url:{description:"The URL to send the webhook to.",type:"string"}}},WebhookDetailResponse:{type:"object",properties:{id:{description:"The ID of the webhook. Can be used as reference in update or delete calls.",type:"string"}}}}}};function K({sqlType:t,fieldName:n}){let r;if(["serial","int","integer","tinyint","smallint","mediumint"].includes(t)&&(r="Int"),["real","decimal","double","float"].includes(t)&&(r="Float"),["string","text","varchar","char","text(256)"].includes(t)&&(n&&(n.toLowerCase().endsWith("_id")||n.toLowerCase().endsWith("id"))?r="ID":r="String"),["uuid"].includes(t)&&(r="ID"),["boolean"].includes(t)&&(r="Boolean"),["timestamp","datetime"].includes(t)&&(r="DateTime"),["date"].includes(t)&&(r="Date"),["json"].includes(t)&&(r="JSON"),r!==void 0)return r;throw G(t,"SQL to GQL")}var Pe=t=>typeof t!="object"?false:!!Object.keys(t).some(n=>["args","nullable","query","subscribe","description","type","resolve"].find(r=>r===n)),ae=({db:t,schemaBuilder:n,makePubSubInstance:r,whereArgImplementer:p,orderArgImplementer:i,enumImplementer:e,abilityBuilder:y})=>({table:l,refName:u,readAction:m="read",adjust:a})=>{let f=B({db:t,tsName:l});Object.keys(f.primaryColumns).length===0&&console.warn(`Could not find primary key for ${l.toString()}. Cannot register subscriptions!`);let s=Object.values(f.primaryColumns)[0],{registerOnInstance:h}=r({table:l});return n.drizzleObject(l,{name:u??z(l.toString()),subscribe:(o,b,d)=>{if(!s)return;let T=b[s.name];if(!T){console.warn(`Could not find primary key value for ${JSON.stringify(b)}. Cannot register subscription!`);return}h({instance:o,action:"updated",primaryKeyValue:T});},applyFilters:y?.registeredFilters?.[l]?.[m],fields:o=>{let b=f.columns,d=(S,g,x)=>{let c=K({sqlType:S,fieldName:g});switch(c){case "Int":return o.exposeInt(g,{nullable:x});case "String":return o.exposeString(g,{nullable:x});case "Boolean":return o.exposeBoolean(g,{nullable:x});case "Date":return o.field({type:"Date",resolve:R=>R[g],nullable:x});case "DateTime":return o.field({type:"DateTime",resolve:R=>R[g],nullable:x});case "Float":return o.exposeFloat(g,{nullable:x});case "ID":return o.exposeID(g,{nullable:x});case "JSON":return o.field({type:"JSON",resolve:R=>R[g],nullable:x});default:throw new I(`Unsupported object type ${c} for column ${g}`)}},T=new Map,C=a?.(new Proxy(o,{get:(S,g)=>typeof S[g]=="function"?(...x)=>{let c=S[g](...x),R=x.find(Pe);if(!R)throw new I("Expected config object to be passed to adjust field");return T.set(c,{params:x,creatorFunction:S[g],configObject:R}),c}:S[g]}))??{},D=Object.entries(b).reduce((S,[g,x])=>{if(C[g]){let{params:c,creatorFunction:R,configObject:P}=T.get(C[g]);return typeof P.nullable!="boolean"&&(P.nullable=!x.notNull),C[g]=R.bind(o)(...c),S}if(W(x)){let c=e({enumColumn:x});S[g]=o.field({type:c,resolve:R=>R[g],nullable:!x.notNull});}else S[g]=d(x.getSQLType(),g,!x.notNull);return S},{}),A=Object.entries(f.relations??{}).reduce((S,[g,x])=>{let c=B({db:t,table:x.targetTable}),R=p({dbName:c.dbName}),P=i({dbName:c.dbName}),w=r({table:c.tsName}),F=false,q=true,E="many";x instanceof One&&(q=false,F=x.optional,E="single");let Q=(N,j)=>{w.registerOnInstance({instance:N,action:"created"}),w.registerOnInstance({instance:N,action:"removed"});};if(C[g]){let{params:N,creatorFunction:j,configObject:O}=T.get(C[g]);return typeof O.nullable!="boolean"&&(O.nullable=F),typeof O.subscribe!="function"&&(O.subscribe=Q),C[g]=j.bind(o)(...N),S}return S[g]=o.relation(g,{args:{where:o.arg({type:R,required:false}),orderBy:o.arg({type:P,required:false}),...q?{offset:o.arg.int({required:false}),limit:o.arg.int({required:false})}:{}},subscribe:Q,nullable:F,query:(N,j)=>{N=JSON.parse(JSON.stringify(N));let O=j.abilities[c.tsName].filter(m,{inject:{where:N.where,limit:N.limit}}).query[E];return N.offset&&(O.offset=N.offset),N.orderBy&&(O.orderBy=N.orderBy),O}}),S},{});return {...D,...A,...C}}})};var Fe=t=>`${z(toCamelCase(t.toString()))}OrderInputArgument`,le=({db:t,schemaBuilder:n})=>{let r=new Map,p=v(()=>n.enumType("SortingParameter",{values:["asc","desc"]})),i=({table:e,refName:y,dbName:l})=>{let u=B({db:t,dbName:l,tsName:e}),m=y??Fe(u.tsName),a=r.get(m);return a||(a=n.inputType(m,{fields:s=>{let h=Object.entries(u.columns).reduce((b,[d,T])=>(b[d]=s.field({type:p(),required:false}),b),{}),o=Object.entries(u.relations??{}).reduce((b,[d,T])=>{let C=B({db:t,table:T.targetTable}),D=i({dbName:C.dbName});return b[d]=s.field({type:D,required:false}),b},{});return {...h,...o}}}),r.set(m,a),a)};return i};var Oe="RUMBLE_SUBSCRIPTION_NOTIFICATION",ze="REMOVED",qe="UPDATED",Le="CREATED",pe=({subscriptions:t,db:n})=>{let r=t?createPubSub(...t):createPubSub();return {pubsub:r,makePubSubInstance:({table:i})=>{function e({action:y,tableName:l,primaryKeyValue:u}){let m;switch(y){case "created":m=Le;break;case "removed":m=ze;break;case "updated":m=qe;break;default:throw new Error(`Unknown action: ${y}`)}return `${Oe}/${l}${u?`/${u}`:""}/${m}`}return {registerOnInstance({instance:y,action:l,primaryKeyValue:u}){let m=e({tableName:i.toString(),action:l,primaryKeyValue:u});y.register(m);},created(){let y=e({tableName:i.toString(),action:"created"});return r.publish(y)},removed(y){let l=e({tableName:i.toString(),action:"removed"});return r.publish(l)},updated(y){let u=(Array.isArray(y)?y:[y]).map(a=>e({tableName:i.toString(),action:"updated",primaryKeyValue:a})),m=Array.from(new Set(u));for(let a of m)r.publish(a);}}}}};var me=({db:t,schemaBuilder:n,whereArgImplementer:r,orderArgImplementer:p,makePubSubInstance:i})=>({table:e,readAction:y="read",listAction:l="read"})=>{let u=r({table:e}),m=p({table:e}),a=B({db:t,tsName:e}),f=Object.values(a.primaryColumns)[0],{registerOnInstance:s}=i({table:e});return n.queryFields(h=>({[plural(e.toString())]:h.drizzleField({type:[e],nullable:false,smartSubscription:true,subscribe:(o,b,d,T,C)=>{s({instance:o,action:"created"}),s({instance:o,action:"removed"});},args:{where:h.arg({type:u,required:false}),orderBy:h.arg({type:m,required:false}),limit:h.arg.int({required:false}),offset:h.arg.int({required:false})},resolve:(o,b,d,T,C)=>{d=JSON.parse(JSON.stringify(d));let D=T.abilities[e].filter(l,d.where||d.limit||d.offset?{inject:{where:d.where,limit:d.limit}}:void 0).query.many;d.offset&&(D.offset=d.offset),d.orderBy&&(D.orderBy=d.orderBy);let A=o(D);return D.columns&&(A.columns=D.columns),t.query[e].findMany(A)}}),[singular(e.toString())]:h.drizzleField({type:e,nullable:false,smartSubscription:true,args:{id:h.arg.id({required:true})},resolve:(o,b,d,T,C)=>{d=JSON.parse(JSON.stringify(d));let D=T.abilities[e].filter(y,{inject:{where:{[f.name]:d.id}}}).query.single,A=o(D);return D.columns&&(A.columns=D.columns),t.query[e].findFirst(A).then(V)}})}))};var ye="ManualFiltersPlugin",de=ye,ce="applyFilters",$=class extends BasePlugin{wrapResolve(n,r){return async(p,i,e,y)=>{let l,u=r?.type;if(u.kind==="List"?l=u.type?.ref.currentConfig.pothosOptions[ce]:u.kind==="Object"&&(l=u.ref.currentConfig.pothosOptions[ce]),!l||!Array.isArray(l)||l.length===0)return n(p,i,e,y);let m=await n(p,i,e,y),a=Array.isArray(m)?m:[m],f=Array.isArray(l)?l:[l],s=await ee({filters:f,entities:a,context:e});return Array.isArray(m)?s:s[0]??null}}};Ue.registerPlugin(ye,$);var Ge=t=>`${z(toCamelCase(t.toString()))}WhereInputArgument`,fe=({db:t,schemaBuilder:n,enumImplementer:r})=>{let p=new Map,i=({table:e,refName:y,dbName:l})=>{let u=B({db:t,dbName:l,tsName:e}),m=y??Ge(u.tsName),a=p.get(m);return a||(a=n.inputType(m,{fields:s=>{let h=(d,T)=>{let C=K({sqlType:d,fieldName:T});switch(C){case "Int":return s.field({type:"IntWhereInputArgument"});case "String":return s.field({type:"StringWhereInputArgument"});case "Boolean":return s.boolean({required:false});case "Date":return s.field({type:"DateWhereInputArgument"});case "DateTime":return s.field({type:"DateWhereInputArgument"});case "Float":return s.field({type:"FloatWhereInputArgument"});case "ID":return s.id({required:false});case "JSON":return s.field({type:"JSON",required:false});default:throw new I(`Unsupported argument type ${C} for column ${d}`)}},o=Object.entries(u.columns).reduce((d,[T,C])=>{if(W(C)){let D=r({enumColumn:C});d[T]=s.field({type:D,required:false});}else d[T]=h(C.getSQLType(),T);return d},{}),b=Object.entries(u.relations??{}).reduce((d,[T,C])=>{let D=B({db:t,table:C.targetTable}),A=i({dbName:D.dbName});return d[T]=s.field({type:A,required:false}),d},{});return {...o,...b}}}),p.set(m,a),a)};return i};function ge(t){let n=t.inputRef("IntWhereInputArgument").implement({fields:e=>({eq:e.int(),ne:e.int(),gt:e.int(),gte:e.int(),lt:e.int(),lte:e.int(),in:e.intList(),notIn:e.intList(),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.intList(),arrayContained:e.intList(),arrayContains:e.intList(),AND:e.field({type:[n]}),OR:e.field({type:[n]}),NOT:e.field({type:n})})}),r=t.inputRef("FloatWhereInputArgument").implement({fields:e=>({eq:e.float(),ne:e.float(),gt:e.float(),gte:e.float(),lt:e.float(),lte:e.float(),in:e.floatList(),notIn:e.floatList(),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.floatList(),arrayContained:e.floatList(),arrayContains:e.floatList(),AND:e.field({type:[r]}),OR:e.field({type:[r]}),NOT:e.field({type:r})})}),p=t.inputRef("StringWhereInputArgument").implement({fields:e=>({eq:e.string(),ne:e.string(),gt:e.string(),gte:e.string(),lt:e.string(),lte:e.string(),in:e.stringList(),notIn:e.stringList(),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.stringList(),arrayContained:e.stringList(),arrayContains:e.stringList(),AND:e.field({type:[p]}),OR:e.field({type:[p]}),NOT:e.field({type:p})})}),i=t.inputRef("DateWhereInputArgument").implement({fields:e=>({eq:e.field({type:"Date"}),ne:e.field({type:"Date"}),gt:e.field({type:"Date"}),gte:e.field({type:"Date"}),lt:e.field({type:"Date"}),lte:e.field({type:"Date"}),in:e.field({type:["Date"]}),notIn:e.field({type:["Date"]}),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.field({type:["Date"]}),arrayContained:e.field({type:["Date"]}),arrayContains:e.field({type:["Date"]}),AND:e.field({type:[i]}),OR:e.field({type:[i]}),NOT:e.field({type:i})})});}var be=({db:t,disableDefaultObjects:n,pubsub:r,pothosConfig:p})=>{let i=new Ue({...p,plugins:[de,Ke,_e,...p?.plugins??[]],drizzle:{client:t,relations:t._.relations,getTableConfig(e){return {columns:Object.values(e[Symbol.for("drizzle:Columns")]),primaryKeys:Object.values(e[Symbol.for("drizzle:Columns")]).filter(y=>y.primary)}}},smartSubscriptions:{...subscribeOptionsFromIterator((e,y)=>r.subscribe(e))}});return i.addScalarType("JSON",JSONResolver),i.addScalarType("Date",DateResolver),i.addScalarType("DateTime",DateTimeISOResolver),ge(i),n?.query||i.queryType({}),n?.subscription||i.subscriptionType({}),n?.mutation||i.mutationType({}),{schemaBuilder:i}};var Xe=t=>{t.actions||(t.actions=["read","update","delete"]),t.defaultLimit===void 0&&(t.defaultLimit=100);let n=re(t),r=ie({...t,abilityBuilder:n}),{makePubSubInstance:p,pubsub:i}=pe({...t}),{schemaBuilder:e}=be({...t,pubsub:i}),y=oe({...t,schemaBuilder:e}),l=fe({...t,schemaBuilder:e,enumImplementer:y}),u=le({...t,schemaBuilder:e}),m=ae({...t,schemaBuilder:e,makePubSubInstance:p,whereArgImplementer:l,orderArgImplementer:u,enumImplementer:y,abilityBuilder:n}),a=me({...t,schemaBuilder:e,whereArgImplementer:l,orderArgImplementer:u,makePubSubInstance:p}),f=v(()=>e.toSchema());return {abilityBuilder:n,schemaBuilder:e,createYoga:o=>createYoga({...o,schema:f(),context:r}),createSofa:o=>(o.openAPI&&(o.openAPI={...se,...o.openAPI}),useSofa({...o,schema:f(),context:r})),object:m,whereArg:l,orderArg:u,query:a,pubsub:p,enum_:y}};export{I as RumbleError,k as RumbleErrorSafe,V as assertFindFirstExists,De as assertFirstEntryExists,Re as mapNullFieldsToUndefined,Xe as rumble};//# sourceMappingURL=index.js.map
|
9
9
|
//# sourceMappingURL=index.js.map
|