@gqloom/core 0.12.1 → 0.13.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/dist/index.js CHANGED
@@ -1,243 +1,6 @@
1
- import { AUTO_ALIASING, DERIVED_DEPENDENCIES, FIELD_HIDDEN, GET_GRAPHQL_TYPE, IS_RESOLVER, WEAVER_CONFIG, assignContextMap, getDeepResolvingFields, getMemoizationMap, getResolvingFields, isOnlyMemoryPayload, onlyMemoization, parseResolvingFields, symbols_exports } from "./context-BxqO4Eg9.js";
1
+ import { a as getMemoizationMap, c as FIELD_HIDDEN, d as IS_RESOLVER, f as WEAVER_CONFIG, h as DERIVED_DEPENDENCIES, i as assignContextMap, l as GET_GRAPHQL_ARGUMENT_CONFIG, m as AUTO_ALIASING, n as getResolvingFields, o as isOnlyMemoryPayload, p as symbols_exports, r as parseResolvingFields, s as onlyMemoization, t as getDeepResolvingFields, u as GET_GRAPHQL_TYPE } from "./parse-resolving-fields-BS_BL7I_.js";
2
2
  import { GraphQLError, GraphQLInputObjectType, GraphQLInterfaceType, GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLSchema, GraphQLUnionType, assertName, isEnumType, isInputObjectType, isInterfaceType, isListType, isNonNullType, isObjectType, isScalarType, isUnionType, resolveObjMapThunk } from "graphql";
3
3
 
