@m1212e/rumble 0.15.4 → 0.16.2

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.mjs CHANGED
@@ -1,12 +1,8 @@
1
- import { access, mkdir, rm, writeFile } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { getIntrospectedSchema, minifyIntrospectionQuery } from "@urql/introspection";
4
- import { uneval } from "devalue";
5
- import { GraphQLEnumType, GraphQLError, GraphQLInputObjectType, GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLScalarType } from "graphql";
6
- import { capitalize, cloneDeep, debounce, merge, toMerged } from "es-toolkit";
7
- import { empty, map, merge as merge$1, onPush, pipe, share, take, toObservable, toPromise } from "wonka";
1
+ import { t as generateFromSchema } from "./generate-lRQdmIB7.mjs";
2
+ import { GraphQLError } from "graphql";
8
3
  import { EnvelopArmorPlugin } from "@escape.tech/graphql-armor";
9
4
  import { useDisableIntrospection } from "@graphql-yoga/plugin-disable-introspection";
5
+ import { capitalize, cloneDeep, debounce, merge, toMerged } from "es-toolkit";
10
6
  import { createPubSub, createYoga } from "graphql-yoga";
11
7
  import { useSofa } from "sofa-api";
12
8
  import { One, count, relationsFilterToSQL, sql } from "drizzle-orm";
@@ -20,425 +16,6 @@ import DrizzlePlugin from "@pothos/plugin-drizzle";
20
16
  import SmartSubscriptionsPlugin, { subscribeOptionsFromIterator } from "@pothos/plugin-smart-subscriptions";
21
17
  import { DateResolver, DateTimeISOResolver, JSONResolver } from "graphql-scalars";
22
18
 
