@graphql-mesh/runtime 1.0.0-alpha-20220804093904-8e2e41f7f → 1.0.0-alpha-20230420220344-25b6b92bf

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs DELETED
@@ -1,429 +0,0 @@
1
- import { getNamedType, isLeafType, Kind, introspectionFromSchema, getOperationAST } from 'graphql';
2
- import { printWithCache, applySchemaTransforms, applyRequestTransforms, applyResultTransforms, PubSub, DefaultLogger, groupTransforms, getHeadersObj, parseWithCache } from '@graphql-mesh/utils';
3
- import { parseSelectionSet, isDocumentNode, isAsyncIterable, getOperationASTFromRequest, memoize1, mapAsyncIterator as mapAsyncIterator$1, AggregateError } from '@graphql-tools/utils';
4
- import { mapAsyncIterator, envelop, useExtendContext, enableIf } from '@envelop/core';
5
- import { useExtendedValidation, OneOfInputObjectsRule } from '@envelop/extended-validation';
6
- import { batchDelegateToSchema } from '@graphql-tools/batch-delegate';
7
- import { delegateToSchema, createDefaultExecutor } from '@graphql-tools/delegate';
8
- import { WrapQuery } from '@graphql-tools/wrap';
9
-
10
- const MESH_CONTEXT_SYMBOL = Symbol('isMeshContext');
11
- const MESH_API_CONTEXT_SYMBOL = Symbol('isMeshAPIContext');
12
-
13
- async function getInContextSDK(unifiedSchema, rawSources, logger) {
14
- const inContextSDK = {};
15
- const sourceMap = unifiedSchema.extensions.sourceMap;
16
- for (const rawSource of rawSources) {
17
- const rawSourceLogger = logger.child(`${rawSource.name}`);
18
- const rawSourceContext = {
19
- rawSource,
20
- [MESH_API_CONTEXT_SYMBOL]: true,
21
- };
22
- // TODO: Somehow rawSource reference got lost in somewhere
23
- let rawSourceSubSchemaConfig;
24
- const stitchingInfo = unifiedSchema.extensions.stitchingInfo;
25
- if (stitchingInfo) {
26
- for (const [subschemaConfig, subschema] of stitchingInfo.subschemaMap) {
27
- if (subschemaConfig.name === rawSource.name) {
28
- rawSourceSubSchemaConfig = subschema;
29
- break;
30
- }
31
- }
32
- }
33
- else {
34
- rawSourceSubSchemaConfig = rawSource;
35
- }
36
- // If there is a single source, there is no unifiedSchema
37
- const transformedSchema = sourceMap.get(rawSource);
38
- const rootTypes = {
39
- query: transformedSchema.getQueryType(),
40
- mutation: transformedSchema.getMutationType(),
41
- subscription: transformedSchema.getSubscriptionType(),
42
- };
43
- rawSourceLogger.debug(`Generating In Context SDK`);
44
- for (const operationType in rootTypes) {
45
- const rootType = rootTypes[operationType];
46
- if (rootType) {
47
- rawSourceContext[rootType.name] = {};
48
- const rootTypeFieldMap = rootType.getFields();
49
- for (const fieldName in rootTypeFieldMap) {
50
- const rootTypeField = rootTypeFieldMap[fieldName];
51
- const inContextSdkLogger = rawSourceLogger.child(`InContextSDK.${rootType.name}.${fieldName}`);
52
- const namedReturnType = getNamedType(rootTypeField.type);
53
- const shouldHaveSelectionSet = !isLeafType(namedReturnType);
54
- rawSourceContext[rootType.name][fieldName] = ({ root, args, context, info = {
55
- fieldName,
56
- fieldNodes: [],
57
- returnType: namedReturnType,
58
- parentType: rootType,
59
- path: {
60
- typename: rootType.name,
61
- key: fieldName,
62
- prev: undefined,
63
- },
64
- schema: transformedSchema,
65
- fragments: {},
66
- rootValue: root,
67
- operation: {
68
- kind: Kind.OPERATION_DEFINITION,
69
- operation: operationType,
70
- selectionSet: {
71
- kind: Kind.SELECTION_SET,
72
- selections: [],
73
- },
74
- },
75
- variableValues: {},
76
- cacheControl: {
77
- setCacheHint: () => { },
78
- cacheHint: {},
79
- },
80
- }, selectionSet, key, argsFromKeys, valuesFromResults, }) => {
81
- inContextSdkLogger.debug(`Called with`, {
82
- args,
83
- key,
84
- });
85
- const commonDelegateOptions = {
86
- schema: rawSourceSubSchemaConfig,
87
- rootValue: root,
88
- operation: operationType,
89
- fieldName,
90
- context,
91
- transformedSchema,
92
- info,
93
- };
94
- // If there isn't an extraction of a value
95
- if (typeof selectionSet !== 'function') {
96
- commonDelegateOptions.returnType = rootTypeField.type;
97
- }
98
- if (shouldHaveSelectionSet) {
99
- let selectionCount = 0;
100
- for (const fieldNode of info.fieldNodes) {
101
- if (fieldNode.selectionSet != null) {
102
- selectionCount += fieldNode.selectionSet.selections.length;
103
- }
104
- }
105
- if (selectionCount === 0) {
106
- if (!selectionSet) {
107
- throw new Error(`You have to provide 'selectionSet' for context.${rawSource.name}.${rootType.name}.${fieldName}`);
108
- }
109
- commonDelegateOptions.info = {
110
- ...info,
111
- fieldNodes: [
112
- {
113
- ...info.fieldNodes[0],
114
- selectionSet: {
115
- kind: Kind.SELECTION_SET,
116
- selections: [
117
- {
118
- kind: Kind.FIELD,
119
- name: {
120
- kind: Kind.NAME,
121
- value: '__typename',
122
- },
123
- },
124
- ],
125
- },
126
- },
127
- ...info.fieldNodes.slice(1),
128
- ],
129
- };
130
- }
131
- }
132
- if (key && argsFromKeys) {
133
- const batchDelegationOptions = {
134
- ...commonDelegateOptions,
135
- key,
136
- argsFromKeys,
137
- valuesFromResults,
138
- };
139
- if (selectionSet) {
140
- const selectionSetFactory = normalizeSelectionSetParamOrFactory(selectionSet);
141
- const path = [fieldName];
142
- const wrapQueryTransform = new WrapQuery(path, selectionSetFactory, identical);
143
- batchDelegationOptions.transforms = [wrapQueryTransform];
144
- }
145
- return batchDelegateToSchema(batchDelegationOptions);
146
- }
147
- else {
148
- const regularDelegateOptions = {
149
- ...commonDelegateOptions,
150
- args,
151
- };
152
- if (selectionSet) {
153
- const selectionSetFactory = normalizeSelectionSetParamOrFactory(selectionSet);
154
- const path = [fieldName];
155
- const wrapQueryTransform = new WrapQuery(path, selectionSetFactory, valuesFromResults || identical);
156
- regularDelegateOptions.transforms = [wrapQueryTransform];
157
- }
158
- return delegateToSchema(regularDelegateOptions);
159
- }
160
- };
161
- }
162
- }
163
- }
164
- inContextSDK[rawSource.name] = rawSourceContext;
165
- }
166
- return inContextSDK;
167
- }
168
- function normalizeSelectionSetParam(selectionSetParam) {
169
- if (typeof selectionSetParam === 'string') {
170
- return parseSelectionSet(selectionSetParam);
171
- }
172
- if (isDocumentNode(selectionSetParam)) {
173
- return parseSelectionSet(printWithCache(selectionSetParam));
174
- }
175
- return selectionSetParam;
176
- }
177
- function normalizeSelectionSetParamOrFactory(selectionSetParamOrFactory) {
178
- return function getSelectionSet(subtree) {
179
- if (typeof selectionSetParamOrFactory === 'function') {
180
- const selectionSetParam = selectionSetParamOrFactory(subtree);
181
- return normalizeSelectionSetParam(selectionSetParam);
182
- }
183
- else {
184
- return normalizeSelectionSetParam(selectionSetParamOrFactory);
185
- }
186
- };
187
- }
188
- function identical(val) {
189
- return val;
190
- }
191
-
192
- function getExecuteFnByArgs(args, subschema) {
193
- var _a, _b;
194
- const transformationContext = {};
195
- const originalRequest = {
196
- document: args.document,
197
- variables: args.variableValues,
198
- operationName: (_a = args.operationName) !== null && _a !== void 0 ? _a : undefined,
199
- rootValue: args.rootValue,
200
- context: args.contextValue,
201
- };
202
- const operationAST = getOperationASTFromRequest(originalRequest);
203
- const delegationContext = {
204
- subschema,
205
- subschemaConfig: subschema,
206
- targetSchema: args.schema,
207
- operation: operationAST.operation,
208
- fieldName: '',
209
- context: args.contextValue,
210
- rootValue: args.rootValue,
211
- transforms: subschema.transforms,
212
- transformedSchema: args.schema,
213
- skipTypeMerging: true,
214
- returnType: {}, // Might not work
215
- };
216
- const executor = (_b = subschema.executor) !== null && _b !== void 0 ? _b : createDefaultExecutor(subschema.schema);
217
- return async function subschemaExecute() {
218
- const transformedRequest = applyRequestTransforms(originalRequest, delegationContext, transformationContext, subschema.transforms);
219
- const originalResult = await executor(transformedRequest);
220
- if (isAsyncIterable(originalResult)) {
221
- return mapAsyncIterator(originalResult, singleResult => applyResultTransforms(singleResult, delegationContext, transformationContext, subschema.transforms));
222
- }
223
- const transformedResult = applyResultTransforms(originalResult, delegationContext, transformationContext, subschema.transforms);
224
- return transformedResult;
225
- };
226
- }
227
- // Creates an envelop plugin to execute a subschema inside Envelop
228
- function useSubschema(subschema) {
229
- const transformedSchema = applySchemaTransforms(subschema.schema, subschema, subschema.schema, subschema.transforms);
230
- const plugin = {
231
- onPluginInit({ setSchema }) {
232
- setSchema(transformedSchema);
233
- },
234
- onExecute({ args, setExecuteFn, setResultAndStopExecution }) {
235
- // TODO: This is a hack to make introspection work properly
236
- if (args.operationName === 'IntrospectionQuery') {
237
- setResultAndStopExecution({
238
- data: introspectionFromSchema(args.schema),
239
- });
240
- }
241
- setExecuteFn(getExecuteFnByArgs(args, subschema));
242
- },
243
- onSubscribe({ args, setSubscribeFn }) {
244
- setSubscribeFn(getExecuteFnByArgs(args, subschema));
245
- },
246
- };
247
- return {
248
- transformedSchema,
249
- plugin,
250
- };
251
- }
252
-
253
- const memoizedGetOperationType = memoize1((document) => {
254
- const operationAST = getOperationAST(document, undefined);
255
- if (!operationAST) {
256
- throw new Error('Must provide document with a valid operation');
257
- }
258
- return operationAST.operation;
259
- });
260
- const memoizedGetEnvelopedFactory = memoize1(function getEnvelopedFactory(plugins) {
261
- const getEnveloped = envelop({ plugins });
262
- return memoize1(function getEnvelopedByContext(initialContext) {
263
- return getEnveloped(initialContext);
264
- });
265
- });
266
- async function getMesh(options) {
267
- const rawSources = [];
268
- const { pubsub = new PubSub(), cache, logger = new DefaultLogger('🕸️ Mesh'), additionalEnvelopPlugins = [], sources, merger, additionalResolvers = [], additionalTypeDefs = [], transforms = [], } = options;
269
- const getMeshLogger = logger.child('GetMesh');
270
- getMeshLogger.debug(`Getting subschemas from source handlers`);
271
- let failed = false;
272
- await Promise.allSettled(sources.map(async (apiSource) => {
273
- const apiName = apiSource.name;
274
- const sourceLogger = logger.child(apiName);
275
- sourceLogger.debug(`Generating the schema`);
276
- try {
277
- const source = await apiSource.handler.getMeshSource();
278
- sourceLogger.debug(`The schema has been generated successfully`);
279
- let apiSchema = source.schema;
280
- sourceLogger.debug(`Analyzing transforms`);
281
- let transforms;
282
- const { wrapTransforms, noWrapTransforms } = groupTransforms(apiSource.transforms);
283
- if (!(wrapTransforms === null || wrapTransforms === void 0 ? void 0 : wrapTransforms.length) && (noWrapTransforms === null || noWrapTransforms === void 0 ? void 0 : noWrapTransforms.length)) {
284
- sourceLogger.debug(`${noWrapTransforms.length} bare transforms found and applying`);
285
- apiSchema = applySchemaTransforms(apiSchema, source, null, noWrapTransforms);
286
- }
287
- else {
288
- transforms = apiSource.transforms;
289
- }
290
- rawSources.push({
291
- name: apiName,
292
- schema: apiSchema,
293
- executor: source.executor,
294
- transforms,
295
- contextVariables: source.contextVariables || {},
296
- handler: apiSource.handler,
297
- batch: 'batch' in source ? source.batch : true,
298
- merge: apiSource.merge,
299
- });
300
- }
301
- catch (e) {
302
- sourceLogger.error(`Failed to generate the schema`, e);
303
- failed = true;
304
- }
305
- }));
306
- if (failed) {
307
- throw new Error(`Schemas couldn't be generated successfully. Check for the logs by running Mesh with DEBUG=1 environmental variable to get more verbose output.`);
308
- }
309
- getMeshLogger.debug(`Schemas have been generated by the source handlers`);
310
- getMeshLogger.debug(`Merging schemas using the defined merging strategy.`);
311
- const unifiedSubschema = await merger.getUnifiedSchema({
312
- rawSources,
313
- typeDefs: additionalTypeDefs,
314
- resolvers: additionalResolvers,
315
- });
316
- unifiedSubschema.transforms = unifiedSubschema.transforms || [];
317
- unifiedSubschema.transforms.push(...transforms);
318
- let inContextSDK$;
319
- const { plugin: subschemaPlugin, transformedSchema: finalSchema } = useSubschema(unifiedSubschema);
320
- finalSchema.extensions = unifiedSubschema.schema.extensions;
321
- const plugins = [
322
- subschemaPlugin,
323
- // TODO: Not a good practise to expect users to be a Yoga user
324
- useExtendContext(({ request, req }) => {
325
- // Maybe Node-like environment
326
- if (req === null || req === void 0 ? void 0 : req.headers) {
327
- return {
328
- headers: req.headers,
329
- };
330
- }
331
- // Fetch environment
332
- if (request === null || request === void 0 ? void 0 : request.headers) {
333
- return {
334
- headers: getHeadersObj(request.headers),
335
- };
336
- }
337
- return {};
338
- }),
339
- useExtendContext(() => ({
340
- pubsub,
341
- cache,
342
- logger,
343
- [MESH_CONTEXT_SYMBOL]: true,
344
- })),
345
- useExtendContext(() => {
346
- if (!inContextSDK$) {
347
- inContextSDK$ = getInContextSDK(finalSchema, rawSources, logger);
348
- }
349
- return inContextSDK$;
350
- }),
351
- enableIf(!!finalSchema.getDirective('oneOf'), () => useExtendedValidation({
352
- rules: [OneOfInputObjectsRule],
353
- })),
354
- {
355
- onParse({ setParseFn }) {
356
- setParseFn(parseWithCache);
357
- },
358
- },
359
- ...additionalEnvelopPlugins,
360
- ];
361
- const EMPTY_ROOT_VALUE = {};
362
- const EMPTY_CONTEXT_VALUE = {};
363
- const EMPTY_VARIABLES_VALUE = {};
364
- async function meshExecute(documentOrSDL, variableValues = EMPTY_VARIABLES_VALUE, contextValue = EMPTY_CONTEXT_VALUE, rootValue = EMPTY_ROOT_VALUE, operationName) {
365
- const getEnveloped = memoizedGetEnvelopedFactory(plugins);
366
- const { execute, contextFactory, parse } = getEnveloped(contextValue);
367
- return execute({
368
- document: typeof documentOrSDL === 'string' ? parse(documentOrSDL) : documentOrSDL,
369
- contextValue: await contextFactory(),
370
- rootValue,
371
- variableValues: variableValues,
372
- schema: unifiedSubschema.schema,
373
- operationName,
374
- });
375
- }
376
- async function meshSubscribe(documentOrSDL, variableValues = EMPTY_VARIABLES_VALUE, contextValue = EMPTY_CONTEXT_VALUE, rootValue = EMPTY_ROOT_VALUE, operationName) {
377
- const getEnveloped = memoizedGetEnvelopedFactory(plugins);
378
- const { subscribe, contextFactory, parse } = getEnveloped(contextValue);
379
- return subscribe({
380
- document: typeof documentOrSDL === 'string' ? parse(documentOrSDL) : documentOrSDL,
381
- contextValue: await contextFactory(),
382
- rootValue,
383
- variableValues: variableValues,
384
- schema: unifiedSubschema.schema,
385
- operationName,
386
- });
387
- }
388
- function sdkRequesterFactory(globalContext) {
389
- return async function meshSdkRequester(document, variables, contextValue) {
390
- const executeFn = memoizedGetOperationType(document) === 'subscription' ? meshSubscribe : meshExecute;
391
- const result = await executeFn(document, variables, {
392
- ...globalContext,
393
- ...contextValue,
394
- });
395
- if (isAsyncIterable(result)) {
396
- return mapAsyncIterator$1(result, extractDataOrThrowErrors);
397
- }
398
- return extractDataOrThrowErrors(result);
399
- };
400
- }
401
- return {
402
- execute: meshExecute,
403
- subscribe: meshSubscribe,
404
- schema: finalSchema,
405
- rawSources,
406
- cache,
407
- pubsub,
408
- destroy() {
409
- return pubsub.publish('destroy', undefined);
410
- },
411
- logger,
412
- plugins,
413
- get getEnveloped() {
414
- return memoizedGetEnvelopedFactory(plugins);
415
- },
416
- sdkRequesterFactory,
417
- };
418
- }
419
- function extractDataOrThrowErrors(result) {
420
- if (result.errors) {
421
- if (result.errors.length === 1) {
422
- throw result.errors[0];
423
- }
424
- throw new AggregateError(result.errors);
425
- }
426
- return result.data;
427
- }
428
-
429
- export { getMesh, useSubschema };
package/types.d.ts DELETED
@@ -1,42 +0,0 @@
1
- import { KeyValueCache, MeshPubSub, GraphQLOperation, MeshHandler, MeshTransform, YamlConfig, Logger, MeshMerger } from '@graphql-mesh/types';
2
- import { DocumentNode, ExecutionResult } from 'graphql';
3
- import { IResolvers, Source } from '@graphql-tools/utils';
4
- import { MESH_CONTEXT_SYMBOL } from './constants';
5
- import { MergedTypeConfig } from '@graphql-tools/delegate';
6
- import { MeshInstance } from './get-mesh';
7
- import { envelop } from '@envelop/core';
8
- export declare type GetMeshOptions = {
9
- sources: MeshResolvedSource[];
10
- transforms?: MeshTransform[];
11
- additionalTypeDefs?: DocumentNode[];
12
- additionalResolvers?: IResolvers | IResolvers[];
13
- cache: KeyValueCache;
14
- pubsub?: MeshPubSub;
15
- merger: MeshMerger;
16
- logger?: Logger;
17
- additionalEnvelopPlugins?: Parameters<typeof envelop>[0]['plugins'];
18
- documents?: Source[];
19
- };
20
- export declare type MeshResolvedSource = {
21
- name: string;
22
- handler: MeshHandler;
23
- transforms?: MeshTransform[];
24
- merge?: Record<string, MergedTypeConfig>;
25
- };
26
- export declare type ExecuteMeshFn<TData = any, TVariables = any, TContext = any, TRootValue = any> = (document: GraphQLOperation<TData, TVariables>, variables: TVariables, context?: TContext, rootValue?: TRootValue, operationName?: string) => Promise<ExecutionResult<TData>>;
27
- export declare type SubscribeMeshFn<TVariables = any, TContext = any, TRootValue = any, TData = any> = (document: GraphQLOperation<TData, TVariables>, variables?: TVariables, context?: TContext, rootValue?: TRootValue, operationName?: string) => Promise<ExecutionResult<TData> | AsyncIterable<ExecutionResult<TData>>>;
28
- export declare type MeshContext = {
29
- [MESH_CONTEXT_SYMBOL]: true;
30
- } & {
31
- pubsub: MeshPubSub;
32
- cache: KeyValueCache;
33
- logger: Logger;
34
- };
35
- export interface ServeMeshOptions {
36
- baseDir: string;
37
- getBuiltMesh: () => Promise<MeshInstance>;
38
- logger: Logger;
39
- rawServeConfig: YamlConfig.Config['serve'];
40
- argsPort?: number;
41
- playgroundTitle?: string;
42
- }
package/useSubschema.d.ts DELETED
@@ -1,7 +0,0 @@
1
- import { SubschemaConfig } from '@graphql-tools/delegate';
2
- import { Plugin } from '@envelop/core';
3
- import { GraphQLSchema } from 'graphql';
4
- export declare function useSubschema(subschema: SubschemaConfig): {
5
- transformedSchema: GraphQLSchema;
6
- plugin: Plugin;
7
- };
File without changes