4
- //#region src/utils/args.ts
5
- function getOperationOptions(resolveOrOptions) {
6
- if (typeof resolveOrOptions === "function") return { resolve: resolveOrOptions };
7
- return resolveOrOptions;
8
- }
9
- function getSubscriptionOptions(subscribeOrOptions) {
10
- if (typeof subscribeOrOptions === "function") return { subscribe: subscribeOrOptions };
11
- return subscribeOrOptions;
12
- }
13
- function getFieldOptions({ description, deprecationReason, extensions }, extraExtensions) {
14
- return {
15
- description,
16
- deprecationReason,
17
- extensions: extraExtensions ? {
18
- ...extensions,
19
- ...extraExtensions
20
- } : extensions
21
- };
22
- }
23
-
24
- //#endregion
25
- //#region src/utils/middleware.ts
26
- const defaultOperations = [
27
- "field",
28
- "mutation",
29
- "query",
30
- "subscription.subscribe"
31
- ];
32
- function applyMiddlewares(options, resolveFunction, middlewares) {
33
- const next = (index) => {
34
- if (index >= middlewares.length) return resolveFunction();
35
- const middleware = middlewares[index];
36
- const callableOptions = Object.assign(() => next(index + 1), {
37
- ...options,
38
- next: () => next(index + 1)
39
- });
40
- return middleware(callableOptions);
41
- };
42
- return next(0);
43
- }
44
- function filterMiddlewares(operation, ...middlewareList) {
45
- return middlewareList.reduce((acc, m) => {
46
- if (!m) return acc;
47
- acc.push(...ensureArray(m).filter((m$1) => {
48
- return (m$1.operations ?? defaultOperations).includes(operation);
49
- }));
50
- return acc;
51
- }, []);
52
- }
53
- function ensureArray(value) {
54
- if (value != null && typeof value === "object" && Symbol.iterator in value) return Array.from(value);
55
- return [value];
56
- }
57
-
58
- //#endregion
59
- //#region src/utils/object.ts
60
- /**
61
- * Creates an object map with the same keys as `map` and values generated by
62
- * running each value of `record` thru `fn`.
63
- */
64
- function mapValue(record, fn) {
65
- const result = Object.create(null);
66
- for (const key of Object.keys(record)) {
67
- const value = fn(record[key], key);
68
- if (value === SKIP) continue;
69
- result[key] = value;
70
- }
71
- return result;
72
- }
73
- const SKIP = Symbol.for("mapValue.skip");
74
- mapValue.SKIP = SKIP;
75
- function toObjMap(obj) {
76
- if (obj == null) return Object.create(null);
77
- if (Object.getPrototypeOf(obj) === null) return obj;
78
- const map = Object.create(null);
79
- for (const [key, value] of Object.entries(obj)) map[key] = value;
80
- return map;
81
- }
82
- function notNullish(x) {
83
- return x != null;
84
- }
85
- function deepMerge(...objects) {
86
- const result = {};
87
- for (const obj of objects) {
88
- if (obj == null) continue;
89
- for (const [key, value] of Object.entries(obj)) if (value !== null && typeof value === "object") if (Array.isArray(value)) {
90
- if (!Array.isArray(result[key])) result[key] = [];
91
- result[key] = [...result[key], ...value];
92
- } else result[key] = deepMerge(result[key], value);
93
- else result[key] = value;
94
- }
95
- return result;
96
- }
97
- /**
98
- * Wraps the provided data in an object with a single key `"~meta"`.
99
- *
100
- * @template T - The type of the data to be wrapped.
101
- * @param {T} data - The data to be wrapped.
102
- * @returns {{ "~meta": T }} - An object with a single key `"~meta"` containing the provided data.
103
- * @example
104
- * const originalData = { key: "value" };
105
- * const metaData = meta(originalData);
106
- * console.log(metaData); // Output: { "~meta": { key: "value" } }
107
- */
108
- function meta(data) {
109
- return { "~meta": data };
110
- }
111
-
112
- //#endregion
113
- //#region src/utils/string.ts
114
- function pascalCase(str) {
115
- return str.split(/[\s-_]+/).map((word, index) => index === 0 ? word.charAt(0).toUpperCase() + word.slice(1) : word.charAt(0).toUpperCase() + word.slice(1)).join("");
116
- }
117
- function capitalize(str) {
118
- return str.slice(0, 1).toUpperCase() + str.slice(1);
119
- }
120
- function screamingSnakeCase(str) {
121
- return str.replace(/([a-z])([A-Z])/g, "$1_$2").split(/[\s-_]+/).map((word) => word.toUpperCase()).join("_");
122
- }
123
-
124
- //#endregion
125
- //#region src/utils/error.ts
126
- function markErrorLocation(error, ...locations) {
127
- if (error instanceof Error) error.message = markLocation(error.message, ...locations);
128
- return error;
129
- }
130
- function tryIn(func, ...locations) {
131
- try {
132
- return func();
133
- } catch (error) {
134
- throw markErrorLocation(error, ...locations);
135
- }
136
- }
137
- /**
138
- * mark message with location
139
- * @param message origin message
140
- * @param locations where error happened
141
- * @returns message with location
142
- * @example markLocation("error", "banana") // "[banana] hello"
143
- * @example markLocation("error", fruit, banana) // "[fruit.banana] error"
144
- * @example markLocation("[banana] error", "fruit") // "[fruit.banana] error"
145
- * @example markLocation("[fruit.banana] error", "favorite") // "[favorite.fruit.banana] error"
146
- */
147
- function markLocation(message, ...locations) {
148
- if (locations.length === 0) return message;
149
- const [existingPrefix, newMessage] = (() => {
150
- const match = /^\[(.*?)\]/.exec(message);
151
- if (match) return [match[1], message.slice(match[0].length).trim()];
152
- return [void 0, message];
153
- })();
154
- return `[${locations.concat(existingPrefix ? [existingPrefix] : []).join(".")}] ${newMessage}`;
155
- }
156
-
157
- //#endregion
158
- //#region src/utils/loader.ts
159
- /**
160
- * GraphQL Loom built-in data loader.
161
- */
162
- var LoomDataLoader = class LoomDataLoader {
163
- results;
164
- resolvers;
165
- constructor() {
166
- this.results = /* @__PURE__ */ new Map();
167
- this.resolvers = /* @__PURE__ */ new Map();
168
- }
169
- /**
170
- * Load data for a given key.
171
- * @param key - The key to load data for.
172
- * @returns A promise that resolves to the loaded data.
173
- */
174
- load(key) {
175
- const existing = this.results.get(key);
176
- if (existing) return existing;
177
- const promise = new Promise((resolve, reject) => {
178
- this.resolvers.set(key, [resolve, reject]);
179
- this.nextTickBatchLoad();
180
- });
181
- this.results.set(key, promise);
182
- return promise;
183
- }
184
- /**
185
- * Clear the cache and reset the loader.
186
- */
187
- clear() {
188
- this.results = /* @__PURE__ */ new Map();
189
- this.resolvers = /* @__PURE__ */ new Map();
190
- }
191
- async executeBatchLoad() {
192
- if (this.resolvers.size === 0) return;
193
- const resolvers = this.resolvers;
194
- this.resolvers = /* @__PURE__ */ new Map();
195
- const keys = Array.from(resolvers.keys());
196
- try {
197
- const list = await this.batchLoad(keys);
198
- for (let i = 0; i < list.length; i++) {
199
- const data = list[i];
200
- const [resolve, reject] = resolvers.get(keys[i]) ?? [];
201
- if (data instanceof Error) reject?.(data);
202
- else resolve?.(data);
203
- }
204
- } catch (error) {
205
- for (const key of keys) {
206
- const reject = resolvers.get(key)?.[1];
207
- reject?.(error);
208
- }
209
- }
210
- }
211
- nextTickPromise;
212
- nextTickBatchLoad() {
213
- const load = async () => {
214
- try {
215
- while (this.resolvers.size > 0) {
216
- await LoomDataLoader.nextTick();
217
- await this.executeBatchLoad();
218
- }
219
- } finally {
220
- this.nextTickPromise = void 0;
221
- }
222
- };
223
- this.nextTickPromise ??= load();
224
- return this.nextTickPromise;
225
- }
226
- static nextTick() {
227
- return new Promise((resolve) => setTimeout(resolve));
228
- }
229
- };
230
- var EasyDataLoader = class extends LoomDataLoader {
231
- batchLoad(keys) {
232
- return this.batchLoadFn(keys);
233
- }
234
- constructor(batchLoadFn) {
235
- super();
236
- this.batchLoadFn = batchLoadFn;
237
- }
238
- };
239
-
240
- //#endregion
241
4
  //#region src/schema/weaver-context.ts