23
- //#region lib/client/generate/client.ts
24
- function generateClient({ apiUrl, rumbleImportPath, useExternalUrqlClient, availableSubscriptions, schemaPath, forceReactivity }) {
25
- const imports = [];
26
- let code = "";
27
- if (typeof useExternalUrqlClient === "string") imports.push(`import { urqlClient } from "${useExternalUrqlClient}";`);
28
- imports.push(`import { Client, fetchExchange } from '@urql/core';`);
29
- imports.push(`import { cacheExchange } from '@urql/exchange-graphcache';`);
30
- imports.push(`import { nativeDateExchange } from '${rumbleImportPath}';`);
31
- imports.push(`import { schema } from '${schemaPath}';`);
32
- imports.push(`import { makeLiveQuery, makeMutation, makeSubscription, makeQuery } from '${rumbleImportPath}';`);
33
- const forceReactivityValueString = typeof forceReactivity === "boolean" && forceReactivity ? "true" : "";
34
- const forceReactivityFieldString = forceReactivityValueString !== "" ? `forceReactivity: ${forceReactivityValueString}` : "";
35
- code += `
36
- export const defaultOptions: ConstructorParameters<Client>[0] = {
37
- url: "${apiUrl ?? "PLEASE PROVIDE A URL WHEN GENERATING OR IMPORT AN EXTERNAL URQL CLIENT"}",
38
- fetchSubscriptions: true,
39
- exchanges: [cacheExchange({ schema }), nativeDateExchange, fetchExchange],
40
- fetchOptions: {
41
- credentials: "include",
42
- },
43
- requestPolicy: "cache-and-network",
44
- }
45
- `;
46
- if (!useExternalUrqlClient) code += `
47
- const urqlClient = new Client(defaultOptions);
48
- `;
49
- code += `
50
- export const client = {
51
- /**
52
- * A query and subscription combination. First queries and if exists, also subscribes to a subscription of the same name.
53
- * Combines the results of both, so the result is first the query result and then live updates from the subscription.
54
- * Assumes that the query and subscription return the same fields as per default when using the rumble query helpers.
55
- * If no subscription with the same name exists, this will just be a query.
56
- */
57
- liveQuery: makeLiveQuery<Query${`, ${forceReactivityValueString}`}>({
58
- urqlClient,
59
- availableSubscriptions: new Set([${availableSubscriptions.values().toArray().map((value) => `"${value}"`).join(", ")}]),
60
- ${forceReactivityFieldString}
61
- }),
62
- /**
63
- * A mutation that can be used to e.g. create, update or delete data.
64
- */
65
- mutate: makeMutation<Mutation${`, ${forceReactivityValueString}`}>({
66
- urqlClient,
67
- ${forceReactivityFieldString}
68
- }),
69
- /**
70
- * A continuous stream of results that updates when the server sends new data.
71
- */
72
- subscribe: makeSubscription<Subscription${`, ${forceReactivityValueString}`}>({
73
- urqlClient,
74
- ${forceReactivityFieldString}
75
- }),
76
- /**
77
- * A one-time fetch of data.
78
- */
79
- query: makeQuery<Query${`, ${forceReactivityValueString}`}>({
80
- urqlClient,
81
- ${forceReactivityValueString !== "" ? `forceReactivity: ${forceReactivityValueString}` : ""}
82
- }),
83
- }`;
84
- return {
85
- imports,
86
- code
87
- };
88
- }
89
-
90
- //#endregion
91
- //#region lib/client/generate/tsRepresentation.ts
92
- function makeTSRepresentation(model) {
93
- if (model instanceof GraphQLObjectType) return makeTSTypeFromObject(model);
94
- else if (model instanceof GraphQLScalarType) return mapGraphqlScalarToTSTypeString(model);
95
- else if (model instanceof GraphQLEnumType) return makeStringLiteralUnionFromEnum(model);
96
- else if (model instanceof GraphQLInputObjectType) return makeTSTypeFromInputObject(model);
97
- throw new Error(`Unknown model type: ${model}`);
98
- }
99
- function makeTSTypeFromObject(model) {
100
- const stringifiedFields = /* @__PURE__ */ new Map();
101
- for (const [key, value] of Object.entries(model.getFields())) stringifiedFields.set(key, makeTSObjectTypeField(value.type, value.args));
102
- return `{
103
- ${stringifiedFields.entries().map(([key, value]) => `${key}: ${value}`).toArray().join(",\n ")}
104
- }`;
105
- }
106
- function makeTSTypeFromInputObject(model) {
107
- const stringifiedFields = /* @__PURE__ */ new Map();
108
- for (const [key, value] of Object.entries(model.getFields())) stringifiedFields.set(key, makeTSInputObjectTypeField(value.type));
109
- return `{
110
- ${stringifiedFields.entries().map(([key, value]) => `${key}${value.includes("| undefined") ? "?" : ""}: ${value}`).toArray().join(",\n ")}
111
- }`;
112
- }
113
- function makeTSObjectTypeField(returnType, args) {
114
- let isNonNullReturnType = false;
115
- let isList = false;
116
- for (let index = 0; index < 3; index++) {
117
- if (returnType instanceof GraphQLList) {
118
- isList = true;
119
- returnType = returnType.ofType;
120
- }
121
- if (returnType instanceof GraphQLNonNull) {
122
- isNonNullReturnType = true;
123
- returnType = returnType.ofType;
124
- }
125
- }
126
- let returnTypeString = returnType.name;
127
- if (isList) returnTypeString += "[]";
128
- if (!isNonNullReturnType) returnTypeString += " | null";
129
- const isRelationType = returnType instanceof GraphQLObjectType;
130
- const argsStringMap = /* @__PURE__ */ new Map();
131
- for (const arg of args ?? []) argsStringMap.set(arg.name, stringifyTSObjectArg(arg.type));
132
- if (isRelationType) {
133
- const makePOptional = argsStringMap.entries().every(([, value]) => value.includes("| undefined"));
134
- return `(${(args ?? []).length > 0 ? `p${makePOptional ? "?" : ""}: {
135
- ${argsStringMap.entries().map(([key, value]) => ` ${key}${value.includes("| undefined") ? "?" : ""}: ${value}`).toArray().join(",\n ")}
136
- }` : ""}) => ${returnTypeString}`;
137
- } else return returnTypeString;
138
- }
139
- function makeTSInputObjectTypeField(returnType) {
140
- let isNonNullReturnType = false;
141
- let isList = false;
142
- for (let index = 0; index < 3; index++) {
143
- if (returnType instanceof GraphQLList) {
144
- isList = true;
145
- returnType = returnType.ofType;
146
- }
147
- if (returnType instanceof GraphQLNonNull) {
148
- isNonNullReturnType = true;
149
- returnType = returnType.ofType;
150
- }
151
- }
152
- let returnTypeString = returnType.name;
153
- if (isList) returnTypeString += "[]";
154
- if (!isNonNullReturnType) returnTypeString += " | null | undefined";
155
- else if (isList) returnTypeString += " | undefined";
156
- return returnTypeString;
157
- }
158
- function stringifyTSObjectArg(arg) {
159
- let ret = "unknown";
160
- let isNullable = true;
161
- if (arg instanceof GraphQLNonNull) {
162
- isNullable = false;
163
- arg = arg.ofType;
164
- }
165
- if (arg instanceof GraphQLInputObjectType || arg instanceof GraphQLScalarType) ret = arg.name;
166
- if (isNullable) ret += " | null | undefined";
167
- return ret;
168
- }
169
- function mapGraphqlScalarToTSTypeString(arg) {
170
- switch (arg.name) {
171
- case "ID": return "string";
172
- case "String": return "string";
173
- case "Boolean": return "boolean";
174
- case "Int": return "number";
175
- case "Float": return "number";
176
- case "Date": return "Date";
177
- case "DateTime": return "Date";
178
- case "JSON": return "any";
179
- default: return "unknown";
180
- }
181
- }
182
- function makeStringLiteralUnionFromEnum(enumType) {
183
- return enumType.getValues().map((value) => `"${value.name}"`).join(" | ");
184
- }
185
-
186
- //#endregion
187
- //#region lib/client/generate/generate.ts
188
- async function generateFromSchema({ outputPath, schema, rumbleImportPath = "@m1212e/rumble", apiUrl, useExternalUrqlClient = false, removeExisting = true, forceReactivity }) {
189
- if (removeExisting) try {
190
- await access(outputPath);
191
- await rm(outputPath, {
192
- recursive: true,
193
- force: true
194
- });
195
- } catch (_error) {}
196
- await mkdir(outputPath, { recursive: true });
197
- if (!outputPath.endsWith("/")) outputPath += "/";
198
- const imports = [];
199
- let code = "";
200
- const typeMap = /* @__PURE__ */ new Map();
201
- for (const [key, object] of Object.entries(schema.getTypeMap())) {
202
- if (key.startsWith("__")) continue;
203
- typeMap.set(key, object);
204
- }
205
- for (const [key, object] of typeMap.entries()) {
206
- const rep = makeTSRepresentation(object);
207
- if (rep === key) continue;
208
- code += `
209
- export type ${key} = ${rep};
210
- `;
211
- }
212
- const schemaFileName = "schema";
213
- const c = generateClient({
214
- apiUrl,
215
- schemaPath: `./${schemaFileName}`,
216
- useExternalUrqlClient,
217
- rumbleImportPath,
218
- availableSubscriptions: new Set(Object.keys(schema.getSubscriptionType()?.getFields() || {})),
219
- forceReactivity
220
- });
221
- imports.push(...c.imports);
222
- code += c.code;
223
- await Promise.all([writeFile(join(outputPath, "client.ts"), `${imports.join("\n")}\n${code}`), writeFile(join(outputPath, `${schemaFileName}.ts`), `// @ts-ignore
224
- export const schema = ${uneval(minifyIntrospectionQuery(getIntrospectedSchema(schema)))}`)]);
225
- }
226
-
227
- //#endregion
228
- //#region lib/client/request.ts
229
- const argsKey = "__args";
230
- function makeGraphQLQueryRequest({ queryName, input, client, enableSubscription = false, forceReactivity }) {
231
- const otwQueryName = `${capitalize(queryName)}Query`;
232
- const argsString = stringifyArgumentObjectToGraphqlList(input?.[argsKey] ?? {});
233
- const operationString = (operationVerb) => `${operationVerb} ${otwQueryName} { ${queryName}${argsString} ${input ? `{ ${stringifySelection(input)} }` : ""}}`;
234
- const awaitedReturnValueReference = {};
235
- const source = pipe(merge$1([client.query(operationString("query"), {}), enableSubscription ? client.subscription(operationString("subscription"), {}) : empty]), share, map((v) => {
236
- const data = v.data?.[queryName];
237
- if (!data && v.error) throw v.error;
238
- return data;
239
- }), onPush((data) => {
240
- if (typeof data === "object" && data !== null && typeof forceReactivity === "boolean" && forceReactivity) Object.assign(awaitedReturnValueReference, data);
241
- }));
242
- const observable = toObservable(source);
243
- const promise = toPromise(pipe(source, take(1), map((data) => {
244
- Object.assign(awaitedReturnValueReference, observable);
245
- if (typeof data === "object" && data !== null && typeof forceReactivity === "boolean" && forceReactivity) {
246
- Object.assign(awaitedReturnValueReference, data);
247
- return awaitedReturnValueReference;
248
- }
249
- return data;
250
- })));
251
- Object.assign(promise, observable);
252
- return promise;
253
- }
254
- function makeGraphQLMutationRequest({ mutationName, input, client, forceReactivity }) {
255
- const operationString = `mutation ${`${capitalize(mutationName)}Mutation`} { ${mutationName}${stringifyArgumentObjectToGraphqlList(input[argsKey] ?? {})} { ${stringifySelection(input)} }}`;
256
- const response = pipe(client.mutation(operationString, {}), map((v) => {
257
- const data = v.data?.[mutationName];
258
- if (!data && v.error) throw v.error;
259
- return data;
260
- }));
261
- const observable = toObservable(response);
262
- const promise = toPromise(pipe(response, take(1)));
263
- Object.assign(promise, observable);
264
- return promise;
265
- }
266
- function makeGraphQLSubscriptionRequest({ subscriptionName, input, client, forceReactivity }) {
267
- const operationString = `subscription ${`${capitalize(subscriptionName)}Subscription`} { ${subscriptionName}${stringifyArgumentObjectToGraphqlList(input[argsKey] ?? {})} { ${stringifySelection(input)} }}`;
268
- return pipe(client.subscription(operationString, {}), map((v) => {
269
- const data = v.data?.[subscriptionName];
270
- if (!data && v.error) throw v.error;
271
- return data;
272
- }), toObservable);
273
- }
274
- function stringifySelection(selection) {
275
- return Object.entries(selection).filter(([key]) => key !== argsKey).reduce((acc, [key, value]) => {
276
- if (typeof value === "object") {
277
- if (value[argsKey]) {
278
- const argsString = stringifyArgumentObjectToGraphqlList(value[argsKey]);
279
- acc += `${key}${argsString} { ${stringifySelection(value)} }
280
- `;
281
- return acc;
282
- }
283
- acc += `${key} {
284
- ${stringifySelection(value)} }
285
- `;
286
- } else acc += `${key}
287
- `;
288
- return acc;
289
- }, "");
290
- }
291
- function stringifyArgumentObjectToGraphqlList(args) {
292
- const entries = Object.entries(args);
293
- if (Array.isArray(args)) return `(${stringifyArgumentValue(args)})`;
294
- if (entries.length > 0) return `(${entries.map(([key, value]) => `${key}: ${stringifyArgumentValue(value)}`).join(", ")})`;
295
- return "";
296
- }
297
- function stringifyArgumentValue(arg) {
298
- if (arg === null) return "null";
299
- if (Array.isArray(arg)) return `[${arg.map(stringifyArgumentValue).join(", ")}]`;
300
- switch (typeof arg) {
301
- case "string": return `"${arg}"`;
302
- case "number": return `${arg}`;
303
- case "bigint": return `${arg}`;
304
- case "boolean": return `${arg}`;
305
- case "symbol": throw new Error("Cannot stringify a symbol to send as gql arg");
306
- case "undefined": return "null";
307
- case "object": return `{ ${Object.entries(arg).map(([key, value]) => `${key}: ${stringifyArgumentValue(value)}`).join(", ")} }`;
308
- case "function": throw new Error("Cannot stringify a function to send as gql arg");
309
- }
310
- }
311
-
312
- //#endregion
313
- //#region lib/client/liveQuery.ts
314
- function makeLiveQuery({ urqlClient, availableSubscriptions, forceReactivity }) {
315
- return new Proxy({}, { get: (_target, prop) => {
316
- return (input) => {
317
- return makeGraphQLQueryRequest({
318
- queryName: prop,
319
- input,
320
- client: urqlClient,
321
- enableSubscription: availableSubscriptions.has(prop),
322
- forceReactivity
323
- });
324
- };
325
- } });
326
- }
327
-
328
- //#endregion
329
- //#region lib/client/mutation.ts
330
- function makeMutation({ urqlClient, forceReactivity }) {
331
- return new Proxy({}, { get: (_target, prop) => {
332
- return (input) => {
333
- return makeGraphQLMutationRequest({
334
- mutationName: prop,
335
- input,
336
- client: urqlClient,
337
- forceReactivity
338
- });
339
- };
340
- } });
341
- }
342
-
343
- //#endregion
344
- //#region lib/helpers/deepMap.ts
345
- /**
346
- * Recursively applies a mapping function to every value in a nested structure.
347
- *
348
- * This helper will traverse arrays and plain objects (objects with `constructor === Object`)
349
- * and apply the provided `fn` to any value that is not an array or a plain object.
350
- * - Arrays are mapped to new arrays (a fresh array is returned).
351
- * - Plain objects are traversed and their own enumerable properties are replaced in-place.
352
- * - Non-plain objects (e.g. Date, Map, Set, class instances, functions) are treated as leaves
353
- * and passed directly to `fn`.
354
- * - `null` and `undefined` are passed to `fn`.
355
- * - Circular references are detected using a `WeakSet`. When a circular reference is encountered,
356
- * the original reference is returned unchanged (it is not re-traversed or re-mapped).
357
- *
358
- * Note: Because plain objects are mutated in-place, callers who need immutability should first
359
- * clone the object graph or pass a deep-cloned input to avoid modifying the original.
360
- *
361
- * @param input - The value to traverse and map. May be any value (primitive, array, object, etc.).
362
- * @param fn - A function invoked for every non-array, non-plain-object value encountered.
363
- * Receives the current value and should return the mapped value.
364
- * @returns The transformed structure: arrays are returned as new arrays, plain objects are the
365
- * same object instances with their property values replaced, and other values are the
366
- * result of `fn`.
367
- *
368
- * @example
369
- * // Map all primitive values to their string representation:
370
- * // const result = mapValuesDeep({ a: 1, b: [2, { c: 3 }] }, v => String(v));
371
- * // result => { a: "1", b: ["2", { c: "3" }] }
372
- *
373
- * @remarks
374
- * - Only plain objects (constructed by `Object`) are recursively traversed. This avoids
375
- * unintentionally iterating internal structure of class instances or built-in collections.
376
- * - Circular structures are preserved by returning the original reference when detected.
377
- */
378
- function mapValuesDeep(input, fn) {
379
- const seen = /* @__PURE__ */ new WeakSet();
380
- const recurse = (value) => {
381
- if (Array.isArray(value)) return value.map(recurse);
382
- if (value !== null && value !== void 0 && typeof value === "object" && value.constructor === Object) {
383
- if (seen.has(value)) return value;
384
- seen.add(value);
385
- for (const key of Object.keys(value)) value[key] = recurse(value[key]);
386
- return value;
387
- }
388
- return fn(value);
389
- };
390
- return recurse(input);
391
- }
392
-
393
- //#endregion
394
- //#region lib/client/nativeDateExchange.ts
395
- const dateIsoRegex = /^\d{4}-\d{2}-\d{2}(?:[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})?)?$/;
396
- const nativeDateExchange = ({ client, forward }) => {
397
- return (operations$) => {
398
- return pipe(forward(operations$), map((r) => {
399
- r.data = mapValuesDeep(r.data, (value) => {
400
- if (typeof value !== "string" || !dateIsoRegex.test(value)) return value;
401
- const date = Date.parse(value);
402
- if (!Number.isNaN(date)) return new Date(date);
403
- return value;
404
- });
405
- return r;
406
- }));
407
- };
408
- };
409
-
410
- //#endregion
411
- //#region lib/client/query.ts
412
- function makeQuery({ urqlClient, forceReactivity }) {
413
- return new Proxy({}, { get: (_target, prop) => {
414
- return (input) => {
415
- return makeGraphQLQueryRequest({
416
- queryName: prop,
417
- input,
418
- client: urqlClient,
419
- enableSubscription: false,
420
- forceReactivity
421
- });
422
- };
423
- } });
424
- }
425
-
426
- //#endregion
427
- //#region lib/client/subscription.ts
428
- function makeSubscription({ urqlClient, forceReactivity }) {
429
- return new Proxy({}, { get: (_target, prop) => {
430
- return (input) => {
431
- return makeGraphQLSubscriptionRequest({
432
- subscriptionName: prop,
433
- input,
434
- client: urqlClient,
435
- forceReactivity
436
- });
437
- };
438
- } });
439
- }
440
-
441
- //#endregion
442
19
  //#region lib/types/rumbleError.ts
