@gqloom/core 0.8.4 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,453 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/context/index.ts
21
+ var context_exports = {};
22
+ __export(context_exports, {
23
+ ContextMemoization: () => ContextMemoization,
24
+ InjectableContext: () => InjectableContext,
25
+ asyncContextProvider: () => asyncContextProvider,
26
+ bindAsyncIterator: () => bindAsyncIterator,
27
+ createContext: () => createContext,
28
+ createMemoization: () => createMemoization,
29
+ isAsyncIterator: () => isAsyncIterator,
30
+ resolverPayloadStorage: () => resolverPayloadStorage,
31
+ useContext: () => useContext,
32
+ useMemoizationMap: () => useMemoizationMap,
33
+ useResolverPayload: () => useResolverPayload,
34
+ useResolvingFields: () => useResolvingFields
35
+ });
36
+ module.exports = __toCommonJS(context_exports);
37
+
38
+ // src/utils/parse-resolving-fields.ts
39
+ var import_graphql3 = require("graphql");
40
+
41
+ // src/utils/constants.ts
42
+ var DERIVED_DEPENDENCIES = "loom.derived-from-dependencies";
43
+
44
+ // src/utils/type.ts
45
+ var import_graphql = require("graphql");
46
+ var import_graphql2 = require("graphql");
47
+ function unwrapType(gqlType) {
48
+ if ((0, import_graphql2.isNonNullType)(gqlType)) {
49
+ return unwrapType(gqlType.ofType);
50
+ }
51
+ if ((0, import_graphql.isListType)(gqlType)) {
52
+ return unwrapType(gqlType.ofType);
53
+ }
54
+ return gqlType;
55
+ }
56
+
57
+ // src/utils/parse-resolving-fields.ts
58
+ function getResolvingFields(payload) {
59
+ const requestedFields = parseResolvingFields(payload.info);
60
+ const derivedFields = /* @__PURE__ */ new Set();
61
+ const derivedDependencies = /* @__PURE__ */ new Set();
62
+ const resolvingObject = unwrapType(payload.info.returnType);
63
+ if ((0, import_graphql3.isObjectType)(resolvingObject)) {
64
+ const objectFields = resolvingObject.getFields();
65
+ for (const requestedFieldName of requestedFields) {
66
+ const field = objectFields[requestedFieldName];
67
+ if (field) {
68
+ const deps = field.extensions?.[DERIVED_DEPENDENCIES];
69
+ if (deps && Array.isArray(deps) && deps.length > 0) {
70
+ derivedFields.add(requestedFieldName);
71
+ for (const d of deps) derivedDependencies.add(d);
72
+ }
73
+ }
74
+ }
75
+ }
76
+ const selectedFields = new Set(requestedFields);
77
+ for (const f of derivedFields) selectedFields.delete(f);
78
+ for (const d of derivedDependencies) selectedFields.add(d);
79
+ return { requestedFields, derivedFields, derivedDependencies, selectedFields };
80
+ }
81
+ function parseResolvingFields(info, maxDepth = 1) {
82
+ return new ResolvingFieldsParser(info, maxDepth).parse();
83
+ }
84
+ var ResolvingFieldsParser = class {
85
+ /** Store unique field paths */
86
+ fields = /* @__PURE__ */ new Set();
87
+ /** Track visited fragments to prevent circular references */
88
+ visitedFragments = /* @__PURE__ */ new Set();
89
+ /** The GraphQL resolve info object */
90
+ info;
91
+ /** Maximum depth of nested fields to parse */
92
+ maxDepth;
93
+ constructor(info, maxDepth) {
94
+ this.info = info;
95
+ this.maxDepth = maxDepth;
96
+ }
97
+ /**
98
+ * Parses the GraphQL resolve info to extract all requested fields.
99
+ * @returns A Set of field paths
100
+ */
101
+ parse() {
102
+ for (const fieldNode of this.info.fieldNodes) {
103
+ this.collectFields(fieldNode.selectionSet);
104
+ }
105
+ return this.fields;
106
+ }
107
+ /**
108
+ * Recursively collects fields from a selection set.
109
+ * Handles fields, inline fragments, and fragment spreads.
110
+ *
111
+ * @param selectionSet - The selection set to process
112
+ * @param parentPath - The path of the parent field (for nested fields)
113
+ * @param currentDepth - Current depth of recursion
114
+ */
115
+ collectFields(selectionSet, parentPath = "", currentDepth = 0) {
116
+ if (!selectionSet?.selections.length || currentDepth >= this.maxDepth)
117
+ return;
118
+ for (const selection of selectionSet.selections) {
119
+ if (!this.shouldIncludeNode(selection)) continue;
120
+ switch (selection.kind) {
121
+ case import_graphql3.Kind.FIELD: {
122
+ const fieldName = selection.name.value;
123
+ const fieldPath = parentPath ? `${parentPath}.${fieldName}` : fieldName;
124
+ this.fields.add(fieldPath);
125
+ const hasSelectionSet = selection.selectionSet != null;
126
+ if (hasSelectionSet) {
127
+ this.collectFields(
128
+ selection.selectionSet,
129
+ fieldPath,
130
+ currentDepth + 1
131
+ );
132
+ }
133
+ break;
134
+ }
135
+ case import_graphql3.Kind.INLINE_FRAGMENT: {
136
+ if (selection.selectionSet) {
137
+ this.collectFields(selection.selectionSet, parentPath, currentDepth);
138
+ }
139
+ break;
140
+ }
141
+ case import_graphql3.Kind.FRAGMENT_SPREAD: {
142
+ const fragmentName = selection.name.value;
143
+ if (this.visitedFragments.has(fragmentName)) continue;
144
+ this.visitedFragments.add(fragmentName);
145
+ const fragment = this.info.fragments[fragmentName];
146
+ if (fragment) {
147
+ this.collectFields(fragment.selectionSet, parentPath, currentDepth);
148
+ }
149
+ break;
150
+ }
151
+ }
152
+ }
153
+ }
154
+ /**
155
+ * Extracts the boolean value from a directive's 'if' argument.
156
+ * Handles both literal boolean values and variables.
157
+ *
158
+ * @param directive - The directive node to extract value from
159
+ * @returns The boolean value of the directive's condition
160
+ */
161
+ getDirectiveValue(directive) {
162
+ const ifArg = directive.arguments?.find(
163
+ (arg) => arg.name.value === "if"
164
+ );
165
+ if (!ifArg) return true;
166
+ const value = ifArg.value;
167
+ if (value.kind === import_graphql3.Kind.BOOLEAN) {
168
+ return value.value;
169
+ }
170
+ if (value.kind === import_graphql3.Kind.VARIABLE) {
171
+ const variableName = value.name.value;
172
+ const variableValue = this.info.variableValues?.[variableName];
173
+ return variableValue === true;
174
+ }
175
+ return true;
176
+ }
177
+ /**
178
+ * Determines if a selection node should be included based on its directives.
179
+ * Handles both @include and @skip directives.
180
+ *
181
+ * @param node - The selection node to check
182
+ * @returns Whether the node should be included
183
+ */
184
+ shouldIncludeNode(node) {
185
+ if (!node.directives?.length) return true;
186
+ return node.directives.every((directive) => {
187
+ const isIncludeDirective = directive.name.value === "include";
188
+ if (isIncludeDirective) {
189
+ return this.getDirectiveValue(directive);
190
+ }
191
+ if (directive.name.value === "skip") {
192
+ return !this.getDirectiveValue(directive);
193
+ }
194
+ return true;
195
+ });
196
+ }
197
+ };
198
+
199
+ // src/context/context.ts
200
+ var import_node_async_hooks = require("async_hooks");
201
+
202
+ // src/utils/symbols.ts
203
+ var GET_GRAPHQL_TYPE = Symbol.for("gqloom.get_graphql_type");
204
+ var WEAVER_CONFIG = Symbol.for("gqloom.weaver_config");
205
+ var RESOLVER_OPTIONS_KEY = Symbol.for("gqloom.resolver-options");
206
+ var IS_RESOLVER = Symbol.for("gqloom.is-resolver");
207
+ var CONTEXT_MAP_KEY = Symbol.for("gqloom.context-map");
208
+ var FIELD_HIDDEN = Symbol.for("gqloom.field-hidden");
209
+
210
+ // src/utils/context.ts
211
+ function onlyMemoization() {
212
+ return { memoization: /* @__PURE__ */ new WeakMap(), isMemoization: true };
213
+ }
214
+ function isOnlyMemoryPayload(payload) {
215
+ return payload.isMemoization === true;
216
+ }
217
+ function getMemoizationMap(payload) {
218
+ if (isOnlyMemoryPayload(payload)) return payload.memoization;
219
+ if (typeof payload.context === "undefined") {
220
+ Object.defineProperty(payload, "context", { value: {} });
221
+ }
222
+ return assignContextMap(payload.context);
223
+ }
224
+ function assignContextMap(target) {
225
+ target[CONTEXT_MAP_KEY] ??= /* @__PURE__ */ new WeakMap();
226
+ return target[CONTEXT_MAP_KEY];
227
+ }
228
+
229
+ // src/context/async-iterator.ts
230
+ function bindAsyncIterator(storage, generator) {
231
+ const store = storage.getStore();
232
+ const next = generator.next;
233
+ Object.defineProperty(generator, "next", {
234
+ value: (...args) => storage.run(store, () => next.apply(generator, args)),
235
+ writable: false
236
+ });
237
+ return generator;
238
+ }
239
+ function isAsyncIterator(value) {
240
+ return value !== null && typeof value === "object" && "next" in value && typeof value.next === "function";
241
+ }
242
+
243
+ // src/context/context.ts
244
+ var resolverPayloadStorage = new import_node_async_hooks.AsyncLocalStorage();
245
+ function useResolverPayload() {
246
+ const payload = resolverPayloadStorage.getStore();
247
+ if (payload === void 0 || isOnlyMemoryPayload(payload)) return;
248
+ return payload;
249
+ }
250
+ function useContext() {
251
+ return useResolverPayload()?.context;
252
+ }
253
+ function useMemoizationMap() {
254
+ const payload = resolverPayloadStorage.getStore();
255
+ if (payload == null) return;
256
+ return getMemoizationMap(payload);
257
+ }
258
+ var InjectableContext = class {
259
+ /**
260
+ * Creates a new instance of InjectableContext.
261
+ *
262
+ * @param getter - A function that returns the default value when no custom implementation is provided
263
+ * @param options - Optional configuration for the context
264
+ * @param options.getContextMap - A function that returns the WeakMap used to store context values. Defaults to useMemoizationMap
265
+ * @param options.key - A unique key used to identify this context in the WeakMap. Defaults to the getter function
266
+ */
267
+ constructor(getter, options = {}) {
268
+ this.getter = getter;
269
+ this.getter = getter;
270
+ this.getContextMap = options.getContextMap ?? useMemoizationMap;
271
+ this.key = options.key ?? this.getter;
272
+ }
273
+ /**
274
+ * A function that returns the WeakMap used to store context values.
275
+ * This can be customized to use different storage mechanisms.
276
+ */
277
+ getContextMap;
278
+ /**
279
+ * A unique key used to identify this context in the WeakMap.
280
+ * This is used to store and retrieve values from the context map.
281
+ */
282
+ key;
283
+ /**
284
+ * Retrieves the value from the context.
285
+ * If a custom implementation is provided, it will be used.
286
+ * Otherwise, the default getter function will be called.
287
+ *
288
+ * @returns The value of type T
289
+ */
290
+ get() {
291
+ const getter = this.getContextMap()?.get(this.key) ?? this.getter;
292
+ if (typeof getter === "function") return getter();
293
+ return getter;
294
+ }
295
+ /**
296
+ * Provides a new implementation for this context.
297
+ *
298
+ * @param getter - A function that returns the new value
299
+ * @returns A tuple containing the key and the new getter function
300
+ */
301
+ provide(getter) {
302
+ return [this.key, getter];
303
+ }
304
+ };
305
+ var ContextMemoization = class {
306
+ constructor(getter, options = {}) {
307
+ this.getter = getter;
308
+ this.getter = getter;
309
+ this.getContextMap = options.getContextMap ?? useMemoizationMap;
310
+ this.key = options.key ?? this.getter;
311
+ }
312
+ getContextMap;
313
+ key;
314
+ /**
315
+ * Get the value in memoization or call the getter function
316
+ * @returns the value of the getter function
317
+ */
318
+ get() {
319
+ const map = this.getContextMap();
320
+ if (!map) return this.getter();
321
+ if (!map.has(this.key)) {
322
+ map.set(this.key, this.getter());
323
+ }
324
+ return map.get(this.key);
325
+ }
326
+ /**
327
+ * Clear the memoization
328
+ * @returns true if the memoization is cleared, undefined if the context is not found
329
+ */
330
+ clear() {
331
+ const map = this.getContextMap();
332
+ if (!map) return;
333
+ return map.delete(this.key);
334
+ }
335
+ /**
336
+ * Check if the memoization exists
337
+ * @returns true if the memoization exists, undefined if the context is not found
338
+ */
339
+ exists() {
340
+ const map = this.getContextMap();
341
+ if (!map) return;
342
+ return map.has(this.key);
343
+ }
344
+ /**
345
+ * Set a new value to the memoization
346
+ * @param value the new value to set
347
+ * @returns the memoization map or undefined if the context is not found
348
+ */
349
+ set(value) {
350
+ const map = this.getContextMap();
351
+ if (!map) return;
352
+ return map.set(this.key, value);
353
+ }
354
+ provide(value) {
355
+ return [this.key, value];
356
+ }
357
+ };
358
+ function createContext(...args) {
359
+ const context = new InjectableContext(...args);
360
+ const callable = () => context.get();
361
+ Object.defineProperty(context, "key", {
362
+ value: callable,
363
+ writable: false,
364
+ configurable: false
365
+ });
366
+ return Object.assign(callable, {
367
+ key: context.key,
368
+ get: () => context.get(),
369
+ provide: (getter) => context.provide(getter),
370
+ getContextMap: () => context.getContextMap(),
371
+ getter: context.getter
372
+ });
373
+ }
374
+ function createMemoization(...args) {
375
+ const memoization = new ContextMemoization(...args);
376
+ const callable = () => memoization.get();
377
+ Object.defineProperty(memoization, "key", {
378
+ value: callable,
379
+ writable: false,
380
+ configurable: false
381
+ });
382
+ return Object.assign(callable, {
383
+ key: memoization.key,
384
+ get: () => memoization.get(),
385
+ set: (value) => memoization.set(value),
386
+ clear: () => memoization.clear(),
387
+ exists: () => memoization.exists(),
388
+ getter: memoization.getter,
389
+ provide: (value) => memoization.provide(value),
390
+ getContextMap: () => memoization.getContextMap()
391
+ });
392
+ }
393
+ var createProvider = (...keyValues) => {
394
+ return ({ next, payload, operation }) => {
395
+ const store = payload ?? onlyMemoization();
396
+ const map = getMemoizationMap(store);
397
+ if (map) {
398
+ for (const [key, value] of keyValues) {
399
+ map.set(key, value);
400
+ }
401
+ }
402
+ if (operation === "subscription.subscribe") {
403
+ return resolverPayloadStorage.run(store, async () => {
404
+ let result = await next();
405
+ if (isAsyncIterator(result)) {
406
+ result = bindAsyncIterator(resolverPayloadStorage, result);
407
+ }
408
+ return result;
409
+ });
410
+ }
411
+ return resolverPayloadStorage.run(store, next);
412
+ };
413
+ };
414
+ var asyncContextProvider = Object.assign(
415
+ createProvider(),
416
+ {
417
+ operations: [
418
+ "query",
419
+ "mutation",
420
+ "field",
421
+ "subscription.resolve",
422
+ "subscription.subscribe",
423
+ "resolveReference"
424
+ ],
425
+ with: (...keyValues) => {
426
+ return createProvider(...keyValues);
427
+ }
428
+ }
429
+ );
430
+
431
+ // src/context/use-resolving-fields.ts
432
+ var useResolvingFields = createContext(
433
+ () => {
434
+ const payload = useResolverPayload();
435
+ if (!payload) return;
436
+ return getResolvingFields(payload);
437
+ }
438
+ );
439
+ // Annotate the CommonJS export names for ESM import in node:
440
+ 0 && (module.exports = {
441
+ ContextMemoization,
442
+ InjectableContext,
443
+ asyncContextProvider,
444
+ bindAsyncIterator,
445
+ createContext,
446
+ createMemoization,
447
+ isAsyncIterator,
448
+ resolverPayloadStorage,
449
+ useContext,
450
+ useMemoizationMap,
451
+ useResolverPayload,
452
+ useResolvingFields
453
+ });
@@ -0,0 +1,137 @@
1
+ import { P as OnlyMemoizationPayload, R as ResolverPayload, B as BaseField, v as Middleware, K as ResolvingFields } from './context-DsvT0-C6.cjs';
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+ import 'graphql';
4
+
5
+ /**
6
+ * the AsyncLocalStorage instance to store the resolver payload
7
+ */
8
+ declare const resolverPayloadStorage: AsyncLocalStorage<OnlyMemoizationPayload | ResolverPayload<object, BaseField>>;
9
+ /**
10
+ * use detailed payload of the current resolver
11
+ * @returns the resolver payload
12
+ */
13
+ declare function useResolverPayload(): ResolverPayload | undefined;
14
+ /**
15
+ * use context of the current resolver
16
+ * @returns the context of the current resolver
17
+ */
18
+ declare function useContext<TContextType = object>(): TContextType;
19
+ /**
20
+ * use the MemoizationMap of the current context
21
+ */
22
+ declare function useMemoizationMap(): WeakMap<WeakKey, any> | undefined;
23
+ interface ContextOptions {
24
+ getContextMap: () => WeakMap<WeakKey, any> | undefined;
25
+ key: WeakKey;
26
+ }
27
+ /**
28
+ * A class that provides dependency injection and context sharing capabilities.
29
+ * It allows you to create injectable dependencies that can be shared across different parts of your application.
30
+ *
31
+ * @template T The type of the value that will be injected
32
+ *
33
+ */
34
+ declare class InjectableContext<T> implements ContextOptions {
35
+ readonly getter: () => T;
36
+ /**
37
+ * Creates a new instance of InjectableContext.
38
+ *
39
+ * @param getter - A function that returns the default value when no custom implementation is provided
40
+ * @param options - Optional configuration for the context
41
+ * @param options.getContextMap - A function that returns the WeakMap used to store context values. Defaults to useMemoizationMap
42
+ * @param options.key - A unique key used to identify this context in the WeakMap. Defaults to the getter function
43
+ */
44
+ constructor(getter: () => T, options?: Partial<ContextOptions>);
45
+ /**
46
+ * A function that returns the WeakMap used to store context values.
47
+ * This can be customized to use different storage mechanisms.
48
+ */
49
+ getContextMap: () => WeakMap<WeakKey, any> | undefined;
50
+ /**
51
+ * A unique key used to identify this context in the WeakMap.
52
+ * This is used to store and retrieve values from the context map.
53
+ */
54
+ readonly key: WeakKey;
55
+ /**
56
+ * Retrieves the value from the context.
57
+ * If a custom implementation is provided, it will be used.
58
+ * Otherwise, the default getter function will be called.
59
+ *
60
+ * @returns The value of type T
61
+ */
62
+ get(): T;
63
+ /**
64
+ * Provides a new implementation for this context.
65
+ *
66
+ * @param getter - A function that returns the new value
67
+ * @returns A tuple containing the key and the new getter function
68
+ */
69
+ provide(getter: () => T): [WeakKey, () => T];
70
+ }
71
+ /**
72
+ * Create a memoization in context to store the result of a getter function
73
+ */
74
+ declare class ContextMemoization<T> implements ContextOptions {
75
+ readonly getter: () => T;
76
+ constructor(getter: () => T, options?: Partial<ContextOptions>);
77
+ getContextMap: () => WeakMap<WeakKey, any> | undefined;
78
+ readonly key: WeakKey;
79
+ /**
80
+ * Get the value in memoization or call the getter function
81
+ * @returns the value of the getter function
82
+ */
83
+ get(): T;
84
+ /**
85
+ * Clear the memoization
86
+ * @returns true if the memoization is cleared, undefined if the context is not found
87
+ */
88
+ clear(): boolean | undefined;
89
+ /**
90
+ * Check if the memoization exists
91
+ * @returns true if the memoization exists, undefined if the context is not found
92
+ */
93
+ exists(): boolean | undefined;
94
+ /**
95
+ * Set a new value to the memoization
96
+ * @param value the new value to set
97
+ * @returns the memoization map or undefined if the context is not found
98
+ */
99
+ set(value: T): WeakMap<WeakKey, any> | undefined;
100
+ provide(value: T): [WeakKey, T];
101
+ }
102
+ interface CallableContext<T> extends InjectableContext<T> {
103
+ (): T;
104
+ }
105
+ /**
106
+ * Create a callable context
107
+ * @param args - The arguments to pass to the InjectableContext constructor
108
+ * @returns A callable context
109
+ */
110
+ declare function createContext<T>(...args: ConstructorParameters<typeof InjectableContext<T>>): CallableContext<T>;
111
+ /**
112
+ * Async Memoization with a callable function
113
+ */
114
+ interface CallableContextMemoization<T> extends ContextMemoization<T> {
115
+ (): T;
116
+ }
117
+ /**
118
+ * Create a memoization in context to store the result of a getter function
119
+ */
120
+ declare function createMemoization<T>(...args: ConstructorParameters<typeof ContextMemoization<T>>): CallableContextMemoization<T>;
121
+ interface AsyncContextProvider extends Middleware {
122
+ with: (...keyValues: [WeakKey, any][]) => Middleware;
123
+ }
124
+ declare const asyncContextProvider: AsyncContextProvider;
125
+
126
+ /**
127
+ * A hook that analyzes and processes field resolution in a GraphQL query.
128
+ *
129
+ * @returns An object containing sets of different field types,
130
+ * or undefined if no resolver payload is available
131
+ */
132
+ declare const useResolvingFields: CallableContext<ResolvingFields | undefined>;
133
+
134
+ declare function bindAsyncIterator<TAsyncLocalStorage extends AsyncLocalStorage<unknown>, TAsyncIterator extends AsyncIterator<unknown, unknown, unknown>>(storage: TAsyncLocalStorage, generator: TAsyncIterator): TAsyncIterator;
135
+ declare function isAsyncIterator(value: unknown): value is AsyncIterator<unknown, unknown, unknown>;
136
+
137
+ export { type AsyncContextProvider, type CallableContext, type CallableContextMemoization, ContextMemoization, InjectableContext, asyncContextProvider, bindAsyncIterator, createContext, createMemoization, isAsyncIterator, resolverPayloadStorage, useContext, useMemoizationMap, useResolverPayload, useResolvingFields };