242
5
  var WeaverContext = class WeaverContext {
243
6
  static increasingID = 1;
@@ -420,152 +183,402 @@ function collectNames(...namesList) {
420
183
  WeaverContext.names.set(schema, name);
421
184
  namesRecord[name] = schema;
422
185
  }
423
- return namesRecord;
424
- }
425
- /**
426
- * collect name for schema
427
- * @param name - name for
428
- * @param schema - schema to be named
429
- * @returns schema
430
- */
431
- function collectName(name, schema) {
432
- WeaverContext.names.set(schema, name);
433
- return schema;
434
- }
186
+ return namesRecord;
187
+ }
188
+ /**
189
+ * collect name for schema
190
+ * @param name - name for
191
+ * @param schema - schema to be named
192
+ * @returns schema
193
+ */
194
+ function collectName(name, schema) {
195
+ WeaverContext.names.set(schema, name);
196
+ return schema;
197
+ }
198
+
199
+ //#endregion
200
+ //#region src/resolver/silk.ts
201
+ function silk(type, validate = (value) => ({ value: value ?? void 0 })) {
202
+ return {
203
+ [GET_GRAPHQL_TYPE]: typeof type === "function" ? type : () => type,
204
+ "~standard": {
205
+ version: 1,
206
+ vendor: "gqloom.silk",
207
+ validate
208
+ }
209
+ };
210
+ }
211
+ silk.parse = parseSilk;
212
+ silk.getType = getGraphQLType;
213
+ silk.nonNull = nonNullSilk;
214
+ silk.list = listSilk;
215
+ silk.nullable = nullableSilk;
216
+ /**
217
+ * Non-nullable Silk.
218
+ */
219
+ function nonNullSilk(origin) {
220
+ return {
221
+ ...origin,
222
+ [GET_GRAPHQL_TYPE]: () => {
223
+ const originType = getGraphQLType(origin);
224
+ if (originType instanceof GraphQLNonNull) return originType;
225
+ else return new GraphQLNonNull(originType);
226
+ }
227
+ };
228
+ }
229
+ /**
230
+ * List Silk.
231
+ */
232
+ function listSilk(origin) {
233
+ return {
234
+ ...origin,
235
+ [GET_GRAPHQL_TYPE]: () => {
236
+ let originType = getGraphQLType(origin);
237
+ if (originType instanceof GraphQLNonNull && originType.ofType instanceof GraphQLList) originType = originType.ofType.ofType;
238
+ if (originType instanceof GraphQLList) originType = originType.ofType;
239
+ return new GraphQLNonNull(new GraphQLList(originType));
240
+ }
241
+ };
242
+ }
243
+ /**
244
+ * Nullable Silk.
245
+ */
246
+ function nullableSilk(origin) {
247
+ return {
248
+ ...origin,
249
+ [GET_GRAPHQL_TYPE]: () => {
250
+ const originType = getGraphQLType(origin);
251
+ if (originType instanceof GraphQLNonNull) return originType.ofType;
252
+ else return originType;
253
+ }
254
+ };
255
+ }
256
+ /**
257
+ * Get GraphQL Output Type from Silk.
258
+ * @param silk GraphQL Silk
259
+ * @returns GraphQL Output Type
260
+ */
261
+ function getGraphQLType(silk$1) {
262
+ if (GET_GRAPHQL_TYPE in silk$1 && silk$1[GET_GRAPHQL_TYPE] != null) return typeof silk$1[GET_GRAPHQL_TYPE] === "function" ? silk$1[GET_GRAPHQL_TYPE]() : silk$1[GET_GRAPHQL_TYPE];
263
+ const vendorWeavers = weaverContext.vendorWeavers;
264
+ if (vendorWeavers == null) throw new Error("Schema Weaver is not initialized");
265
+ const weaver = vendorWeavers.get(silk$1["~standard"].vendor);
266
+ if (weaver == null) throw new Error(`Schema Weaver for ${silk$1["~standard"].vendor} is not found`);
267
+ return weaver.getGraphQLType(silk$1);
268
+ }
269
+ /**
270
+ * Get GraphQL Argument Config from Silk.
271
+ * @param silk GraphQL Silk
272
+ * @returns GraphQL Argument Config
273
+ */
274
+ function getGraphQLArgumentConfig(silk$1) {
275
+ if (GET_GRAPHQL_ARGUMENT_CONFIG in silk$1 && silk$1[GET_GRAPHQL_ARGUMENT_CONFIG] != null) return typeof silk$1[GET_GRAPHQL_ARGUMENT_CONFIG] === "function" ? silk$1[GET_GRAPHQL_ARGUMENT_CONFIG]() : silk$1[GET_GRAPHQL_ARGUMENT_CONFIG];
276
+ const vendorWeavers = weaverContext.vendorWeavers;
277
+ if (vendorWeavers == null) return void 0;
278
+ const weaver = vendorWeavers.get(silk$1["~standard"]?.vendor);
279
+ if (weaver == null) return void 0;
280
+ if (weaver.getGraphQLArgumentConfig == null) return void 0;
281
+ return weaver.getGraphQLArgumentConfig(silk$1);
282
+ }
283
+ /**
284
+ * Validate and transform input to output
285
+ * @param silk silk GraphQL Silk
286
+ * @param input
287
+ * @returns output
288
+ */
289
+ function parseSilk(silk$1, input) {
290
+ return silk$1["~standard"].validate(input);
291
+ }
292
+ function isSilk(target) {
293
+ if (typeof target !== "object" && typeof target !== "function") return false;
294
+ if (target == null) return false;
295
+ if (GET_GRAPHQL_TYPE in target) return true;
296
+ if (!("~standard" in target)) return false;
297
+ return "vendor" in target["~standard"] && typeof target["~standard"].vendor === "string" && "version" in target["~standard"] && typeof target["~standard"].version === "number";
298
+ }
299
+
300
+ //#endregion
301
+ //#region src/resolver/input.ts
302
+ function createInputParser(schema, value) {
303
+ let result;
304
+ const parse = async () => {
305
+ if (result !== void 0) return result;
306
+ result = await parseInputValue(schema, value);
307
+ return result;
308
+ };
309
+ Object.assign(parse, {
310
+ schema,
311
+ value
312
+ });
313
+ Object.defineProperty(parse, "result", {
314
+ get: () => result,
315
+ set: (value$1) => result = value$1
316
+ });
317
+ Object.defineProperty(parse, "getResult", { value: async () => getStandardValue(await parse()) });
318
+ Object.defineProperty(parse, "setResult", { value: (value$1) => result = { value: value$1 } });
319
+ Object.defineProperty(parse, "clearResult", { value: () => result = void 0 });
320
+ return parse;
321
+ }
322
+ function parseInputValue(inputSchema, input) {
323
+ if (inputSchema === void 0) return { value: input };
324
+ if (isSilk(inputSchema)) return inputSchema["~standard"].validate(input);
325
+ return parseInputEntries(inputSchema, input);
326
+ }
327
+ async function parseInputEntries(inputSchema, input = {}) {
328
+ const result = {};
329
+ const issues = [];
330
+ await Promise.all(Object.entries(inputSchema).map(async ([key, value]) => {
331
+ const res = await value["~standard"].validate(input[key]);
332
+ if ("value" in res) result[key] = res.value;
333
+ if (res.issues) issues.push(...res.issues.slice());
334
+ }));
335
+ return {
336
+ value: result,
337
+ ...issues.length > 0 ? { issues } : null
338
+ };
339
+ }
340
+ function getStandardValue(result) {
341
+ if (result == null) return result;
342
+ const { issues } = result;
343
+ if (issues?.length) throw new GraphQLError(issues?.[0]?.message ?? "Invalid input", { extensions: { issues } });
344
+ if ("value" in result) return result.value;
345
+ else throw new GraphQLError("Invalid input");
346
+ }
347
+
348
+ //#endregion
349
+ //#region src/utils/args.ts
350
+ function getOperationOptions(resolveOrOptions) {
351
+ if (typeof resolveOrOptions === "function") return { resolve: resolveOrOptions };
352
+ return resolveOrOptions;
353
+ }
354
+ function getSubscriptionOptions(subscribeOrOptions) {
355
+ if (typeof subscribeOrOptions === "function") return { subscribe: subscribeOrOptions };
356
+ return subscribeOrOptions;
357
+ }
358
+ function getFieldOptions({ description, deprecationReason, extensions }, extraExtensions) {
359
+ return {
360
+ description,
361
+ deprecationReason,
362
+ extensions: extraExtensions ? {
363
+ ...extensions,
364
+ ...extraExtensions
365
+ } : extensions
366
+ };
367
+ }
368
+
369
+ //#endregion
370
+ //#region src/utils/error.ts
371
+ function markErrorLocation(error, ...locations) {
372
+ if (error instanceof Error) error.message = markLocation(error.message, ...locations);
373
+ return error;
374
+ }
375
+ function tryIn(func, ...locations) {
376
+ try {
377
+ return func();
378
+ } catch (error) {
379
+ throw markErrorLocation(error, ...locations);
380
+ }
381
+ }
382
+ /**
383
+ * mark message with location
384
+ * @param message origin message
385
+ * @param locations where error happened
386
+ * @returns message with location
387
+ * @example markLocation("error", "banana") // "[banana] hello"
388
+ * @example markLocation("error", fruit, banana) // "[fruit.banana] error"
389
+ * @example markLocation("[banana] error", "fruit") // "[fruit.banana] error"
390
+ * @example markLocation("[fruit.banana] error", "favorite") // "[favorite.fruit.banana] error"
391
+ */
392
+ function markLocation(message, ...locations) {
393
+ if (locations.length === 0) return message;
394
+ const [existingPrefix, newMessage] = (() => {
395
+ const match = /^\[(.*?)\]/.exec(message);
396
+ if (match) return [match[1], message.slice(match[0].length).trim()];
397
+ return [void 0, message];
398
+ })();
399
+ return `[${locations.concat(existingPrefix ? [existingPrefix] : []).join(".")}] ${newMessage}`;
400
+ }
401
+
402
+ //#endregion
403
+ //#region src/utils/loader.ts
404
+ /**
405
+ * GraphQL Loom built-in data loader.
406
+ */
407
+ var LoomDataLoader = class LoomDataLoader {
408
+ results;
409
+ resolvers;
410
+ constructor() {
411
+ this.results = /* @__PURE__ */ new Map();
412
+ this.resolvers = /* @__PURE__ */ new Map();
413
+ }
414
+ /**
415
+ * Load data for a given key.
416
+ * @param key - The key to load data for.
417
+ * @returns A promise that resolves to the loaded data.
418
+ */
419
+ load(key) {
420
+ const existing = this.results.get(key);
421
+ if (existing) return existing;
422
+ const promise = new Promise((resolve, reject) => {
423
+ this.resolvers.set(key, [resolve, reject]);
424
+ this.nextTickBatchLoad();
425
+ });
426
+ this.results.set(key, promise);
427
+ return promise;
428
+ }
429
+ /**
430
+ * Clear the cache and reset the loader.
431
+ */
432
+ clear() {
433
+ this.results = /* @__PURE__ */ new Map();
434
+ this.resolvers = /* @__PURE__ */ new Map();
435
+ }
436
+ async executeBatchLoad() {
437
+ if (this.resolvers.size === 0) return;
438
+ const resolvers = this.resolvers;
439
+ this.resolvers = /* @__PURE__ */ new Map();
440
+ const keys = Array.from(resolvers.keys());
441
+ try {
442
+ const list = await this.batchLoad(keys);
443
+ for (let i = 0; i < list.length; i++) {
444
+ const data = list[i];
445
+ const [resolve, reject] = resolvers.get(keys[i]) ?? [];
446
+ if (data instanceof Error) reject?.(data);
447
+ else resolve?.(data);
448
+ }
449
+ } catch (error) {
450
+ for (const key of keys) {
451
+ const reject = resolvers.get(key)?.[1];
452
+ reject?.(error);
453
+ }
454
+ }
455
+ }
456
+ nextTickPromise;
457
+ nextTickBatchLoad() {
458
+ const load = async () => {
459
+ try {
460
+ while (this.resolvers.size > 0) {
461
+ await LoomDataLoader.nextTick();
462
+ await this.executeBatchLoad();
463
+ }
464
+ } finally {
465
+ this.nextTickPromise = void 0;
466
+ }
467
+ };
468
+ this.nextTickPromise ??= load();
469
+ return this.nextTickPromise;
470
+ }
471
+ static nextTick() {
472
+ return new Promise((resolve) => setTimeout(resolve));
473
+ }
474
+ };
475
+ var EasyDataLoader = class extends LoomDataLoader {
476
+ batchLoad(keys) {
477
+ return this.batchLoadFn(keys);
478
+ }
479
+ constructor(batchLoadFn) {
480
+ super();
481
+ this.batchLoadFn = batchLoadFn;
482
+ }
483
+ };
435
484
 
