graphql-modules 3.1.2-alpha-20260121023952-c6236f99446644c787494ddb1a9a973180bab70e → 3.1.2-alpha-20260121024633-8af430e29a180a1d00c50c4bf74d342b3518267c

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.
Files changed (161) hide show
  1. package/cjs/application/apollo.js +81 -0
  2. package/cjs/application/application.js +149 -0
  3. package/cjs/application/context.js +144 -0
  4. package/cjs/application/di.js +48 -0
  5. package/cjs/application/execution.js +42 -0
  6. package/cjs/application/operation-controller.js +16 -0
  7. package/cjs/application/subscription.js +54 -0
  8. package/cjs/application/tokens.js +20 -0
  9. package/cjs/application/types.js +0 -0
  10. package/cjs/di/decorators.js +78 -0
  11. package/cjs/di/errors.js +87 -0
  12. package/cjs/di/forward-ref.js +26 -0
  13. package/cjs/di/index.js +19 -0
  14. package/cjs/di/injector.js +173 -0
  15. package/cjs/di/metadata.js +22 -0
  16. package/cjs/di/providers.js +60 -0
  17. package/cjs/di/registry.js +44 -0
  18. package/cjs/di/resolution.js +166 -0
  19. package/cjs/di/utils.js +44 -0
  20. package/cjs/index.js +31 -0
  21. package/cjs/module/factory.js +71 -0
  22. package/cjs/module/metadata.js +110 -0
  23. package/cjs/module/module.js +27 -0
  24. package/cjs/module/resolvers.js +341 -0
  25. package/cjs/module/tokens.js +21 -0
  26. package/cjs/module/type-defs.js +24 -0
  27. package/cjs/module/types.js +0 -0
  28. package/cjs/package.json +1 -0
  29. package/cjs/shared/di.js +0 -0
  30. package/cjs/shared/errors.js +82 -0
  31. package/cjs/shared/gql.js +12 -0
  32. package/cjs/shared/middleware.js +109 -0
  33. package/cjs/shared/types.js +0 -0
  34. package/cjs/shared/utils.js +115 -0
  35. package/cjs/testing/di.js +9 -0
  36. package/cjs/testing/graphql.js +10 -0
  37. package/cjs/testing/index.js +17 -0
  38. package/cjs/testing/test-application.js +65 -0
  39. package/cjs/testing/test-injector.js +22 -0
  40. package/cjs/testing/test-module.js +270 -0
  41. package/esm/application/apollo.js +77 -0
  42. package/esm/application/application.js +146 -0
  43. package/esm/application/context.js +140 -0
  44. package/esm/application/di.js +42 -0
  45. package/esm/application/execution.js +39 -0
  46. package/esm/application/operation-controller.js +13 -0
  47. package/esm/application/subscription.js +51 -0
  48. package/esm/application/tokens.js +17 -0
  49. package/esm/application/types.js +0 -0
  50. package/esm/di/decorators.js +72 -0
  51. package/esm/di/errors.js +79 -0
  52. package/esm/di/forward-ref.js +22 -0
  53. package/esm/di/index.js +4 -0
  54. package/esm/di/injector.js +168 -0
  55. package/esm/di/metadata.js +17 -0
  56. package/esm/di/providers.js +50 -0
  57. package/esm/di/registry.js +40 -0
  58. package/esm/di/resolution.js +159 -0
  59. package/esm/di/utils.js +36 -0
  60. package/esm/index.js +16 -0
  61. package/esm/module/factory.js +68 -0
  62. package/esm/module/metadata.js +107 -0
  63. package/esm/module/module.js +24 -0
  64. package/esm/module/resolvers.js +337 -0
  65. package/esm/module/tokens.js +18 -0
  66. package/esm/module/type-defs.js +21 -0
  67. package/esm/module/types.js +0 -0
  68. package/esm/shared/di.js +0 -0
  69. package/esm/shared/errors.js +69 -0
  70. package/esm/shared/gql.js +9 -0
  71. package/esm/shared/middleware.js +103 -0
  72. package/esm/shared/types.js +0 -0
  73. package/esm/shared/utils.js +101 -0
  74. package/esm/testing/di.js +6 -0
  75. package/esm/testing/graphql.js +7 -0
  76. package/esm/testing/index.js +14 -0
  77. package/esm/testing/test-application.js +62 -0
  78. package/esm/testing/test-injector.js +18 -0
  79. package/esm/testing/test-module.js +266 -0
  80. package/package.json +29 -9
  81. package/typings/application/apollo.d.ts +22 -0
  82. package/typings/application/application.d.ts +32 -0
  83. package/typings/application/context.d.ts +24 -0
  84. package/typings/application/di.d.ts +22 -0
  85. package/typings/application/execution.d.ts +8 -0
  86. package/typings/application/operation-controller.d.ts +5 -0
  87. package/typings/application/subscription.d.ts +8 -0
  88. package/typings/application/tokens.d.ts +17 -0
  89. package/typings/application/types.d.ts +130 -0
  90. package/typings/di/decorators.d.ts +11 -0
  91. package/typings/di/errors.d.ts +16 -0
  92. package/typings/di/forward-ref.d.ts +7 -0
  93. package/typings/di/index.d.ts +5 -0
  94. package/typings/di/injector.d.ts +50 -0
  95. package/typings/di/metadata.d.ts +12 -0
  96. package/typings/di/providers.d.ts +44 -0
  97. package/typings/di/registry.d.ts +11 -0
  98. package/typings/di/resolution.d.ts +63 -0
  99. package/typings/di/utils.d.ts +8 -0
  100. package/typings/index.d.ts +13 -0
  101. package/typings/module/factory.d.ts +16 -0
  102. package/typings/module/metadata.d.ts +12 -0
  103. package/typings/module/module.d.ts +22 -0
  104. package/typings/module/resolvers.d.ts +13 -0
  105. package/typings/module/tokens.d.ts +18 -0
  106. package/typings/module/type-defs.d.ts +7 -0
  107. package/typings/module/types.d.ts +51 -0
  108. package/typings/shared/di.d.ts +3 -0
  109. package/typings/shared/errors.d.ts +36 -0
  110. package/typings/shared/gql.d.ts +2 -0
  111. package/typings/shared/middleware.d.ts +21 -0
  112. package/typings/shared/types.d.ts +22 -0
  113. package/typings/shared/utils.d.ts +12 -0
  114. package/typings/testing/di.d.ts +2 -0
  115. package/typings/testing/graphql.d.ts +14 -0
  116. package/typings/testing/index.d.ts +14 -0
  117. package/typings/testing/test-application.d.ts +2 -0
  118. package/typings/testing/test-injector.d.ts +4 -0
  119. package/typings/testing/test-module.d.ts +10 -0
  120. package/LICENSE.md +0 -21
  121. package/index.js +0 -2359
  122. package/index.mjs +0 -2344
  123. /package/{application/apollo.d.ts → typings/application/apollo.d.cts} +0 -0
  124. /package/{application/application.d.ts → typings/application/application.d.cts} +0 -0
  125. /package/{application/context.d.ts → typings/application/context.d.cts} +0 -0
  126. /package/{application/di.d.ts → typings/application/di.d.cts} +0 -0
  127. /package/{application/execution.d.ts → typings/application/execution.d.cts} +0 -0
  128. /package/{application/operation-controller.d.ts → typings/application/operation-controller.d.cts} +0 -0
  129. /package/{application/subscription.d.ts → typings/application/subscription.d.cts} +0 -0
  130. /package/{application/tokens.d.ts → typings/application/tokens.d.cts} +0 -0
  131. /package/{application/types.d.ts → typings/application/types.d.cts} +0 -0
  132. /package/{di/decorators.d.ts → typings/di/decorators.d.cts} +0 -0
  133. /package/{di/errors.d.ts → typings/di/errors.d.cts} +0 -0
  134. /package/{di/forward-ref.d.ts → typings/di/forward-ref.d.cts} +0 -0
  135. /package/{di/index.d.ts → typings/di/index.d.cts} +0 -0
  136. /package/{di/injector.d.ts → typings/di/injector.d.cts} +0 -0
  137. /package/{di/metadata.d.ts → typings/di/metadata.d.cts} +0 -0
  138. /package/{di/providers.d.ts → typings/di/providers.d.cts} +0 -0
  139. /package/{di/registry.d.ts → typings/di/registry.d.cts} +0 -0
  140. /package/{di/resolution.d.ts → typings/di/resolution.d.cts} +0 -0
  141. /package/{di/utils.d.ts → typings/di/utils.d.cts} +0 -0
  142. /package/{index.d.ts → typings/index.d.cts} +0 -0
  143. /package/{module/factory.d.ts → typings/module/factory.d.cts} +0 -0
  144. /package/{module/metadata.d.ts → typings/module/metadata.d.cts} +0 -0
  145. /package/{module/module.d.ts → typings/module/module.d.cts} +0 -0
  146. /package/{module/resolvers.d.ts → typings/module/resolvers.d.cts} +0 -0
  147. /package/{module/tokens.d.ts → typings/module/tokens.d.cts} +0 -0
  148. /package/{module/type-defs.d.ts → typings/module/type-defs.d.cts} +0 -0
  149. /package/{module/types.d.ts → typings/module/types.d.cts} +0 -0
  150. /package/{shared/di.d.ts → typings/shared/di.d.cts} +0 -0
  151. /package/{shared/errors.d.ts → typings/shared/errors.d.cts} +0 -0
  152. /package/{shared/gql.d.ts → typings/shared/gql.d.cts} +0 -0
  153. /package/{shared/middleware.d.ts → typings/shared/middleware.d.cts} +0 -0
  154. /package/{shared/types.d.ts → typings/shared/types.d.cts} +0 -0
  155. /package/{shared/utils.d.ts → typings/shared/utils.d.cts} +0 -0
  156. /package/{testing/di.d.ts → typings/testing/di.d.cts} +0 -0
  157. /package/{testing/graphql.d.ts → typings/testing/graphql.d.cts} +0 -0
  158. /package/{testing/index.d.ts → typings/testing/index.d.cts} +0 -0
  159. /package/{testing/test-application.d.ts → typings/testing/test-application.d.cts} +0 -0
  160. /package/{testing/test-injector.d.ts → typings/testing/test-injector.d.cts} +0 -0
  161. /package/{testing/test-module.d.ts → typings/testing/test-module.d.cts} +0 -0