443
20
  /**
444
21
  * An error that gets raised by rumble whenever something does not go according to plan.
@@ -912,10 +489,10 @@ const createAbilityBuilder = ({ db, actions, defaultLimit }) => {
912
489
  /**
913
490
  * Merges the current query filters with the provided filters for this call only
914
491
  */
915
- function merge$2(p) {
492
+ function merge$1(p) {
916
493
  return internalTransformer(mergeFilters(ret.query.many, p), p.limit);
917
494
  }
918
- ret.merge = merge$2;
495
+ ret.merge = merge$1;
919
496
  return ret;
920
497
  }
921
498
  return { withContext: (userContext) => {
@@ -2014,5 +1591,5 @@ export const db = drizzle(
2014
1591
  };
2015
1592
 
2016
1593
  //#endregion
2017
- export { RumbleError, RumbleErrorSafe, assertFindFirstExists, assertFirstEntryExists, generateFromSchema, makeLiveQuery, makeMutation, makeQuery, makeSubscription, mapNullFieldsToUndefined, nativeDateExchange, rumble };
1594
+ export { RumbleError, RumbleErrorSafe, assertFindFirstExists, assertFirstEntryExists, mapNullFieldsToUndefined, rumble };
2018
1595
  //# sourceMappingURL=index.mjs.map