@m1212e/rumble 0.10.12 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -0
- package/index.cjs +102 -6
- package/index.cjs.map +1 -1
- package/index.d.cts +81 -3
- package/index.d.ts +81 -3
- package/index.js +102 -6
- package/index.js.map +1 -1
- package/package.json +1 -1
package/index.d.cts
CHANGED
@@ -1,6 +1,7 @@
|
|
1
|
+
import { GraphQLSchema, GraphQLFieldResolver, GraphQLError } from 'graphql';
|
2
|
+
import { Client } from '@urql/core';
|
1
3
|
import * as SchemaBuilder from '@pothos/core';
|
2
4
|
import SchemaBuilder__default, { SchemaTypes, BasePlugin, PothosOutputFieldConfig } from '@pothos/core';
|
3
|
-
import { GraphQLFieldResolver, GraphQLError } from 'graphql';
|
4
5
|
import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
|
5
6
|
import { PgDatabase, PgEnum } from 'drizzle-orm/pg-core';
|
6
7
|
import * as _pothos_plugin_drizzle from '@pothos/plugin-drizzle';
|
@@ -14,6 +15,73 @@ import { MySqlDatabase } from 'drizzle-orm/mysql-core';
|
|
14
15
|
import { SingleStoreDatabase } from 'drizzle-orm/singlestore-core';
|
15
16
|
import { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';
|
16
17
|
|
18
|
+
declare function generateFromSchema({ outputPath, schema, rumbleImportPath, apiUrl, useExternalUrqlClient, }: {
|
19
|
+
schema: GraphQLSchema;
|
20
|
+
outputPath: string;
|
21
|
+
rumbleImportPath?: string;
|
22
|
+
apiUrl?: string;
|
23
|
+
useExternalUrqlClient?: boolean | string;
|
24
|
+
}): Promise<void>;
|
25
|
+
|
26
|
+
declare const argsKey = "__args";
|
27
|
+
|
28
|
+
type UnArray<T> = T extends Array<infer U> ? U : T;
|
29
|
+
type RequireAtLeastOneFieldSet<T> = {
|
30
|
+
[K in keyof T]: Required<Pick<T, K>> & Partial<Omit<T, K>>;
|
31
|
+
}[keyof T];
|
32
|
+
|
33
|
+
/**
|
34
|
+
* A gql object defined from the generated types.
|
35
|
+
* Most keys are functions that take a selection set and return a promise of the selected data.
|
36
|
+
*/
|
37
|
+
type QueryableObjectFromGeneratedTypes<Q> = {
|
38
|
+
[Key in keyof Q]: QueryableObjectField$1<Q[Key]>;
|
39
|
+
};
|
40
|
+
type QueryableObjectField$1<T> = T extends (p: infer QueryArgs) => infer QueryResponse ? <Selected extends QueryArgs extends Record<string, any> ? // in that case we want to extend the object with an args key property
|
41
|
+
ObjectFieldSelection<UnArray<NonNullable<QueryResponse>>> & {
|
42
|
+
[argsKey]: QueryArgs;
|
43
|
+
} : ObjectFieldSelection<UnArray<NonNullable<QueryResponse>>>>(s: Selected) => QueryResponse extends null ? Response<QueryResponse extends Array<any> ? ApplySelection<NonNullable<UnArray<QueryResponse>>, Selected>[] : ApplySelection<NonNullable<UnArray<QueryResponse>>, Selected>> | null : Response<QueryResponse extends Array<any> ? ApplySelection<UnArray<QueryResponse>, Selected>[] : ApplySelection<UnArray<QueryResponse>, Selected>> : Response<T>;
|
44
|
+
/**
|
45
|
+
* The input to select fields for an object
|
46
|
+
*/
|
47
|
+
type ObjectFieldSelection<O> = RequireAtLeastOneFieldSet<{
|
48
|
+
[Key in keyof O]: NonNullable<UnArray<O[Key]>> extends (p: infer P) => infer A ? P extends Record<string, any> ? ObjectFieldSelection<UnArray<NonNullable<A>>> & {
|
49
|
+
[argsKey]: P;
|
50
|
+
} : ObjectFieldSelection<UnArray<NonNullable<A>>> : boolean;
|
51
|
+
}>;
|
52
|
+
type ApplySelection<Object, Selection> = {
|
53
|
+
[Key in keyof Selection & keyof Object]: Object[Key] extends (p: infer _P) => infer _A ? ReturnType<Object[Key]> extends Array<any> ? Array<ApplySelection<UnArray<ReturnType<Object[Key]>>, Selection[Key]>> : ApplySelection<UnArray<Object[Key]>, Selection[Key]> : Object[Key];
|
54
|
+
};
|
55
|
+
type Subscribeable<Data> = {
|
56
|
+
subscribe: (subscription: (value: Data) => void) => () => void;
|
57
|
+
};
|
58
|
+
type Response<Data> = {
|
59
|
+
then: (onFulfilled: (value: Subscribeable<Data> & Data) => void) => void;
|
60
|
+
} & Subscribeable<Data | undefined>;
|
61
|
+
|
62
|
+
declare function makeLiveQuery<Query extends Record<string, any>>({ urqlClient, availableSubscriptions, }: {
|
63
|
+
urqlClient: Client;
|
64
|
+
availableSubscriptions: Set<string>;
|
65
|
+
}): QueryableObjectFromGeneratedTypes<Query>;
|
66
|
+
|
67
|
+
declare function makeMutation<Mutation extends Record<string, any>>({ urqlClient, }: {
|
68
|
+
urqlClient: Client;
|
69
|
+
}): QueryableObjectFromGeneratedTypes<Mutation>;
|
70
|
+
|
71
|
+
declare function makeQuery<Query extends Record<string, any>>({ urqlClient, }: {
|
72
|
+
urqlClient: Client;
|
73
|
+
}): QueryableObjectFromGeneratedTypes<Query>;
|
74
|
+
|
75
|
+
declare function makeSubscription<Subscription extends Record<string, any>>({ urqlClient, }: {
|
76
|
+
urqlClient: Client;
|
77
|
+
}): SubscriptionObject<Subscription>;
|
78
|
+
type SubscriptionObject<Q> = {
|
79
|
+
[Key in keyof Q]: QueryableObjectField<Q[Key]>;
|
80
|
+
};
|
81
|
+
type QueryableObjectField<T> = T extends (p: infer QueryArgs) => infer QueryResponse ? <Selected extends QueryArgs extends Record<string, any> ? ObjectFieldSelection<UnArray<NonNullable<QueryResponse>>> & {
|
82
|
+
[argsKey]: QueryArgs;
|
83
|
+
} : ObjectFieldSelection<UnArray<NonNullable<QueryResponse>>>>(s: Selected) => QueryResponse extends null ? Subscribeable<NonNullable<QueryResponse> extends Array<any> ? ApplySelection<UnArray<NonNullable<QueryResponse>>, Selected>[] : ApplySelection<UnArray<NonNullable<QueryResponse>>, Selected>> | null : Subscribeable<QueryResponse extends Array<any> ? ApplySelection<UnArray<QueryResponse>, Selected>[] : ApplySelection<UnArray<QueryResponse>, Selected>> : Subscribeable<T>;
|
84
|
+
|
17
85
|
declare const pluginName = "ManualFiltersPlugin";
|
18
86
|
|
19
87
|
declare const applyFiltersKey = "applyFilters";
|
@@ -692,7 +760,7 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
692
760
|
primaryKeyValue?: string;
|
693
761
|
}): void;
|
694
762
|
created(): void;
|
695
|
-
removed(
|
763
|
+
removed(): void;
|
696
764
|
updated(primaryKeyValue?: any | any[]): void;
|
697
765
|
};
|
698
766
|
/**
|
@@ -749,6 +817,16 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
749
817
|
DateWhereInputArgument: DateWhereInputArgument;
|
750
818
|
};
|
751
819
|
}>, any, any>;
|
820
|
+
/**
|
821
|
+
* Create a client to consume a rumble graphql api at the specified location.
|
822
|
+
* Requires GraphQL, does not work with the SOFA REST API.
|
823
|
+
*/
|
824
|
+
clientCreator: ({ apiUrl, outputPath, rumbleImportPath, useExternalUrqlClient, }: {
|
825
|
+
outputPath: string;
|
826
|
+
apiUrl?: string;
|
827
|
+
rumbleImportPath?: string;
|
828
|
+
useExternalUrqlClient?: string;
|
829
|
+
}) => Promise<void>;
|
752
830
|
};
|
753
831
|
|
754
832
|
/**
|
@@ -766,4 +844,4 @@ declare class RumbleError extends Error {
|
|
766
844
|
declare class RumbleErrorSafe extends GraphQLError {
|
767
845
|
}
|
768
846
|
|
769
|
-
export { RumbleError, RumbleErrorSafe, assertFindFirstExists, assertFirstEntryExists, mapNullFieldsToUndefined, rumble };
|
847
|
+
export { RumbleError, RumbleErrorSafe, assertFindFirstExists, assertFirstEntryExists, generateFromSchema, makeLiveQuery, makeMutation, makeQuery, makeSubscription, mapNullFieldsToUndefined, rumble };
|
package/index.d.ts
CHANGED
@@ -1,6 +1,7 @@
|
|
1
|
+
import { GraphQLSchema, GraphQLFieldResolver, GraphQLError } from 'graphql';
|
2
|
+
import { Client } from '@urql/core';
|
1
3
|
import * as SchemaBuilder from '@pothos/core';
|
2
4
|
import SchemaBuilder__default, { SchemaTypes, BasePlugin, PothosOutputFieldConfig } from '@pothos/core';
|
3
|
-
import { GraphQLFieldResolver, GraphQLError } from 'graphql';
|
4
5
|
import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
|
5
6
|
import { PgDatabase, PgEnum } from 'drizzle-orm/pg-core';
|
6
7
|
import * as _pothos_plugin_drizzle from '@pothos/plugin-drizzle';
|
@@ -14,6 +15,73 @@ import { MySqlDatabase } from 'drizzle-orm/mysql-core';
|
|
14
15
|
import { SingleStoreDatabase } from 'drizzle-orm/singlestore-core';
|
15
16
|
import { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';
|
16
17
|
|
18
|
+
declare function generateFromSchema({ outputPath, schema, rumbleImportPath, apiUrl, useExternalUrqlClient, }: {
|
19
|
+
schema: GraphQLSchema;
|
20
|
+
outputPath: string;
|
21
|
+
rumbleImportPath?: string;
|
22
|
+
apiUrl?: string;
|
23
|
+
useExternalUrqlClient?: boolean | string;
|
24
|
+
}): Promise<void>;
|
25
|
+
|
26
|
+
declare const argsKey = "__args";
|
27
|
+
|
28
|
+
type UnArray<T> = T extends Array<infer U> ? U : T;
|
29
|
+
type RequireAtLeastOneFieldSet<T> = {
|
30
|
+
[K in keyof T]: Required<Pick<T, K>> & Partial<Omit<T, K>>;
|
31
|
+
}[keyof T];
|
32
|
+
|
33
|
+
/**
|
34
|
+
* A gql object defined from the generated types.
|
35
|
+
* Most keys are functions that take a selection set and return a promise of the selected data.
|
36
|
+
*/
|
37
|
+
type QueryableObjectFromGeneratedTypes<Q> = {
|
38
|
+
[Key in keyof Q]: QueryableObjectField$1<Q[Key]>;
|
39
|
+
};
|
40
|
+
type QueryableObjectField$1<T> = T extends (p: infer QueryArgs) => infer QueryResponse ? <Selected extends QueryArgs extends Record<string, any> ? // in that case we want to extend the object with an args key property
|
41
|
+
ObjectFieldSelection<UnArray<NonNullable<QueryResponse>>> & {
|
42
|
+
[argsKey]: QueryArgs;
|
43
|
+
} : ObjectFieldSelection<UnArray<NonNullable<QueryResponse>>>>(s: Selected) => QueryResponse extends null ? Response<QueryResponse extends Array<any> ? ApplySelection<NonNullable<UnArray<QueryResponse>>, Selected>[] : ApplySelection<NonNullable<UnArray<QueryResponse>>, Selected>> | null : Response<QueryResponse extends Array<any> ? ApplySelection<UnArray<QueryResponse>, Selected>[] : ApplySelection<UnArray<QueryResponse>, Selected>> : Response<T>;
|
44
|
+
/**
|
45
|
+
* The input to select fields for an object
|
46
|
+
*/
|
47
|
+
type ObjectFieldSelection<O> = RequireAtLeastOneFieldSet<{
|
48
|
+
[Key in keyof O]: NonNullable<UnArray<O[Key]>> extends (p: infer P) => infer A ? P extends Record<string, any> ? ObjectFieldSelection<UnArray<NonNullable<A>>> & {
|
49
|
+
[argsKey]: P;
|
50
|
+
} : ObjectFieldSelection<UnArray<NonNullable<A>>> : boolean;
|
51
|
+
}>;
|
52
|
+
type ApplySelection<Object, Selection> = {
|
53
|
+
[Key in keyof Selection & keyof Object]: Object[Key] extends (p: infer _P) => infer _A ? ReturnType<Object[Key]> extends Array<any> ? Array<ApplySelection<UnArray<ReturnType<Object[Key]>>, Selection[Key]>> : ApplySelection<UnArray<Object[Key]>, Selection[Key]> : Object[Key];
|
54
|
+
};
|
55
|
+
type Subscribeable<Data> = {
|
56
|
+
subscribe: (subscription: (value: Data) => void) => () => void;
|
57
|
+
};
|
58
|
+
type Response<Data> = {
|
59
|
+
then: (onFulfilled: (value: Subscribeable<Data> & Data) => void) => void;
|
60
|
+
} & Subscribeable<Data | undefined>;
|
61
|
+
|
62
|
+
declare function makeLiveQuery<Query extends Record<string, any>>({ urqlClient, availableSubscriptions, }: {
|
63
|
+
urqlClient: Client;
|
64
|
+
availableSubscriptions: Set<string>;
|
65
|
+
}): QueryableObjectFromGeneratedTypes<Query>;
|
66
|
+
|
67
|
+
declare function makeMutation<Mutation extends Record<string, any>>({ urqlClient, }: {
|
68
|
+
urqlClient: Client;
|
69
|
+
}): QueryableObjectFromGeneratedTypes<Mutation>;
|
70
|
+
|
71
|
+
declare function makeQuery<Query extends Record<string, any>>({ urqlClient, }: {
|
72
|
+
urqlClient: Client;
|
73
|
+
}): QueryableObjectFromGeneratedTypes<Query>;
|
74
|
+
|
75
|
+
declare function makeSubscription<Subscription extends Record<string, any>>({ urqlClient, }: {
|
76
|
+
urqlClient: Client;
|
77
|
+
}): SubscriptionObject<Subscription>;
|
78
|
+
type SubscriptionObject<Q> = {
|
79
|
+
[Key in keyof Q]: QueryableObjectField<Q[Key]>;
|
80
|
+
};
|
81
|
+
type QueryableObjectField<T> = T extends (p: infer QueryArgs) => infer QueryResponse ? <Selected extends QueryArgs extends Record<string, any> ? ObjectFieldSelection<UnArray<NonNullable<QueryResponse>>> & {
|
82
|
+
[argsKey]: QueryArgs;
|
83
|
+
} : ObjectFieldSelection<UnArray<NonNullable<QueryResponse>>>>(s: Selected) => QueryResponse extends null ? Subscribeable<NonNullable<QueryResponse> extends Array<any> ? ApplySelection<UnArray<NonNullable<QueryResponse>>, Selected>[] : ApplySelection<UnArray<NonNullable<QueryResponse>>, Selected>> | null : Subscribeable<QueryResponse extends Array<any> ? ApplySelection<UnArray<QueryResponse>, Selected>[] : ApplySelection<UnArray<QueryResponse>, Selected>> : Subscribeable<T>;
|
84
|
+
|
17
85
|
declare const pluginName = "ManualFiltersPlugin";
|
18
86
|
|
19
87
|
declare const applyFiltersKey = "applyFilters";
|
@@ -692,7 +760,7 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
692
760
|
primaryKeyValue?: string;
|
693
761
|
}): void;
|
694
762
|
created(): void;
|
695
|
-
removed(
|
763
|
+
removed(): void;
|
696
764
|
updated(primaryKeyValue?: any | any[]): void;
|
697
765
|
};
|
698
766
|
/**
|
@@ -749,6 +817,16 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
749
817
|
DateWhereInputArgument: DateWhereInputArgument;
|
750
818
|
};
|
751
819
|
}>, any, any>;
|
820
|
+
/**
|
821
|
+
* Create a client to consume a rumble graphql api at the specified location.
|
822
|
+
* Requires GraphQL, does not work with the SOFA REST API.
|
823
|
+
*/
|
824
|
+
clientCreator: ({ apiUrl, outputPath, rumbleImportPath, useExternalUrqlClient, }: {
|
825
|
+
outputPath: string;
|
826
|
+
apiUrl?: string;
|
827
|
+
rumbleImportPath?: string;
|
828
|
+
useExternalUrqlClient?: string;
|
829
|
+
}) => Promise<void>;
|
752
830
|
};
|
753
831
|
|
754
832
|
/**
|
@@ -766,4 +844,4 @@ declare class RumbleError extends Error {
|
|
766
844
|
declare class RumbleErrorSafe extends GraphQLError {
|
767
845
|
}
|
768
846
|
|
769
|
-
export { RumbleError, RumbleErrorSafe, assertFindFirstExists, assertFirstEntryExists, mapNullFieldsToUndefined, rumble };
|
847
|
+
export { RumbleError, RumbleErrorSafe, assertFindFirstExists, assertFirstEntryExists, generateFromSchema, makeLiveQuery, makeMutation, makeQuery, makeSubscription, mapNullFieldsToUndefined, rumble };
|
package/index.js
CHANGED
@@ -1,9 +1,105 @@
|
|
1
|
-
import {EnvelopArmorPlugin}from'@escape.tech/graphql-armor';import {useDisableIntrospection}from'@graphql-yoga/plugin-disable-introspection';import {
|
2
|
-
|
3
|
-
|
1
|
+
import {exists,rm,mkdir,writeFile}from'fs/promises';import {join}from'path';import {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 {plural,singular}from'pluralize';import {MySqlTable}from'drizzle-orm/mysql-core';import {SQLiteTable}from'drizzle-orm/sqlite-core';import kr,{BasePlugin}from'@pothos/core';import Vr from'@pothos/plugin-drizzle';import Mr,{subscribeOptionsFromIterator}from'@pothos/plugin-smart-subscriptions';import {JSONResolver,DateResolver,DateTimeISOResolver}from'graphql-scalars';function et({apiUrl:e,rumbleImportPath:t,useExternalUrqlClient:n,availableSubscriptions:r}){let o=[],i="";return typeof n=="string"?o.push(`import { urqlClient } from "${n}";`):(o.push("import { Client, fetchExchange } from '@urql/core';"),o.push("import { cacheExchange } from '@urql/exchange-graphcache';")),o.push(`import { makeLiveQuery, makeMutation, makeSubscription, makeQuery } from '${t}';`),n||(i+=`
|
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
|
+
`),i+=`
|
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([${r.values().toArray().map(s=>`"${s}"`).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:i}}function C(e,t){throw new Error(t)}function ce(e){return typeof e=="object"&&e!==null}function tt(e,t){throw new Error("Unexpected invariant triggered.")}var Yt=/\r\n|[\n\r]/g;function re(e,t){let n=0,r=1;for(let o of e.body.matchAll(Yt)){if(typeof o.index=="number"||tt(),o.index>=t)break;n=o.index+o[0].length,r+=1;}return {line:r,column:t+1-n}}function rt(e){return Re(e.source,re(e.source,e.start))}function Re(e,t){let n=e.locationOffset.column-1,r="".padStart(n)+e.body,o=t.line-1,i=e.locationOffset.line-1,s=t.line+i,l=t.line===1?n:0,u=t.column+l,p=`${e.name}:${s}:${u}
|
42
|
+
`,a=r.split(/\r\n|[\n\r]/g),m=a[o];if(m.length>120){let c=Math.floor(u/80),x=u%80,h=[];for(let y=0;y<m.length;y+=80)h.push(m.slice(y,y+80));return p+nt([[`${s} |`,h[0]],...h.slice(1,c+1).map(y=>["|",y]),["|","^".padStart(x)],["|",h[c+1]]])}return p+nt([[`${s-1} |`,a[o-1]],[`${s} |`,m],["|","^".padStart(u)],[`${s+1} |`,a[o+1]]])}function nt(e){let t=e.filter(([r,o])=>o!==void 0),n=Math.max(...t.map(([r])=>r.length));return t.map(([r,o])=>r.padStart(n)+(o?" "+o:"")).join(`
|
43
|
+
`)}function Ht(e){let t=e[0];return t==null||"kind"in t||"length"in t?{nodes:t,source:e[1],positions:e[2],path:e[3],originalError:e[4],extensions:e[5]}:t}var L=class e extends Error{constructor(t,...n){var r,o,i;let{nodes:s,source:l,positions:u,path:p,originalError:a,extensions:m}=Ht(n);super(t),this.name="GraphQLError",this.path=p??void 0,this.originalError=a??void 0,this.nodes=it(Array.isArray(s)?s:s?[s]:void 0);let c=it((r=this.nodes)===null||r===void 0?void 0:r.map(h=>h.loc).filter(h=>h!=null));this.source=l??(c==null||(o=c[0])===null||o===void 0?void 0:o.source),this.positions=u??c?.map(h=>h.start),this.locations=u&&l?u.map(h=>re(l,h)):c?.map(h=>re(h.source,h.start));let x=ce(a?.extensions)?a?.extensions:void 0;this.extensions=(i=m??x)!==null&&i!==void 0?i: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,e):Object.defineProperty(this,"stack",{value:Error().stack,writable:true,configurable:true});}get[Symbol.toStringTag](){return "GraphQLError"}toString(){let t=this.message;if(this.nodes)for(let n of this.nodes)n.loc&&(t+=`
|
4
44
|
|
5
|
-
`+
|
45
|
+
`+rt(n.loc));else if(this.source&&this.locations)for(let n of this.locations)t+=`
|
6
46
|
|
7
|
-
|
8
|
-
Please ensure that you use the enum at least once as a column of a table!`);a=C.enumValues;}else if(t){let o=Object.entries(e._.relations.schema).find(([C,y])=>y===t.config.enum);if(!o)throw new A(`Could not find enum in schema for ${t.name}!`);m=o[0],a=t.enumValues;}if(!m||!a)throw new A("Could not determine enum structure!");let c=s??`${capitalize(toCamelCase(m))}Enum`,l=r.get(c);return l||(l=n.enumType(c,{values:a}),r.set(c,l),l)}};var ue={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"}}},DateTime:{type:"string",format:"date-time"},Date:{type:"string",format:"date"}}}};function _({sqlType:e,fieldName:n}){let r;if(["serial","int","integer","tinyint","smallint","mediumint"].includes(e)&&(r="Int"),["real","decimal","double","float"].includes(e)&&(r="Float"),["string","text","varchar","char","text(256)"].includes(e)&&(n&&(n.toLowerCase().endsWith("_id")||n.toLowerCase().endsWith("id"))?r="ID":r="String"),["uuid"].includes(e)&&(r="ID"),["boolean"].includes(e)&&(r="Boolean"),["timestamp","datetime"].includes(e)&&(r="DateTime"),["date"].includes(e)&&(r="Date"),["json"].includes(e)&&(r="JSON"),r!==void 0)return r;throw G(e,"SQL to GQL")}function je(e){let n=new Set;for(let u of Object.values(e))typeof u=="object"&&(u instanceof PgTable?n.add("postgres"):u instanceof MySqlTable?n.add("mysql"):u 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 pe(e){return je(e._.relations.schema)==="postgres"}async function ce(e){if(!pe(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 K({search:e,args:n,tableSchema:r,abilities:u}){if(e?.enabled&&n.search&&n.search.length>0){let i=cloneDeep(n.orderBy);n.orderBy=s=>{let m=sql.join(Object.entries(i??{}).map(([b,o])=>{if(o==="asc")return sql`${s[b]} ASC`;if(o==="desc")return sql`${s[b]} DESC`;throw new Error(`Invalid value ${o} for orderBy`)}),sql.raw(", ")),a=u.query.many.columns?Object.entries(r.columns).filter(([b,o])=>u.query.many.columns[b]):Object.entries(r.columns),c=sql`GREATEST(${sql.join(a.map(([b,o])=>sql`similarity(${s[b]}::TEXT, ${n.search})`),sql.raw(", "))}) DESC`;return i?sql.join([m,c],sql.raw(", ")):c};let t=cloneDeep(n.where);n.where={AND:[t??{},{RAW:s=>sql`GREATEST(${sql.join(Object.entries(r.columns).map(([m,a])=>sql`similarity(${s[m]}::TEXT, ${n.search})`),sql.raw(", "))}) > ${e.threshold??.1}`}]};}}var $e=e=>typeof e!="object"?false:!!Object.keys(e).some(n=>["args","nullable","query","subscribe","description","type","resolve"].find(r=>r===n)),ye=({db:e,search:n,schemaBuilder:r,makePubSubInstance:u,whereArgImplementer:i,orderArgImplementer:t,enumImplementer:s,abilityBuilder:m})=>({table:a,refName:c,readAction:l="read",adjust:b})=>{let o=P({db:e,tsName:a});Object.keys(o.primaryColumns).length===0&&console.warn(`Could not find primary key for ${a.toString()}. Cannot register subscriptions!`);let C=Object.values(o.primaryColumns)[0],{registerOnInstance:y}=u({table:a});return r.drizzleObject(a,{name:c??capitalize(a.toString()),subscribe:(d,h,S)=>{if(!C)return;let g=h[C.name];if(!g){console.warn(`Could not find primary key value for ${JSON.stringify(h)}. Cannot register subscription!`);return}y({instance:d,action:"updated",primaryKeyValue:g});},applyFilters:m?.z_registeredFilters?.[a]?.[l],fields:d=>{let h=o.columns,S=(D,f,p)=>{let x=_({sqlType:D,fieldName:f});switch(x){case "Int":return d.exposeInt(f,{nullable:p});case "String":return d.exposeString(f,{nullable:p});case "Boolean":return d.exposeBoolean(f,{nullable:p});case "Date":return d.field({type:"Date",resolve:R=>R[f],nullable:p});case "DateTime":return d.field({type:"DateTime",resolve:R=>R[f],nullable:p});case "Float":return d.exposeFloat(f,{nullable:p});case "ID":return d.exposeID(f,{nullable:p});case "JSON":return d.field({type:"JSON",resolve:R=>R[f],nullable:p});default:throw new A(`Unsupported object type ${x} for column ${f}`)}},g=new Map,T=b?.(new Proxy(d,{get:(D,f)=>typeof D[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")?D[f]:(...p)=>{let x=D[f](...p),R=p.find($e);if(!R)throw new A("Expected config object to be passed to adjust field");return g.set(x,{params:p,creatorFunction:D[f],configObject:R}),x}}))??{},v=Object.entries(h).reduce((D,[f,p])=>{if(T[f]){let{params:x,creatorFunction:R,configObject:q}=g.get(T[f]);return typeof q.nullable!="boolean"&&(q.nullable=!p.notNull),T[f]=R.bind(d)(...x),D}if(W(p)){let x=s({enumColumn:p});D[f]=d.field({type:x,resolve:R=>R[f],nullable:!p.notNull});}else D[f]=S(p.getSQLType(),f,!p.notNull);return D},{}),I=Object.entries(o.relations??{}).reduce((D,[f,p])=>{let x=P({db:e,table:p.targetTable}),R=i({dbName:x.dbName}),q=t({dbName:x.dbName}),w=u({table:x.tsName}),O=false,N=true,j="many";p instanceof One&&(N=false,O=p.optional,j="single");let H=(E,U)=>{w.registerOnInstance({instance:E,action:"created"}),w.registerOnInstance({instance:E,action:"removed"});};if(T[f]){let{params:E,creatorFunction:U,configObject:F}=g.get(T[f]);return typeof F.nullable!="boolean"&&(F.nullable=O),typeof F.subscribe!="function"&&(F.subscribe=H),T[f]=U.bind(d)(...E),D}let X={where:d.arg({type:R,required:false}),orderBy:d.arg({type:q,required:false}),...N?{offset:d.arg.int({required:false}),limit:d.arg.int({required:false})}:{},search:d.arg.string({required:false})};return (!n?.enabled||!N)&&delete X.search,D[f]=d.relation(f,{args:X,subscribe:H,nullable:O,description:`Get the ${plural(x.tsName)} related to this ${singular(o.tsName)}`,query:(E,U)=>{E=JSON.parse(JSON.stringify(E)),N&&K({search:n,args:E,tableSchema:x,abilities:U.abilities[x.tsName].filter(l)});let F=U.abilities[x.tsName].filter(l,{inject:{where:E.where,limit:E.limit}}).query[j];return E.offset&&(F.offset=E.offset),E.orderBy&&(F.orderBy=E.orderBy),F}}),D},{});return {...v,...I,...T}}})};var Je=e=>`${capitalize(toCamelCase(e.toString()))}OrderInputArgument`,de=({db:e,schemaBuilder:n})=>{let r=new Map,u=z(()=>n.enumType("SortingParameter",{values:["asc","desc"]})),i=({table:t,refName:s,dbName:m})=>{let a=P({db:e,dbName:m,tsName:t}),c=s??Je(a.tsName),l=r.get(c);return l||(l=n.inputType(c,{fields:o=>{let C=Object.entries(a.columns).reduce((d,[h,S])=>(d[h]=o.field({type:u(),required:false}),d),{}),y=Object.entries(a.relations??{}).reduce((d,[h,S])=>{let g=P({db:e,table:S.targetTable}),T=i({dbName:g.dbName});return d[h]=o.field({type:T,required:false}),d},{});return {...C,...y}}}),r.set(c,l),l)};return i};var He="RUMBLE_SUBSCRIPTION_NOTIFICATION",Xe="REMOVED",Ye="UPDATED",Ze="CREATED",be=({subscriptions:e,db:n})=>{let r=e?createPubSub(...e):createPubSub();return {pubsub:r,makePubSubInstance:({table:i})=>{function t({action:s,tableName:m,primaryKeyValue:a}){let c;switch(s){case "created":c=Ze;break;case "removed":c=Xe;break;case "updated":c=Ye;break;default:throw new Error(`Unknown action: ${s}`)}return `${He}/${m}${a?`/${a}`:""}/${c}`}return {registerOnInstance({instance:s,action:m,primaryKeyValue:a}){let c=t({tableName:i.toString(),action:m,primaryKeyValue:a});s.register(c);},created(){let s=t({tableName:i.toString(),action:"created"});return r.publish(s)},removed(s){let m=t({tableName:i.toString(),action:"removed"});return r.publish(m)},updated(s){let a=(Array.isArray(s)?s:[s]).map(l=>t({tableName:i.toString(),action:"updated",primaryKeyValue:l})),c=Array.from(new Set(a));for(let l of c)r.publish(l);}}}}};var Te=({db:e,schemaBuilder:n,search:r,whereArgImplementer:u,orderArgImplementer:i,makePubSubInstance:t})=>({table:s,readAction:m="read",listAction:a="read"})=>{let c=u({table:s}),l=i({table:s}),b=P({db:e,tsName:s}),o=Object.values(b.primaryColumns)[0],{registerOnInstance:C}=t({table:s});return n.queryFields(y=>{let d={where:y.arg({type:c,required:false}),orderBy:y.arg({type:l,required:false}),limit:y.arg.int({required:false}),offset:y.arg.int({required:false}),search:y.arg.string({required:false})};return r?.enabled||delete d.search,{[plural(s.toString())]:y.drizzleField({type:[s],nullable:false,smartSubscription:true,description:`List all ${plural(s.toString())}`,subscribe:(h,S,g,T,v)=>{C({instance:h,action:"created"}),C({instance:h,action:"removed"});},args:d,resolve:(h,S,g,T,v)=>{g=JSON.parse(JSON.stringify(g)),K({search:r,args:g,tableSchema:b,abilities:T.abilities[s].filter(a)});let I=T.abilities[s].filter(a,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 D=h(I);return I.columns&&(D.columns=I.columns),e.query[s].findMany(D)}}),[singular(s.toString())]:y.drizzleField({type:s,nullable:false,smartSubscription:true,description:`Get a single ${singular(s.toString())} by ID`,args:{id:y.arg.id({required:true})},resolve:(h,S,g,T,v)=>{g=JSON.parse(JSON.stringify(g));let I=T.abilities[s].filter(m,{inject:{where:{[o.name]:g.id}}}).query.single,D=h(I);return I.columns&&(D.columns=I.columns),e.query[s].findFirst(D).then(V)}})}})};var De="ManualFiltersPlugin",Ce=De,xe="applyFilters",J=class extends BasePlugin{wrapResolve(n,r){return async(u,i,t,s)=>{let m,a=r?.type;if(a.kind==="List"?m=a.type?.ref.currentConfig.pothosOptions[xe]:a.kind==="Object"&&(m=a.ref.currentConfig.pothosOptions[xe]),!m||!Array.isArray(m)||m.length===0)return n(u,i,t,s);let c=await n(u,i,t,s),l=Array.isArray(c)?c:[c],b=Array.isArray(m)?m:[m],o=await re({filters:b,entities:l,context:t});return Array.isArray(c)?o:o[0]??null}}};et.registerPlugin(De,J);var it=e=>`${capitalize(toCamelCase(e.toString()))}WhereInputArgument`,Se=({db:e,schemaBuilder:n,enumImplementer:r})=>{let u=new Map,i=({table:t,refName:s,dbName:m})=>{let a=P({db:e,dbName:m,tsName:t}),c=s??it(a.tsName),l=u.get(c);return l||(l=n.inputType(c,{fields:o=>{let C=(h,S)=>{let g=_({sqlType:h,fieldName:S});switch(g){case "Int":return o.field({type:"IntWhereInputArgument"});case "String":return o.field({type:"StringWhereInputArgument"});case "Boolean":return o.boolean({required:false});case "Date":return o.field({type:"DateWhereInputArgument"});case "DateTime":return o.field({type:"DateWhereInputArgument"});case "Float":return o.field({type:"FloatWhereInputArgument"});case "ID":return o.id({required:false});case "JSON":return o.field({type:"JSON",required:false});default:throw new A(`Unsupported argument type ${g} for column ${h}`)}},y=Object.entries(a.columns).reduce((h,[S,g])=>{if(W(g)){let T=r({enumColumn:g});h[S]=o.field({type:T,required:false});}else h[S]=C(g.getSQLType(),S);return h},{}),d=Object.entries(a.relations??{}).reduce((h,[S,g])=>{let T=P({db:e,table:g.targetTable}),v=i({dbName:T.dbName});return h[S]=o.field({type:v,required:false}),h},{});return {...y,...d}}}),u.set(c,l),l)};return i};function Re(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})})}),u=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:[u]}),OR:t.field({type:[u]}),NOT:t.field({type:u})})}),i=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:[i]}),OR:t.field({type:[i]}),NOT:t.field({type:i})})});}var Ae=({db:e,disableDefaultObjects:n,pubsub:r,pothosConfig:u})=>{let i=new et({...u,plugins:[Ce,st,at,...u?.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(s=>s.primary)}}},smartSubscriptions:{...subscribeOptionsFromIterator((t,s)=>r.subscribe(t))}});return i.addScalarType("JSON",JSONResolver),i.addScalarType("Date",DateResolver),i.addScalarType("DateTime",DateTimeISOResolver),Re(i),n?.query||i.queryType({}),n?.subscription||i.subscriptionType({}),n?.mutation||i.mutationType({}),{schemaBuilder:i}};var gt=e=>{e.actions||(e.actions=["read","update","delete"]),e.defaultLimit===void 0&&(e.defaultLimit=100),e.search?.enabled&&ce(e.db);let n=se(e),r=ae({...e,abilityBuilder:n}),{makePubSubInstance:u,pubsub:i}=be({...e}),{schemaBuilder:t}=Ae({...e,pubsub:i}),s=le({...e,schemaBuilder:t}),m=Se({...e,schemaBuilder:t,enumImplementer:s}),a=de({...e,schemaBuilder:t}),c=ye({...e,schemaBuilder:t,makePubSubInstance:u,whereArgImplementer:m,orderArgImplementer:a,enumImplementer:s,abilityBuilder:n}),l=Te({...e,schemaBuilder:t,whereArgImplementer:m,orderArgImplementer:a,makePubSubInstance:u}),b=z(()=>t.toSchema());return {abilityBuilder:n,schemaBuilder:t,createYoga:y=>{let d=y?.enableApiDocs??process?.env?.NODE_ENV==="development"??false;return createYoga({...y,graphiql:d,plugins:[...y?.plugins??[],...d?[]:[useDisableIntrospection(),EnvelopArmorPlugin()]].filter(Boolean),schema:b(),context:r})},createSofa:y=>(y.openAPI&&merge(y.openAPI,ue),useSofa({...y,schema:b(),context:r})),object:c,whereArg:m,orderArg:a,query:l,pubsub:u,enum_:s}};export{A as RumbleError,k as RumbleErrorSafe,V as assertFindFirstExists,Pe as assertFirstEntryExists,ve as mapNullFieldsToUndefined,gt as rumble};//# sourceMappingURL=index.js.map
|
47
|
+
`+Re(this.source,n);return t}toJSON(){let t={message:this.message};return this.locations!=null&&(t.locations=this.locations),this.path!=null&&(t.path=this.path),this.extensions!=null&&Object.keys(this.extensions).length>0&&(t.extensions=this.extensions),t}};function it(e){return e===void 0||e.length===0?void 0:e}var ve={Name:[],Document:["definitions"],OperationDefinition:["name","variableDefinitions","directives","selectionSet"],VariableDefinition:["variable","type","defaultValue","directives"],Variable:["name"],SelectionSet:["selections"],Field:["alias","name","arguments","directives","selectionSet"],Argument:["name","value"],FragmentSpread:["name","directives"],InlineFragment:["typeCondition","directives","selectionSet"],FragmentDefinition:["name","variableDefinitions","typeCondition","directives","selectionSet"],IntValue:[],FloatValue:[],StringValue:[],BooleanValue:[],NullValue:[],EnumValue:[],ListValue:["values"],ObjectValue:["fields"],ObjectField:["name","value"],Directive:["name","arguments"],NamedType:["name"],ListType:["type"],NonNullType:["type"],SchemaDefinition:["description","directives","operationTypes"],OperationTypeDefinition:["type"],ScalarTypeDefinition:["description","name","directives"],ObjectTypeDefinition:["description","name","interfaces","directives","fields"],FieldDefinition:["description","name","arguments","type","directives"],InputValueDefinition:["description","name","type","defaultValue","directives"],InterfaceTypeDefinition:["description","name","interfaces","directives","fields"],UnionTypeDefinition:["description","name","directives","types"],EnumTypeDefinition:["description","name","directives","values"],EnumValueDefinition:["description","name","directives"],InputObjectTypeDefinition:["description","name","directives","fields"],DirectiveDefinition:["description","name","arguments","locations"],SchemaExtension:["directives","operationTypes"],ScalarTypeExtension:["name","directives"],ObjectTypeExtension:["name","interfaces","directives","fields"],InterfaceTypeExtension:["name","interfaces","directives","fields"],UnionTypeExtension:["name","directives","types"],EnumTypeExtension:["name","directives","values"],InputObjectTypeExtension:["name","directives","fields"]},Xt=new Set(Object.keys(ve));function Oe(e){let t=e?.kind;return typeof t=="string"&&Xt.has(t)}var ot;(function(e){e.QUERY="query",e.MUTATION="mutation",e.SUBSCRIPTION="subscription";})(ot||(ot={}));var B;(function(e){e.NAME="Name",e.DOCUMENT="Document",e.OPERATION_DEFINITION="OperationDefinition",e.VARIABLE_DEFINITION="VariableDefinition",e.SELECTION_SET="SelectionSet",e.FIELD="Field",e.ARGUMENT="Argument",e.FRAGMENT_SPREAD="FragmentSpread",e.INLINE_FRAGMENT="InlineFragment",e.FRAGMENT_DEFINITION="FragmentDefinition",e.VARIABLE="Variable",e.INT="IntValue",e.FLOAT="FloatValue",e.STRING="StringValue",e.BOOLEAN="BooleanValue",e.NULL="NullValue",e.ENUM="EnumValue",e.LIST="ListValue",e.OBJECT="ObjectValue",e.OBJECT_FIELD="ObjectField",e.DIRECTIVE="Directive",e.NAMED_TYPE="NamedType",e.LIST_TYPE="ListType",e.NON_NULL_TYPE="NonNullType",e.SCHEMA_DEFINITION="SchemaDefinition",e.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",e.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",e.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",e.FIELD_DEFINITION="FieldDefinition",e.INPUT_VALUE_DEFINITION="InputValueDefinition",e.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",e.UNION_TYPE_DEFINITION="UnionTypeDefinition",e.ENUM_TYPE_DEFINITION="EnumTypeDefinition",e.ENUM_VALUE_DEFINITION="EnumValueDefinition",e.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",e.DIRECTIVE_DEFINITION="DirectiveDefinition",e.SCHEMA_EXTENSION="SchemaExtension",e.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",e.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",e.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",e.UNION_TYPE_EXTENSION="UnionTypeExtension",e.ENUM_TYPE_EXTENSION="EnumTypeExtension",e.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension";})(B||(B={}));function Le(e){return e===9||e===32}function Zt(e){return e>=48&&e<=57}function st(e){return e>=97&&e<=122||e>=65&&e<=90}function at(e){return st(e)||e===95}function lt(e){return st(e)||Zt(e)||e===95}function ut(e,t){let n=e.replace(/"""/g,'\\"""'),r=n.split(/\r\n|[\n\r]/g),o=r.length===1,i=r.length>1&&r.slice(1).every(x=>x.length===0||Le(x.charCodeAt(0))),s=n.endsWith('\\"""'),l=e.endsWith('"')&&!s,u=e.endsWith("\\"),p=l||u,a=(!o||e.length>70||p||i||s),m="",c=o&&Le(e.charCodeAt(0));return (a&&!c||i)&&(m+=`
|
48
|
+
`),m+=n,(a||p)&&(m+=`
|
49
|
+
`),'"""'+m+'"""'}function P(e){return me(e,[])}function me(e,t){switch(typeof e){case "string":return JSON.stringify(e);case "function":return e.name?`[function ${e.name}]`:"[function]";case "object":return en(e,t);default:return String(e)}}function en(e,t){if(e===null)return "null";if(t.includes(e))return "[Circular]";let n=[...t,e];if(tn(e)){let r=e.toJSON();if(r!==e)return typeof r=="string"?r:me(r,n)}else if(Array.isArray(e))return rn(e,n);return nn(e,n)}function tn(e){return typeof e.toJSON=="function"}function nn(e,t){let n=Object.entries(e);return n.length===0?"{}":t.length>2?"["+on(e)+"]":"{ "+n.map(([o,i])=>o+": "+me(i,t)).join(", ")+" }"}function rn(e,t){if(e.length===0)return "[]";if(t.length>2)return "[Array]";let n=Math.min(10,e.length),r=e.length-n,o=[];for(let i=0;i<n;++i)o.push(me(e[i],t));return r===1?o.push("... 1 more item"):r>1&&o.push(`... ${r} more items`),"["+o.join(", ")+"]"}function on(e){let t=Object.prototype.toString.call(e).replace(/^\[object /,"").replace(/]$/,"");if(t==="Object"&&typeof e.constructor=="function"){let n=e.constructor.name;if(typeof n=="string"&&n!=="")return n}return t}var sn=globalThis.process&&process.env.NODE_ENV==="production",z=sn?function(t,n){return t instanceof n}:function(t,n){if(t instanceof n)return true;if(typeof t=="object"&&t!==null){var r;let o=n.prototype[Symbol.toStringTag],i=Symbol.toStringTag in t?t[Symbol.toStringTag]:(r=t.constructor)===null||r===void 0?void 0:r.name;if(o===i){let s=P(t);throw new Error(`Cannot use ${o} "${s}" from another module or realm.
|
50
|
+
|
51
|
+
Ensure that there is only one instance of "graphql" in the node_modules
|
52
|
+
directory. If different versions of "graphql" are the dependencies of other
|
53
|
+
relied on modules, use "resolutions" to ensure only one version is installed.
|
54
|
+
|
55
|
+
https://yarnpkg.com/en/docs/selective-version-resolutions
|
56
|
+
|
57
|
+
Duplicate "graphql" modules cannot be used at the same time since different
|
58
|
+
versions may have different capabilities and behavior. The data from one
|
59
|
+
version used in the function from another could produce confusing and
|
60
|
+
spurious results.`)}}return false};function pt(e,t){let[n,r]=t?[e,t]:[void 0,e],o=" Did you mean ";n&&(o+=n+" ");let i=r.map(u=>`"${u}"`);switch(i.length){case 0:return "";case 1:return o+i[0]+"?";case 2:return o+i[0]+" or "+i[1]+"?"}let s=i.slice(0,5),l=s.pop();return o+s.join(", ")+", or "+l+"?"}function Be(e){return e}function ct(e,t){let n=Object.create(null);for(let r of e)n[t(r)]=r;return n}function ie(e,t,n){let r=Object.create(null);for(let o of e)r[t(o)]=n(o);return r}function oe(e,t){let n=Object.create(null);for(let r of Object.keys(e))n[r]=t(e[r],r);return n}function mt(e,t){let n=0,r=0;for(;n<e.length&&r<t.length;){let o=e.charCodeAt(n),i=t.charCodeAt(r);if(fe(o)&&fe(i)){let s=0;do++n,s=s*10+o-we,o=e.charCodeAt(n);while(fe(o)&&s>0);let l=0;do++r,l=l*10+i-we,i=t.charCodeAt(r);while(fe(i)&&l>0);if(s<l)return -1;if(s>l)return 1}else {if(o<i)return -1;if(o>i)return 1;++n,++r;}}return e.length-t.length}var we=48,an=57;function fe(e){return !isNaN(e)&&we<=e&&e<=an}function dt(e,t){let n=Object.create(null),r=new Pe(e),o=Math.floor(e.length*.4)+1;for(let i of t){let s=r.measure(i,o);s!==void 0&&(n[i]=s);}return Object.keys(n).sort((i,s)=>{let l=n[i]-n[s];return l!==0?l:mt(i,s)})}var Pe=class{constructor(t){this._input=t,this._inputLowerCase=t.toLowerCase(),this._inputArray=ft(this._inputLowerCase),this._rows=[new Array(t.length+1).fill(0),new Array(t.length+1).fill(0),new Array(t.length+1).fill(0)];}measure(t,n){if(this._input===t)return 0;let r=t.toLowerCase();if(this._inputLowerCase===r)return 1;let o=ft(r),i=this._inputArray;if(o.length<i.length){let a=o;o=i,i=a;}let s=o.length,l=i.length;if(s-l>n)return;let u=this._rows;for(let a=0;a<=l;a++)u[0][a]=a;for(let a=1;a<=s;a++){let m=u[(a-1)%3],c=u[a%3],x=c[0]=a;for(let h=1;h<=l;h++){let y=o[a-1]===i[h-1]?0:1,T=Math.min(m[h]+1,c[h-1]+1,m[h-1]+y);if(a>1&&h>1&&o[a-1]===i[h-2]&&o[a-2]===i[h-1]){let N=u[(a-2)%3][h-2];T=Math.min(T,N+1);}T<x&&(x=T),c[h]=T;}if(x>n)return}let p=u[s%3][l];return p<=n?p:void 0}};function ft(e){let t=e.length,n=new Array(t);for(let r=0;r<t;++r)n[r]=e.charCodeAt(r);return n}function k(e){if(e==null)return Object.create(null);if(Object.getPrototypeOf(e)===null)return e;let t=Object.create(null);for(let[n,r]of Object.entries(e))t[n]=r;return t}function yt(e){return `"${e.replace(ln,un)}"`}var ln=/[\x00-\x1f\x22\x5c\x7f-\x9f]/g;function un(e){return pn[e.charCodeAt(0)]}var pn=["\\u0000","\\u0001","\\u0002","\\u0003","\\u0004","\\u0005","\\u0006","\\u0007","\\b","\\t","\\n","\\u000B","\\f","\\r","\\u000E","\\u000F","\\u0010","\\u0011","\\u0012","\\u0013","\\u0014","\\u0015","\\u0016","\\u0017","\\u0018","\\u0019","\\u001A","\\u001B","\\u001C","\\u001D","\\u001E","\\u001F","","",'\\"',"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\\\","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\u007F","\\u0080","\\u0081","\\u0082","\\u0083","\\u0084","\\u0085","\\u0086","\\u0087","\\u0088","\\u0089","\\u008A","\\u008B","\\u008C","\\u008D","\\u008E","\\u008F","\\u0090","\\u0091","\\u0092","\\u0093","\\u0094","\\u0095","\\u0096","\\u0097","\\u0098","\\u0099","\\u009A","\\u009B","\\u009C","\\u009D","\\u009E","\\u009F"];var cn=Object.freeze({});function ht(e,t,n=ve){let r=new Map;for(let N of Object.values(B))r.set(N,mn(t,N));let o,i=Array.isArray(e),s=[e],l=-1,u=[],p=e,a,m,c=[],x=[];do{l++;let N=l===s.length,g=N&&u.length!==0;if(N){if(a=x.length===0?void 0:c[c.length-1],p=m,m=x.pop(),g)if(i){p=p.slice();let R=0;for(let[I,E]of u){let b=I-R;E===null?(p.splice(b,1),R++):p[b]=E;}}else {p={...p};for(let[R,I]of u)p[R]=I;}l=o.index,s=o.keys,u=o.edits,i=o.inArray,o=o.prev;}else if(m){if(a=i?l:s[l],p=m[a],p==null)continue;c.push(a);}let D;if(!Array.isArray(p)){var h,y;Oe(p)||C(false,`Invalid AST Node: ${P(p)}.`);let R=N?(h=r.get(p.kind))===null||h===void 0?void 0:h.leave:(y=r.get(p.kind))===null||y===void 0?void 0:y.enter;if(D=R?.call(t,p,a,m,c,x),D===cn)break;if(D===false){if(!N){c.pop();continue}}else if(D!==void 0&&(u.push([a,D]),!N))if(Oe(D))p=D;else {c.pop();continue}}if(D===void 0&&g&&u.push([a,p]),N)c.pop();else {var T;o={inArray:i,index:l,keys:s,edits:u,prev:o},i=Array.isArray(p),s=i?p:(T=n[p.kind])!==null&&T!==void 0?T:[],l=-1,u=[],m&&x.push(m),m=p;}}while(o!==void 0);return u.length!==0?u[u.length-1][1]:e}function mn(e,t){let n=e[t];return typeof n=="object"?n:typeof n=="function"?{enter:n,leave:void 0}:{enter:e.enter,leave:e.leave}}function Fe(e){return ht(e,dn)}var fn=80,dn={Name:{leave:e=>e.value},Variable:{leave:e=>"$"+e.name},Document:{leave:e=>f(e.definitions,`
|
61
|
+
|
62
|
+
`)},OperationDefinition:{leave(e){let t=S("(",f(e.variableDefinitions,", "),")"),n=f([e.operation,f([e.name,t]),f(e.directives," ")]," ");return (n==="query"?"":n+" ")+e.selectionSet}},VariableDefinition:{leave:({variable:e,type:t,defaultValue:n,directives:r})=>e+": "+t+S(" = ",n)+S(" ",f(r," "))},SelectionSet:{leave:({selections:e})=>q(e)},Field:{leave({alias:e,name:t,arguments:n,directives:r,selectionSet:o}){let i=S("",e,": ")+t,s=i+S("(",f(n,", "),")");return s.length>fn&&(s=i+S(`(
|
63
|
+
`,de(f(n,`
|
64
|
+
`)),`
|
65
|
+
)`)),f([s,f(r," "),o]," ")}},Argument:{leave:({name:e,value:t})=>e+": "+t},FragmentSpread:{leave:({name:e,directives:t})=>"..."+e+S(" ",f(t," "))},InlineFragment:{leave:({typeCondition:e,directives:t,selectionSet:n})=>f(["...",S("on ",e),f(t," "),n]," ")},FragmentDefinition:{leave:({name:e,typeCondition:t,variableDefinitions:n,directives:r,selectionSet:o})=>`fragment ${e}${S("(",f(n,", "),")")} on ${t} ${S("",f(r," ")," ")}`+o},IntValue:{leave:({value:e})=>e},FloatValue:{leave:({value:e})=>e},StringValue:{leave:({value:e,block:t})=>t?ut(e):yt(e)},BooleanValue:{leave:({value:e})=>e?"true":"false"},NullValue:{leave:()=>"null"},EnumValue:{leave:({value:e})=>e},ListValue:{leave:({values:e})=>"["+f(e,", ")+"]"},ObjectValue:{leave:({fields:e})=>"{"+f(e,", ")+"}"},ObjectField:{leave:({name:e,value:t})=>e+": "+t},Directive:{leave:({name:e,arguments:t})=>"@"+e+S("(",f(t,", "),")")},NamedType:{leave:({name:e})=>e},ListType:{leave:({type:e})=>"["+e+"]"},NonNullType:{leave:({type:e})=>e+"!"},SchemaDefinition:{leave:({description:e,directives:t,operationTypes:n})=>S("",e,`
|
66
|
+
`)+f(["schema",f(t," "),q(n)]," ")},OperationTypeDefinition:{leave:({operation:e,type:t})=>e+": "+t},ScalarTypeDefinition:{leave:({description:e,name:t,directives:n})=>S("",e,`
|
67
|
+
`)+f(["scalar",t,f(n," ")]," ")},ObjectTypeDefinition:{leave:({description:e,name:t,interfaces:n,directives:r,fields:o})=>S("",e,`
|
68
|
+
`)+f(["type",t,S("implements ",f(n," & ")),f(r," "),q(o)]," ")},FieldDefinition:{leave:({description:e,name:t,arguments:n,type:r,directives:o})=>S("",e,`
|
69
|
+
`)+t+(bt(n)?S(`(
|
70
|
+
`,de(f(n,`
|
71
|
+
`)),`
|
72
|
+
)`):S("(",f(n,", "),")"))+": "+r+S(" ",f(o," "))},InputValueDefinition:{leave:({description:e,name:t,type:n,defaultValue:r,directives:o})=>S("",e,`
|
73
|
+
`)+f([t+": "+n,S("= ",r),f(o," ")]," ")},InterfaceTypeDefinition:{leave:({description:e,name:t,interfaces:n,directives:r,fields:o})=>S("",e,`
|
74
|
+
`)+f(["interface",t,S("implements ",f(n," & ")),f(r," "),q(o)]," ")},UnionTypeDefinition:{leave:({description:e,name:t,directives:n,types:r})=>S("",e,`
|
75
|
+
`)+f(["union",t,f(n," "),S("= ",f(r," | "))]," ")},EnumTypeDefinition:{leave:({description:e,name:t,directives:n,values:r})=>S("",e,`
|
76
|
+
`)+f(["enum",t,f(n," "),q(r)]," ")},EnumValueDefinition:{leave:({description:e,name:t,directives:n})=>S("",e,`
|
77
|
+
`)+f([t,f(n," ")]," ")},InputObjectTypeDefinition:{leave:({description:e,name:t,directives:n,fields:r})=>S("",e,`
|
78
|
+
`)+f(["input",t,f(n," "),q(r)]," ")},DirectiveDefinition:{leave:({description:e,name:t,arguments:n,repeatable:r,locations:o})=>S("",e,`
|
79
|
+
`)+"directive @"+t+(bt(n)?S(`(
|
80
|
+
`,de(f(n,`
|
81
|
+
`)),`
|
82
|
+
)`):S("(",f(n,", "),")"))+(r?" repeatable":"")+" on "+f(o," | ")},SchemaExtension:{leave:({directives:e,operationTypes:t})=>f(["extend schema",f(e," "),q(t)]," ")},ScalarTypeExtension:{leave:({name:e,directives:t})=>f(["extend scalar",e,f(t," ")]," ")},ObjectTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:r})=>f(["extend type",e,S("implements ",f(t," & ")),f(n," "),q(r)]," ")},InterfaceTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:r})=>f(["extend interface",e,S("implements ",f(t," & ")),f(n," "),q(r)]," ")},UnionTypeExtension:{leave:({name:e,directives:t,types:n})=>f(["extend union",e,f(t," "),S("= ",f(n," | "))]," ")},EnumTypeExtension:{leave:({name:e,directives:t,values:n})=>f(["extend enum",e,f(t," "),q(n)]," ")},InputObjectTypeExtension:{leave:({name:e,directives:t,fields:n})=>f(["extend input",e,f(t," "),q(n)]," ")}};function f(e,t=""){var n;return (n=e?.filter(r=>r).join(t))!==null&&n!==void 0?n:""}function q(e){return S(`{
|
83
|
+
`,de(f(e,`
|
84
|
+
`)),`
|
85
|
+
}`)}function S(e,t,n=""){return t!=null&&t!==""?e+t+n:""}function de(e){return S(" ",e.replace(/\n/g,`
|
86
|
+
`))}function bt(e){var t;return (t=e?.some(n=>n.includes(`
|
87
|
+
`)))!==null&&t!==void 0?t:false}function ye(e,t){switch(e.kind){case B.NULL:return null;case B.INT:return parseInt(e.value,10);case B.FLOAT:return parseFloat(e.value);case B.STRING:case B.ENUM:case B.BOOLEAN:return e.value;case B.LIST:return e.values.map(n=>ye(n,t));case B.OBJECT:return ie(e.fields,n=>n.name.value,n=>ye(n.value,t));case B.VARIABLE:return t?.[e.name.value]}}function Q(e){if(e!=null||C(false,"Must provide name."),typeof e=="string"||C(false,"Expected name to be a string."),e.length===0)throw new L("Expected name to be a non-empty string.");for(let t=1;t<e.length;++t)if(!lt(e.charCodeAt(t)))throw new L(`Names must only contain [_a-zA-Z0-9] but "${e}" does not.`);if(!at(e.charCodeAt(0)))throw new L(`Names must start with [_a-zA-Z] but "${e}" does not.`);return e}function je(e){if(e==="true"||e==="false"||e==="null")throw new L(`Enum values cannot be named: ${e}`);return Q(e)}function be(e){return _e(e)||Qe(e)||ke(e)||qe(e)||ze(e)||Ue(e)||Ge(e)||ge(e)}function _e(e){return z(e,W)}function Qe(e){return z(e,J)}function ke(e){return z(e,se)}function qe(e){return z(e,ae)}function ze(e){return z(e,X)}function Ue(e){return z(e,K)}function Ge(e){return z(e,M)}function ge(e){return z(e,U)}var M=class{constructor(t){be(t)||C(false,`Expected ${P(t)} to be a GraphQL type.`),this.ofType=t;}get[Symbol.toStringTag](){return "GraphQLList"}toString(){return "["+String(this.ofType)+"]"}toJSON(){return this.toString()}},U=class{constructor(t){$e(t)||C(false,`Expected ${P(t)} to be a GraphQL nullable type.`),this.ofType=t;}get[Symbol.toStringTag](){return "GraphQLNonNull"}toString(){return String(this.ofType)+"!"}toJSON(){return this.toString()}};function $e(e){return be(e)&&!ge(e)}function Te(e){return typeof e=="function"?e():e}function xe(e){return typeof e=="function"?e():e}var W=class{constructor(t){var n,r,o,i;let s=(n=t.parseValue)!==null&&n!==void 0?n:Be;this.name=Q(t.name),this.description=t.description,this.specifiedByURL=t.specifiedByURL,this.serialize=(r=t.serialize)!==null&&r!==void 0?r:Be,this.parseValue=s,this.parseLiteral=(o=t.parseLiteral)!==null&&o!==void 0?o:(l,u)=>s(ye(l,u)),this.extensions=k(t.extensions),this.astNode=t.astNode,this.extensionASTNodes=(i=t.extensionASTNodes)!==null&&i!==void 0?i:[],t.specifiedByURL==null||typeof t.specifiedByURL=="string"||C(false,`${this.name} must provide "specifiedByURL" as a string, but got: ${P(t.specifiedByURL)}.`),t.serialize==null||typeof t.serialize=="function"||C(false,`${this.name} must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.`),t.parseLiteral&&(typeof t.parseValue=="function"&&typeof t.parseLiteral=="function"||C(false,`${this.name} must provide both "parseValue" and "parseLiteral" functions.`));}get[Symbol.toStringTag](){return "GraphQLScalarType"}toConfig(){return {name:this.name,description:this.description,specifiedByURL:this.specifiedByURL,serialize:this.serialize,parseValue:this.parseValue,parseLiteral:this.parseLiteral,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}},J=class{constructor(t){var n;this.name=Q(t.name),this.description=t.description,this.isTypeOf=t.isTypeOf,this.extensions=k(t.extensions),this.astNode=t.astNode,this.extensionASTNodes=(n=t.extensionASTNodes)!==null&&n!==void 0?n:[],this._fields=()=>xt(t),this._interfaces=()=>Tt(t),t.isTypeOf==null||typeof t.isTypeOf=="function"||C(false,`${this.name} must provide "isTypeOf" as a function, but got: ${P(t.isTypeOf)}.`);}get[Symbol.toStringTag](){return "GraphQLObjectType"}getFields(){return typeof this._fields=="function"&&(this._fields=this._fields()),this._fields}getInterfaces(){return typeof this._interfaces=="function"&&(this._interfaces=this._interfaces()),this._interfaces}toConfig(){return {name:this.name,description:this.description,interfaces:this.getInterfaces(),fields:St(this.getFields()),isTypeOf:this.isTypeOf,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}};function Tt(e){var t;let n=Te((t=e.interfaces)!==null&&t!==void 0?t:[]);return Array.isArray(n)||C(false,`${e.name} interfaces must be an Array or a function which returns an Array.`),n}function xt(e){let t=xe(e.fields);return Z(t)||C(false,`${e.name} fields must be an object with field names as keys or a function which returns such an object.`),oe(t,(n,r)=>{var o;Z(n)||C(false,`${e.name}.${r} field config must be an object.`),n.resolve==null||typeof n.resolve=="function"||C(false,`${e.name}.${r} field resolver must be a function if provided, but got: ${P(n.resolve)}.`);let i=(o=n.args)!==null&&o!==void 0?o:{};return Z(i)||C(false,`${e.name}.${r} args must be an object with argument names as keys.`),{name:Q(r),description:n.description,type:n.type,args:yn(i),resolve:n.resolve,subscribe:n.subscribe,deprecationReason:n.deprecationReason,extensions:k(n.extensions),astNode:n.astNode}})}function yn(e){return Object.entries(e).map(([t,n])=>({name:Q(t),description:n.description,type:n.type,defaultValue:n.defaultValue,deprecationReason:n.deprecationReason,extensions:k(n.extensions),astNode:n.astNode}))}function Z(e){return ce(e)&&!Array.isArray(e)}function St(e){return oe(e,t=>({description:t.description,type:t.type,args:hn(t.args),resolve:t.resolve,subscribe:t.subscribe,deprecationReason:t.deprecationReason,extensions:t.extensions,astNode:t.astNode}))}function hn(e){return ie(e,t=>t.name,t=>({description:t.description,type:t.type,defaultValue:t.defaultValue,deprecationReason:t.deprecationReason,extensions:t.extensions,astNode:t.astNode}))}var se=class{constructor(t){var n;this.name=Q(t.name),this.description=t.description,this.resolveType=t.resolveType,this.extensions=k(t.extensions),this.astNode=t.astNode,this.extensionASTNodes=(n=t.extensionASTNodes)!==null&&n!==void 0?n:[],this._fields=xt.bind(void 0,t),this._interfaces=Tt.bind(void 0,t),t.resolveType==null||typeof t.resolveType=="function"||C(false,`${this.name} must provide "resolveType" as a function, but got: ${P(t.resolveType)}.`);}get[Symbol.toStringTag](){return "GraphQLInterfaceType"}getFields(){return typeof this._fields=="function"&&(this._fields=this._fields()),this._fields}getInterfaces(){return typeof this._interfaces=="function"&&(this._interfaces=this._interfaces()),this._interfaces}toConfig(){return {name:this.name,description:this.description,interfaces:this.getInterfaces(),fields:St(this.getFields()),resolveType:this.resolveType,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}},ae=class{constructor(t){var n;this.name=Q(t.name),this.description=t.description,this.resolveType=t.resolveType,this.extensions=k(t.extensions),this.astNode=t.astNode,this.extensionASTNodes=(n=t.extensionASTNodes)!==null&&n!==void 0?n:[],this._types=bn.bind(void 0,t),t.resolveType==null||typeof t.resolveType=="function"||C(false,`${this.name} must provide "resolveType" as a function, but got: ${P(t.resolveType)}.`);}get[Symbol.toStringTag](){return "GraphQLUnionType"}getTypes(){return typeof this._types=="function"&&(this._types=this._types()),this._types}toConfig(){return {name:this.name,description:this.description,types:this.getTypes(),resolveType:this.resolveType,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}};function bn(e){let t=Te(e.types);return Array.isArray(t)||C(false,`Must provide Array of types or a function which returns such an array for Union ${e.name}.`),t}var X=class{constructor(t){var n;this.name=Q(t.name),this.description=t.description,this.extensions=k(t.extensions),this.astNode=t.astNode,this.extensionASTNodes=(n=t.extensionASTNodes)!==null&&n!==void 0?n:[],this._values=typeof t.values=="function"?t.values:gt(this.name,t.values),this._valueLookup=null,this._nameLookup=null;}get[Symbol.toStringTag](){return "GraphQLEnumType"}getValues(){return typeof this._values=="function"&&(this._values=gt(this.name,this._values())),this._values}getValue(t){return this._nameLookup===null&&(this._nameLookup=ct(this.getValues(),n=>n.name)),this._nameLookup[t]}serialize(t){this._valueLookup===null&&(this._valueLookup=new Map(this.getValues().map(r=>[r.value,r])));let n=this._valueLookup.get(t);if(n===void 0)throw new L(`Enum "${this.name}" cannot represent value: ${P(t)}`);return n.name}parseValue(t){if(typeof t!="string"){let r=P(t);throw new L(`Enum "${this.name}" cannot represent non-string value: ${r}.`+he(this,r))}let n=this.getValue(t);if(n==null)throw new L(`Value "${t}" does not exist in "${this.name}" enum.`+he(this,t));return n.value}parseLiteral(t,n){if(t.kind!==B.ENUM){let o=Fe(t);throw new L(`Enum "${this.name}" cannot represent non-enum value: ${o}.`+he(this,o),{nodes:t})}let r=this.getValue(t.value);if(r==null){let o=Fe(t);throw new L(`Value "${o}" does not exist in "${this.name}" enum.`+he(this,o),{nodes:t})}return r.value}toConfig(){let t=ie(this.getValues(),n=>n.name,n=>({description:n.description,value:n.value,deprecationReason:n.deprecationReason,extensions:n.extensions,astNode:n.astNode}));return {name:this.name,description:this.description,values:t,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}};function he(e,t){let n=e.getValues().map(o=>o.name),r=dt(t,n);return pt("the enum value",r)}function gt(e,t){return Z(t)||C(false,`${e} values must be an object with value names as keys.`),Object.entries(t).map(([n,r])=>(Z(r)||C(false,`${e}.${n} must refer to an object with a "value" key representing an internal value but got: ${P(r)}.`),{name:je(n),description:r.description,value:r.value!==void 0?r.value:n,deprecationReason:r.deprecationReason,extensions:k(r.extensions),astNode:r.astNode}))}var K=class{constructor(t){var n,r;this.name=Q(t.name),this.description=t.description,this.extensions=k(t.extensions),this.astNode=t.astNode,this.extensionASTNodes=(n=t.extensionASTNodes)!==null&&n!==void 0?n:[],this.isOneOf=(r=t.isOneOf)!==null&&r!==void 0?r:false,this._fields=gn.bind(void 0,t);}get[Symbol.toStringTag](){return "GraphQLInputObjectType"}getFields(){return typeof this._fields=="function"&&(this._fields=this._fields()),this._fields}toConfig(){let t=oe(this.getFields(),n=>({description:n.description,type:n.type,defaultValue:n.defaultValue,deprecationReason:n.deprecationReason,extensions:n.extensions,astNode:n.astNode}));return {name:this.name,description:this.description,fields:t,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes,isOneOf:this.isOneOf}}toString(){return this.name}toJSON(){return this.toString()}};function gn(e){let t=xe(e.fields);return Z(t)||C(false,`${e.name} fields must be an object with field names as keys or a function which returns such an object.`),oe(t,(n,r)=>(!("resolve"in n)||C(false,`${e.name}.${r} field has a resolve property, but Input Types cannot define resolvers.`),{name:Q(r),description:n.description,type:n.type,defaultValue:n.defaultValue,deprecationReason:n.deprecationReason,extensions:k(n.extensions),astNode:n.astNode}))}function Ve(e){if(e instanceof J)return Kn(e);if(e instanceof W)return er(e);if(e instanceof X)return tr(e);if(e instanceof K)return Yn(e)}function Kn(e){let t=new Map;for(let[n,r]of Object.entries(e.getFields()))t.set(n,Hn(r.type,r.args));return `{
|
88
|
+
${t.entries().map(([n,r])=>`${n}: ${r}`).toArray().join(`,
|
89
|
+
`)}
|
90
|
+
}`}function Yn(e){let t=new Map;for(let[n,r]of Object.entries(e.getFields()))t.set(n,Xn(r.type));return `{
|
91
|
+
${t.entries().map(([n,r])=>`${n}${r.includes("| undefined")?"?":""}: ${r}`).toArray().join(`,
|
92
|
+
`)}
|
93
|
+
}`}function Hn(e,t){let n=false,r=false;for(let l=0;l<3;l++)e instanceof M&&(r=true,e=e.ofType),e instanceof U&&(n=true,e=e.ofType);let o=e.name;r&&(o+="[]"),n||(o+=" | null");let i=e instanceof J,s=new Map;for(let l of t??[])s.set(l.name,Zn(l.type));if(i){let l=s.entries().every(([,p])=>p.includes("| undefined"));return `(${(t??[]).length>0?`p${l?"?":""}: {
|
94
|
+
${s.entries().map(([p,a])=>` ${p}${a.includes("| undefined")?"?":""}: ${a}`).toArray().join(`,
|
95
|
+
`)}
|
96
|
+
}`:""}) => ${o}`}else return o}function Xn(e){let t=false,n=false;for(let o=0;o<3;o++)e instanceof M&&(n=true,e=e.ofType),e instanceof U&&(t=true,e=e.ofType);let r=e.name;return n&&(r+="[]"),t?n&&(r+=" | undefined"):r+=" | null | undefined",r}function Zn(e){let t="unknown",n=true;return e instanceof U&&(n=false,e=e.ofType),(e instanceof K||e instanceof W)&&(t=e.name),n&&(t+=" | null | undefined"),t}function er(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 tr(e){return e.getValues().map(t=>`"${t.name}"`).join(" | ")}async function Me({outputPath:e,schema:t,rumbleImportPath:n="@m1212e/rumble",apiUrl:r,useExternalUrqlClient:o=false}){await exists(e)&&await rm(e,{recursive:true,force:true}),await mkdir(e,{recursive:true}),e.endsWith("/")||(e+="/");let i=[],s="",l=new Map;for(let[p,a]of Object.entries(t.getTypeMap()))p.startsWith("__")||l.set(p,a);for(let[p,a]of l.entries())Ve(a)!==p&&(s+=`
|
97
|
+
export type ${p} = ${Ve(a)};
|
98
|
+
`);let u=et({apiUrl:r,useExternalUrqlClient:o,rumbleImportPath:n,availableSubscriptions:new Set(Object.keys(t.getSubscriptionType()?.getFields()||{}))});i.push(...u.imports),s+=u.code,await writeFile(join(e,"client.ts"),`${i.join(`
|
99
|
+
`)}
|
100
|
+
${s}`);}var ee="__args";function De({queryName:e,input:t,client:n,enableSubscription:r=false}){let o=`${capitalize(e)}Query`,i=Ne(t[ee]??{}),s=a=>`${a} ${o} { ${e}${i} { ${ue(t)} }}`,l,u=pipe(merge$1([n.query(s("query"),{}),r?n.subscription(s("subscription"),{}):empty]),map(a=>{let m=a.data?.[e];if(!m&&a.error)throw a.error;return m}),onPush(a=>{l&&Object.assign(l,a);})),p=new Promise(a=>{let m=toObservable(u).subscribe(c=>{m();let x=pipe(merge$1([u,fromValue(c)]),toObservable);l={...c,...x},a(l);}).unsubscribe;});return Object.assign(p,toObservable(u)),p}function Nt({mutationName:e,input:t,client:n}){let r=`${capitalize(e)}Mutation`,o=Ne(t[ee]??{}),i=pipe(n.mutation(`mutation ${r} { ${e}${o} { ${ue(t)} }}`,{}),map(u=>{let p=u.data?.[e];if(!p&&u.error)throw u.error;return p})),s=toObservable(i),l=toPromise(i).then(u=>(Object.assign(u,s),u));return Object.assign(l,s),l}function Et({subscriptionName:e,input:t,client:n}){let r=`${capitalize(e)}Subscription`,o=Ne(t[ee]??{});return pipe(n.subscription(`subscription ${r} { ${e}${o} { ${ue(t)} }}`,{}),map(i=>{let s=i.data?.[e];if(!s&&i.error)throw i.error;return s}),toObservable)}function ue(e){return Object.entries(e).filter(([t])=>t!==ee).reduce((t,[n,r])=>{if(typeof r=="object"){if(r[ee]){let o=Ne(r[ee]);return t+=`${n}${o} { ${ue(r)} }
|
101
|
+
`,t}t+=`${n} { ${ue(r)} }
|
102
|
+
`;}else t+=`${n}
|
103
|
+
`;return t},"")}function Ne(e){let t=Object.entries(e);return t.length===0?"":`(${t.map(([n,r])=>`${n}: ${At(r)}`).join(", ")})`}function At(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(([t,n])=>`${t}: ${At(n)}`).join(", ")} }`;case "function":throw new Error("Cannot stringify a function to send as gql arg")}}function cr({urqlClient:e,availableSubscriptions:t}){return new Proxy({},{get:(n,r)=>o=>De({queryName:r,input:o,client:e,enableSubscription:t.has(r)})})}function mr({urqlClient:e}){return new Proxy({},{get:(t,n)=>r=>Nt({mutationName:n,input:r,client:e})})}function fr({urqlClient:e}){return new Proxy({},{get:(t,n)=>r=>De({queryName:n,input:r,client:e,enableSubscription:false})})}function dr({urqlClient:e}){return new Proxy({},{get:(t,n)=>r=>Et({subscriptionName:n,input:r,client:e})})}var O=class extends Error{constructor(t){super(t),this.name="RumbleError";}},te=class extends L{};var Ke=e=>{if(!e)throw new te("Value not found but required (findFirst)");return e},yr=e=>{let t=e.at(0);if(!t)throw new te("Value not found but required (firstEntry)");return t},Ct=async({filters:e,entities:t,context:n})=>(await Promise.all(e.map(r=>r({context:n,entities:t})))).reduce((r,o)=>(r.push(...o),r),[]);function hr(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n===null?void 0:n]))}function G(e){let t,n=false;return ()=>(n||(t=e(),n=true),t)}var Ee=(e,t)=>new O(`RumbleError: Unknown SQL type '${e}'. Please open an issue (https://github.com/m1212e/rumble/issues) so it can be added. (${t})`);function It(e){if(["serial","int","integer","tinyint","smallint","mediumint"].includes(e))return {value1:1,value2:2};if(["real","decimal","double","float"].includes(e))return {value1:1.1,value2:2.2};if(["string","text","varchar","char","text(256)"].includes(e))return {value1:"a",value2:"b"};if(["uuid"].includes(e))return {value1:"fba31870-5528-42d7-b27e-2e5ee657aea5",value2:"fc65db81-c2d1-483d-8a25-a30e2cf6e02d"};if(["boolean"].includes(e))return {value1:true,value2:false};if(["timestamp","datetime"].includes(e))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(["date"].includes(e))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(["json"].includes(e))return {value1:{a:1},value2:{b:2}};throw Ee(e,"Distinct")}var Ye=Symbol.for("drizzle:Name"),Rt=Symbol.for("drizzle:Columns");function _({dbName:e,tsName:t,table:n,db:r}){let o=n;if(t&&(o=r._.relations.schema[t]),e&&(o=Object.values(r._.relations.schema).find(i=>i[Ye]===e)),!o)throw new O(`Could not find schema for ${JSON.stringify({tsName:t,dbName:e,table:n?.[Ye]}).toString()}`);return {tableSchema:o,columns:o[Rt],get primaryColumns(){return Object.entries(o[Rt]).filter(([,i])=>i.primary).reduce((i,[s,l])=>(i[s]=l,i),{})},relations:r._.relations.config[t],dbName:o[Ye],get tsName(){return Object.entries(r._.relations.schema).find(([,i])=>i===o).at(0)}}}function gr(e){return typeof e!="function"}function Tr(e){return typeof e=="function"&&e.constructor.name!=="AsyncFunction"}var vt=({db:e,actions:t,defaultLimit:n})=>{let r={},o={},i={},s=l=>{for(let u of t)i[l]||(i[l]={}),i[l][u]||(i[l][u]=[]);return {allow:u=>{let p=o[l];p||(p={},o[l]=p);let a=Array.isArray(u)?u:[u];for(let m of a){let c=p[m];c||(c="unspecified",p[m]=c);}return {when:m=>{for(let c of a)p[c]==="unspecified"&&(p[c]=[]),p[c].push(m);}}},filter:u=>{let p=Array.isArray(u)?u:[u];return {by:a=>{for(let m of p)i[l][m].push(a);}}}}};for(let l of Object.keys(e.query))r[l]=s(l);return {...r,z_registeredQueryFilters:o,z_registeredFilters:i,z_buildWithUserContext:l=>{let u={},p=a=>({filter:(m,c)=>{let x=d=>{let A=G(()=>{if(!(!d?.where&&!c?.inject?.where)){if(c?.inject?.where&&d?.where)return {AND:[d?.where,c?.inject?.where]};if(c?.inject?.where&&!d?.where)return c?.inject?.where;if(!c?.inject?.where&&d?.where)return d?.where;!c?.inject?.where&&d?.where;}}),v=G(()=>{let w=A();if(!w)return;let pe=_({tsName:a,db:e});return relationsFilterToSQL(pe.tableSchema,w)}),Y=G(()=>{let w=d?.limit??n;return c?.inject?.limit&&(!w||w>c.inject.limit)&&(w=c.inject.limit),d?.limit&&(!w||d.limit>w)&&(w=d.limit),w??void 0}),H=G(()=>{if(!(!d?.columns&&!c?.inject?.columns))return {...d?.columns,...c?.inject?.columns}}),$={query:{single:{get where(){return A()},columns:H()},many:{get where(){return A()},columns:H(),get limit(){return Y()}}},sql:{get where(){return v()},columns:H(),get limit(){return Y()}}};return H()||(delete $.sql.columns,delete $.query.many.columns,delete $.query.single.columns),$},h=()=>{let d=_({db:e,tsName:a});if(Object.keys(d.primaryColumns).length===0)throw new O(`No primary key found for entity ${a.toString()}`);let A=Object.values(d.primaryColumns)[0],v=It(A.getSQLType());return {where:{AND:[{[A.name]:v.value1},{[A.name]:v.value2}]}}},y=o?.[a]?.[m];if(y==="unspecified")return x();y||(y=[h()]);let T=y.filter(gr),N=y.filter(Tr).map(d=>d(l)),g=N.some(d=>d==="allow"),D=[...T,...N].filter(d=>d!==void 0).filter(d=>d!=="allow");!g&&D.length===0&&(D=[h()]);let R;for(let d of D)d?.limit&&(R===void 0||d.limit>R)&&(R=d.limit);let I;for(let d of [...D,c?.inject])d?.columns&&(I===void 0?I=d.columns:I={...I,...d.columns});let E=g?[]:D.filter(d=>d?.where).map(d=>d.where),b=E.length>0?{OR:E}:void 0;return x({where:b,columns:I,limit:R})},runtimeFilters:m=>i[a][m]});for(let a of Object.keys(e.query))u[a]=p(a);return u}}};var Ot=({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:n,outputPath:r,rumbleImportPath:o,useExternalUrqlClient:i})=>{let s=e();await Me({schema:s,outputPath:r,rumbleImportPath:o,apiUrl:n,useExternalUrqlClient:i});});var Lt=({context:e,abilityBuilder:t})=>async n=>{let r=e?await e(n):{};return {...r,abilities:t.z_buildWithUserContext(r)}};function Ae(e){return e instanceof PgEnumColumn}var Bt=({db:e,schemaBuilder:t})=>{let n=new Map;return ({tsName:o,enumColumn:i,refName:s})=>{let l,u;if(o){let c=e._.relations.schema[o];l=o.toString();let x=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===c);if(!x)throw new O(`Could not find applied enum column for ${o.toString()}.
|
104
|
+
Please ensure that you use the enum at least once as a column of a table!`);u=x.enumValues;}else if(i){let c=Object.entries(e._.relations.schema).find(([,x])=>x===i.config.enum);if(!c)throw new O(`Could not find enum in schema for ${i.name}!`);l=c[0],u=i.enumValues;}if(!l||!u)throw new O("Could not determine enum structure!");let p=s??`${capitalize(toCamelCase(l))}Enum`,a=n.get(p);return a||(a=t.enumType(p,{values:u}),n.set(p,a),a)}};var wt={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 Ce({sqlType:e,fieldName:t}){let n;if(["serial","int","integer","tinyint","smallint","mediumint"].includes(e)&&(n="Int"),["real","decimal","double","float"].includes(e)&&(n="Float"),["string","text","varchar","char","text(256)"].includes(e)&&(t&&(t.toLowerCase().endsWith("_id")||t.toLowerCase().endsWith("id"))?n="ID":n="String"),["uuid"].includes(e)&&(n="ID"),["boolean"].includes(e)&&(n="Boolean"),["timestamp","datetime"].includes(e)&&(n="DateTime"),["date"].includes(e)&&(n="Date"),["json"].includes(e)&&(n="JSON"),n!==void 0)return n;throw Ee(e,"SQL to GQL")}function Cr(e){let t=new Set;for(let r of Object.values(e))typeof r=="object"&&(r instanceof PgTable?t.add("postgres"):r instanceof MySqlTable?t.add("mysql"):r instanceof SQLiteTable&&t.add("sqlite"));let n=Array.from(t);if(n.length===1)return n[0];throw n.length===0?new Error("No tables found in schema, could not determine dialect"):new Error(`Multiple dialects found in schema: ${n.join(", ")}`)}function Pt(e){return Cr(e._.relations.schema)==="postgres"}async function jt(e){if(!Pt(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 Ie({search:e,args:t,tableSchema:n,abilities:r}){if(e?.enabled&&t.search&&t.search.length>0){let o=cloneDeep(t.orderBy);t.orderBy=s=>{let l=sql.join(Object.entries(o??{}).map(([m,c])=>{if(c==="asc")return sql`${s[m]} ASC`;if(c==="desc")return sql`${s[m]} DESC`;throw new Error(`Invalid value ${c} for orderBy`)}),sql.raw(", ")),u=r.query.many.columns?Object.entries(n.columns).filter(([m])=>r.query.many.columns[m]):Object.entries(n.columns),p=sql`GREATEST(${sql.join(u.map(([m])=>sql`similarity(${s[m]}::TEXT, ${t.search})`),sql.raw(", "))}) DESC`;return o?sql.join([l,p],sql.raw(", ")):p};let i=cloneDeep(t.where);t.where={AND:[i??{},{RAW:s=>sql`GREATEST(${sql.join(Object.entries(n.columns).map(([l])=>sql`similarity(${s[l]}::TEXT, ${t.search})`),sql.raw(", "))}) > ${e.threshold??.1}`}]};}}var Lr=e=>typeof e!="object"?false:!!Object.keys(e).some(t=>["args","nullable","query","subscribe","description","type","resolve"].find(n=>n===t)),_t=({db:e,search:t,schemaBuilder:n,makePubSubInstance:r,whereArgImplementer:o,orderArgImplementer:i,enumImplementer:s,abilityBuilder:l})=>({table:u,refName:p,readAction:a="read",adjust:m})=>{let c=_({db:e,tsName:u});Object.keys(c.primaryColumns).length===0&&console.warn(`Could not find primary key for ${u.toString()}. Cannot register subscriptions!`);let x=Object.values(c.primaryColumns)[0],{registerOnInstance:h}=r({table:u});return n.drizzleObject(u,{name:p??capitalize(u.toString()),subscribe:(y,T,N)=>{if(!x)return;let g=T[x.name];if(!g){console.warn(`Could not find primary key value for ${JSON.stringify(T)}. Cannot register subscription!`);return}h({instance:y,action:"updated",primaryKeyValue:g});},applyFilters:l?.z_registeredFilters?.[u]?.[a],fields:y=>{let T=c.columns,N=(E,b,d)=>{let A=Ce({sqlType:E,fieldName:b});switch(A){case "Int":return y.exposeInt(b,{nullable:d});case "String":return y.exposeString(b,{nullable:d});case "Boolean":return y.exposeBoolean(b,{nullable:d});case "Date":return y.field({type:"Date",resolve:v=>v[b],nullable:d});case "DateTime":return y.field({type:"DateTime",resolve:v=>v[b],nullable:d});case "Float":return y.exposeFloat(b,{nullable:d});case "ID":return y.exposeID(b,{nullable:d});case "JSON":return y.field({type:"JSON",resolve:v=>v[b],nullable:d});default:throw new O(`Unsupported object type ${A} for column ${b}`)}},g=new Map,D=m?.(new Proxy(y,{get:(E,b)=>typeof E[b]!="function"||b==="arg"||b==="builder"||b==="graphqlKind"||b==="kind"||b==="listRef"||b==="table"||b==="typename"||b==="variant"||b.toString().startsWith("boolean")||b.toString().startsWith("float")||b.toString().startsWith("id")||b.toString().startsWith("int")||b.toString().startsWith("string")||b.toString().startsWith("expose")?E[b]:(...d)=>{let A=E[b](...d),v=d.find(Lr);if(!v)throw new O("Expected config object to be passed to adjust field");return g.set(A,{params:d,creatorFunction:E[b],configObject:v}),A}}))??{},R=Object.entries(T).reduce((E,[b,d])=>{if(D[b]){let{params:A,creatorFunction:v,configObject:Y}=g.get(D[b]);return typeof Y.nullable!="boolean"&&(Y.nullable=!d.notNull),D[b]=v.bind(y)(...A),E}if(Ae(d)){let A=s({enumColumn:d});E[b]=y.field({type:A,resolve:v=>v[b],nullable:!d.notNull});}else E[b]=N(d.getSQLType(),b,!d.notNull);return E},{}),I=Object.entries(c.relations??{}).reduce((E,[b,d])=>{let A=_({db:e,table:d.targetTable}),v=o({dbName:A.dbName}),Y=i({dbName:A.dbName}),H=r({table:A.tsName}),$=false,w=true,pe="many";d instanceof One&&(w=false,$=d.optional,pe="single");let Xe=(j,ne)=>{H.registerOnInstance({instance:j,action:"created"}),H.registerOnInstance({instance:j,action:"removed"});};if(D[b]){let{params:j,creatorFunction:ne,configObject:V}=g.get(D[b]);return typeof V.nullable!="boolean"&&(V.nullable=$),typeof V.subscribe!="function"&&(V.subscribe=Xe),D[b]=ne.bind(y)(...j),E}let Ze={where:y.arg({type:v,required:false}),orderBy:y.arg({type:Y,required:false}),...w?{offset:y.arg.int({required:false}),limit:y.arg.int({required:false})}:{},search:y.arg.string({required:false})};return (!t?.enabled||!w)&&delete Ze.search,E[b]=y.relation(b,{args:Ze,subscribe:Xe,nullable:$,description:`Get the ${plural(A.tsName)} related to this ${singular(c.tsName)}`,query:(j,ne)=>{j=JSON.parse(JSON.stringify(j)),w&&Ie({search:t,args:j,tableSchema:A,abilities:ne.abilities[A.tsName].filter(a)});let V=ne.abilities[A.tsName].filter(a,{inject:{where:j.where,limit:j.limit}}).query[pe];return j.offset&&(V.offset=j.offset),j.orderBy&&(V.orderBy=j.orderBy),V}}),E},{});return {...R,...I,...D}}})};var Pr=e=>`${capitalize(toCamelCase(e.toString()))}OrderInputArgument`,Qt=({db:e,schemaBuilder:t})=>{let n=new Map,r=G(()=>t.enumType("SortingParameter",{values:["asc","desc"]})),o=({table:i,refName:s,dbName:l})=>{let u=_({db:e,dbName:l,tsName:i}),p=s??Pr(u.tsName),a=n.get(p);return a||(a=t.inputType(p,{fields:c=>{let x=Object.entries(u.columns).reduce((y,[T])=>(y[T]=c.field({type:r(),required:false}),y),{}),h=Object.entries(u.relations??{}).reduce((y,[T,N])=>{let g=_({db:e,table:N.targetTable}),D=o({dbName:g.dbName});return y[T]=c.field({type:D,required:false}),y},{});return {...x,...h}}}),n.set(p,a),a)};return o};var Fr="RUMBLE_SUBSCRIPTION_NOTIFICATION",jr="REMOVED",_r="UPDATED",Qr="CREATED",qt=({subscriptions:e})=>{let t=e?createPubSub(...e):createPubSub();return {pubsub:t,makePubSubInstance:({table:r})=>{function o({action:i,tableName:s,primaryKeyValue:l}){let u;switch(i){case "created":u=Qr;break;case "removed":u=jr;break;case "updated":u=_r;break;default:throw new Error(`Unknown action: ${i}`)}return `${Fr}/${s}${l?`/${l}`:""}/${u}`}return {registerOnInstance({instance:i,action:s,primaryKeyValue:l}){let u=o({tableName:r.toString(),action:s,primaryKeyValue:l});i.register(u);},created(){let i=o({tableName:r.toString(),action:"created"});return t.publish(i)},removed(){let i=o({tableName:r.toString(),action:"removed"});return t.publish(i)},updated(i){let l=(Array.isArray(i)?i:[i]).map(p=>o({tableName:r.toString(),action:"updated",primaryKeyValue:p})),u=Array.from(new Set(l));for(let p of u)t.publish(p);}}}}};var Gt=({db:e,schemaBuilder:t,search:n,whereArgImplementer:r,orderArgImplementer:o,makePubSubInstance:i})=>({table:s,readAction:l="read",listAction:u="read"})=>{let p=r({table:s}),a=o({table:s}),m=_({db:e,tsName:s}),c=Object.values(m.primaryColumns)[0],{registerOnInstance:x}=i({table:s});return t.queryFields(h=>{let y={where:h.arg({type:p,required:false}),orderBy:h.arg({type:a,required:false}),limit:h.arg.int({required:false}),offset:h.arg.int({required:false}),search:h.arg.string({required:false})};return n?.enabled||delete y.search,{[plural(s.toString())]:h.drizzleField({type:[s],nullable:false,smartSubscription:true,description:`List all ${plural(s.toString())}`,subscribe:(T,N,g,D,R)=>{x({instance:T,action:"created"}),x({instance:T,action:"removed"});},args:y,resolve:(T,N,g,D,R)=>{g=JSON.parse(JSON.stringify(g)),Ie({search:n,args:g,tableSchema:m,abilities:D.abilities[s].filter(u)});let I=D.abilities[s].filter(u,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 E=T(I);return I.columns&&(E.columns=I.columns),e.query[s].findMany(E)}}),[singular(s.toString())]:h.drizzleField({type:s,nullable:false,smartSubscription:true,description:`Get a single ${singular(s.toString())} by ID`,args:{id:h.arg.id({required:true})},resolve:(T,N,g,D,R)=>{g=JSON.parse(JSON.stringify(g));let I=D.abilities[s].filter(l,{inject:{where:{[c.name]:g.id}}}).query.single,E=T(I);return I.columns&&(E.columns=I.columns),e.query[s].findFirst(E).then(Ke)}})}})};var Vt="ManualFiltersPlugin",Mt=Vt,$t="applyFilters",He=class extends BasePlugin{wrapResolve(t,n){return async(r,o,i,s)=>{let l,u=n?.type;if(u.kind==="List"?l=u.type?.ref.currentConfig.pothosOptions[$t]:u.kind==="Object"&&(l=u.ref.currentConfig.pothosOptions[$t]),!l||!Array.isArray(l)||l.length===0)return t(r,o,i,s);let p=await t(r,o,i,s),a=Array.isArray(p)?p:[p],m=Array.isArray(l)?l:[l],c=await Ct({filters:m,entities:a,context:i});return Array.isArray(p)?c:c[0]??null}}};kr.registerPlugin(Vt,He);var Gr=e=>`${capitalize(toCamelCase(e.toString()))}WhereInputArgument`,Wt=({db:e,schemaBuilder:t,enumImplementer:n})=>{let r=new Map,o=({table:i,refName:s,dbName:l})=>{let u=_({db:e,dbName:l,tsName:i}),p=s??Gr(u.tsName),a=r.get(p);return a||(a=t.inputType(p,{fields:c=>{let x=(T,N)=>{let g=Ce({sqlType:T,fieldName:N});switch(g){case "Int":return c.field({type:"IntWhereInputArgument"});case "String":return c.field({type:"StringWhereInputArgument"});case "Boolean":return c.boolean({required:false});case "Date":return c.field({type:"DateWhereInputArgument"});case "DateTime":return c.field({type:"DateWhereInputArgument"});case "Float":return c.field({type:"FloatWhereInputArgument"});case "ID":return c.id({required:false});case "JSON":return c.field({type:"JSON",required:false});default:throw new O(`Unsupported argument type ${g} for column ${T}`)}},h=Object.entries(u.columns).reduce((T,[N,g])=>{if(Ae(g)){let D=n({enumColumn:g});T[N]=c.field({type:D,required:false});}else T[N]=x(g.getSQLType(),N);return T},{}),y=Object.entries(u.relations??{}).reduce((T,[N,g])=>{let D=_({db:e,table:g.targetTable}),R=o({dbName:D.dbName});return T[N]=c.field({type:R,required:false}),T},{});return {...h,...y}}}),r.set(p,a),a)};return o};function Jt(e){let t=e.inputRef("IntWhereInputArgument").implement({fields:i=>({eq:i.int(),ne:i.int(),gt:i.int(),gte:i.int(),lt:i.int(),lte:i.int(),in:i.intList(),notIn:i.intList(),like:i.string(),ilike:i.string(),notLike:i.string(),notIlike:i.string(),isNull:i.boolean(),isNotNull:i.boolean(),arrayOverlaps:i.intList(),arrayContained:i.intList(),arrayContains:i.intList(),AND:i.field({type:[t]}),OR:i.field({type:[t]}),NOT:i.field({type:t})})}),n=e.inputRef("FloatWhereInputArgument").implement({fields:i=>({eq:i.float(),ne:i.float(),gt:i.float(),gte:i.float(),lt:i.float(),lte:i.float(),in:i.floatList(),notIn:i.floatList(),like:i.string(),ilike:i.string(),notLike:i.string(),notIlike:i.string(),isNull:i.boolean(),isNotNull:i.boolean(),arrayOverlaps:i.floatList(),arrayContained:i.floatList(),arrayContains:i.floatList(),AND:i.field({type:[n]}),OR:i.field({type:[n]}),NOT:i.field({type:n})})}),r=e.inputRef("StringWhereInputArgument").implement({fields:i=>({eq:i.string(),ne:i.string(),gt:i.string(),gte:i.string(),lt:i.string(),lte:i.string(),in:i.stringList(),notIn:i.stringList(),like:i.string(),ilike:i.string(),notLike:i.string(),notIlike:i.string(),isNull:i.boolean(),isNotNull:i.boolean(),arrayOverlaps:i.stringList(),arrayContained:i.stringList(),arrayContains:i.stringList(),AND:i.field({type:[r]}),OR:i.field({type:[r]}),NOT:i.field({type:r})})}),o=e.inputRef("DateWhereInputArgument").implement({fields:i=>({eq:i.field({type:"Date"}),ne:i.field({type:"Date"}),gt:i.field({type:"Date"}),gte:i.field({type:"Date"}),lt:i.field({type:"Date"}),lte:i.field({type:"Date"}),in:i.field({type:["Date"]}),notIn:i.field({type:["Date"]}),like:i.string(),ilike:i.string(),notLike:i.string(),notIlike:i.string(),isNull:i.boolean(),isNotNull:i.boolean(),arrayOverlaps:i.field({type:["Date"]}),arrayContained:i.field({type:["Date"]}),arrayContains:i.field({type:["Date"]}),AND:i.field({type:[o]}),OR:i.field({type:[o]}),NOT:i.field({type:o})})});}var Kt=({db:e,disableDefaultObjects:t,pubsub:n,pothosConfig:r})=>{let o=new kr({...r,plugins:[Mt,Vr,Mr,...r?.plugins??[]],drizzle:{client:e,relations:e._.relations,getTableConfig(i){return {columns:Object.values(i[Symbol.for("drizzle:Columns")]),primaryKeys:Object.values(i[Symbol.for("drizzle:Columns")]).filter(s=>s.primary)}}},smartSubscriptions:{...subscribeOptionsFromIterator((i,s)=>n.subscribe(i))}});return o.addScalarType("JSON",JSONResolver),o.addScalarType("Date",DateResolver),o.addScalarType("DateTime",DateTimeISOResolver),Jt(o),t?.query||o.queryType({}),t?.subscription||o.subscriptionType({}),t?.mutation||o.mutationType({}),{schemaBuilder:o}};var ni=e=>{e.actions||(e.actions=["read","update","delete"]),e.defaultLimit===void 0&&(e.defaultLimit=100),e.search?.enabled&&jt(e.db);let t=vt(e),n=Lt({...e,abilityBuilder:t}),{makePubSubInstance:r,pubsub:o}=qt({...e}),{schemaBuilder:i}=Kt({...e,pubsub:o}),s=Bt({...e,schemaBuilder:i}),l=Wt({...e,schemaBuilder:i,enumImplementer:s}),u=Qt({...e,schemaBuilder:i}),p=_t({...e,schemaBuilder:i,makePubSubInstance:r,whereArgImplementer:l,orderArgImplementer:u,enumImplementer:s,abilityBuilder:t}),a=Gt({...e,schemaBuilder:i,whereArgImplementer:l,orderArgImplementer:u,makePubSubInstance:r}),m=G(()=>i.toSchema()),c=y=>{let T=y?.enableApiDocs??process?.env?.NODE_ENV==="development"??false;return createYoga({...y,graphiql:T,plugins:[...y?.plugins??[],...T?[]:[useDisableIntrospection(),EnvelopArmorPlugin()]].filter(Boolean),schema:m(),context:n})},x=y=>(y.openAPI&&merge(y.openAPI,wt),useSofa({...y,schema:m(),context:n})),h=Ot({...e,builtSchema:m});return {abilityBuilder:t,schemaBuilder:i,createYoga:c,createSofa:x,object:p,whereArg:l,orderArg:u,query:a,pubsub:r,enum_:s,clientCreator:h}};export{O as RumbleError,te as RumbleErrorSafe,Ke as assertFindFirstExists,yr as assertFirstEntryExists,Me as generateFromSchema,cr as makeLiveQuery,mr as makeMutation,fr as makeQuery,dr as makeSubscription,hr as mapNullFieldsToUndefined,ni as rumble};//# sourceMappingURL=index.js.map
|
9
105
|
//# sourceMappingURL=index.js.map
|