package/index.mjs DELETED
@@ -1,2344 +0,0 @@
1
- import { makeExecutableSchema } from '@graphql-tools/schema';
2
- import { GraphQLSchema, execute as execute$1, subscribe, visit, Kind, concatAST, defaultFieldResolver, GraphQLScalarType, parse } from 'graphql';
3
- import async_context from '#async-context';
4
- import { wrapSchema } from '@graphql-tools/wrap';
5
- import { mergeDeepWith } from 'ramda';
6
-
7
- const ERROR_ORIGINAL_ERROR = 'diOriginalError';
8
- function getOriginalError(error) {
9
- return error[ERROR_ORIGINAL_ERROR];
10
- }
11
- function wrappedError(message, originalError) {
12
- const msg = `${message} caused by: ${originalError instanceof Error ? originalError.message : originalError}`;
13
- const error = Error(msg);
14
- error[ERROR_ORIGINAL_ERROR] = originalError;
15
- return error;
16
- }
17
- function stringify(token) {
18
- if (typeof token === 'string') {
19
- return token;
20
- }
21
- if (token == null) {
22
- return '' + token;
23
- }
24
- if (token.name) {
25
- return `${token.name}`;
26
- }
27
- const res = token.toString();
28
- const newLineIndex = res.indexOf('\n');
29
- return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
30
- }
31
-
32
- function invalidProviderError(provider) {
33
- return Error(`Invalid provider - only instances of Provider and Type are allowed, got: ${provider}`);
34
- }
35
- function noInjectableError(type) {
36
- return Error(`Missing @Injectable decorator for '${stringify(type)}'`);
37
- }
38
- function noAnnotationError(typeOrFunc, params) {
39
- const signature = [];
40
- for (let i = 0, len = params.length; i < len; i++) {
41
- const parameter = params[i];
42
- if (!parameter.type) {
43
- signature.push('?');
44
- }
45
- else {
46
- signature.push(stringify(parameter.type));
47
- }
48
- }
49
- return Error("Cannot resolve all parameters for '" +
50
- stringify(typeOrFunc) +
51
- "'(" +
52
- signature.join(', ') +
53
- '). ' +
54
- "Make sure that all the parameters are decorated with Inject or have valid type annotations and that '" +
55
- stringify(typeOrFunc) +
56
- "' is decorated with Injectable.");
57
- }
58
- function cyclicDependencyError(injector, key) {
59
- return injectionError(injector, key, function () {
60
- return `Cannot instantiate cyclic dependency!${constructResolvingPath(this.keys)}`;
61
- });
62
- }
63
- function noProviderError(injector, key) {
64
- return injectionError(injector, key, function () {
65
- const first = stringify(this.keys[0].token);
66
- return `No provider for ${first}!${constructResolvingPath(this.keys)}`;
67
- });
68
- }
69
- function instantiationError(injector, originalException, key) {
70
- return injectionError(injector, key, function () {
71
- const first = stringify(this.keys[0].token);
72
- return `Error during instantiation of ${first}: ${getOriginalError(this).message}${constructResolvingPath(this.keys)}`;
73
- }, originalException);
74
- }
75
- function injectionError(injector, key, constructResolvingMessage, originalError) {
76
- const error = (originalError ? wrappedError('', originalError) : Error());
77
- error.addKey = addKey;
78
- error.keys = [key];
79
- error.constructResolvingMessage =
80
- function wrappedConstructResolvingMessage() {
81
- return (constructResolvingMessage.call(this) + ` - in ${injector.displayName}`);
82
- };
83
- error.message = error.constructResolvingMessage();
84
- error[ERROR_ORIGINAL_ERROR] = originalError;
85
- return error;
86
- }
87
- function constructResolvingPath(keys) {
88
- if (keys.length > 1) {
89
- const reversed = findFirstClosedCycle(keys.slice().reverse());
90
- const tokenStrs = reversed.map((k) => stringify(k.token));
91
- return ' (' + tokenStrs.join(' -> ') + ')';
92
- }
93
- return '';
94
- }
95
- function findFirstClosedCycle(keys) {
96
- const res = [];
97
- for (let i = 0; i < keys.length; ++i) {
98
- if (res.indexOf(keys[i]) > -1) {
99
- res.push(keys[i]);
100
- return res;
101
- }
102
- res.push(keys[i]);
103
- }
104
- return res;
105
- }
106
- function addKey(key) {
107
- this.keys.push(key);
108
- this.message = this.constructResolvingMessage();
109
- }
110
-
111
- const INJECTABLE = Symbol('di:injectable');
112
- function readInjectableMetadata(type, throwOnMissing) {
113
- const meta = type[INJECTABLE];
114
- if (!meta && throwOnMissing) {
115
- throw noInjectableError(type);
116
- }
117
- return meta;
118
- }
119
- function ensureInjectableMetadata(type) {
120
- if (!readInjectableMetadata(type)) {
121
- const meta = {
122
- params: [],
123
- };
124
- type[INJECTABLE] = meta;
125
- }
126
- }
127
-
128
- const Type = Function;
129
- /// @ts-ignore
130
- class InjectionToken {
131
- constructor(_desc) {
132
- this._desc = _desc;
133
- }
134
- toString() {
135
- return `InjectionToken ${this._desc}`;
136
- }
137
- }
138
- function isType(v) {
139
- return typeof v === 'function' && v !== Object;
140
- }
141
- var Scope;
142
- (function (Scope) {
143
- Scope[Scope["Singleton"] = 0] = "Singleton";
144
- Scope[Scope["Operation"] = 1] = "Operation";
145
- })(Scope || (Scope = {}));
146
- function onlySingletonProviders(providers = []) {
147
- return providers.filter((provider) => {
148
- if (isType(provider)) {
149
- const { options } = readInjectableMetadata(provider, true);
150
- return (options === null || options === void 0 ? void 0 : options.scope) !== Scope.Operation;
151
- }
152
- else {
153
- return provider.scope !== Scope.Operation;
154
- }
155
- });
156
- }
157
- function onlyOperationProviders(providers = []) {
158
- return providers.filter((provider) => {
159
- if (isType(provider)) {
160
- const { options } = readInjectableMetadata(provider, true);
161
- return (options === null || options === void 0 ? void 0 : options.scope) === Scope.Operation;
162
- }
163
- else {
164
- return provider.scope === Scope.Operation;
165
- }
166
- });
167
- }
168
- function isClassProvider(provider) {
169
- return typeof provider.useClass !== 'undefined';
170
- }
171
- function isFactoryProvider(provider) {
172
- return typeof provider.useFactory !== 'undefined';
173
- }
174
-
175
- function ensureReflect() {
176
- if (!(Reflect && Reflect.getOwnMetadata)) {
177
- throw 'reflect-metadata shim is required when using class decorators';
178
- }
179
- }
180
- function Injectable(options) {
181
- return (target) => {
182
- var _a;
183
- ensureReflect();
184
- const params = (Reflect.getMetadata('design:paramtypes', target) || []).map((param) => (isType(param) ? param : null));
185
- const existingMeta = readInjectableMetadata(target);
186
- const meta = {
187
- params: ((_a = existingMeta === null || existingMeta === void 0 ? void 0 : existingMeta.params) === null || _a === void 0 ? void 0 : _a.length) > 0 && params.length === 0
188
- ? existingMeta === null || existingMeta === void 0 ? void 0 : existingMeta.params
189
- : params.map((param, i) => {
190
- var _a;
191
- const existingParam = (_a = existingMeta === null || existingMeta === void 0 ? void 0 : existingMeta.params) === null || _a === void 0 ? void 0 : _a[i];
192
- return {
193
- type: (existingParam === null || existingParam === void 0 ? void 0 : existingParam.type) || param,
194
- optional: typeof (existingParam === null || existingParam === void 0 ? void 0 : existingParam.optional) === 'boolean'
195
- ? existingParam.optional
196
- : false,
197
- };
198
- }),
199
- options: {
200
- ...((existingMeta === null || existingMeta === void 0 ? void 0 : existingMeta.options) || {}),
201
- ...(options || {}),
202
- },
203
- };
204
- target[INJECTABLE] = meta;
205
- return target;
206
- };
207
- }
208
- function Optional() {
209
- return (target, _, index) => {
210
- ensureReflect();
211
- ensureInjectableMetadata(target);
212
- const meta = readInjectableMetadata(target);
213
- meta.params[index] = {
214
- ...meta.params[index],
215
- optional: true,
216
- };
217
- };
218
- }
219
- function Inject(type) {
220
- return (target, _, index) => {
221
- ensureReflect();
222
- ensureInjectableMetadata(target);
223
- const meta = readInjectableMetadata(target);
224
- meta.params[index] = {
225
- type,
226
- optional: false,
227
- };
228
- };
229
- }
230
- function ExecutionContext() {
231
- return (obj, propertyKey) => {
232
- ensureReflect();
233
- const target = obj.constructor;
234
- ensureInjectableMetadata(target);
235
- const meta = readInjectableMetadata(target);
236
- if (!meta.options) {
237
- meta.options = {};
238
- }
239
- if (!meta.options.executionContextIn) {
240
- meta.options.executionContextIn = [];
241
- }
242
- meta.options.executionContextIn.push(propertyKey);
243
- };
244
- }
245
-
246
- const forwardRefSymbol = Symbol('__forward_ref__');
247
- /**
248
- * Useful in "circular dependencies of modules" situation
249
- */
250
- function forwardRef(forwardRefFn) {
251
- forwardRefFn[forwardRefSymbol] = forwardRef;
252
- forwardRefFn.toString = function () {
253
- return stringify(this());
254
- };
255
- return forwardRefFn;
256
- }
257
- function resolveForwardRef(type) {
258
- if (typeof type === 'function' &&
259
- type.hasOwnProperty(forwardRefSymbol) &&
260
- type[forwardRefSymbol] === forwardRef) {
261
- return type();
262
- }
263
- else {
264
- return type;
265
- }
266
- }
267
-
268
- class Key {
269
- constructor(token, id) {
270
- this.token = token;
271
- this.id = id;
272
- if (!token) {
273
- throw new Error('Token must be defined!');
274
- }
275
- }
276
- /**
277
- * Returns a stringified token.
278
- */
279
- get displayName() {
280
- return stringify(this.token);
281
- }
282
- static get(token) {
283
- return _globalKeyRegistry.get(resolveForwardRef(token));
284
- }
285
- }
286
- class GlobalKeyRegistry {
287
- constructor() {
288
- this._allKeys = new Map();
289
- }
290
- get(token) {
291
- if (token instanceof Key) {
292
- return token;
293
- }
294
- if (this._allKeys.has(token)) {
295
- return this._allKeys.get(token);
296
- }
297
- const newKey = new Key(token, _globalKeyRegistry.numberOfKeys);
298
- this._allKeys.set(token, newKey);
299
- return newKey;
300
- }
301
- get numberOfKeys() {
302
- return this._allKeys.size;
303
- }
304
- }
305
- const _globalKeyRegistry = new GlobalKeyRegistry();
306
-
307
- const _EMPTY_LIST = [];
308
- class ResolvedProvider {
309
- constructor(key, factory) {
310
- this.key = key;
311
- this.factory = factory;
312
- }
313
- }
314
- class ResolvedFactory {
315
- constructor(
316
- /**
317
- * Factory function which can return an instance of an object represented by a key.
318
- */
319
- factory,
320
- /**
321
- * Arguments (dependencies) to the `factory` function.
322
- */
323
- dependencies,
324
- /**
325
- * Methods invoked within ExecutionContext.
326
- */
327
- executionContextIn,
328
- /**
329
- * Has onDestroy hook
330
- */
331
- hasOnDestroyHook,
332
- /**
333
- * Is Global
334
- */
335
- isGlobal) {
336
- this.factory = factory;
337
- this.dependencies = dependencies;
338
- this.executionContextIn = executionContextIn;
339
- this.hasOnDestroyHook = hasOnDestroyHook;
340
- this.isGlobal = isGlobal;
341
- }
342
- }
343
- class Dependency {
344
- constructor(key, optional) {
345
- this.key = key;
346
- this.optional = optional;
347
- }
348
- static fromKey(key) {
349
- return new Dependency(key, false);
350
- }
351
- }
352
- function resolveProviders(providers) {
353
- const normalized = normalizeProviders(providers, []);
354
- const resolved = normalized.map(resolveProvider);
355
- const resolvedProviderMap = mergeResolvedProviders(resolved, new Map());
356
- return Array.from(resolvedProviderMap.values());
357
- }
358
- function resolveProvider(provider) {
359
- return new ResolvedProvider(Key.get(provider.provide), resolveFactory(provider));
360
- }
361
- function mergeResolvedProviders(providers, normalizedProvidersMap) {
362
- for (let i = 0; i < providers.length; i++) {
363
- const provider = providers[i];
364
- normalizedProvidersMap.set(provider.key.id, provider);
365
- }
366
- return normalizedProvidersMap;
367
- }
368
- function normalizeProviders(providers, res) {
369
- providers.forEach((token) => {
370
- if (token instanceof Type) {
371
- res.push({ provide: token, useClass: token });
372
- }
373
- else if (token &&
374
- typeof token === 'object' &&
375
- token.provide !== undefined) {
376
- res.push(token);
377
- }
378
- else if (token instanceof Array) {
379
- normalizeProviders(token, res);
380
- }
381
- else {
382
- throw invalidProviderError(token);
383
- }
384
- });
385
- return res;
386
- }
387
- function resolveFactory(provider) {
388
- let factoryFn;
389
- let resolvedDeps = _EMPTY_LIST;
390
- let executionContextIn = _EMPTY_LIST;
391
- let hasOnDestroyHook = false;
392
- let isGlobal;
393
- if (isClassProvider(provider)) {
394
- const useClass = resolveForwardRef(provider.useClass);
395
- factoryFn = makeFactory(useClass);
396
- resolvedDeps = dependenciesFor(useClass);
397
- executionContextIn = executionContextInFor(useClass);
398
- isGlobal = globalFor(useClass);
399
- hasOnDestroyHook = typeof useClass.prototype.onDestroy === 'function';
400
- }
401
- else if (isFactoryProvider(provider)) {
402
- factoryFn = provider.useFactory;
403
- resolvedDeps = constructDependencies(provider.useFactory, provider.deps || []);
404
- isGlobal = provider.global;
405
- if (provider.executionContextIn) {
406
- executionContextIn = provider.executionContextIn;
407
- }
408
- }
409
- else {
410
- factoryFn = () => provider.useValue;
411
- resolvedDeps = _EMPTY_LIST;
412
- isGlobal = provider.global;
413
- }
414
- return new ResolvedFactory(factoryFn, resolvedDeps, executionContextIn, hasOnDestroyHook, isGlobal !== null && isGlobal !== void 0 ? isGlobal : false);
415
- }
416
- function dependenciesFor(type) {
417
- const { params } = readInjectableMetadata(type, true);
418
- if (!params) {
419
- return [];
420
- }
421
- if (params.some((p) => p.type == null)) {
422
- throw noAnnotationError(type, params);
423
- }
424
- return params.map((p) => extractToken(p, params));
425
- }
426
- function executionContextInFor(type) {
427
- const { options } = readInjectableMetadata(type, true);
428
- if ((options === null || options === void 0 ? void 0 : options.executionContextIn) &&
429
- options.executionContextIn !== _EMPTY_LIST) {
430
- return options === null || options === void 0 ? void 0 : options.executionContextIn;
431
- }
432
- return [];
433
- }
434
- function globalFor(type) {
435
- var _a;
436
- const { options } = readInjectableMetadata(type);
437
- return (_a = options === null || options === void 0 ? void 0 : options.global) !== null && _a !== void 0 ? _a : false;
438
- }
439
- function constructDependencies(typeOrFunc, dependencies) {
440
- if (!dependencies) {
441
- return dependenciesFor(typeOrFunc);
442
- }
443
- else {
444
- const params = dependencies.map((d) => ({ type: d, optional: false }));
445
- return params.map((t) => extractToken(t, params));
446
- }
447
- }
448
- function extractToken(param, params) {
449
- const token = resolveForwardRef(param.type);
450
- if (token) {
451
- return createDependency(token, param.optional);
452
- }
453
- throw noAnnotationError(param.type, params);
454
- }
455
- function createDependency(token, optional) {
456
- return new Dependency(Key.get(token), optional);
457
- }
458
- function makeFactory(t) {
459
- return (...args) => new t(...args);
460
- }
461
-
462
- const _THROW_IF_NOT_FOUND = new Object();
463
- const UNDEFINED = new Object();
464
- const NOT_FOUND = new Object();
465
- function notInExecutionContext() {
466
- throw new Error('Not in execution context');
467
- }
468
- // Publicly available Injector.
469
- // We use ReflectiveInjector everywhere
470
- // but we don't want to leak its API to everyone
471
- class Injector {
472
- }
473
- class ReflectiveInjector {
474
- constructor({ name, providers, parent, fallbackParent, globalProvidersMap = new Map(), }) {
475
- this._constructionCounter = 0;
476
- this._executionContextGetter = notInExecutionContext;
477
- this.displayName = name;
478
- this._parent = parent || null;
479
- this._fallbackParent = fallbackParent || null;
480
- this._providers = providers;
481
- this._globalProvidersMap = globalProvidersMap;
482
- const len = this._providers.length;
483
- this._keyIds = new Array(len);
484
- this._objs = new Array(len);
485
- for (let i = 0; i < len; i++) {
486
- this._keyIds[i] = this._providers[i].key.id;
487
- this._objs[i] = UNDEFINED;
488
- }
489
- }
490
- static createFromResolved({ name, providers, parent, fallbackParent, globalProvidersMap, }) {
491
- return new ReflectiveInjector({
492
- name,
493
- providers,
494
- parent,
495
- fallbackParent,
496
- globalProvidersMap,
497
- });
498
- }
499
- static resolve(providers) {
500
- return resolveProviders(providers);
501
- }
502
- get parent() {
503
- return this._parent;
504
- }
505
- get fallbackParent() {
506
- return this._fallbackParent;
507
- }
508
- get(token, notFoundValue = _THROW_IF_NOT_FOUND) {
509
- return this._getByKey(Key.get(token), notFoundValue);
510
- }
511
- setExecutionContextGetter(getter) {
512
- this._executionContextGetter = getter;
513
- }
514
- _getByKey(key, notFoundValue) {
515
- let inj = this;
516
- function getObj() {
517
- while (inj instanceof ReflectiveInjector) {
518
- const inj_ = inj;
519
- const obj = inj_._getObjByKeyId(key.id);
520
- if (obj !== UNDEFINED) {
521
- return obj;
522
- }
523
- inj = inj_._parent;
524
- }
525
- return NOT_FOUND;
526
- }
527
- const resolvedValue = getObj();
528
- if (resolvedValue !== NOT_FOUND) {
529
- return resolvedValue;
530
- }
531
- // search in fallback Injector
532
- if (this._fallbackParent) {
533
- inj = this._fallbackParent;
534
- const resolvedFallbackValue = getObj();
535
- if (resolvedFallbackValue !== NOT_FOUND) {
536
- return resolvedFallbackValue;
537
- }
538
- }
539
- if (inj !== null) {
540
- return inj.get(key.token, notFoundValue);
541
- }
542
- return this._throwOrNull(key, notFoundValue);
543
- }
544
- _isObjectDefinedByKeyId(keyId) {
545
- for (let i = 0; i < this._keyIds.length; i++) {
546
- if (this._keyIds[i] === keyId) {
547
- return this._objs[i] !== UNDEFINED;
548
- }
549
- }
550
- return false;
551
- }
552
- _getObjByKeyId(keyId) {
553
- var _a, _b;
554
- if ((_a = this._globalProvidersMap) === null || _a === void 0 ? void 0 : _a.has(keyId)) {
555
- return (_b = this._globalProvidersMap.get(keyId)) === null || _b === void 0 ? void 0 : _b._getObjByKeyId(keyId);
556
- }
557
- for (let i = 0; i < this._keyIds.length; i++) {
558
- if (this._keyIds[i] === keyId) {
559
- if (this._objs[i] === UNDEFINED) {
560
- this._objs[i] = this._new(this._providers[i]);
561
- }
562
- return this._objs[i];
563
- }
564
- }
565
- return UNDEFINED;
566
- }
567
- _throwOrNull(key, notFoundValue) {
568
- if (notFoundValue !== _THROW_IF_NOT_FOUND) {
569
- return notFoundValue;
570
- }
571
- else {
572
- throw noProviderError(this, key);
573
- }
574
- }
575
- instantiateAll() {
576
- this._providers.forEach((provider) => {
577
- this._getByKey(provider.key, _THROW_IF_NOT_FOUND);
578
- });
579
- }
580
- _instantiateProvider(provider) {
581
- const factory = provider.factory.factory;
582
- let deps;
583
- try {
584
- deps = provider.factory.dependencies.map((dep) => this._getByDependency(dep));
585
- }
586
- catch (e) {
587
- if (e.addKey) {
588
- e.addKey(provider.key);
589
- }
590
- throw e;
591
- }
592
- let obj;
593
- try {
594
- obj = factory(...deps);
595
- // attach execution context getter
596
- if (provider.factory.executionContextIn.length > 0) {
597
- for (const prop of provider.factory.executionContextIn) {
598
- Object.defineProperty(obj, prop, {
599
- get: () => {
600
- return this._executionContextGetter();
601
- },
602
- });
603
- }
604
- }
605
- }
606
- catch (e) {
607
- throw instantiationError(this, e, provider.key);
608
- }
609
- return obj;
610
- }
611
- _getByDependency(dep) {
612
- return this._getByKey(dep.key, dep.optional ? null : _THROW_IF_NOT_FOUND);
613
- }
614
- _new(provider) {
615
- if (this._constructionCounter++ > this._getMaxNumberOfObjects()) {
616
- throw cyclicDependencyError(this, provider.key);
617
- }
618
- return this._instantiateProvider(provider);
619
- }
620
- _getMaxNumberOfObjects() {
621
- return this._objs.length;
622
- }
623
- toString() {
624
- return this.displayName;
625
- }
626
- }
627
-
628
- class ModuleNonUniqueIdError extends ExtendableBuiltin(Error) {
629
- constructor(message, ...rest) {
630
- super(composeMessage(message, ...rest));
631
- this.name = this.constructor.name;
632
- this.message = composeMessage(message, ...rest);
633
- }
634
- }
635
- class ModuleDuplicatedError extends ExtendableBuiltin(Error) {
636
- constructor(message, ...rest) {
637
- super(composeMessage(message, ...rest));
638
- this.name = this.constructor.name;
639
- this.message = composeMessage(message, ...rest);
640
- }
641
- }
642
- class ExtraResolverError extends ExtendableBuiltin(Error) {
643
- constructor(message, ...rest) {
644
- super(composeMessage(message, ...rest));
645
- this.name = this.constructor.name;
646
- this.message = composeMessage(message, ...rest);
647
- }
648
- }
649
- class ExtraMiddlewareError extends ExtendableBuiltin(Error) {
650
- constructor(message, ...rest) {
651
- super(composeMessage(message, ...rest));
652
- this.name = this.constructor.name;
653
- this.message = composeMessage(message, ...rest);
654
- }
655
- }
656
- class ResolverDuplicatedError extends ExtendableBuiltin(Error) {
657
- constructor(message, ...rest) {
658
- super(composeMessage(message, ...rest));
659
- this.name = this.constructor.name;
660
- this.message = composeMessage(message, ...rest);
661
- }
662
- }
663
- class ResolverInvalidError extends ExtendableBuiltin(Error) {
664
- constructor(message, ...rest) {
665
- super(composeMessage(message, ...rest));
666
- this.name = this.constructor.name;
667
- this.message = composeMessage(message, ...rest);
668
- }
669
- }
670
- class NonDocumentNodeError extends ExtendableBuiltin(Error) {
671
- constructor(message, ...rest) {
672
- super(composeMessage(message, ...rest));
673
- this.name = this.constructor.name;
674
- this.message = composeMessage(message, ...rest);
675
- }
676
- }
677
- // helpers
678
- function useLocation({ dirname, id }) {
679
- return dirname
680
- ? `Module "${id}" located at ${dirname}`
681
- : [
682
- `Module "${id}"`,
683
- `Hint: pass __dirname to "dirname" option of your modules to get more insightful errors`,
684
- ].join('\n');
685
- }
686
- function ExtendableBuiltin(cls) {
687
- function ExtendableBuiltin() {
688
- cls.apply(this, arguments);
689
- }
690
- ExtendableBuiltin.prototype = Object.create(cls.prototype);
691
- Object.setPrototypeOf(ExtendableBuiltin, cls);
692
- return ExtendableBuiltin;
693
- }
694
- function composeMessage(...lines) {
695
- return lines.join('\n');
696
- }
697
-
698
- function flatten(arr) {
699
- return Array.prototype.concat(...arr);
700
- }
701
- function isDefined(val) {
702
- return !isNil(val);
703
- }
704
- function isNil(val) {
705
- return val === null || typeof val === 'undefined';
706
- }
707
- function isPrimitive(val) {
708
- return ['number', 'string', 'boolean', 'symbol', 'bigint'].includes(typeof val);
709
- }
710
- function isAsyncIterable(obj) {
711
- return obj && typeof obj[Symbol.asyncIterator] === 'function';
712
- }
713
- function tapAsyncIterator(iterable, doneCallback) {
714
- const iteratorMethod = iterable[Symbol.asyncIterator];
715
- const iterator = iteratorMethod.call(iterable);
716
- function mapResult(result) {
717
- if (result.done) {
718
- doneCallback();
719
- }
720
- return result;
721
- }
722
- return {
723
- async next() {
724
- try {
725
- let result = await iterator.next();
726
- return mapResult(result);
727
- }
728
- catch (error) {
729
- doneCallback();
730
- throw error;
731
- }
732
- },
733
- async return(value) {
734
- try {
735
- const result = await iterator.return(value);
736
- return mapResult(result);
737
- }
738
- catch (error) {
739
- doneCallback();
740
- throw error;
741
- }
742
- },
743
- throw(error) {
744
- doneCallback();
745
- return iterator.throw(error);
746
- },
747
- [Symbol.asyncIterator]() {
748
- return this;
749
- },
750
- };
751
- }
752
- function once(cb) {
753
- let called = false;
754
- return () => {
755
- if (!called) {
756
- called = true;
757
- cb();
758
- }
759
- };
760
- }
761
- function share(factory) {
762
- let cached = null;
763
- return (arg) => {
764
- if (!cached) {
765
- cached = factory(arg);
766
- }
767
- return cached;
768
- };
769
- }
770
- function uniqueId(isNotUsed) {
771
- let id;
772
- while (!isNotUsed((id = Math.random().toString(16).substr(2)))) { }
773
- return id;
774
- }
775
- function isNotSchema(obj) {
776
- return obj instanceof GraphQLSchema === false;
777
- }
778
- function merge(source, target) {
779
- const result = {
780
- ...source,
781
- ...target,
782
- };
783
- function attachSymbols(obj) {
784
- const symbols = Object.getOwnPropertySymbols(obj);
785
- for (const symbol of symbols) {
786
- result[symbol] = obj[symbol];
787
- }
788
- }
789
- if (source) {
790
- attachSymbols(source);
791
- }
792
- attachSymbols(target);
793
- return result;
794
- }
795
-
796
- function instantiateSingletonProviders({ appInjector, modulesMap, }) {
797
- appInjector.instantiateAll();
798
- modulesMap.forEach((mod) => {
799
- mod.injector.instantiateAll();
800
- });
801
- }
802
- function createGlobalProvidersMap({ modules, scope, }) {
803
- const globalProvidersMap = {};
804
- const propType = scope === Scope.Singleton ? 'singletonProviders' : 'operationProviders';
805
- modules.forEach((mod) => {
806
- mod[propType].forEach((provider) => {
807
- if (provider.factory.isGlobal) {
808
- const key = provider.key.id;
809
- if (globalProvidersMap[key]) {
810
- throw duplicatedGlobalTokenError(provider, [
811
- mod.id,
812
- globalProvidersMap[key],
813
- ]);
814
- }
815
- globalProvidersMap[key] = mod.id;
816
- }
817
- });
818
- });
819
- return globalProvidersMap;
820
- }
821
- function attachGlobalProvidersMap({ injector, globalProvidersMap, moduleInjectorGetter, }) {
822
- injector._globalProvidersMap = {
823
- has(key) {
824
- return typeof globalProvidersMap[key] === 'string';
825
- },
826
- get(key) {
827
- return moduleInjectorGetter(globalProvidersMap[key]);
828
- },
829
- };
830
- }
831
- function duplicatedGlobalTokenError(provider, modules) {
832
- return Error([
833
- `Failed to define '${provider.key.displayName}' token as global.`,
834
- `Token provided by two modules: '${modules.join("', '")}'`,
835
- ].join(' '));
836
- }
837
-
838
- /**
839
- * @api
840
- * `CONTEXT` is an InjectionToken representing the provided `GraphQLModules.GlobalContext`
841
- *
842
- * @example
843
- *
844
- * ```typescript
845
- * import { CONTEXT, Inject, Injectable } from 'graphql-modules';
846
- *
847
- * (A)Injectable()
848
- * export class Data {
849
- * constructor((A)Inject(CONTEXT) private context: GraphQLModules.GlobalContext) {}
850
- * }
851
- * ```
852
- */
853
- const CONTEXT = new InjectionToken('context');
854
-
855
- function createContextBuilder({ appInjector, modulesMap, appLevelOperationProviders, singletonGlobalProvidersMap, operationGlobalProvidersMap, }) {
856
- // This is very critical. It creates an execution context.
857
- // It has to run on every operation.
858
- const contextBuilder = (context) => {
859
- // Cache for context per module
860
- let contextCache = {};
861
- // A list of providers with OnDestroy hooks
862
- // It's a tuple because we want to know which Injector controls the provider
863
- // and we want to know if the provider was even instantiated.
864
- let providersToDestroy = [];
865
- function registerProvidersToDestroy(injector) {
866
- injector._providers.forEach((provider) => {
867
- if (provider.factory.hasOnDestroyHook) {
868
- // keep provider key's id (it doesn't change over time)
869
- // and related injector
870
- providersToDestroy.push([injector, provider.key.id]);
871
- }
872
- });
873
- }
874
- let appContext;
875
- attachGlobalProvidersMap({
876
- injector: appInjector,
877
- globalProvidersMap: singletonGlobalProvidersMap,
878
- moduleInjectorGetter(moduleId) {
879
- return modulesMap.get(moduleId).injector;
880
- },
881
- });
882
- appInjector.setExecutionContextGetter(function executionContextGetter() {
883
- var _a;
884
- return (((_a = async_context.getAsyncContext()) === null || _a === void 0 ? void 0 : _a.getApplicationContext()) || appContext);
885
- });
886
- function createModuleExecutionContextGetter(moduleId) {
887
- return function moduleExecutionContextGetter() {
888
- var _a;
889
- return (((_a = async_context.getAsyncContext()) === null || _a === void 0 ? void 0 : _a.getModuleContext(moduleId)) ||
890
- getModuleContext(moduleId, context));
891
- };
892
- }
893
- modulesMap.forEach((mod, moduleId) => {
894
- mod.injector.setExecutionContextGetter(createModuleExecutionContextGetter(moduleId));
895
- });
896
- // As the name of the Injector says, it's an Operation scoped Injector
897
- // Application level
898
- // Operation scoped - means it's created and destroyed on every GraphQL Operation
899
- const operationAppInjector = ReflectiveInjector.createFromResolved({
900
- name: 'App (Operation Scope)',
901
- providers: appLevelOperationProviders.concat(ReflectiveInjector.resolve([
902
- {
903
- provide: CONTEXT,
904
- useValue: context,
905
- },
906
- ])),
907
- parent: appInjector,
908
- });
909
- // Create a context for application-level ExecutionContext
910
- appContext = merge(context, {
911
- injector: operationAppInjector,
912
- });
913
- // Track Providers with OnDestroy hooks
914
- registerProvidersToDestroy(operationAppInjector);
915
- function getModuleContext(moduleId, ctx) {
916
- var _a;
917
- // Reuse a context or create if not available
918
- if (!contextCache[moduleId]) {
919
- // We're interested in operation-scoped providers only
920
- const providers = (_a = modulesMap.get(moduleId)) === null || _a === void 0 ? void 0 : _a.operationProviders;
921
- // Create module-level Operation-scoped Injector
922
- const operationModuleInjector = ReflectiveInjector.createFromResolved({
923
- name: `Module "${moduleId}" (Operation Scope)`,
924
- providers: providers.concat(ReflectiveInjector.resolve([
925
- {
926
- provide: CONTEXT,
927
- useFactory() {
928
- return contextCache[moduleId];
929
- },
930
- },
931
- ])),
932
- // This injector has a priority
933
- parent: modulesMap.get(moduleId).injector,
934
- // over this one
935
- fallbackParent: operationAppInjector,
936
- });
937
- // Same as on application level, we need to collect providers with OnDestroy hooks
938
- registerProvidersToDestroy(operationModuleInjector);
939
- contextCache[moduleId] = merge(ctx, {
940
- injector: operationModuleInjector,
941
- moduleId,
942
- });
943
- }
944
- return contextCache[moduleId];
945
- }
946
- const sharedContext = merge(
947
- // We want to pass the received context
948
- context || {}, {
949
- // Here's something very crutial
950
- // It's a function that is used in module's context creation
951
- ɵgetModuleContext: getModuleContext,
952
- });
953
- attachGlobalProvidersMap({
954
- injector: operationAppInjector,
955
- globalProvidersMap: operationGlobalProvidersMap,
956
- moduleInjectorGetter(moduleId) {
957
- return getModuleContext(moduleId, sharedContext).injector;
958
- },
959
- });
960
- const env = {
961
- ɵdestroy: once(() => {
962
- providersToDestroy.forEach(([injector, keyId]) => {
963
- // If provider was instantiated
964
- if (injector._isObjectDefinedByKeyId(keyId)) {
965
- // call its OnDestroy hook
966
- injector._getObjByKeyId(keyId).onDestroy();
967
- }
968
- });
969
- contextCache = {};
970
- }),
971
- ɵinjector: operationAppInjector,
972
- context: sharedContext,
973
- };
974
- return {
975
- ...env,
976
- runWithContext(cb) {
977
- return async_context.runWithAsyncContext({
978
- getApplicationContext() {
979
- return appContext;
980
- },
981
- getModuleContext(moduleId) {
982
- return getModuleContext(moduleId, context);
983
- },
984
- }, cb, env);
985
- },
986
- };
987
- };
988
- return contextBuilder;
989
- }
990
-
991
- function executionCreator({ contextBuilder, }) {
992
- const createExecution = (options) => {
993
- // Custom or original execute function
994
- const executeFn = (options === null || options === void 0 ? void 0 : options.execute) || execute$1;
995
- return (argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) => {
996
- function perform({ context, ɵdestroy: destroy, }) {
997
- const executionArgs = isNotSchema(argsOrSchema)
998
- ? {
999
- ...argsOrSchema,
1000
- contextValue: context,
1001
- }
1002
- : {
1003
- schema: argsOrSchema,
1004
- document: document,
1005
- rootValue,
1006
- contextValue: context,
1007
- variableValues,
1008
- operationName,
1009
- fieldResolver,
1010
- typeResolver,
1011
- };
1012
- // It's important to wrap the executeFn within a promise
1013
- // so we can easily control the end of execution (with finally)
1014
- return Promise.resolve()
1015
- .then(() => executeFn(executionArgs))
1016
- .finally(destroy);
1017
- }
1018
- if (options === null || options === void 0 ? void 0 : options.controller) {
1019
- return perform(options.controller);
1020
- }
1021
- return contextBuilder(isNotSchema(argsOrSchema)
1022
- ? argsOrSchema.contextValue
1023
- : contextValue).runWithContext(perform);
1024
- };
1025
- };
1026
- return createExecution;
1027
- }
1028
-
1029
- function subscriptionCreator({ contextBuilder, }) {
1030
- const createSubscription = (options) => {
1031
- // Custom or original subscribe function
1032
- const subscribeFn = (options === null || options === void 0 ? void 0 : options.subscribe) || subscribe;
1033
- return (argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) => {
1034
- function perform({ context, ɵdestroy: destroy, }) {
1035
- const subscriptionArgs = isNotSchema(argsOrSchema)
1036
- ? {
1037
- ...argsOrSchema,
1038
- contextValue: context,
1039
- }
1040
- : {
1041
- schema: argsOrSchema,
1042
- document: document,
1043
- rootValue,
1044
- contextValue: context,
1045
- variableValues,
1046
- operationName,
1047
- fieldResolver,
1048
- subscribeFieldResolver,
1049
- };
1050
- let isIterable = false;
1051
- // It's important to wrap the subscribeFn within a promise
1052
- // so we can easily control the end of subscription (with finally)
1053
- return Promise.resolve()
1054
- .then(() => subscribeFn(subscriptionArgs))
1055
- .then((sub) => {
1056
- if (isAsyncIterable(sub)) {
1057
- isIterable = true;
1058
- return tapAsyncIterator(sub, destroy);
1059
- }
1060
- return sub;
1061
- })
1062
- .finally(() => {
1063
- if (!isIterable) {
1064
- destroy();
1065
- }
1066
- });
1067
- }
1068
- if (options === null || options === void 0 ? void 0 : options.controller) {
1069
- return perform(options.controller);
1070
- }
1071
- return contextBuilder(isNotSchema(argsOrSchema)
1072
- ? argsOrSchema.contextValue
1073
- : contextValue).runWithContext(perform);
1074
- };
1075
- };
1076
- return createSubscription;
1077
- }
1078
-
1079
- const CONTEXT_ID = Symbol.for('context-id');
1080
- function apolloExecutorCreator({ createExecution, }) {
1081
- return function createApolloExecutor(options) {
1082
- const executor = createExecution(options);
1083
- return async function executorAdapter(requestContext) {
1084
- return executor({
1085
- schema: requestContext.schema,
1086
- document: requestContext.document,
1087
- operationName: requestContext.operationName,
1088
- variableValues: requestContext.request.variables,
1089
- contextValue: requestContext.context,
1090
- });
1091
- };
1092
- };
1093
- }
1094
- function apolloSchemaCreator({ createSubscription, contextBuilder, schema, }) {
1095
- const createApolloSchema = () => {
1096
- const sessions = {};
1097
- const subscription = createSubscription();
1098
- function getSession(ctx, { context, ɵdestroy: destroy }) {
1099
- if (!ctx[CONTEXT_ID]) {
1100
- ctx[CONTEXT_ID] = uniqueId((id) => !sessions[id]);
1101
- sessions[ctx[CONTEXT_ID]] = {
1102
- count: 0,
1103
- session: {
1104
- context,
1105
- destroy() {
1106
- if (--sessions[ctx[CONTEXT_ID]].count === 0) {
1107
- destroy();
1108
- delete sessions[ctx[CONTEXT_ID]];
1109
- delete ctx[CONTEXT_ID];
1110
- }
1111
- },
1112
- },
1113
- };
1114
- }
1115
- sessions[ctx[CONTEXT_ID]].count++;
1116
- return sessions[ctx[CONTEXT_ID]].session;
1117
- }
1118
- return wrapSchema({
1119
- schema,
1120
- batch: true,
1121
- executor(input) {
1122
- if (input.operationType === 'subscription') {
1123
- return subscription({
1124
- schema,
1125
- document: input.document,
1126
- variableValues: input.variables,
1127
- contextValue: input.context,
1128
- rootValue: input.rootValue,
1129
- operationName: input.operationName,
1130
- });
1131
- }
1132
- // Create an execution context and run within it
1133
- return contextBuilder(input.context).runWithContext((env) => {
1134
- const { context, destroy } = getSession(input.context, env);
1135
- // It's important to wrap the executeFn within a promise
1136
- // so we can easily control the end of execution (with finally)
1137
- return Promise.resolve()
1138
- .then(() => execute$1({
1139
- schema,
1140
- document: input.document,
1141
- contextValue: context,
1142
- variableValues: input.variables,
1143
- rootValue: input.rootValue,
1144
- operationName: input.operationName,
1145
- }))
1146
- .finally(destroy);
1147
- });
1148
- },
1149
- });
1150
- };
1151
- return createApolloSchema;
1152
- }
1153
-
1154
- function operationControllerCreator(options) {
1155
- const { contextBuilder } = options;
1156
- return (input) => {
1157
- const operation = contextBuilder(input.context);
1158
- const ɵdestroy = input.autoDestroy ? operation.ɵdestroy : () => { };
1159
- return {
1160
- context: operation.context,
1161
- injector: operation.ɵinjector,
1162
- destroy: operation.ɵdestroy,
1163
- ɵdestroy,
1164
- };
1165
- };
1166
- }
1167
-
1168
- /**
1169
- * @api
1170
- * Creates Application out of Modules. Accepts `ApplicationConfig`.
1171
- *
1172
- * @example
1173
- *
1174
- * ```typescript
1175
- * import { createApplication } from 'graphql-modules';
1176
- * import { usersModule } from './users';
1177
- * import { postsModule } from './posts';
1178
- * import { commentsModule } from './comments';
1179
- *
1180
- * const app = createApplication({
1181
- * modules: [
1182
- * usersModule,
1183
- * postsModule,
1184
- * commentsModule
1185
- * ]
1186
- * })
1187
- * ```
1188
- */
1189
- function createApplication(applicationConfig) {
1190
- function applicationFactory(cfg) {
1191
- const config = cfg || applicationConfig;
1192
- const providers = config.providers && typeof config.providers === 'function'
1193
- ? config.providers()
1194
- : config.providers;
1195
- // Creates an Injector with singleton classes at application level
1196
- const appSingletonProviders = ReflectiveInjector.resolve(onlySingletonProviders(providers));
1197
- const appInjector = ReflectiveInjector.createFromResolved({
1198
- name: 'App (Singleton Scope)',
1199
- providers: appSingletonProviders,
1200
- });
1201
- // Filter Operation-scoped providers, and keep it here
1202
- // so we don't do it over and over again
1203
- const appOperationProviders = ReflectiveInjector.resolve(onlyOperationProviders(providers));
1204
- const middlewareMap = config.middlewares || {};
1205
- // Validations
1206
- ensureModuleUniqueIds(config.modules);
1207
- // Create all modules
1208
- const modules = config.modules.map((mod) => mod.factory({
1209
- injector: appInjector,
1210
- middlewares: middlewareMap,
1211
- }));
1212
- const modulesMap = createModulesMap(modules);
1213
- const singletonGlobalProvidersMap = createGlobalProvidersMap({
1214
- modules,
1215
- scope: Scope.Singleton,
1216
- });
1217
- const operationGlobalProvidersMap = createGlobalProvidersMap({
1218
- modules,
1219
- scope: Scope.Operation,
1220
- });
1221
- attachGlobalProvidersMap({
1222
- injector: appInjector,
1223
- globalProvidersMap: singletonGlobalProvidersMap,
1224
- moduleInjectorGetter(moduleId) {
1225
- return modulesMap.get(moduleId).injector;
1226
- },
1227
- });
1228
- // Creating a schema, flattening the typedefs and resolvers
1229
- // is not expensive since it happens only once
1230
- const typeDefs = flatten(modules.map((mod) => mod.typeDefs));
1231
- const resolvers = modules.map((mod) => mod.resolvers).filter(isDefined);
1232
- const schema = (applicationConfig.schemaBuilder || makeExecutableSchema)({
1233
- typeDefs,
1234
- resolvers,
1235
- });
1236
- const contextBuilder = createContextBuilder({
1237
- appInjector,
1238
- appLevelOperationProviders: appOperationProviders,
1239
- modulesMap: modulesMap,
1240
- singletonGlobalProvidersMap,
1241
- operationGlobalProvidersMap,
1242
- });
1243
- const createOperationController = operationControllerCreator({
1244
- contextBuilder,
1245
- });
1246
- const createSubscription = subscriptionCreator({ contextBuilder });
1247
- const createExecution = executionCreator({ contextBuilder });
1248
- const createSchemaForApollo = apolloSchemaCreator({
1249
- createSubscription,
1250
- contextBuilder,
1251
- schema,
1252
- });
1253
- const createApolloExecutor = apolloExecutorCreator({
1254
- createExecution,
1255
- });
1256
- instantiateSingletonProviders({
1257
- appInjector,
1258
- modulesMap,
1259
- });
1260
- return {
1261
- typeDefs,
1262
- resolvers,
1263
- schema,
1264
- injector: appInjector,
1265
- createOperationController,
1266
- createSubscription,
1267
- createExecution,
1268
- createSchemaForApollo,
1269
- createApolloExecutor,
1270
- ɵfactory: applicationFactory,
1271
- ɵconfig: config,
1272
- };
1273
- }
1274
- return applicationFactory();
1275
- }
1276
- function createModulesMap(modules) {
1277
- var _a;
1278
- const modulesMap = new Map();
1279
- for (const module of modules) {
1280
- if (modulesMap.has(module.id)) {
1281
- const location = module.metadata.dirname;
1282
- const existingLocation = (_a = modulesMap.get(module.id)) === null || _a === void 0 ? void 0 : _a.metadata.dirname;
1283
- const info = [];
1284
- if (existingLocation) {
1285
- info.push(`Already registered module located at: ${existingLocation}`);
1286
- }
1287
- if (location) {
1288
- info.push(`Duplicated module located at: ${location}`);
1289
- }
1290
- throw new ModuleDuplicatedError(`Module "${module.id}" already exists`, ...info);
1291
- }
1292
- modulesMap.set(module.id, module);
1293
- }
1294
- return modulesMap;
1295
- }
1296
- function ensureModuleUniqueIds(modules) {
1297
- const collisions = modules
1298
- .filter((mod, i, all) => i !== all.findIndex((m) => m.id === mod.id))
1299
- .map((m) => m.id);
1300
- if (collisions.length) {
1301
- throw new ModuleNonUniqueIdError(`Modules with non-unique ids: ${collisions.join(', ')}`, `All modules should have unique ids, please locate and fix them.`);
1302
- }
1303
- }
1304
-
1305
- function metadataFactory(typeDefs, config) {
1306
- const implemented = {};
1307
- const extended = {};
1308
- function collectObjectDefinition(node) {
1309
- if (!implemented[node.name.value]) {
1310
- implemented[node.name.value] = [];
1311
- }
1312
- if (node.fields && node.fields.length > 0) {
1313
- implemented[node.name.value].push(...node.fields.map((field) => field.name.value));
1314
- }
1315
- if (node.kind === Kind.OBJECT_TYPE_DEFINITION) {
1316
- implemented[node.name.value].push('__isTypeOf');
1317
- }
1318
- if (node.kind === Kind.OBJECT_TYPE_DEFINITION) {
1319
- implemented[node.name.value].push('__resolveReference');
1320
- implemented[node.name.value].push('__resolveObject');
1321
- }
1322
- if (node.kind === Kind.INTERFACE_TYPE_DEFINITION) {
1323
- implemented[node.name.value].push('__resolveType');
1324
- }
1325
- }
1326
- function collectObjectExtension(node) {
1327
- if (node.fields) {
1328
- if (!extended[node.name.value]) {
1329
- extended[node.name.value] = [];
1330
- }
1331
- node.fields.forEach((field) => {
1332
- extended[node.name.value].push(field.name.value);
1333
- });
1334
- }
1335
- }
1336
- for (const doc of typeDefs) {
1337
- visit(doc, {
1338
- // Object
1339
- ObjectTypeDefinition(node) {
1340
- collectObjectDefinition(node);
1341
- },
1342
- ObjectTypeExtension(node) {
1343
- collectObjectExtension(node);
1344
- },
1345
- // Interface
1346
- InterfaceTypeDefinition(node) {
1347
- collectObjectDefinition(node);
1348
- },
1349
- InterfaceTypeExtension(node) {
1350
- collectObjectExtension(node);
1351
- },
1352
- // Union
1353
- UnionTypeDefinition(node) {
1354
- if (!implemented[node.name.value]) {
1355
- implemented[node.name.value] = [];
1356
- }
1357
- if (node.types) {
1358
- implemented[node.name.value].push(...node.types.map((type) => type.name.value));
1359
- }
1360
- implemented[node.name.value].push('__resolveType');
1361
- },
1362
- UnionTypeExtension(node) {
1363
- if (node.types) {
1364
- if (!extended[node.name.value]) {
1365
- extended[node.name.value] = [];
1366
- }
1367
- extended[node.name.value].push(...node.types.map((type) => type.name.value));
1368
- }
1369
- },
1370
- // Input
1371
- InputObjectTypeDefinition(node) {
1372
- collectObjectDefinition(node);
1373
- },
1374
- InputObjectTypeExtension(node) {
1375
- collectObjectExtension(node);
1376
- },
1377
- // Enum
1378
- EnumTypeDefinition(node) {
1379
- if (node.values) {
1380
- if (!implemented[node.name.value]) {
1381
- implemented[node.name.value] = [];
1382
- }
1383
- implemented[node.name.value].push(...node.values.map((value) => value.name.value));
1384
- }
1385
- },
1386
- EnumTypeExtension(node) {
1387
- if (node.values) {
1388
- if (!extended[node.name.value]) {
1389
- extended[node.name.value] = [];
1390
- }
1391
- extended[node.name.value].push(...node.values.map((value) => value.name.value));
1392
- }
1393
- },
1394
- // Scalar
1395
- ScalarTypeDefinition(node) {
1396
- if (!implemented.__scalars) {
1397
- implemented.__scalars = [];
1398
- }
1399
- implemented.__scalars.push(node.name.value);
1400
- },
1401
- });
1402
- }
1403
- return {
1404
- id: config.id,
1405
- typeDefs,
1406
- implements: implemented,
1407
- extends: extended,
1408
- dirname: config.dirname,
1409
- };
1410
- }
1411
-
1412
- function compose(middleware) {
1413
- if (!Array.isArray(middleware)) {
1414
- throw new TypeError('Middleware stack must be an array!');
1415
- }
1416
- for (const fn of middleware) {
1417
- if (typeof fn !== 'function') {
1418
- throw new TypeError('Middleware must be composed of functions!');
1419
- }
1420
- }
1421
- return function composed(context, next) {
1422
- // last called middleware
1423
- let index = -1;
1424
- function dispatch(i) {
1425
- if (i <= index) {
1426
- return Promise.reject(new Error('next() called multiple times'));
1427
- }
1428
- index = i;
1429
- const fn = i === middleware.length ? next : middleware[i];
1430
- if (!fn) {
1431
- return Promise.resolve();
1432
- }
1433
- try {
1434
- return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
1435
- }
1436
- catch (err) {
1437
- return Promise.reject(err);
1438
- }
1439
- }
1440
- return dispatch(0);
1441
- };
1442
- }
1443
- function createMiddleware(path, middlewareMap) {
1444
- const middlewares = middlewareMap ? pickMiddlewares(path, middlewareMap) : [];
1445
- return compose(middlewares);
1446
- }
1447
- function mergeMiddlewareMaps(app, mod) {
1448
- const merge = (left, right) => {
1449
- return mergeDeepWith((l, r) => {
1450
- if (Array.isArray(l)) {
1451
- return l.concat(r || []);
1452
- }
1453
- return merge(l, r);
1454
- }, left, right);
1455
- };
1456
- return merge(app, mod);
1457
- }
1458
- function pickMiddlewares(path, middlewareMap) {
1459
- var _a;
1460
- const middlewares = [];
1461
- const [type, field] = path;
1462
- if ((_a = middlewareMap['*']) === null || _a === void 0 ? void 0 : _a['*']) {
1463
- middlewares.push(...middlewareMap['*']['*']);
1464
- }
1465
- const typeMap = middlewareMap[type];
1466
- if (typeMap) {
1467
- if (typeMap['*']) {
1468
- middlewares.push(...typeMap['*']);
1469
- }
1470
- if (field && typeMap[field]) {
1471
- middlewares.push(...typeMap[field]);
1472
- }
1473
- }
1474
- return middlewares.filter(isDefined);
1475
- }
1476
- function validateMiddlewareMap(middlewareMap, metadata) {
1477
- const exists = checkExistence(metadata);
1478
- for (const typeName in middlewareMap.types) {
1479
- if (middlewareMap.types.hasOwnProperty(typeName)) {
1480
- const typeMiddlewareMap = middlewareMap[typeName];
1481
- if (!exists.type(typeName)) {
1482
- throw new ExtraMiddlewareError(`Cannot apply a middleware to non existing "${typeName}" type`, useLocation({ dirname: metadata.dirname, id: metadata.id }));
1483
- }
1484
- for (const fieldName in typeMiddlewareMap[typeName]) {
1485
- if (typeMiddlewareMap[typeName].hasOwnProperty(fieldName)) {
1486
- if (!exists.field(typeName, fieldName)) {
1487
- throw new ExtraMiddlewareError(`Cannot apply a middleware to non existing "${typeName}.${fieldName}" type.field`, useLocation({ dirname: metadata.dirname, id: metadata.id }));
1488
- }
1489
- }
1490
- }
1491
- }
1492
- }
1493
- }
1494
- /**
1495
- * Helps to make sure a middleware has a corresponding type/field definition.
1496
- * We don't want to pass a module-level middlewares that are not related to the module.
1497
- * Not because it's dangerous but to prevent unused middlewares.
1498
- */
1499
- function checkExistence(metadata) {
1500
- return {
1501
- type(name) {
1502
- var _a, _b;
1503
- return isDefined(((_a = metadata.implements) === null || _a === void 0 ? void 0 : _a[name]) || ((_b = metadata.extends) === null || _b === void 0 ? void 0 : _b[name]));
1504
- },
1505
- field(type, name) {
1506
- var _a, _b, _c, _d;
1507
- return isDefined(((_b = (_a = metadata.implements) === null || _a === void 0 ? void 0 : _a[type]) === null || _b === void 0 ? void 0 : _b.includes(name)) ||
1508
- ((_d = (_c = metadata.extends) === null || _c === void 0 ? void 0 : _c[type]) === null || _d === void 0 ? void 0 : _d.includes(name)));
1509
- },
1510
- };
1511
- }
1512
-
1513
- const resolverMetadataProp = Symbol('metadata');
1514
- function createResolvers(config, metadata, app) {
1515
- const ensure = ensureImplements(metadata);
1516
- const normalizedModuleMiddlewareMap = config.middlewares || {};
1517
- const middlewareMap = mergeMiddlewareMaps(app.middlewareMap, normalizedModuleMiddlewareMap);
1518
- validateMiddlewareMap(normalizedModuleMiddlewareMap, metadata);
1519
- const resolvers = addDefaultResolvers(mergeResolvers(config), middlewareMap, config);
1520
- // Wrap resolvers
1521
- for (const typeName in resolvers) {
1522
- if (resolvers.hasOwnProperty(typeName)) {
1523
- const obj = resolvers[typeName];
1524
- if (isScalarResolver(obj)) {
1525
- continue;
1526
- }
1527
- else if (isEnumResolver(obj)) {
1528
- continue;
1529
- }
1530
- else if (obj && typeof obj === 'object') {
1531
- for (const fieldName in obj) {
1532
- if (obj.hasOwnProperty(fieldName)) {
1533
- ensure.type(typeName, fieldName);
1534
- const path = [typeName, fieldName];
1535
- // function
1536
- if (isResolveFn(obj[fieldName])) {
1537
- const resolver = wrapResolver({
1538
- config,
1539
- resolver: obj[fieldName],
1540
- middlewareMap,
1541
- path,
1542
- isTypeResolver: fieldName === '__isTypeOf' || fieldName === '__resolveType',
1543
- isReferenceResolver: fieldName === '__resolveReference',
1544
- isObjectResolver: fieldName === '__resolveObject',
1545
- });
1546
- resolvers[typeName][fieldName] = resolver;
1547
- }
1548
- else if (isResolveOptions(obj[fieldName])) {
1549
- // { resolve }
1550
- if (isDefined(obj[fieldName].resolve)) {
1551
- const resolver = wrapResolver({
1552
- config,
1553
- resolver: obj[fieldName].resolve,
1554
- middlewareMap,
1555
- path,
1556
- });
1557
- resolvers[typeName][fieldName].resolve = resolver;
1558
- }
1559
- // { subscribe }
1560
- if (isDefined(obj[fieldName].subscribe)) {
1561
- const resolver = wrapResolver({
1562
- config,
1563
- resolver: obj[fieldName].subscribe,
1564
- middlewareMap,
1565
- path,
1566
- });
1567
- resolvers[typeName][fieldName].subscribe = resolver;
1568
- }
1569
- if (isDefined(obj[fieldName].extensions)) {
1570
- // Do NOT add a resolve if one is not specified, it will cause
1571
- // change in behavior in systems like `grafast`
1572
- resolvers[typeName][fieldName].extensions =
1573
- obj[fieldName].extensions;
1574
- }
1575
- }
1576
- }
1577
- }
1578
- }
1579
- }
1580
- }
1581
- return resolvers;
1582
- }
1583
- /**
1584
- * Wrap a resolver so we use module's context instead of app context.
1585
- * Use a middleware if available.
1586
- * Attach metadata to a resolver (we will see if it's helpful, probably in error handling)
1587
- */
1588
- function wrapResolver({ resolver, config, path, middlewareMap, isTypeResolver, isReferenceResolver, isObjectResolver, }) {
1589
- if (isTypeResolver || isReferenceResolver) {
1590
- const wrappedResolver = (root, context, info) => {
1591
- const ctx = {
1592
- root,
1593
- context: isReferenceResolver
1594
- ? context.ɵgetModuleContext(config.id, context)
1595
- : // We mark the context object as possibly undefined,
1596
- // because graphql-jit for some reason doesn't pass it for isTypeOf or resolveType methods
1597
- context === null || context === void 0 ? void 0 : context.ɵgetModuleContext(config.id, context),
1598
- info,
1599
- };
1600
- return resolver(ctx.root, ctx.context, ctx.info);
1601
- };
1602
- writeResolverMetadata(wrappedResolver, config);
1603
- return wrappedResolver;
1604
- }
1605
- if (isObjectResolver) {
1606
- const wrappedResolver = (root, fields, context, info) => {
1607
- const moduleContext = context.ɵgetModuleContext(config.id, context);
1608
- return resolver(root, fields, moduleContext, info);
1609
- };
1610
- writeResolverMetadata(wrappedResolver, config);
1611
- return wrappedResolver;
1612
- }
1613
- const middleware = createMiddleware(path, middlewareMap);
1614
- const wrappedResolver = (root, args, context, info) => {
1615
- const ctx = {
1616
- root,
1617
- args,
1618
- context: context.ɵgetModuleContext(config.id, context),
1619
- info,
1620
- };
1621
- return middleware(ctx, () => resolver(ctx.root, ctx.args, ctx.context, ctx.info));
1622
- };
1623
- writeResolverMetadata(wrappedResolver, config);
1624
- return wrappedResolver;
1625
- }
1626
- /**
1627
- * We iterate over every defined resolver and check if it's valid and not duplicated
1628
- */
1629
- function mergeResolvers(config) {
1630
- if (!config.resolvers) {
1631
- return {};
1632
- }
1633
- const resolvers = Array.isArray(config.resolvers)
1634
- ? config.resolvers
1635
- : [config.resolvers];
1636
- const container = {};
1637
- for (const currentResolvers of resolvers) {
1638
- for (const typeName in currentResolvers) {
1639
- if (currentResolvers.hasOwnProperty(typeName)) {
1640
- const value = currentResolvers[typeName];
1641
- if (isNil(value)) {
1642
- continue;
1643
- }
1644
- else if (isScalarResolver(value)) {
1645
- addScalar({ typeName, resolver: value, container, config });
1646
- }
1647
- else if (isEnumResolver(value)) {
1648
- addEnum({ typeName, resolver: value, container, config });
1649
- }
1650
- else if (value && typeof value === 'object') {
1651
- addObject({ typeName, fields: value, container, config });
1652
- }
1653
- else {
1654
- throw new ResolverInvalidError(`Resolver of "${typeName}" is invalid`, useLocation({ dirname: config.dirname, id: config.id }));
1655
- }
1656
- }
1657
- }
1658
- }
1659
- return container;
1660
- }
1661
- function addObject({ typeName, fields, container, config, }) {
1662
- if (!container[typeName]) {
1663
- container[typeName] = {};
1664
- }
1665
- for (const fieldName in fields) {
1666
- if (fields.hasOwnProperty(fieldName)) {
1667
- const resolver = fields[fieldName];
1668
- if (isResolveFn(resolver)) {
1669
- if (container[typeName][fieldName]) {
1670
- throw new ResolverDuplicatedError(`Duplicated resolver of "${typeName}.${fieldName}"`, useLocation({ dirname: config.dirname, id: config.id }));
1671
- }
1672
- writeResolverMetadata(resolver, config);
1673
- container[typeName][fieldName] = resolver;
1674
- }
1675
- else if (isResolveOptions(resolver)) {
1676
- if (!container[typeName][fieldName]) {
1677
- container[typeName][fieldName] = {};
1678
- }
1679
- // resolve
1680
- if (isDefined(resolver.resolve)) {
1681
- if (container[typeName][fieldName].resolve) {
1682
- throw new ResolverDuplicatedError(`Duplicated resolver of "${typeName}.${fieldName}" (resolve method)`, useLocation({ dirname: config.dirname, id: config.id }));
1683
- }
1684
- writeResolverMetadata(resolver.resolve, config);
1685
- container[typeName][fieldName].resolve = resolver.resolve;
1686
- }
1687
- // subscribe
1688
- if (isDefined(resolver.subscribe)) {
1689
- if (container[typeName][fieldName].subscribe) {
1690
- throw new ResolverDuplicatedError(`Duplicated resolver of "${typeName}.${fieldName}" (subscribe method)`, useLocation({ dirname: config.dirname, id: config.id }));
1691
- }
1692
- writeResolverMetadata(resolver.subscribe, config);
1693
- container[typeName][fieldName].subscribe = resolver.subscribe;
1694
- }
1695
- // extensions
1696
- if (isDefined(resolver.extensions)) {
1697
- if (container[typeName][fieldName].extensions) {
1698
- throw new ResolverDuplicatedError(`Duplicated resolver of "${typeName}.${fieldName}" (extensions object)`, useLocation({ dirname: config.dirname, id: config.id }));
1699
- }
1700
- writeResolverMetadata(resolver.extensions, config);
1701
- container[typeName][fieldName].extensions = resolver.extensions;
1702
- }
1703
- }
1704
- }
1705
- }
1706
- }
1707
- function addScalar({ typeName, resolver, container, config, }) {
1708
- if (container[typeName]) {
1709
- throw new ResolverDuplicatedError(`Duplicated resolver of scalar "${typeName}"`, useLocation({ dirname: config.dirname, id: config.id }));
1710
- }
1711
- writeResolverMetadata(resolver.parseLiteral, config);
1712
- writeResolverMetadata(resolver.parseValue, config);
1713
- writeResolverMetadata(resolver.serialize, config);
1714
- container[typeName] = resolver;
1715
- }
1716
- function addEnum({ typeName, resolver, container, config, }) {
1717
- if (!container[typeName]) {
1718
- container[typeName] = {};
1719
- }
1720
- for (const key in resolver) {
1721
- if (resolver.hasOwnProperty(key)) {
1722
- const value = resolver[key];
1723
- if (container[typeName][key]) {
1724
- throw new ResolverDuplicatedError(`Duplicated resolver of "${typeName}.${key}" enum value`, useLocation({ dirname: config.dirname, id: config.id }));
1725
- }
1726
- container[typeName][key] = value;
1727
- }
1728
- }
1729
- }
1730
- /**
1731
- * Helps to make sure a resolver has a corresponding type/field definition.
1732
- * We don't want to pass resolve function that are not related to the module.
1733
- */
1734
- function ensureImplements(metadata) {
1735
- return {
1736
- type(name, field) {
1737
- var _a, _b;
1738
- const type = []
1739
- .concat((_a = metadata.implements) === null || _a === void 0 ? void 0 : _a[name], (_b = metadata.extends) === null || _b === void 0 ? void 0 : _b[name])
1740
- .filter(isDefined);
1741
- if (type === null || type === void 0 ? void 0 : type.includes(field)) {
1742
- return true;
1743
- }
1744
- const id = `"${name}.${field}"`;
1745
- throw new ExtraResolverError(`Resolver of "${id}" type cannot be implemented`, `${id} is not defined`, useLocation({ dirname: metadata.dirname, id: metadata.id }));
1746
- },
1747
- scalar(name) {
1748
- var _a;
1749
- if ((((_a = metadata.implements) === null || _a === void 0 ? void 0 : _a.__scalars) || []).includes(name)) {
1750
- return true;
1751
- }
1752
- throw new ExtraResolverError(`Resolver of "${name}" scalar cannot be implemented`, `${name} is not defined`, useLocation({ dirname: metadata.dirname, id: metadata.id }));
1753
- },
1754
- };
1755
- }
1756
- function writeResolverMetadata(resolver, config) {
1757
- if (!resolver) {
1758
- return;
1759
- }
1760
- resolver[resolverMetadataProp] = {
1761
- moduleId: config.id,
1762
- };
1763
- }
1764
- /**
1765
- * In order to use middlewares on fields
1766
- * that are defined in SDL but have no implemented resolvers,
1767
- * we would have to recreate GraphQLSchema and wrap resolve functions.
1768
- *
1769
- * Since we can't access GraphQLSchema on a module level
1770
- * and recreating GraphQLSchema seems unreasonable,
1771
- * we can create default resolvers instead.
1772
- *
1773
- * @example
1774
- *
1775
- * gql`
1776
- * type Query {
1777
- * me: User!
1778
- * }
1779
- *
1780
- * type User {
1781
- * name: String!
1782
- * }
1783
- * `
1784
- *
1785
- * The resolver of `Query.me` is implemented and resolver of `User.name` is not.
1786
- * In case where a middleware wants to intercept the resolver of `User.name`,
1787
- * we use a default field resolver from `graphql` package
1788
- * and put it next to other defined resolvers.
1789
- *
1790
- * This way our current logic of wrapping resolvers and running
1791
- * middleware functions stays untouched.
1792
- */
1793
- function addDefaultResolvers(resolvers, middlewareMap, config) {
1794
- const container = resolvers;
1795
- const sdl = Array.isArray(config.typeDefs)
1796
- ? concatAST(config.typeDefs)
1797
- : config.typeDefs;
1798
- function hasMiddleware(typeName, fieldName) {
1799
- var _a, _b, _c, _d, _e, _f;
1800
- return ((((_b = (_a = middlewareMap['*']) === null || _a === void 0 ? void 0 : _a['*']) === null || _b === void 0 ? void 0 : _b.length) ||
1801
- ((_d = (_c = middlewareMap[typeName]) === null || _c === void 0 ? void 0 : _c['*']) === null || _d === void 0 ? void 0 : _d.length) ||
1802
- ((_f = (_e = middlewareMap[typeName]) === null || _e === void 0 ? void 0 : _e[fieldName]) === null || _f === void 0 ? void 0 : _f.length)) > 0);
1803
- }
1804
- sdl.definitions.forEach((definition) => {
1805
- if (definition.kind === Kind.OBJECT_TYPE_DEFINITION ||
1806
- definition.kind === Kind.OBJECT_TYPE_EXTENSION) {
1807
- // Right now we only support Object type
1808
- if (definition.fields) {
1809
- const typeName = definition.name.value;
1810
- definition.fields.forEach((field) => {
1811
- var _a;
1812
- const fieldName = field.name.value;
1813
- if (!((_a = container[typeName]) === null || _a === void 0 ? void 0 : _a[fieldName]) &&
1814
- hasMiddleware(typeName, fieldName)) {
1815
- if (!container[typeName]) {
1816
- container[typeName] = {};
1817
- }
1818
- container[typeName][fieldName] = defaultFieldResolver;
1819
- }
1820
- });
1821
- }
1822
- }
1823
- });
1824
- return container;
1825
- }
1826
- //
1827
- // Resolver helpers
1828
- //
1829
- function isResolveFn(value) {
1830
- return typeof value === 'function';
1831
- }
1832
- function isResolveOptions(value) {
1833
- return (isDefined(value.resolve) ||
1834
- isDefined(value.subscribe) ||
1835
- isDefined(value.extensions));
1836
- }
1837
- function isScalarResolver(obj) {
1838
- return obj instanceof GraphQLScalarType;
1839
- }
1840
- function isEnumResolver(obj) {
1841
- return Object.values(obj).every(isPrimitive);
1842
- }
1843
-
1844
- /**
1845
- * Create a list of DocumentNode objects based on Module's config.
1846
- * Add a location, so we get richer errors.
1847
- */
1848
- function createTypeDefs(config) {
1849
- const typeDefs = Array.isArray(config.typeDefs)
1850
- ? config.typeDefs
1851
- : [config.typeDefs];
1852
- ensureDocumentNode(config, typeDefs);
1853
- return typeDefs;
1854
- }
1855
- function ensureDocumentNode(config, typeDefs) {
1856
- function ensureEach(doc, i) {
1857
- if ((doc === null || doc === void 0 ? void 0 : doc.kind) !== Kind.DOCUMENT) {
1858
- throw new NonDocumentNodeError(`Expected parsed document but received ${typeof doc} at index ${i} in typeDefs list`, useLocation(config));
1859
- }
1860
- }
1861
- typeDefs.forEach(ensureEach);
1862
- }
1863
-
1864
- /**
1865
- * @api
1866
- * `MODULE_ID` is an InjectionToken representing module's ID
1867
- *
1868
- * @example
1869
- * ```typescript
1870
- * import { MODULE_ID, Inject, Injectable } from 'graphql-modules';
1871
- *
1872
- * (A)Injectable()
1873
- * export class Data {
1874
- * constructor((A)Inject(MODULE_ID) moduleId: string) {
1875
- * console.log(`Data used in ${moduleId} module`)
1876
- * }
1877
- * }
1878
- * ```
1879
- */
1880
- const MODULE_ID = new InjectionToken('module-id');
1881
-
1882
- function lazy(getter) {
1883
- let called = false;
1884
- let computedValue;
1885
- return {
1886
- get value() {
1887
- if (!called) {
1888
- called = true;
1889
- computedValue = getter();
1890
- }
1891
- return computedValue;
1892
- },
1893
- };
1894
- }
1895
- function moduleFactory(config) {
1896
- const typeDefs = createTypeDefs(config);
1897
- const metadata = metadataFactory(typeDefs, config);
1898
- const providers = lazy(() => typeof config.providers === 'function'
1899
- ? config.providers()
1900
- : config.providers);
1901
- // Filter providers and keep them this way
1902
- // so we don't do this filtering multiple times.
1903
- // Providers don't change over time, so it's safe to do it.
1904
- const operationProviders = lazy(() => ReflectiveInjector.resolve(onlyOperationProviders(providers.value)));
1905
- const singletonProviders = lazy(() => ReflectiveInjector.resolve(onlySingletonProviders(providers.value)));
1906
- const mod = {
1907
- id: config.id,
1908
- config,
1909
- metadata,
1910
- typeDefs,
1911
- // Factory is called once on application creation,
1912
- // before we even handle GraphQL Operation
1913
- factory(app) {
1914
- const resolvedModule = mod;
1915
- resolvedModule.singletonProviders = singletonProviders.value;
1916
- resolvedModule.operationProviders = operationProviders.value;
1917
- // Create a module-level Singleton injector
1918
- const injector = ReflectiveInjector.createFromResolved({
1919
- name: `Module "${config.id}" (Singleton Scope)`,
1920
- providers: resolvedModule.singletonProviders.concat(resolveProviders([
1921
- {
1922
- // with module's id, useful in Logging and stuff
1923
- provide: MODULE_ID,
1924
- useValue: config.id,
1925
- },
1926
- ])),
1927
- parent: app.injector,
1928
- });
1929
- // We attach injector property to existing `mod` object
1930
- // because we want to keep references
1931
- // that are later on used in testing utils
1932
- resolvedModule.injector = injector;
1933
- // Create resolvers object based on module's config
1934
- // It involves wrapping a resolver with middlewares
1935
- // and other things like validation
1936
- resolvedModule.resolvers = createResolvers(config, metadata, {
1937
- middlewareMap: app.middlewares,
1938
- });
1939
- return resolvedModule;
1940
- },
1941
- };
1942
- return mod;
1943
- }
1944
-
1945
- /**
1946
- * @api
1947
- * Creates a Module, an element used by Application. Accepts `ModuleConfig`.
1948
- *
1949
- * @example
1950
- *
1951
- * ```typescript
1952
- * import { createModule, gql } from 'graphql-modules';
1953
- *
1954
- * export const usersModule = createModule({
1955
- * id: 'users',
1956
- * typeDefs: gql`
1957
- * // GraphQL SDL
1958
- * `,
1959
- * resolvers: {
1960
- * // ...
1961
- * }
1962
- * });
1963
- * ```
1964
- */
1965
- function createModule(config) {
1966
- return moduleFactory(config);
1967
- }
1968
-
1969
- function gql(literals) {
1970
- const result = typeof literals === 'string' ? literals : literals[0];
1971
- const parsed = parse(result);
1972
- if (!parsed || parsed.kind !== Kind.DOCUMENT) {
1973
- throw new Error('Not a valid GraphQL document.');
1974
- }
1975
- return parsed;
1976
- }
1977
-
1978
- function mockApplication(app) {
1979
- function mockedFactory(newConfig) {
1980
- const sharedFactory = share(() => app.ɵfactory(newConfig));
1981
- return {
1982
- get typeDefs() {
1983
- return sharedFactory().typeDefs;
1984
- },
1985
- get resolvers() {
1986
- return sharedFactory().resolvers;
1987
- },
1988
- get schema() {
1989
- return sharedFactory().schema;
1990
- },
1991
- get injector() {
1992
- return sharedFactory().injector;
1993
- },
1994
- createOperationController(options) {
1995
- return sharedFactory().createOperationController(options);
1996
- },
1997
- createSubscription(options) {
1998
- return sharedFactory().createSubscription(options);
1999
- },
2000
- createExecution(options) {
2001
- return sharedFactory().createExecution(options);
2002
- },
2003
- createSchemaForApollo() {
2004
- return sharedFactory().createSchemaForApollo();
2005
- },
2006
- createApolloExecutor() {
2007
- return sharedFactory().createApolloExecutor();
2008
- },
2009
- get ɵfactory() {
2010
- return sharedFactory().ɵfactory;
2011
- },
2012
- get ɵconfig() {
2013
- return sharedFactory().ɵconfig;
2014
- },
2015
- replaceModule(newModule) {
2016
- const config = sharedFactory().ɵconfig;
2017
- return mockedFactory({
2018
- ...config,
2019
- modules: config.modules.map((mod) => mod.id === newModule.ɵoriginalModule.id ? newModule : mod),
2020
- });
2021
- },
2022
- addProviders(newProviders) {
2023
- const config = sharedFactory().ɵconfig;
2024
- const existingProviders = typeof config.providers === 'function'
2025
- ? config.providers()
2026
- : config.providers;
2027
- const providers = Array.isArray(existingProviders)
2028
- ? existingProviders.concat(newProviders)
2029
- : newProviders;
2030
- return mockedFactory({
2031
- ...config,
2032
- providers,
2033
- });
2034
- },
2035
- };
2036
- }
2037
- return mockedFactory();
2038
- }
2039
-
2040
- function mockModule(testedModule, overrideConfig) {
2041
- const sourceProviders = typeof testedModule.config.providers === 'function'
2042
- ? testedModule.config.providers()
2043
- : testedModule.config.providers;
2044
- const overrideProviders = typeof overrideConfig.providers === 'function'
2045
- ? overrideConfig.providers()
2046
- : overrideConfig.providers;
2047
- const newModule = createModule({
2048
- ...testedModule.config,
2049
- providers: [...(sourceProviders || []), ...(overrideProviders || [])],
2050
- });
2051
- newModule['ɵoriginalModule'] = testedModule;
2052
- return newModule;
2053
- }
2054
- function testModule(testedModule, config) {
2055
- var _a;
2056
- const mod = transformModule(testedModule, config);
2057
- const modules = [mod].concat((_a = config === null || config === void 0 ? void 0 : config.modules) !== null && _a !== void 0 ? _a : []);
2058
- return createApplication({
2059
- ...(config || {}),
2060
- modules,
2061
- providers: config === null || config === void 0 ? void 0 : config.providers,
2062
- middlewares: config === null || config === void 0 ? void 0 : config.middlewares,
2063
- });
2064
- }
2065
- function transformModule(mod, config) {
2066
- const transforms = [];
2067
- if (config === null || config === void 0 ? void 0 : config.replaceExtensions) {
2068
- transforms.push((m) => moduleFactory({
2069
- ...m.config,
2070
- typeDefs: replaceExtensions(m.typeDefs),
2071
- }));
2072
- }
2073
- if (config === null || config === void 0 ? void 0 : config.typeDefs) {
2074
- transforms.push((m) => moduleFactory({
2075
- ...m.config,
2076
- typeDefs: m.typeDefs.concat(config.typeDefs),
2077
- }));
2078
- }
2079
- if (config === null || config === void 0 ? void 0 : config.inheritTypeDefs) {
2080
- transforms.push((m) => moduleFactory({
2081
- ...m.config,
2082
- typeDefs: inheritTypeDefs(m.typeDefs, config.inheritTypeDefs),
2083
- }));
2084
- }
2085
- if (config === null || config === void 0 ? void 0 : config.resolvers) {
2086
- transforms.push((m) => {
2087
- const resolvers = m.config.resolvers
2088
- ? Array.isArray(m.config.resolvers)
2089
- ? m.config.resolvers
2090
- : [m.config.resolvers]
2091
- : [];
2092
- return moduleFactory({
2093
- ...m.config,
2094
- resolvers: resolvers.concat(config.resolvers),
2095
- });
2096
- });
2097
- }
2098
- if (config === null || config === void 0 ? void 0 : config.providers) {
2099
- transforms.push((m) => {
2100
- const sourceProviders = typeof m.config.providers === 'function'
2101
- ? m.config.providers()
2102
- : m.config.providers;
2103
- const overrideProviders = typeof config.providers === 'function'
2104
- ? config.providers()
2105
- : config.providers;
2106
- return moduleFactory({
2107
- ...m.config,
2108
- providers: [...(sourceProviders || []), ...(overrideProviders || [])],
2109
- });
2110
- });
2111
- }
2112
- if (transforms) {
2113
- return transforms.reduce((m, transform) => transform(m), mod);
2114
- }
2115
- return mod;
2116
- }
2117
- function inheritTypeDefs(originalTypeDefs, modules) {
2118
- const original = concatAST(originalTypeDefs);
2119
- const typeDefs = treeshakeTypesDefs(original, modules.reduce((typeDefs, externalMod) => typeDefs.concat(externalMod.typeDefs), []));
2120
- return typeDefs;
2121
- }
2122
- function replaceExtensions(typeDefs) {
2123
- const types = [];
2124
- const extensions = [];
2125
- // List all object types
2126
- typeDefs.forEach((doc) => {
2127
- visit(doc, {
2128
- ObjectTypeDefinition(node) {
2129
- types.push(node.name.value);
2130
- },
2131
- });
2132
- });
2133
- // turn object type extensions into object types
2134
- return typeDefs.map((doc) => {
2135
- return visit(doc, {
2136
- ObjectTypeExtension(node) {
2137
- // only if object type doesn't exist
2138
- if (extensions.includes(node.name.value) ||
2139
- types.includes(node.name.value)) {
2140
- return node;
2141
- }
2142
- return {
2143
- ...node,
2144
- kind: Kind.OBJECT_TYPE_DEFINITION,
2145
- };
2146
- },
2147
- });
2148
- });
2149
- }
2150
- function treeshakeTypesDefs(originalSource, sources) {
2151
- const namedTypes = originalSource.definitions.filter(isNamedTypeDefinition);
2152
- const typesToVisit = namedTypes.map((def) => def.name.value);
2153
- const rootFields = namedTypes.reduce((acc, node) => {
2154
- const typeName = node.name.value;
2155
- if (isRootType(typeName) && hasFields(node)) {
2156
- if (!acc[typeName]) {
2157
- acc[typeName] = [];
2158
- }
2159
- node.fields.forEach((field) => {
2160
- acc[typeName].push(field.name.value);
2161
- });
2162
- }
2163
- return acc;
2164
- }, {});
2165
- const schema = concatAST([originalSource].concat(sources));
2166
- const involvedTypes = new Set(visitTypes(schema, typesToVisit, rootFields));
2167
- return {
2168
- kind: Kind.DOCUMENT,
2169
- definitions: schema.definitions.filter((def) => {
2170
- var _a, _b;
2171
- if (isNamedTypeDefinition(def)) {
2172
- const typeName = def.name.value;
2173
- if (!involvedTypes.has(def.name.value)) {
2174
- return false;
2175
- }
2176
- if ((_a = rootFields[typeName]) === null || _a === void 0 ? void 0 : _a.length) {
2177
- const rootType = def;
2178
- if ((_b = rootType.fields) === null || _b === void 0 ? void 0 : _b.every((field) => !rootFields[typeName].includes(field.name.value))) {
2179
- return false;
2180
- }
2181
- }
2182
- }
2183
- return true;
2184
- }),
2185
- };
2186
- }
2187
- function isNamedTypeDefinition(def) {
2188
- return (!!def &&
2189
- def.kind !== Kind.SCHEMA_DEFINITION &&
2190
- def.kind !== Kind.SCHEMA_EXTENSION);
2191
- }
2192
- function visitTypes(schema, types, rootFields) {
2193
- const visitedTypes = [];
2194
- const scalars = schema.definitions
2195
- .filter((def) => def.kind === Kind.SCALAR_TYPE_DEFINITION ||
2196
- def.kind === Kind.SCALAR_TYPE_EXTENSION)
2197
- .map((def) => def.name.value);
2198
- for (const typeName of types) {
2199
- collectType(typeName);
2200
- }
2201
- return visitedTypes;
2202
- function collectField(field, parentTypeName) {
2203
- var _a;
2204
- if (parentTypeName &&
2205
- isRootType(parentTypeName) &&
2206
- ((_a = rootFields[parentTypeName]) === null || _a === void 0 ? void 0 : _a.length) &&
2207
- !rootFields[parentTypeName].includes(field.name.value)) {
2208
- return;
2209
- }
2210
- collectType(resolveType(field.type));
2211
- if (field.arguments) {
2212
- field.arguments.forEach((arg) => {
2213
- collectType(resolveType(arg.type));
2214
- });
2215
- }
2216
- if (field.directives) {
2217
- field.directives.forEach((directive) => {
2218
- collectType(directive.name.value);
2219
- });
2220
- }
2221
- }
2222
- function collectType(typeName) {
2223
- if (visitedTypes.includes(typeName)) {
2224
- return;
2225
- }
2226
- if (isScalar(typeName)) {
2227
- visitedTypes.push(typeName);
2228
- return;
2229
- }
2230
- const types = findTypes(typeName);
2231
- visitedTypes.push(typeName);
2232
- types.forEach((type) => {
2233
- if (hasFields(type)) {
2234
- type.fields.forEach((field) => {
2235
- collectField(field, typeName);
2236
- });
2237
- }
2238
- if (hasTypes(type)) {
2239
- type.types.forEach((t) => {
2240
- collectType(resolveType(t));
2241
- });
2242
- }
2243
- if (hasInterfaces(type)) {
2244
- type.interfaces.forEach((i) => {
2245
- collectType(resolveType(i));
2246
- });
2247
- }
2248
- });
2249
- }
2250
- function resolveType(type) {
2251
- if (type.kind === 'ListType') {
2252
- return resolveType(type.type);
2253
- }
2254
- if (type.kind === 'NonNullType') {
2255
- return resolveType(type.type);
2256
- }
2257
- return type.name.value;
2258
- }
2259
- function isScalar(name) {
2260
- return scalars
2261
- .concat(['String', 'Boolean', 'Int', 'ID', 'Float'])
2262
- .includes(name);
2263
- }
2264
- function findTypes(typeName) {
2265
- const types = schema.definitions.filter((def) => isNamedTypeDefinition(def) && def.name.value === typeName);
2266
- if (!types.length) {
2267
- throw new Error(`Missing type "${typeName}"`);
2268
- }
2269
- return types;
2270
- }
2271
- }
2272
- function hasInterfaces(def) {
2273
- return (hasPropValue(def, 'interfaces') &&
2274
- [
2275
- Kind.OBJECT_TYPE_DEFINITION,
2276
- Kind.OBJECT_TYPE_EXTENSION,
2277
- Kind.INTERFACE_TYPE_DEFINITION,
2278
- Kind.INTERFACE_TYPE_EXTENSION,
2279
- ].includes(def.kind));
2280
- }
2281
- function hasTypes(def) {
2282
- return ([Kind.UNION_TYPE_DEFINITION, Kind.UNION_TYPE_EXTENSION].includes(def.kind) && hasPropValue(def, 'types'));
2283
- }
2284
- function hasFields(def) {
2285
- return ([
2286
- Kind.OBJECT_TYPE_DEFINITION,
2287
- Kind.OBJECT_TYPE_EXTENSION,
2288
- Kind.INTERFACE_TYPE_DEFINITION,
2289
- Kind.INTERFACE_TYPE_EXTENSION,
2290
- Kind.INPUT_OBJECT_TYPE_DEFINITION,
2291
- Kind.INPUT_OBJECT_TYPE_EXTENSION,
2292
- ].includes(def.kind) && hasPropValue(def, 'fields'));
2293
- }
2294
- function hasPropValue(obj, prop) {
2295
- return Object.prototype.hasOwnProperty.call(obj, prop) && obj[prop];
2296
- }
2297
- function isRootType(typeName) {
2298
- return (typeName === 'Query' ||
2299
- typeName === 'Mutation' ||
2300
- typeName === 'Subscription');
2301
- }
2302
-
2303
- function testInjector(providers) {
2304
- const resolvedProviders = ReflectiveInjector.resolve([
2305
- { provide: CONTEXT, useValue: {} },
2306
- ...providers,
2307
- ]);
2308
- const injector = ReflectiveInjector.createFromResolved({
2309
- name: 'test',
2310
- providers: resolvedProviders,
2311
- });
2312
- injector.instantiateAll();
2313
- return injector;
2314
- }
2315
- function readProviderOptions(provider) {
2316
- return readInjectableMetadata(provider, true).options;
2317
- }
2318
-
2319
- function execute(app, inputs, options) {
2320
- const executor = app.createExecution(options);
2321
- return executor({
2322
- schema: app.schema,
2323
- ...inputs,
2324
- });
2325
- }
2326
-
2327
- function provideEmpty(token) {
2328
- return {
2329
- provide: token,
2330
- useValue: {},
2331
- };
2332
- }
2333
-
2334
- const testkit = {
2335
- mockApplication,
2336
- mockModule,
2337
- testModule,
2338
- testInjector,
2339
- readProviderOptions,
2340
- provideEmpty,
2341
- execute,
2342
- };
2343
-
2344
- export { CONTEXT, ExecutionContext, Inject, Injectable, InjectionToken, Injector, MODULE_ID, Optional, Scope, createApplication, createModule, forwardRef, gql, metadataFactory, testkit };