436
485
  //#endregion
437
- //#region src/resolver/silk.ts
438
- function silk(type, validate = (value) => ({ value: value ?? void 0 })) {
439
- return {
440
- [GET_GRAPHQL_TYPE]: typeof type === "function" ? type : () => type,
441
- "~standard": {
442
- version: 1,
443
- vendor: "gqloom.silk",
444
- validate
445
- }
486
+ //#region src/utils/middleware.ts
487
+ const defaultOperations = [
488
+ "field",
489
+ "mutation",
490
+ "query",
491
+ "subscription.subscribe"
492
+ ];
493
+ function applyMiddlewares(options, resolveFunction, middlewares) {
494
+ const next = (index) => {
495
+ if (index >= middlewares.length) return resolveFunction();
496
+ const middleware = middlewares[index];
497
+ return middleware(Object.assign(() => next(index + 1), {
498
+ ...options,
499
+ next: () => next(index + 1)
500
+ }));
446
501
  };
502
+ return next(0);
447
503
  }
448
- silk.parse = parseSilk;
449
- silk.getType = getGraphQLType;
450
- silk.nonNull = nonNullSilk;
451
- silk.list = listSilk;
452
- silk.nullable = nullableSilk;
453
- /**
454
- * Non-nullable Silk.
455
- */
456
- function nonNullSilk(origin) {
457
- return {
458
- ...origin,
459
- [GET_GRAPHQL_TYPE]: () => {
460
- const originType = getGraphQLType(origin);
461
- if (originType instanceof GraphQLNonNull) return originType;
462
- else return new GraphQLNonNull(originType);
463
- }
464
- };
504
+ function filterMiddlewares(operation, ...middlewareList) {
505
+ return middlewareList.reduce((acc, m) => {
506
+ if (!m) return acc;
507
+ acc.push(...ensureArray(m).filter((m$1) => {
508
+ return (m$1.operations ?? defaultOperations).includes(operation);
509
+ }));
510
+ return acc;
511
+ }, []);
465
512
  }
466
- /**
467
- * List Silk.
468
- */
469
- function listSilk(origin) {
470
- return {
471
- ...origin,
472
- [GET_GRAPHQL_TYPE]: () => {
473
- let originType = getGraphQLType(origin);
474
- if (originType instanceof GraphQLNonNull && originType.ofType instanceof GraphQLList) originType = originType.ofType.ofType;
475
- if (originType instanceof GraphQLList) originType = originType.ofType;
476
- return new GraphQLNonNull(new GraphQLList(originType));
477
- }
478
- };
513
+ function ensureArray(value) {
514
+ if (value != null && typeof value === "object" && Symbol.iterator in value) return Array.from(value);
515
+ return [value];
479
516
  }
517
+
518
+ //#endregion
519
+ //#region src/utils/object.ts
480
520
  /**
481
- * Nullable Silk.
521
+ * Creates an object map with the same keys as `map` and values generated by
522
+ * running each value of `record` thru `fn`.
482
523
  */
483
- function nullableSilk(origin) {
484
- return {
485
- ...origin,
486
- [GET_GRAPHQL_TYPE]: () => {
487
- const originType = getGraphQLType(origin);
488
- if (originType instanceof GraphQLNonNull) return originType.ofType;
489
- else return originType;
490
- }
491
- };
524
+ function mapValue(record, fn) {
525
+ const result = Object.create(null);
526
+ for (const key of Object.keys(record)) {
527
+ const value = fn(record[key], key);
528
+ if (value === SKIP) continue;
529
+ result[key] = value;
530
+ }
531
+ return result;
492
532
  }
493
- /**
494
- * Get GraphQL Output Type from Silk.
495
- * @param silk GraphQL Silk
496
- * @returns GraphQL Output Type
497
- */
498
- function getGraphQLType(silk$1) {
499
- if (GET_GRAPHQL_TYPE in silk$1 && silk$1[GET_GRAPHQL_TYPE] != null) return silk$1[GET_GRAPHQL_TYPE]();
500
- const vendorWeavers = weaverContext.vendorWeavers;
501
- if (vendorWeavers == null) throw new Error("Schema Weaver is not initialized");
502
- const weaver = vendorWeavers.get(silk$1["~standard"].vendor);
503
- if (weaver == null) throw new Error(`Schema Weaver for ${silk$1["~standard"].vendor} is not found`);
504
- return weaver.getGraphQLType(silk$1);
533
+ const SKIP = Symbol.for("mapValue.skip");
534
+ mapValue.SKIP = SKIP;
535
+ function toObjMap(obj) {
536
+ if (obj == null) return Object.create(null);
537
+ if (Object.getPrototypeOf(obj) === null) return obj;
538
+ const map = Object.create(null);
539
+ for (const [key, value] of Object.entries(obj)) map[key] = value;
540
+ return map;
541
+ }
542
+ function notNullish(x) {
543
+ return x != null;
544
+ }
545
+ function deepMerge(...objects) {
546
+ const result = {};
547
+ for (const obj of objects) {
548
+ if (obj == null) continue;
549
+ for (const [key, value] of Object.entries(obj)) if (value !== null && typeof value === "object") if (Array.isArray(value)) {
550
+ if (!Array.isArray(result[key])) result[key] = [];
551
+ result[key] = [...result[key], ...value];
552
+ } else result[key] = deepMerge(result[key], value);
553
+ else result[key] = value;
554
+ }
555
+ return result;
505
556
  }
506
557
  /**
507
- * Validate and transform input to output
508
- * @param silk silk GraphQL Silk
509
- * @param input
510
- * @returns output
558
+ * Wraps the provided data in an object with a single key `"~meta"`.
559
+ *
560
+ * @template T - The type of the data to be wrapped.
561
+ * @param {T} data - The data to be wrapped.
562
+ * @returns {{ "~meta": T }} - An object with a single key `"~meta"` containing the provided data.
563
+ * @example
564
+ * const originalData = { key: "value" };
565
+ * const metaData = meta(originalData);
566
+ * console.log(metaData); // Output: { "~meta": { key: "value" } }
511
567
  */
512
- function parseSilk(silk$1, input) {
513
- return silk$1["~standard"].validate(input);
514
- }
515
- function isSilk(target) {
516
- if (typeof target !== "object" && typeof target !== "function") return false;
517
- if (target == null) return false;
518
- if (GET_GRAPHQL_TYPE in target) return true;
519
- if (!("~standard" in target)) return false;
520
- return "vendor" in target["~standard"] && typeof target["~standard"].vendor === "string" && "version" in target["~standard"] && typeof target["~standard"].version === "number";
568
+ function meta(data) {
569
+ return { "~meta": data };
521
570
  }
522
571
 
523
572
  //#endregion
524
- //#region src/resolver/input.ts
525
- function createInputParser(schema, value) {
526
- let result;
527
- const parse = async () => {
528
- if (result !== void 0) return result;
529
- result = await parseInputValue(schema, value);
530
- return result;
531
- };
532
- Object.assign(parse, {
533
- schema,
534
- value
535
- });
536
- Object.defineProperty(parse, "result", {
537
- get: () => result,
538
- set: (value$1) => result = value$1
539
- });
540
- Object.defineProperty(parse, "getResult", { value: async () => getStandardValue(await parse()) });
541
- Object.defineProperty(parse, "setResult", { value: (value$1) => result = { value: value$1 } });
542
- Object.defineProperty(parse, "clearResult", { value: () => result = void 0 });
543
- return parse;
544
- }
545
- function parseInputValue(inputSchema, input) {
546
- if (inputSchema === void 0) return { value: input };
547
- if (isSilk(inputSchema)) return inputSchema["~standard"].validate(input);
548
- return parseInputEntries(inputSchema, input);
573
+ //#region src/utils/string.ts
574
+ function pascalCase(str) {
575
+ return str.split(/[\s-_]+/).map((word, index) => index === 0 ? word.charAt(0).toUpperCase() + word.slice(1) : word.charAt(0).toUpperCase() + word.slice(1)).join("");
549
576
  }
550
- async function parseInputEntries(inputSchema, input = {}) {
551
- const result = {};
552
- const issues = [];
553
- await Promise.all(Object.entries(inputSchema).map(async ([key, value]) => {
554
- const res = await value["~standard"].validate(input[key]);
555
- if ("value" in res) result[key] = res.value;
556
- if (res.issues) issues.push(...res.issues.slice());
557
- }));
558
- return {
559
- value: result,
560
- ...issues.length > 0 ? { issues } : null
561
- };
577
+ function capitalize(str) {
578
+ return str.slice(0, 1).toUpperCase() + str.slice(1);
562
579
  }
563
- function getStandardValue(result) {
564
- if (result == null) return result;
565
- const { issues } = result;
566
- if (issues?.length) throw new GraphQLError(issues?.[0]?.message ?? "Invalid input", { extensions: { issues } });
567
- if ("value" in result) return result.value;
568
- else throw new GraphQLError("Invalid input");
580
+ function screamingSnakeCase(str) {
581
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").split(/[\s-_]+/).map((word) => word.toUpperCase()).join("_");
569
582
  }
570
583
 
571
584
  //#endregion
@@ -1276,8 +1289,7 @@ function inputToArgs(input, options) {
1276
1289
  let inputType = getGraphQLType(input);
1277
1290
  if (isNonNullType(inputType)) inputType = inputType.ofType;
1278
1291
  if (isObjectType(inputType)) return mapValue(inputType.toConfig().fields, (it, key) => {
1279
- const fieldName = `${pascalCase(options.fieldName)}${pascalCase(key)}`;
1280
- return toInputFieldConfig(it, { fieldName });
1292
+ return toInputFieldConfig(it, { fieldName: `${pascalCase(options.fieldName)}${pascalCase(key)}` });
1281
1293
  });
1282
1294
  throw new Error(`Cannot convert ${inputType.toString()} to input type`);
1283
1295
  }
@@ -1286,7 +1298,7 @@ function inputToArgs(input, options) {
1286
1298
  tryIn(() => {
1287
1299
  const fieldName = `${pascalCase(options.fieldName)}${pascalCase(name)}`;
1288
1300
  args[name] = {
1289
- ...field$1,
1301
+ ...getGraphQLArgumentConfig(field$1),
1290
1302
  type: ensureInputType(field$1, { fieldName })
1291
1303
  };
1292
1304
  }, name);
@@ -1315,7 +1327,7 @@ function ensureInputObjectType(object, options) {
1315
1327
  if (isInputObjectType(object)) return object;
1316
1328
  const existing = weaverContext.inputMap?.get(object);
1317
1329
  if (existing != null) return existing;
1318
- const { astNode, extensionASTNodes, fields,...config } = object.toConfig();
1330
+ const { astNode: _1, extensionASTNodes: _2, fields,...config } = object.toConfig();
1319
1331
  let name = object.name;
1320
1332
  if (name === AUTO_ALIASING) name = `${pascalCase(options.fieldName)}Input`;
1321
1333
  name = (weaverContext.getConfig("gqloom.core.schema")?.getInputObjectName ?? ((n) => n))(name);
@@ -1528,8 +1540,7 @@ function extract(field$1) {
1528
1540
  };
1529
1541
  }
1530
1542
  function defineFieldMap(fields) {
1531
- const fieldMap = resolveObjMapThunk(fields);
1532
- return mapValue(fieldMap, (fieldConfig, fieldName) => {
1543
+ return mapValue(resolveObjMapThunk(fields), (fieldConfig, fieldName) => {
1533
1544
  const argsConfig = fieldConfig.args ?? {};
1534
1545
  return {
1535
1546
  name: assertName(fieldName),
@@ -1601,6 +1612,29 @@ function parentName(name) {
1601
1612
  return name;
1602
1613
  }
1603
1614
 
1615
+ //#endregion
1616
+ //#region src/schema/interface.ts
1617
+ function ensureInterfaceType(gqlType, interfaceConfig) {
1618
+ if (isInterfaceType(gqlType)) return gqlType;
1619
+ if (!isObjectType(gqlType)) throw new Error(`${gqlType.toString()} is not an object`);
1620
+ const key = gqlType;
1621
+ const existing = weaverContext.interfaceMap?.get(key);
1622
+ if (existing != null) return existing;
1623
+ const { astNode: _, extensionASTNodes: _1, fields,...config } = gqlType.toConfig();
1624
+ const interfaceType = new GraphQLInterfaceType({
1625
+ ...config,
1626
+ ...interfaceConfig,
1627
+ fields: mapValue(fields, (field$1) => {
1628
+ return {
1629
+ ...field$1,
1630
+ type: getCacheType(field$1.type)
1631
+ };
1632
+ })
1633
+ });
1634
+ weaverContext.interfaceMap?.set(key, interfaceType);
1635
+ return interfaceType;
1636
+ }
1637
+
1604
1638
  //#endregion
1605
1639
  //#region src/schema/schema-weaver.ts
1606
1640
  function isSchemaVendorWeaver(some) {
@@ -1654,8 +1688,7 @@ var GraphQLSchemaLoom = class GraphQLSchemaLoom {
1654
1688
  }
1655
1689
  addType(silk$1) {
1656
1690
  let gqlType = provideWeaverContext(() => {
1657
- const gqlType$1 = getGraphQLType(silk$1);
1658
- return getCacheType(gqlType$1);
1691
+ return getCacheType(getGraphQLType(silk$1));
1659
1692
  }, this.context);
1660
1693
  while (isNonNullType(gqlType) || isListType(gqlType)) gqlType = gqlType.ofType;
1661
1694
  this.types.add(gqlType);
@@ -1784,27 +1817,4 @@ var GraphQLSchemaLoom = class GraphQLSchemaLoom {
1784
1817
  const weave = GraphQLSchemaLoom.weave;
1785
1818
 
1786
1819
  //#endregion
1787
- //#region src/schema/interface.ts
1788
- function ensureInterfaceType(gqlType, interfaceConfig) {
1789
- if (isInterfaceType(gqlType)) return gqlType;
1790
- if (!isObjectType(gqlType)) throw new Error(`${gqlType.toString()} is not an object`);
1791
- const key = gqlType;
1792
- const existing = weaverContext.interfaceMap?.get(key);
1793
- if (existing != null) return existing;
1794
- const { astNode: _, extensionASTNodes: _1, fields,...config } = gqlType.toConfig();
1795
- const interfaceType = new GraphQLInterfaceType({
1796
- ...config,
1797
- ...interfaceConfig,
1798
- fields: mapValue(fields, (field$1) => {
1799
- return {
1800
- ...field$1,
1801
- type: getCacheType(field$1.type)
1802
- };
1803
- })
1804
- });
1805
- weaverContext.interfaceMap?.set(key, interfaceType);
1806
- return interfaceType;
1807
- }
1808
-
1809
- //#endregion
1810
- export { AUTO_ALIASING, BaseChainFactory, ChainResolver, DERIVED_DEPENDENCIES, EasyDataLoader, FieldChainFactory, FieldFactoryWithResolve, GlobalWeaverContext, GraphQLSchemaLoom, LoomDataLoader, LoomObjectType, MutationChainFactory, MutationFactoryWithResolve, OPERATION_OBJECT_NAMES, ObjectChainResolver, QueryChainFactory, QueryFactoryWithResolve, symbols_exports as SYMBOLS, SubscriptionChainFactory, WeaverContext, applyMiddlewares, assignContextMap, capitalize, collectName, collectNames, createField, createInputParser, createMutation, createQuery, createSubscription, deepMerge, defaultSubscriptionResolve, ensureInputObjectType, ensureInputType, ensureInterfaceType, field, filterMiddlewares, getCacheType, getDeepResolvingFields, getFieldOptions, getGraphQLType, getMemoizationMap, getOperationOptions, getResolvingFields, getStandardValue, getSubscriptionOptions, initWeaverContext, inputToArgs, isOnlyMemoryPayload, isSchemaVendorWeaver, isSilk, listSilk, loom, mapValue, markErrorLocation, markLocation, meta, mutation, nonNullSilk, notNullish, nullableSilk, onlyMemoization, parseInputValue, parseResolvingFields, parseSilk, pascalCase, provideWeaverContext, query, resolver, screamingSnakeCase, silk, subscription, toObjMap, tryIn, weave, weaverContext };
1820
+ export { AUTO_ALIASING, BaseChainFactory, ChainResolver, DERIVED_DEPENDENCIES, EasyDataLoader, FieldChainFactory, FieldFactoryWithResolve, GlobalWeaverContext, GraphQLSchemaLoom, LoomDataLoader, LoomObjectType, MutationChainFactory, MutationFactoryWithResolve, OPERATION_OBJECT_NAMES, ObjectChainResolver, QueryChainFactory, QueryFactoryWithResolve, symbols_exports as SYMBOLS, SubscriptionChainFactory, WeaverContext, applyMiddlewares, assignContextMap, capitalize, collectName, collectNames, createField, createInputParser, createMutation, createQuery, createSubscription, deepMerge, defaultSubscriptionResolve, ensureInputObjectType, ensureInputType, ensureInterfaceType, field, filterMiddlewares, getCacheType, getDeepResolvingFields, getFieldOptions, getGraphQLArgumentConfig, getGraphQLType, getMemoizationMap, getOperationOptions, getResolvingFields, getStandardValue, getSubscriptionOptions, initWeaverContext, inputToArgs, isOnlyMemoryPayload, isSchemaVendorWeaver, isSilk, listSilk, loom, mapValue, markErrorLocation, markLocation, meta, mutation, nonNullSilk, notNullish, nullableSilk, onlyMemoization, parseInputValue, parseResolvingFields, parseSilk, pascalCase, provideWeaverContext, query, resolver, screamingSnakeCase, silk, subscription, toObjMap, tryIn, weave, weaverContext };