@m1212e/rumble 0.11.7 → 0.12.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/out/index.cjs +1901 -0
- package/out/index.cjs.map +1 -0
- package/out/index.d.cts +922 -0
- package/out/index.d.cts.map +1 -0
- package/out/index.d.ts +922 -0
- package/out/index.d.ts.map +1 -0
- package/out/index.js +1849 -0
- package/out/index.js.map +1 -0
- package/package.json +61 -1
- package/LICENSE +0 -201
- package/README.md +0 -285
- package/index.cjs +0 -65
- package/index.cjs.map +0 -1
- package/index.d.cts +0 -833
- package/index.d.ts +0 -833
- package/index.js +0 -65
- package/index.js.map +0 -1
package/index.js
DELETED
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
import {access,rm,mkdir,writeFile}from'fs/promises';import {join}from'path';import {GraphQLError,GraphQLObjectType,GraphQLScalarType,GraphQLEnumType,GraphQLInputObjectType,GraphQLList,GraphQLNonNull}from'graphql';import {debounce,merge,capitalize,cloneDeep}from'es-toolkit';import {pipe,merge as merge$1,empty,map,onPush,toObservable,fromValue,toPromise}from'wonka';import {EnvelopArmorPlugin}from'@escape.tech/graphql-armor';import {useDisableIntrospection}from'@graphql-yoga/plugin-disable-introspection';import {createYoga,createPubSub}from'graphql-yoga';import {useSofa}from'sofa-api';import {sql,One,relationsFilterToSQL}from'drizzle-orm';import {toCamelCase}from'drizzle-orm/casing';import {PgEnumColumn,PgTable}from'drizzle-orm/pg-core';import ie from'pluralize';import {MySqlTable}from'drizzle-orm/mysql-core';import {SQLiteTable}from'drizzle-orm/sqlite-core';import Kt,{BasePlugin}from'@pothos/core';import Zt from'@pothos/plugin-drizzle';import en,{subscribeOptionsFromIterator}from'@pothos/plugin-smart-subscriptions';import {JSONResolver,DateResolver,DateTimeISOResolver}from'graphql-scalars';function fe({apiUrl:e,rumbleImportPath:n,useExternalUrqlClient:r,availableSubscriptions:i}){let o=[],t="";return typeof r=="string"?o.push(`import { urqlClient } from "${r}";`):(o.push("import { Client, fetchExchange } from '@urql/core';"),o.push("import { cacheExchange } from '@urql/exchange-graphcache';")),o.push(`import { makeLiveQuery, makeMutation, makeSubscription, makeQuery } from '${n}';`),r||(t+=`
|
|
2
|
-
const urqlClient = new Client({
|
|
3
|
-
url: "${e??"PLEASE PROVIDE A URL WHEN GENERATING OR IMPORT AN EXTERNAL URQL CLIENT"}",
|
|
4
|
-
fetchSubscriptions: true,
|
|
5
|
-
exchanges: [cacheExchange({}), fetchExchange],
|
|
6
|
-
fetchOptions: {
|
|
7
|
-
credentials: "include",
|
|
8
|
-
},
|
|
9
|
-
requestPolicy: "cache-and-network",
|
|
10
|
-
});
|
|
11
|
-
`),t+=`
|
|
12
|
-
export const client = {
|
|
13
|
-
/**
|
|
14
|
-
* A query and subscription combination. First queries and if exists, also subscribes to a subscription of the same name.
|
|
15
|
-
* Combines the results of both, so the result is first the query result and then live updates from the subscription.
|
|
16
|
-
* Assumes that the query and subscription return the same fields as per default when using the rumble query helpers.
|
|
17
|
-
* If no subscription with the same name exists, this will just be a query.
|
|
18
|
-
*/
|
|
19
|
-
liveQuery: makeLiveQuery<Query>({
|
|
20
|
-
urqlClient,
|
|
21
|
-
availableSubscriptions: new Set([${i.values().toArray().map(l=>`"${l}"`).join(", ")}]),
|
|
22
|
-
}),
|
|
23
|
-
/**
|
|
24
|
-
* A mutation that can be used to e.g. create, update or delete data.
|
|
25
|
-
*/
|
|
26
|
-
mutate: makeMutation<Mutation>({
|
|
27
|
-
urqlClient,
|
|
28
|
-
}),
|
|
29
|
-
/**
|
|
30
|
-
* A continuous stream of results that updates when the server sends new data.
|
|
31
|
-
*/
|
|
32
|
-
subscribe: makeSubscription<Subscription>({
|
|
33
|
-
urqlClient,
|
|
34
|
-
}),
|
|
35
|
-
/**
|
|
36
|
-
* A one-time fetch of data.
|
|
37
|
-
*/
|
|
38
|
-
query: makeQuery<Query>({
|
|
39
|
-
urqlClient,
|
|
40
|
-
}),
|
|
41
|
-
}`,{imports:o,code:t}}function Te(e){if(e instanceof GraphQLObjectType)return nt(e);if(e instanceof GraphQLScalarType)return at(e);if(e instanceof GraphQLEnumType)return lt(e);if(e instanceof GraphQLInputObjectType)return rt(e);throw new Error(`Unknown model type: ${e}`)}function nt(e){let n=new Map;for(let[r,i]of Object.entries(e.getFields()))n.set(r,it(i.type,i.args));return `{
|
|
42
|
-
${n.entries().map(([r,i])=>`${r}: ${i}`).toArray().join(`,
|
|
43
|
-
`)}
|
|
44
|
-
}`}function rt(e){let n=new Map;for(let[r,i]of Object.entries(e.getFields()))n.set(r,ot(i.type));return `{
|
|
45
|
-
${n.entries().map(([r,i])=>`${r}${i.includes("| undefined")?"?":""}: ${i}`).toArray().join(`,
|
|
46
|
-
`)}
|
|
47
|
-
}`}function it(e,n){let r=false,i=false;for(let a=0;a<3;a++)e instanceof GraphQLList&&(i=true,e=e.ofType),e instanceof GraphQLNonNull&&(r=true,e=e.ofType);let o=e.name;i&&(o+="[]"),r||(o+=" | null");let t=e instanceof GraphQLObjectType,l=new Map;for(let a of n??[])l.set(a.name,st(a.type));if(t){let a=l.entries().every(([,m])=>m.includes("| undefined"));return `(${(n??[]).length>0?`p${a?"?":""}: {
|
|
48
|
-
${l.entries().map(([m,u])=>` ${m}${u.includes("| undefined")?"?":""}: ${u}`).toArray().join(`,
|
|
49
|
-
`)}
|
|
50
|
-
}`:""}) => ${o}`}else return o}function ot(e){let n=false,r=false;for(let o=0;o<3;o++)e instanceof GraphQLList&&(r=true,e=e.ofType),e instanceof GraphQLNonNull&&(n=true,e=e.ofType);let i=e.name;return r&&(i+="[]"),n?r&&(i+=" | undefined"):i+=" | null | undefined",i}function st(e){let n="unknown",r=true;return e instanceof GraphQLNonNull&&(r=false,e=e.ofType),(e instanceof GraphQLInputObjectType||e instanceof GraphQLScalarType)&&(n=e.name),r&&(n+=" | null | undefined"),n}function at(e){switch(e.name){case "ID":return "string";case "String":return "string";case "Boolean":return "boolean";case "Int":return "number";case "Float":return "number";case "Date":return "Date";case "DateTime":return "Date";case "JSON":return "any";default:return "unknown"}}function lt(e){return e.getValues().map(n=>`"${n.name}"`).join(" | ")}async function se({outputPath:e,schema:n,rumbleImportPath:r="@m1212e/rumble",apiUrl:i,useExternalUrqlClient:o=false}){try{await access(e),await rm(e,{recursive:!0,force:!0});}catch{}await mkdir(e,{recursive:true}),e.endsWith("/")||(e+="/");let t=[],l="",a=new Map;for(let[m,u]of Object.entries(n.getTypeMap()))m.startsWith("__")||a.set(m,u);for(let[m,u]of a.entries()){let d=Te(u);d!==m&&(l+=`
|
|
51
|
-
export type ${m} = ${d};
|
|
52
|
-
`);}let s=fe({apiUrl:i,useExternalUrqlClient:o,rumbleImportPath:r,availableSubscriptions:new Set(Object.keys(n.getSubscriptionType()?.getFields()||{}))});t.push(...s.imports),l+=s.code,await writeFile(join(e,"client.ts"),`${t.join(`
|
|
53
|
-
`)}
|
|
54
|
-
${l}`);}var O="__args";function W({queryName:e,input:n,client:r,enableSubscription:i=false}){let o=`${capitalize(e)}Query`,t=_(n[O]??{}),l=u=>`${u} ${o} { ${e}${t} { ${U(n)} }}`,a,s=pipe(merge$1([r.query(l("query"),{}),i?r.subscription(l("subscription"),{}):empty]),map(u=>{let d=u.data?.[e];if(!d&&u.error)throw u.error;return d}),onPush(u=>{a&&Object.assign(a,u);})),m=new Promise(u=>{let d=toObservable(s).subscribe(p=>{d();let D=pipe(merge$1([s,fromValue(p)]),toObservable);a={...p,...D},u(a);}).unsubscribe;});return Object.assign(m,toObservable(s)),m}function Se({mutationName:e,input:n,client:r}){let i=`${capitalize(e)}Mutation`,o=_(n[O]??{}),t=pipe(r.mutation(`mutation ${i} { ${e}${o} { ${U(n)} }}`,{}),map(s=>{let m=s.data?.[e];if(!m&&s.error)throw s.error;return m})),l=toObservable(t),a=toPromise(t).then(s=>(Object.assign(s,l),s));return Object.assign(a,l),a}function De({subscriptionName:e,input:n,client:r}){let i=`${capitalize(e)}Subscription`,o=_(n[O]??{});return pipe(r.subscription(`subscription ${i} { ${e}${o} { ${U(n)} }}`,{}),map(t=>{let l=t.data?.[e];if(!l&&t.error)throw t.error;return l}),toObservable)}function U(e){return Object.entries(e).filter(([n])=>n!==O).reduce((n,[r,i])=>{if(typeof i=="object"){if(i[O]){let o=_(i[O]);return n+=`${r}${o} { ${U(i)} }
|
|
55
|
-
`,n}n+=`${r} { ${U(i)} }
|
|
56
|
-
`;}else n+=`${r}
|
|
57
|
-
`;return n},"")}function _(e){let n=Object.entries(e);return n.length===0?"":`(${n.map(([r,i])=>`${r}: ${Ce(i)}`).join(", ")})`}function Ce(e){switch(typeof e){case "string":return `"${e}"`;case "number":return `${e}`;case "bigint":return `${e}`;case "boolean":return `${e}`;case "symbol":throw new Error("Cannot stringify a symbol to send as gql arg");case "undefined":return "null";case "object":return `{ ${Object.entries(e).map(([n,r])=>`${n}: ${Ce(r)}`).join(", ")} }`;case "function":throw new Error("Cannot stringify a function to send as gql arg")}}function ht({urqlClient:e,availableSubscriptions:n}){return new Proxy({},{get:(r,i)=>o=>W({queryName:i,input:o,client:e,enableSubscription:n.has(i)})})}function Tt({urqlClient:e}){return new Proxy({},{get:(n,r)=>i=>Se({mutationName:r,input:i,client:e})})}function xt({urqlClient:e}){return new Proxy({},{get:(n,r)=>i=>W({queryName:r,input:i,client:e,enableSubscription:false})})}function St({urqlClient:e}){return new Proxy({},{get:(n,r)=>i=>De({subscriptionName:r,input:i,client:e})})}var A=class extends Error{constructor(n){super(n),this.name="RumbleError";}},F=class extends GraphQLError{};var ue=e=>{if(!e)throw new F("Value not found but required (findFirst)");return e},Ct=e=>{let n=e.at(0);if(!n)throw new F("Value not found but required (firstEntry)");return n},Re=async({filters:e,entities:n,context:r})=>Array.from((await Promise.all(e.map(i=>i({context:r,entities:n})))).reduce((i,o)=>(o.forEach(t=>i.add(t)),i),new Set));function Rt(e){return Object.fromEntries(Object.entries(e).map(([n,r])=>[n,r===null?void 0:r]))}function Q(e){let n,r=false;return ()=>(r||(n=e(),r=true),n)}var Ae=["serial","int","integer","tinyint","smallint","mediumint"];function M(e){return Ae.includes(e)}var Ie=["real","decimal","double","float","numeric"];function K(e){return Ie.includes(e)}var Be=["string","text","varchar","char","text(256)"];function V(e){return Be.includes(e)}var Ne=["uuid"];function J(e){return Ne.includes(e)}var Ee=["boolean"];function H(e){return Ee.includes(e)}var Pe=["timestamp","datetime"];function X(e){return Pe.includes(e)}var Le=["date"];function Y(e){return Le.includes(e)}var Qe=["json"];function Z(e){return Qe.includes(e)}var ee=(e,n)=>new A(`RumbleError: Unknown SQL type '${e}'. Please open an issue (https://github.com/m1212e/rumble/issues) so it can be added. (${n})`);function we(e){if(M(e))return {value1:1,value2:2};if(K(e))return {value1:1.1,value2:2.2};if(V(e))return {value1:"a",value2:"b"};if(J(e))return {value1:"fba31870-5528-42d7-b27e-2e5ee657aea5",value2:"fc65db81-c2d1-483d-8a25-a30e2cf6e02d"};if(H(e))return {value1:true,value2:false};if(X(e))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(Y(e))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(Z(e))return {value1:{a:1},value2:{b:2}};throw ee(e,"Distinct")}var pe=Symbol.for("drizzle:Name"),ke=Symbol.for("drizzle:Columns");function E({dbName:e,tsName:n,table:r,db:i}){let o=r;if(n&&(o=i._.relations.schema[n]),e&&(o=Object.values(i._.relations.schema).find(t=>t[pe]===e)),!o)throw new A(`Could not find schema for ${JSON.stringify({tsName:n,dbName:e,table:r?.[pe]}).toString()}`);return {tableSchema:o,columns:o[ke],get primaryColumns(){return Object.entries(o[ke]).filter(([,t])=>t.primary).reduce((t,[l,a])=>(t[l]=a,t),{})},relations:i._.relations.config[n],dbName:o[pe],get tsName(){return Object.entries(i._.relations.schema).find(([,t])=>t===o).at(0)}}}function Bt(e){return typeof e!="function"}function Nt(e){return typeof e=="function"&&e.constructor.name!=="AsyncFunction"}var Et=debounce((e,n)=>{console.warn(`
|
|
58
|
-
Warning! No abilities have been registered for
|
|
59
|
-
|
|
60
|
-
${e}/${n}
|
|
61
|
-
|
|
62
|
-
but has been accessed. This will block everything. If this is intended, you can ignore this warning. If not, please ensure that you register the ability in your ability builder.
|
|
63
|
-
`);},1e3),qe=({db:e,actions:n,defaultLimit:r})=>{let i={},o={},t={},l=a=>{for(let s of n)t[a]||(t[a]={}),t[a][s]||(t[a][s]=[]);return {allow:s=>{let m=o[a];m||(m={},o[a]=m);let u=Array.isArray(s)?s:[s];for(let d of u){let p=m[d];p||(p="unspecified",m[d]=p);}return {when:d=>{for(let p of u)m[p]==="unspecified"&&(m[p]=[]),m[p].push(d);}}},filter:s=>{let m=Array.isArray(s)?s:[s];return {by:u=>{for(let d of m)t[a][d].push(u);}}}}};for(let a of Object.keys(e.query))i[a]=l(a);return {...i,z_registeredQueryFilters:o,z_registeredFilters:t,z_buildWithUserContext:a=>{let s={},m=u=>({filter:(d,p)=>{let D=c=>{let x=Q(()=>{if(!(!c?.where&&!p?.inject?.where)){if(p?.inject?.where&&c?.where)return {AND:[c?.where,p?.inject?.where]};if(p?.inject?.where&&!c?.where)return p?.inject?.where;if(!p?.inject?.where&&c?.where)return c?.where;!p?.inject?.where&&c?.where;}}),C=Q(()=>{let P=x();if(!P)return;let G=E({tsName:u,db:e});return relationsFilterToSQL(G.tableSchema,P)}),q=Q(()=>{let P=c?.limit??r;return p?.inject?.limit&&(!P||P>p.inject.limit)&&(P=p.inject.limit),P??void 0}),z=Q(()=>{if(!(!c?.columns&&!p?.inject?.columns))return {...c?.columns,...p?.inject?.columns}}),k={query:{single:{get where(){return x()},columns:z()},many:{get where(){return x()},columns:z(),get limit(){return q()}}},sql:{get where(){return C()}}};return z()||(delete k.query.many.columns,delete k.query.single.columns),k},h=()=>{let c=E({db:e,tsName:u});if(Object.keys(c.primaryColumns).length===0)throw new A(`No primary key found for entity ${u.toString()}`);let x=Object.values(c.primaryColumns)[0],C=we(x.getSQLType());return {where:{AND:[{[x.name]:C.value1},{[x.name]:C.value2}]}}},y=o?.[u]?.[d];if(y==="unspecified")return D();y||(Et(u.toString(),d),y=[h()]);let b=y.filter(Bt),R=y.filter(Nt).map(c=>c(a)),g=R.some(c=>c==="allow"),T=[...b,...R].filter(c=>c!==void 0).filter(c=>c!=="allow");!g&&T.length===0&&(T=[h()]);let L;for(let c of T)c?.limit&&(L===void 0||c.limit>L)&&(L=c.limit);let I;for(let c of [...T,p?.inject])c?.columns&&(I===void 0?I=c.columns:I={...I,...c.columns});let S=g?[]:T.filter(c=>c?.where).map(c=>c.where),f=S.length>0?{OR:S}:void 0;return D({where:f,columns:I,limit:L})},runtimeFilters:d=>t[u][d]});for(let u of Object.keys(e.query))s[u]=m(u);return s}}};var ze=({builtSchema:e})=>(process.env.NODE_ENV!=="development"&&console.warn("Running rumble client generation in non development mode. Are you sure this is correct?"),async({apiUrl:r,outputPath:i,rumbleImportPath:o,useExternalUrqlClient:t})=>{let l=e();await se({schema:l,outputPath:i,rumbleImportPath:o,apiUrl:r,useExternalUrqlClient:t});});var Oe=({context:e,abilityBuilder:n})=>async r=>{let i=e?await e(r):{};return {...i,abilities:n.z_buildWithUserContext(i)}};function te(e){return e instanceof PgEnumColumn}var Fe=({db:e,schemaBuilder:n})=>{let r=new Map;return ({tsName:o,enumColumn:t,refName:l})=>{let a,s;if(o){let p=e._.relations.schema[o];a=o.toString();let D=Object.values(e._.relations.schema).filter(h=>typeof h=="object").map(h=>Object.values(h[Symbol.for("drizzle:Columns")])).flat(2).find(h=>h.config?.enum===p);if(!D)throw new A(`Could not find applied enum column for ${o.toString()}.
|
|
64
|
-
Please ensure that you use the enum at least once as a column of a table!`);s=D.enumValues;}else if(t){let p=Object.entries(e._.relations.schema).find(([,D])=>D===t.config.enum);if(!p)throw new A(`Could not find enum in schema for ${t.name}!`);a=p[0],s=t.enumValues;}if(!a||!s)throw new A("Could not determine enum structure!");let m=l??`${capitalize(toCamelCase(a))}Enum`,u=r.get(m);return u||(u=n.enumType(m,{values:s}),r.set(m,u),u)}};var ve={paths:{"/webhook":{post:{operationId:"webhook_create",description:"Creates a webhook subscription.",tags:[],parameters:[],requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookCreateBody"}}}},responses:{200:{description:"",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:{description:"",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:{description:"",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"}}},DateTime:{type:"string",format:"date-time"},Date:{type:"string",format:"date"}}}};function ne({sqlType:e,fieldName:n}){let r;if(M(e)&&(r="Int"),K(e)&&(r="Float"),V(e)&&(n&&(n.toLowerCase().endsWith("_id")||n.toLowerCase().endsWith("id"))?r="ID":r="String"),J(e)&&(r="ID"),H(e)&&(r="Boolean"),X(e)&&(r="DateTime"),Y(e)&&(r="Date"),Z(e)&&(r="JSON"),r!==void 0)return r;throw ee(e,"SQL to GQL")}function zt(e){let n=new Set;for(let i of Object.values(e))typeof i=="object"&&(i instanceof PgTable?n.add("postgres"):i instanceof MySqlTable?n.add("mysql"):i instanceof SQLiteTable&&n.add("sqlite"));let r=Array.from(n);if(r.length===1)return r[0];throw r.length===0?new Error("No tables found in schema, could not determine dialect"):new Error(`Multiple dialects found in schema: ${r.join(", ")}`)}function je(e){return zt(e._.relations.schema)==="postgres"}async function Ge(e){if(!je(e)){console.info("Database dialect is not compatible with search, skipping search initialization.");return}await e.execute(sql`CREATE EXTENSION IF NOT EXISTS pg_trgm;`);}function re({search:e,args:n,tableSchema:r,abilities:i}){if(e?.enabled&&n.search&&n.search.length>0){let o=cloneDeep(n.orderBy);n.orderBy=l=>{let a=sql.join(Object.entries(o??{}).map(([d,p])=>{if(p==="asc")return sql`${l[d]} ASC`;if(p==="desc")return sql`${l[d]} DESC`;throw new Error(`Invalid value ${p} for orderBy`)}),sql.raw(", ")),s=i.query.many.columns?Object.entries(r.columns).filter(([d])=>i.query.many.columns[d]):Object.entries(r.columns),m=sql`GREATEST(${sql.join(s.map(([d])=>sql`similarity(${l[d]}::TEXT, ${n.search})`),sql.raw(", "))}) DESC`;return o?sql.join([a,m],sql.raw(", ")):m};let t=cloneDeep(n.where);n.where={AND:[t??{},{RAW:l=>sql`GREATEST(${sql.join(Object.entries(r.columns).map(([a])=>sql`similarity(${l[a]}::TEXT, ${n.search})`),sql.raw(", "))}) > ${e.threshold??.1}`}]};}}var vt=e=>typeof e!="object"?false:!!Object.keys(e).some(n=>["args","nullable","query","subscribe","description","type","resolve"].find(r=>r===n)),We=({db:e,search:n,schemaBuilder:r,makePubSubInstance:i,whereArgImplementer:o,orderArgImplementer:t,enumImplementer:l,abilityBuilder:a})=>({table:s,refName:m,readAction:u="read",adjust:d})=>{let p=E({db:e,tsName:s});Object.keys(p.primaryColumns).length===0&&console.warn(`Could not find primary key for ${s.toString()}. Cannot register subscriptions!`);let D=Object.values(p.primaryColumns)[0],{registerOnInstance:h}=i({table:s});return r.drizzleObject(s,{name:m??capitalize(s.toString()),subscribe:(y,b,R)=>{if(!D)return;let g=b[D.name];if(!g){console.warn(`Could not find primary key value for ${JSON.stringify(b)}. Cannot register subscription!`);return}h({instance:y,action:"updated",primaryKeyValue:g});},applyFilters:a?.z_registeredFilters?.[s]?.[u],fields:y=>{let b=p.columns,R=(S,f,c)=>{let x=ne({sqlType:S,fieldName:f});switch(x){case "Int":return y.exposeInt(f,{nullable:c});case "String":return y.exposeString(f,{nullable:c});case "Boolean":return y.exposeBoolean(f,{nullable:c});case "Date":return y.field({type:"Date",resolve:C=>C[f],nullable:c});case "DateTime":return y.field({type:"DateTime",resolve:C=>C[f],nullable:c});case "Float":return y.exposeFloat(f,{nullable:c});case "ID":return y.exposeID(f,{nullable:c});case "JSON":return y.field({type:"JSON",resolve:C=>C[f],nullable:c});default:throw new A(`Unsupported object type ${x} for column ${f}`)}},g=new Map,T=d?.(new Proxy(y,{get:(S,f)=>typeof S[f]!="function"||f==="arg"||f==="builder"||f==="graphqlKind"||f==="kind"||f==="listRef"||f==="table"||f==="typename"||f==="variant"||f.toString().startsWith("boolean")||f.toString().startsWith("float")||f.toString().startsWith("id")||f.toString().startsWith("int")||f.toString().startsWith("string")||f.toString().startsWith("expose")?S[f]:(...c)=>{let x=S[f](...c),C=c.find(vt);if(!C)throw new A("Expected config object to be passed to adjust field");return g.set(x,{params:c,creatorFunction:S[f],configObject:C}),x}}))??{},L=Object.entries(b).reduce((S,[f,c])=>{if(T[f]){let{params:x,creatorFunction:C,configObject:q}=g.get(T[f]);return typeof q.nullable!="boolean"&&(q.nullable=!c.notNull),T[f]=C.bind(y)(...x),S}if(te(c)){let x=l({enumColumn:c});S[f]=y.field({type:x,resolve:C=>C[f],nullable:!c.notNull});}else S[f]=R(c.getSQLType(),f,!c.notNull);return S},{}),I=Object.entries(p.relations??{}).reduce((S,[f,c])=>{let x=E({db:e,table:c.targetTable}),C=o({dbName:x.dbName}),q=t({dbName:x.dbName}),z=i({table:x.tsName}),k=false,P=true,G="many";c instanceof One&&(P=false,k=c.optional,G="single");let ce=(N,v)=>{z.registerOnInstance({instance:N,action:"created"}),z.registerOnInstance({instance:N,action:"removed"});};if(T[f]){let{params:N,creatorFunction:v,configObject:w}=g.get(T[f]);return typeof w.nullable!="boolean"&&(w.nullable=k),typeof w.subscribe!="function"&&(w.subscribe=ce),T[f]=v.bind(y)(...N),S}let ye={where:y.arg({type:C,required:false}),orderBy:y.arg({type:q,required:false}),...P?{offset:y.arg.int({required:false}),limit:y.arg.int({required:false})}:{},search:y.arg.string({required:false})};return (!n?.enabled||!P)&&delete ye.search,S[f]=y.relation(f,{args:ye,subscribe:ce,nullable:k,description:`Get the ${ie.plural(x.tsName)} related to this ${ie.singular(p.tsName)}`,query:(N,v)=>{N=JSON.parse(JSON.stringify(N)),P&&re({search:n,args:N,tableSchema:x,abilities:v.abilities[x.tsName].filter(u)});let w=v.abilities[x.tsName].filter(u,{inject:{where:N.where,limit:N.limit}}).query[G];return N.offset&&(w.offset=N.offset),N.orderBy&&(w.orderBy=N.orderBy),w}}),S},{});return {...L,...I,...T}}})};var Gt=e=>`${capitalize(toCamelCase(e.toString()))}OrderInputArgument`,_e=({db:e,schemaBuilder:n})=>{let r=new Map,i=Q(()=>n.enumType("SortingParameter",{values:["asc","desc"]})),o=({table:t,refName:l,dbName:a})=>{let s=E({db:e,dbName:a,tsName:t}),m=l??Gt(s.tsName),u=r.get(m);return u||(u=n.inputType(m,{fields:p=>{let D=Object.entries(s.columns).reduce((y,[b])=>(y[b]=p.field({type:i(),required:false}),y),{}),h=Object.entries(s.relations??{}).reduce((y,[b,R])=>{let g=E({db:e,table:R.targetTable}),T=o({dbName:g.dbName});return y[b]=p.field({type:T,required:false}),y},{});return {...D,...h}}}),r.set(m,u),u)};return o};var $t="RUMBLE_SUBSCRIPTION_NOTIFICATION",Wt="REMOVED",_t="UPDATED",Mt="CREATED",Ke=({subscriptions:e})=>{let n=e?createPubSub(...e):createPubSub();return {pubsub:n,makePubSubInstance:({table:i})=>{function o({action:t,tableName:l,primaryKeyValue:a}){let s;switch(t){case "created":s=Mt;break;case "removed":s=Wt;break;case "updated":s=_t;break;default:throw new Error(`Unknown action: ${t}`)}return `${$t}/${l}${a?`/${a}`:""}/${s}`}return {registerOnInstance({instance:t,action:l,primaryKeyValue:a}){let s=o({tableName:i.toString(),action:l,primaryKeyValue:a});t.register(s);},created(){let t=o({tableName:i.toString(),action:"created"});return n.publish(t)},removed(){let t=o({tableName:i.toString(),action:"removed"});return n.publish(t)},updated(t){let a=(Array.isArray(t)?t:[t]).map(m=>o({tableName:i.toString(),action:"updated",primaryKeyValue:m})),s=Array.from(new Set(a));for(let m of s)n.publish(m);}}}}};var Ve=({db:e,schemaBuilder:n,search:r,whereArgImplementer:i,orderArgImplementer:o,makePubSubInstance:t})=>({table:l,readAction:a="read",listAction:s="read"})=>{let m=i({table:l}),u=o({table:l}),d=E({db:e,tsName:l}),p=Object.values(d.primaryColumns)[0],{registerOnInstance:D}=t({table:l});return n.queryFields(h=>{let y={where:h.arg({type:m,required:false}),orderBy:h.arg({type:u,required:false}),limit:h.arg.int({required:false}),offset:h.arg.int({required:false}),search:h.arg.string({required:false})};return r?.enabled||delete y.search,{[ie.plural(l.toString())]:h.drizzleField({type:[l],nullable:false,smartSubscription:true,description:`List all ${ie.plural(l.toString())}`,subscribe:(b,R,g,T,L)=>{D({instance:b,action:"created"}),D({instance:b,action:"removed"});},args:y,resolve:(b,R,g,T,L)=>{g=JSON.parse(JSON.stringify(g)),re({search:r,args:g,tableSchema:d,abilities:T.abilities[l].filter(s)});let I=T.abilities[l].filter(s,g.where||g.limit||g.offset?{inject:{where:g.where,limit:g.limit}}:void 0).query.many;g.offset&&(I.offset=g.offset),g.orderBy&&(I.orderBy=g.orderBy);let S=b(I);return I.columns&&(S.columns=I.columns),e.query[l].findMany(S)}}),[ie.singular(l.toString())]:h.drizzleField({type:l,nullable:false,smartSubscription:true,description:`Get a single ${ie.singular(l.toString())} by ID`,args:{id:h.arg.id({required:true})},resolve:(b,R,g,T,L)=>{g=JSON.parse(JSON.stringify(g));let I=T.abilities[l].filter(a,{inject:{where:{[p.name]:g.id}}}).query.single,S=b(I);return I.columns&&(S.columns=I.columns),e.query[l].findFirst(S).then(ue)}})}})};var He="ManualFiltersPlugin",Xe=He,Je="applyFilters",me=class extends BasePlugin{wrapResolve(n,r){return async(i,o,t,l)=>{let a,s=r?.type;if(s.kind==="List"?a=s.type?.ref.currentConfig.pothosOptions[Je]:s.kind==="Object"&&(a=s.ref.currentConfig.pothosOptions[Je]),!a||!Array.isArray(a)||a.length===0)return n(i,o,t,l);let m=await n(i,o,t,l),u=Array.isArray(m)?m:[m],d=Array.isArray(a)?a:[a],p=await Re({filters:d,entities:u,context:t});return Array.isArray(m)?p:p[0]??null}}};Kt.registerPlugin(He,me);var Xt=e=>`${capitalize(toCamelCase(e.toString()))}WhereInputArgument`,Ye=({db:e,schemaBuilder:n,enumImplementer:r})=>{let i=new Map,o=({table:t,refName:l,dbName:a})=>{let s=E({db:e,dbName:a,tsName:t}),m=l??Xt(s.tsName),u=i.get(m);return u||(u=n.inputType(m,{fields:p=>{let D=(b,R)=>{let g=ne({sqlType:b,fieldName:R});switch(g){case "Int":return p.field({type:"IntWhereInputArgument"});case "String":return p.field({type:"StringWhereInputArgument"});case "Boolean":return p.boolean({required:false});case "Date":return p.field({type:"DateWhereInputArgument"});case "DateTime":return p.field({type:"DateWhereInputArgument"});case "Float":return p.field({type:"FloatWhereInputArgument"});case "ID":return p.id({required:false});case "JSON":return p.field({type:"JSON",required:false});default:throw new A(`Unsupported argument type ${g} for column ${b}`)}},h=Object.entries(s.columns).reduce((b,[R,g])=>{if(te(g)){let T=r({enumColumn:g});b[R]=p.field({type:T,required:false});}else b[R]=D(g.getSQLType(),R);return b},{}),y=Object.entries(s.relations??{}).reduce((b,[R,g])=>{let T=E({db:e,table:g.targetTable}),L=o({dbName:T.dbName});return b[R]=p.field({type:L,required:false}),b},{});return {...h,...y}}}),i.set(m,u),u)};return o};function Ze(e){let n=e.inputRef("IntWhereInputArgument").implement({fields:t=>({eq:t.int(),ne:t.int(),gt:t.int(),gte:t.int(),lt:t.int(),lte:t.int(),in:t.intList(),notIn:t.intList(),like:t.string(),ilike:t.string(),notLike:t.string(),notIlike:t.string(),isNull:t.boolean(),isNotNull:t.boolean(),arrayOverlaps:t.intList(),arrayContained:t.intList(),arrayContains:t.intList(),AND:t.field({type:[n]}),OR:t.field({type:[n]}),NOT:t.field({type:n})})}),r=e.inputRef("FloatWhereInputArgument").implement({fields:t=>({eq:t.float(),ne:t.float(),gt:t.float(),gte:t.float(),lt:t.float(),lte:t.float(),in:t.floatList(),notIn:t.floatList(),like:t.string(),ilike:t.string(),notLike:t.string(),notIlike:t.string(),isNull:t.boolean(),isNotNull:t.boolean(),arrayOverlaps:t.floatList(),arrayContained:t.floatList(),arrayContains:t.floatList(),AND:t.field({type:[r]}),OR:t.field({type:[r]}),NOT:t.field({type:r})})}),i=e.inputRef("StringWhereInputArgument").implement({fields:t=>({eq:t.string(),ne:t.string(),gt:t.string(),gte:t.string(),lt:t.string(),lte:t.string(),in:t.stringList(),notIn:t.stringList(),like:t.string(),ilike:t.string(),notLike:t.string(),notIlike:t.string(),isNull:t.boolean(),isNotNull:t.boolean(),arrayOverlaps:t.stringList(),arrayContained:t.stringList(),arrayContains:t.stringList(),AND:t.field({type:[i]}),OR:t.field({type:[i]}),NOT:t.field({type:i})})}),o=e.inputRef("DateWhereInputArgument").implement({fields:t=>({eq:t.field({type:"Date"}),ne:t.field({type:"Date"}),gt:t.field({type:"Date"}),gte:t.field({type:"Date"}),lt:t.field({type:"Date"}),lte:t.field({type:"Date"}),in:t.field({type:["Date"]}),notIn:t.field({type:["Date"]}),like:t.string(),ilike:t.string(),notLike:t.string(),notIlike:t.string(),isNull:t.boolean(),isNotNull:t.boolean(),arrayOverlaps:t.field({type:["Date"]}),arrayContained:t.field({type:["Date"]}),arrayContains:t.field({type:["Date"]}),AND:t.field({type:[o]}),OR:t.field({type:[o]}),NOT:t.field({type:o})})});}var et=({db:e,disableDefaultObjects:n,pubsub:r,pothosConfig:i})=>{let o=new Kt({...i,plugins:[Xe,Zt,en,...i?.plugins??[]],drizzle:{client:e,relations:e._.relations,getTableConfig(t){return {columns:Object.values(t[Symbol.for("drizzle:Columns")]),primaryKeys:Object.values(t[Symbol.for("drizzle:Columns")]).filter(l=>l.primary)}}},smartSubscriptions:{...subscribeOptionsFromIterator((t,l)=>r.subscribe(t))}});return o.addScalarType("JSON",JSONResolver),o.addScalarType("Date",DateResolver),o.addScalarType("DateTime",DateTimeISOResolver),Ze(o),n?.query||o.queryType({}),n?.subscription||o.subscriptionType({}),n?.mutation||o.mutationType({}),{schemaBuilder:o}};var mn=e=>{e.actions||(e.actions=["read","update","delete"]),e.defaultLimit===void 0&&(e.defaultLimit=100),e.search?.enabled&&Ge(e.db);let n=qe(e),r=Oe({...e,abilityBuilder:n}),{makePubSubInstance:i,pubsub:o}=Ke({...e}),{schemaBuilder:t}=et({...e,pubsub:o}),l=Fe({...e,schemaBuilder:t}),a=Ye({...e,schemaBuilder:t,enumImplementer:l}),s=_e({...e,schemaBuilder:t}),m=We({...e,schemaBuilder:t,makePubSubInstance:i,whereArgImplementer:a,orderArgImplementer:s,enumImplementer:l,abilityBuilder:n}),u=Ve({...e,schemaBuilder:t,whereArgImplementer:a,orderArgImplementer:s,makePubSubInstance:i}),d=Q(()=>t.toSchema()),p=y=>{let b=y?.enableApiDocs??process?.env?.NODE_ENV==="development";return createYoga({...y,graphiql:b,plugins:[...y?.plugins??[],...b?[]:[useDisableIntrospection(),EnvelopArmorPlugin()]].filter(Boolean),schema:d(),context:r})},D=y=>(y.openAPI&&merge(y.openAPI,ve),useSofa({...y,schema:d(),context:r})),h=ze({...e,builtSchema:d});return {abilityBuilder:n,schemaBuilder:t,createYoga:p,createSofa:D,object:m,whereArg:a,orderArg:s,query:u,pubsub:i,enum_:l,clientCreator:h}};export{A as RumbleError,F as RumbleErrorSafe,ue as assertFindFirstExists,Ct as assertFirstEntryExists,se as generateFromSchema,ht as makeLiveQuery,Tt as makeMutation,xt as makeQuery,St as makeSubscription,Rt as mapNullFieldsToUndefined,mn as rumble};//# sourceMappingURL=index.js.map
|
|
65
|
-
//# sourceMappingURL=index.js.map
|