@teambit/graphql 1.0.106 → 1.0.108

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/create-link.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { HttpLink, split } from '@apollo/client';
2
+ import { getMainDefinition } from '@apollo/client/utilities';
3
+ import type { WebSocketLink } from '@apollo/client/link/ws';
4
+
5
+ /**
6
+ * create a link which splits routes data depending on type of operation.
7
+ * @param httpLink http link for apollo graphql
8
+ * @param wsLink web socket link for apollo graphql
9
+ */
10
+ export function createSplitLink(httpLink: HttpLink, wsLink: WebSocketLink) {
11
+ return split(
12
+ // split based on operation type
13
+ ({ query }) => {
14
+ const definition = getMainDefinition(query);
15
+ return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
16
+ },
17
+ wsLink,
18
+ httpLink
19
+ );
20
+ }
@@ -74,11 +74,9 @@ async function getRemoteSchema({
74
74
  }) {
75
75
  const wrappingLink = new (_apolloLink().ApolloLink)((operation, forward) => {
76
76
  return forward(operation).map(response => {
77
- var _context$response;
78
77
  const context = operation.getContext();
79
- if (context !== null && context !== void 0 && (_context$response = context.response) !== null && _context$response !== void 0 && (_context$response = _context$response.headers) !== null && _context$response !== void 0 && _context$response.get('set-cookie')) {
80
- var _context$graphqlConte, _context$response2;
81
- context === null || context === void 0 || (_context$graphqlConte = context.graphqlContext) === null || _context$graphqlConte === void 0 || (_context$graphqlConte = _context$graphqlConte.res) === null || _context$graphqlConte === void 0 || _context$graphqlConte.setHeader('set-cookie', context === null || context === void 0 || (_context$response2 = context.response) === null || _context$response2 === void 0 || (_context$response2 = _context$response2.headers) === null || _context$response2 === void 0 ? void 0 : _context$response2.get('set-cookie'));
78
+ if (context?.response?.headers?.get('set-cookie')) {
79
+ context?.graphqlContext?.res?.setHeader('set-cookie', context?.response?.headers?.get('set-cookie'));
82
80
  }
83
81
  return response;
84
82
  });
@@ -89,9 +87,8 @@ async function getRemoteSchema({
89
87
  fetch: _nodeFetch().default
90
88
  });
91
89
  const httpLink = (0, _apolloLinkContext().setContext)((request, previousContext) => {
92
- var _previousContext$grap;
93
90
  return {
94
- headers: previousContext === null || previousContext === void 0 || (_previousContext$grap = previousContext.graphqlContext) === null || _previousContext$grap === void 0 ? void 0 : _previousContext$grap.headers
91
+ headers: previousContext?.graphqlContext?.headers
95
92
  };
96
93
  }).concat(wrappingLink).concat(http);
97
94
  if (!subscriptionsUri) {
@@ -1 +1 @@
1
- {"version":3,"names":["_nodeFetch","data","_interopRequireDefault","require","_apolloLinkContext","_apolloLinkHttp","_apolloServer","_apolloLinkWs","_apolloLink","_apolloUtilities","_subscriptionsTransportWs","_ws","obj","__esModule","default","getRemoteSchema","uri","subscriptionsUri","wrappingLink","ApolloLink","operation","forward","map","response","_context$response","context","getContext","headers","get","_context$graphqlConte","_context$response2","graphqlContext","res","setHeader","http","HttpLink","fetch","httpLink","setContext","request","previousContext","_previousContext$grap","concat","makeRemoteExecutableSchema","schema","introspectSchema","link","client","SubscriptionClient","reconnect","ws","wsLink","WebSocketLink","split","definition","getMainDefinition","query","kind","createRemoteSchemas","servers","schemasP","server","Promise","all"],"sources":["create-remote-schemas.ts"],"sourcesContent":["import fetch from 'node-fetch';\nimport { setContext } from 'apollo-link-context';\nimport { HttpLink } from 'apollo-link-http';\nimport { makeRemoteExecutableSchema, introspectSchema } from 'apollo-server';\nimport { WebSocketLink } from 'apollo-link-ws';\nimport { split, ApolloLink } from 'apollo-link';\nimport { getMainDefinition } from 'apollo-utilities';\nimport { SubscriptionClient } from 'subscriptions-transport-ws';\nimport ws from 'ws';\nimport { GraphQLServer } from '../graphql-server';\n\nasync function getRemoteSchema({ uri, subscriptionsUri }) {\n const wrappingLink = new ApolloLink((operation, forward) => {\n return forward(operation).map((response) => {\n const context = operation.getContext();\n if (context?.response?.headers?.get('set-cookie')) {\n context?.graphqlContext?.res?.setHeader('set-cookie', context?.response?.headers?.get('set-cookie'));\n }\n return response;\n });\n });\n // @ts-ignore\n const http = new HttpLink({ uri, fetch });\n const httpLink = setContext((request, previousContext) => {\n return {\n headers: previousContext?.graphqlContext?.headers,\n };\n })\n .concat(wrappingLink)\n .concat(http);\n\n if (!subscriptionsUri) {\n return makeRemoteExecutableSchema({\n schema: await introspectSchema(httpLink),\n link: httpLink,\n });\n }\n\n // Create WebSocket link with custom client\n const client = new SubscriptionClient(subscriptionsUri, { reconnect: true }, ws);\n const wsLink = new WebSocketLink(client);\n\n // Using the ability to split links, we can send data to each link\n // depending on what kind of operation is being sent\n const link = split(\n (operation) => {\n const definition = getMainDefinition(operation.query);\n return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';\n },\n wsLink,\n httpLink\n );\n\n return makeRemoteExecutableSchema({\n schema: await introspectSchema(httpLink),\n link,\n });\n}\n\nexport async function createRemoteSchemas(servers: GraphQLServer[]) {\n const schemasP = servers.map(async (server) => {\n return getRemoteSchema({\n uri: server.uri,\n subscriptionsUri: server.subscriptionsUri,\n });\n });\n\n return Promise.all(schemasP);\n}\n"],"mappings":";;;;;;AAAA,SAAAA,WAAA;EAAA,MAAAC,IAAA,GAAAC,sBAAA,CAAAC,OAAA;EAAAH,UAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAG,mBAAA;EAAA,MAAAH,IAAA,GAAAE,OAAA;EAAAC,kBAAA,YAAAA,CAAA;IAAA,OAAAH,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAI,gBAAA;EAAA,MAAAJ,IAAA,GAAAE,OAAA;EAAAE,eAAA,YAAAA,CAAA;IAAA,OAAAJ,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAK,cAAA;EAAA,MAAAL,IAAA,GAAAE,OAAA;EAAAG,aAAA,YAAAA,CAAA;IAAA,OAAAL,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAM,cAAA;EAAA,MAAAN,IAAA,GAAAE,OAAA;EAAAI,a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;EAExC;EACA;EACA,MAAMD,IAAI,GAAG,IAAAO,mBAAK,EACfjC,SAAS,IAAK;IACb,MAAMkC,UAAU,GAAG,IAAAC,oCAAiB,EAACnC,SAAS,CAACoC,KAAK,CAAC;IACrD,OAAOF,UAAU,CAACG,IAAI,KAAK,qBAAqB,IAAIH,UAAU,CAAClC,SAAS,KAAK,cAAc;EAC7F,CAAC,EACD+B,MAAM,EACNd,QACF,CAAC;EAED,OAAO,IAAAM,0CAA0B,EAAC;IAChCC,MAAM,EAAE,MAAM,IAAAC,gCAAgB,EAACR,QAAQ,CAAC;IACxCS;EACF,CAAC,CAAC;AACJ;AAEO,eAAeY,mBAAmBA,CAACC,OAAwB,EAAE;EAClE,MAAMC,QAAQ,GAAGD,OAAO,CAACrC,GAAG,CAAC,MAAOuC,MAAM,IAAK;IAC7C,OAAO9C,eAAe,CAAC;MACrBC,GAAG,EAAE6C,MAAM,CAAC7C,GAAG;MACfC,gBAAgB,EAAE4C,MAAM,CAAC5C;IAC3B,CAAC,CAAC;EACJ,CAAC,CAAC;EAEF,OAAO6C,OAAO,CAACC,GAAG,CAACH,QAAQ,CAAC;AAC9B"}
1
+ {"version":3,"names":["_nodeFetch","data","_interopRequireDefault","require","_apolloLinkContext","_apolloLinkHttp","_apolloServer","_apolloLinkWs","_apolloLink","_apolloUtilities","_subscriptionsTransportWs","_ws","obj","__esModule","default","getRemoteSchema","uri","subscriptionsUri","wrappingLink","ApolloLink","operation","forward","map","response","context","getContext","headers","get","graphqlContext","res","setHeader","http","HttpLink","fetch","httpLink","setContext","request","previousContext","concat","makeRemoteExecutableSchema","schema","introspectSchema","link","client","SubscriptionClient","reconnect","ws","wsLink","WebSocketLink","split","definition","getMainDefinition","query","kind","createRemoteSchemas","servers","schemasP","server","Promise","all"],"sources":["create-remote-schemas.ts"],"sourcesContent":["import fetch from 'node-fetch';\nimport { setContext } from 'apollo-link-context';\nimport { HttpLink } from 'apollo-link-http';\nimport { makeRemoteExecutableSchema, introspectSchema } from 'apollo-server';\nimport { WebSocketLink } from 'apollo-link-ws';\nimport { split, ApolloLink } from 'apollo-link';\nimport { getMainDefinition } from 'apollo-utilities';\nimport { SubscriptionClient } from 'subscriptions-transport-ws';\nimport ws from 'ws';\nimport { GraphQLServer } from '../graphql-server';\n\nasync function getRemoteSchema({ uri, subscriptionsUri }) {\n const wrappingLink = new ApolloLink((operation, forward) => {\n return forward(operation).map((response) => {\n const context = operation.getContext();\n if (context?.response?.headers?.get('set-cookie')) {\n context?.graphqlContext?.res?.setHeader('set-cookie', context?.response?.headers?.get('set-cookie'));\n }\n return response;\n });\n });\n // @ts-ignore\n const http = new HttpLink({ uri, fetch });\n const httpLink = setContext((request, previousContext) => {\n return {\n headers: previousContext?.graphqlContext?.headers,\n };\n })\n .concat(wrappingLink)\n .concat(http);\n\n if (!subscriptionsUri) {\n return makeRemoteExecutableSchema({\n schema: await introspectSchema(httpLink),\n link: httpLink,\n });\n }\n\n // Create WebSocket link with custom client\n const client = new SubscriptionClient(subscriptionsUri, { reconnect: true }, ws);\n const wsLink = new WebSocketLink(client);\n\n // Using the ability to split links, we can send data to each link\n // depending on what kind of operation is being sent\n const link = split(\n (operation) => {\n const definition = getMainDefinition(operation.query);\n return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';\n },\n wsLink,\n httpLink\n );\n\n return makeRemoteExecutableSchema({\n schema: await introspectSchema(httpLink),\n link,\n });\n}\n\nexport async function createRemoteSchemas(servers: GraphQLServer[]) {\n const schemasP = servers.map(async (server) => {\n return getRemoteSchema({\n uri: server.uri,\n subscriptionsUri: server.subscriptionsUri,\n });\n });\n\n return Promise.all(schemasP);\n}\n"],"mappings":";;;;;;AAAA,SAAAA,WAAA;EAAA,MAAAC,IAAA,GAAAC,sBAAA,CAAAC,OAAA;EAAAH,UAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAG,mBAAA;EAAA,MAAAH,IAAA,GAAAE,OAAA;EAAA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AAS,CAACgC,KAAK,CAAC;IACrD,OAAOF,UAAU,CAACG,IAAI,KAAK,qBAAqB,IAAIH,UAAU,CAAC9B,SAAS,KAAK,cAAc;EAC7F,CAAC,EACD2B,MAAM,EACNb,QACF,CAAC;EAED,OAAO,IAAAK,0CAA0B,EAAC;IAChCC,MAAM,EAAE,MAAM,IAAAC,gCAAgB,EAACP,QAAQ,CAAC;IACxCQ;EACF,CAAC,CAAC;AACJ;AAEO,eAAeY,mBAAmBA,CAACC,OAAwB,EAAE;EAClE,MAAMC,QAAQ,GAAGD,OAAO,CAACjC,GAAG,CAAC,MAAOmC,MAAM,IAAK;IAC7C,OAAO1C,eAAe,CAAC;MACrBC,GAAG,EAAEyC,MAAM,CAACzC,GAAG;MACfC,gBAAgB,EAAEwC,MAAM,CAACxC;IAC3B,CAAC,CAAC;EACJ,CAAC,CAAC;EAEF,OAAOyC,OAAO,CAACC,GAAG,CAACH,QAAQ,CAAC;AAC9B"}
@@ -6,7 +6,7 @@ export declare class GraphQlError {
6
6
  /**
7
7
  * error message of the error
8
8
  */
9
- readonly message?: string | undefined;
9
+ readonly message?: string;
10
10
  constructor(
11
11
  /**
12
12
  * http status code of error
@@ -15,5 +15,5 @@ export declare class GraphQlError {
15
15
  /**
16
16
  * error message of the error
17
17
  */
18
- message?: string | undefined);
18
+ message?: string);
19
19
  }
@@ -1,7 +1,7 @@
1
- import React, { ReactNode } from 'react';
1
+ import { ReactNode } from 'react';
2
2
  import type { GraphQLClient } from '../graphql.ui.runtime';
3
- export declare type GraphQLProviderProps = {
3
+ export type GraphQLProviderProps = {
4
4
  client: GraphQLClient<any>;
5
5
  children: ReactNode;
6
6
  };
7
- export declare function GraphQLProvider({ client, children }: GraphQLProviderProps): React.JSX.Element;
7
+ export declare function GraphQLProvider({ client, children }: GraphQLProviderProps): JSX.Element;
@@ -1,2 +1,2 @@
1
- import React from 'react';
2
- export declare const Logo: () => React.JSX.Element;
1
+ /// <reference types="react" />
2
+ export declare const Logo: () => JSX.Element;
@@ -10,16 +10,16 @@ export declare enum Verb {
10
10
  WRITE = "write",
11
11
  READ = "read"
12
12
  }
13
- export declare type GraphQLConfig = {
13
+ export type GraphQLConfig = {
14
14
  port: number;
15
15
  subscriptionsPortRange: number[];
16
16
  subscriptionsPath: string;
17
17
  disableCors?: boolean;
18
18
  };
19
- export declare type GraphQLServerSlot = SlotRegistry<GraphQLServer>;
20
- export declare type SchemaSlot = SlotRegistry<Schema>;
21
- export declare type PubSubSlot = SlotRegistry<PubSubEngine>;
22
- export declare type GraphQLServerOptions = {
19
+ export type GraphQLServerSlot = SlotRegistry<GraphQLServer>;
20
+ export type SchemaSlot = SlotRegistry<Schema>;
21
+ export type PubSubSlot = SlotRegistry<PubSubEngine>;
22
+ export type GraphQLServerOptions = {
23
23
  schemaSlot?: SchemaSlot;
24
24
  app?: Express;
25
25
  graphiql?: boolean;
@@ -76,7 +76,7 @@ export declare class GraphqlMain {
76
76
  /**
77
77
  * returns the schema for a specific aspect by its id.
78
78
  */
79
- getSchema(aspectId: string): Schema | undefined;
79
+ getSchema(aspectId: string): Schema;
80
80
  /**
81
81
  * get multiple schema by aspect ids.
82
82
  */
@@ -214,14 +214,13 @@ class GraphqlMain {
214
214
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
215
215
  (0, _expressGraphql().graphqlHTTP)((request, res, params) => ({
216
216
  customFormatErrorFn: err => {
217
- var _err$originalError, _err$originalError2, _err$originalError3, _err$originalError4;
218
217
  this.logger.error('graphql got an error during running the following query:', params);
219
218
  this.logger.error('graphql error ', err);
220
219
  return Object.assign(err, {
221
220
  // @ts-ignore
222
- ERR_CODE: (err === null || err === void 0 || (_err$originalError = err.originalError) === null || _err$originalError === void 0 || (_err$originalError = _err$originalError.errors) === null || _err$originalError === void 0 ? void 0 : _err$originalError[0].ERR_CODE) || ((_err$originalError2 = err.originalError) === null || _err$originalError2 === void 0 || (_err$originalError2 = _err$originalError2.constructor) === null || _err$originalError2 === void 0 ? void 0 : _err$originalError2.name),
221
+ ERR_CODE: err?.originalError?.errors?.[0].ERR_CODE || err.originalError?.constructor?.name,
223
222
  // @ts-ignore
224
- HTTP_CODE: (err === null || err === void 0 || (_err$originalError3 = err.originalError) === null || _err$originalError3 === void 0 || (_err$originalError3 = _err$originalError3.errors) === null || _err$originalError3 === void 0 ? void 0 : _err$originalError3[0].HTTP_CODE) || ((_err$originalError4 = err.originalError) === null || _err$originalError4 === void 0 ? void 0 : _err$originalError4.code)
223
+ HTTP_CODE: err?.originalError?.errors?.[0].HTTP_CODE || err.originalError?.code
225
224
  });
226
225
  },
227
226
  schema,
@@ -349,9 +348,8 @@ class GraphqlMain {
349
348
  schemaDirectives: schema.schemaDirectives,
350
349
  imports: moduleDeps,
351
350
  context: session => {
352
- var _session$headers;
353
351
  return _objectSpread(_objectSpread({}, session), {}, {
354
- verb: (session === null || session === void 0 || (_session$headers = session.headers) === null || _session$headers === void 0 ? void 0 : _session$headers['x-verb']) || Verb.READ
352
+ verb: session?.headers?.['x-verb'] || Verb.READ
355
353
  });
356
354
  }
357
355
  });
@@ -1 +1 @@
1
- {"version":3,"names":["_schema","data","require","_graphqlDisableIntrospection","_interopRequireDefault","_core","_cli","_harmony","_logger","_express","_expressGraphql","_toolboxNetwork","_graphql","_graphqlSubscriptions","_http","_httpProxy","_subscriptionsTransportWs","_cors","_createRemoteSchemas","_graphql2","obj","__esModule","default","ownKeys","e","r","t","Object","keys","getOwnPropertySymbols","o","filter","getOwnPropertyDescriptor","enumerable","push","apply","_objectSpread","arguments","length","forEach","_defineProperty","getOwnPropertyDescriptors","defineProperties","defineProperty","key","value","_toPropertyKey","configurable","writable","i","_toPrimitive","String","Symbol","toPrimitive","call","TypeError","Number","Verb","exports","GraphqlMain","constructor","config","moduleSlot","context","logger","graphQLServerSlot","pubSubSlot","Map","pubsub","pubSubSlots","values","PubSub","getSchema","aspectId","get","getSchemas","aspectIds","toArray","includes","map","schema","createServer","options","graphiql","disableIntrospection","localSchema","createRootModule","schemaSlot","remoteSchemas","createRemoteSchemas","schemas","concat","x","mergeSchemas","app","express","disableCors","use","cors","origin","callback","credentials","graphqlHTTP","request","res","params","customFormatErrorFn","err","_err$originalError","_err$originalError2","_err$originalError3","_err$originalError4","error","assign","ERR_CODE","originalError","errors","name","HTTP_CODE","code","rootValue","validationRules","NoIntrospection","undefined","server","subscriptionsPort","subscriptionsPortRange","subscriptionServerPort","getPort","port","createSubscription","proxySubscription","registerServer","register","registerPubSub","Error","listen","serverPort","subServer","info","subscriptionsPath","range","from","to","Port","websocketServer","response","writeHead","end","debug","SubscriptionServer","execute","subscribe","onConnect","onWsConnect","path","proxServer","httpProxy","createProxyServer","on","req","socket","head","url","ws","target","host","modules","buildModules","GraphQLModule","imports","schemaSlots","extensionId","moduleDeps","getModuleDependencies","module","typeDefs","resolvers","schemaDirectives","session","_session$headers","verb","headers","READ","set","extension","extensions","deps","getDependencies","ids","dep","id","Array","entries","depId","provider","loggerFactory","createLogger","GraphqlAspect","graphqlMain","Slot","withType","MainRuntime","LoggerAspect","addRuntime"],"sources":["graphql.main.runtime.ts"],"sourcesContent":["import { mergeSchemas } from '@graphql-tools/schema';\nimport NoIntrospection from 'graphql-disable-introspection';\nimport { GraphQLModule } from '@graphql-modules/core';\nimport { MainRuntime } from '@teambit/cli';\nimport { Harmony, Slot, SlotRegistry } from '@teambit/harmony';\nimport { Logger, LoggerAspect, LoggerMain } from '@teambit/logger';\nimport express, { Express } from 'express';\nimport { graphqlHTTP } from 'express-graphql';\nimport { Port } from '@teambit/toolbox.network.get-port';\nimport { execute, subscribe } from 'graphql';\nimport { PubSubEngine, PubSub } from 'graphql-subscriptions';\nimport { createServer, Server } from 'http';\nimport httpProxy from 'http-proxy';\nimport { SubscriptionServer } from 'subscriptions-transport-ws';\nimport cors from 'cors';\nimport { GraphQLServer } from './graphql-server';\nimport { createRemoteSchemas } from './create-remote-schemas';\nimport { GraphqlAspect } from './graphql.aspect';\nimport { Schema } from './schema';\n\nexport enum Verb {\n WRITE = 'write',\n READ = 'read',\n}\n\nexport type GraphQLConfig = {\n port: number;\n subscriptionsPortRange: number[];\n subscriptionsPath: string;\n disableCors?: boolean;\n};\n\nexport type GraphQLServerSlot = SlotRegistry<GraphQLServer>;\n\nexport type SchemaSlot = SlotRegistry<Schema>;\n\nexport type PubSubSlot = SlotRegistry<PubSubEngine>;\n\nexport type GraphQLServerOptions = {\n schemaSlot?: SchemaSlot;\n app?: Express;\n graphiql?: boolean;\n disableIntrospection?: boolean;\n remoteSchemas?: GraphQLServer[];\n subscriptionsPortRange?: number[];\n onWsConnect?: Function;\n};\n\nexport class GraphqlMain {\n constructor(\n /**\n * extension config\n */\n readonly config: GraphQLConfig,\n\n /**\n * slot for registering graphql modules\n */\n private moduleSlot: SchemaSlot,\n\n /**\n * harmony context.\n */\n private context: Harmony,\n\n /**\n * logger extension.\n */\n readonly logger: Logger,\n\n private graphQLServerSlot: GraphQLServerSlot,\n\n /**\n * graphql pubsub. allows to emit events to clients.\n */\n private pubSubSlot: PubSubSlot\n ) {}\n\n get pubsub(): PubSubEngine {\n const pubSubSlots = this.pubSubSlot.values();\n if (pubSubSlots.length) return pubSubSlots[0];\n return new PubSub();\n }\n\n private modules = new Map<string, GraphQLModule>();\n\n /**\n * returns the schema for a specific aspect by its id.\n */\n getSchema(aspectId: string) {\n return this.moduleSlot.get(aspectId);\n }\n\n /**\n * get multiple schema by aspect ids.\n */\n getSchemas(aspectIds: string[]) {\n return this.moduleSlot\n .toArray()\n .filter(([aspectId]) => {\n return aspectIds.includes(aspectId);\n })\n .map(([, schema]) => {\n return schema;\n });\n }\n\n async createServer(options: GraphQLServerOptions) {\n const { graphiql = true, disableIntrospection } = options;\n const localSchema = this.createRootModule(options.schemaSlot);\n const remoteSchemas = await createRemoteSchemas(options.remoteSchemas || this.graphQLServerSlot.values());\n const schemas = [localSchema.schema].concat(remoteSchemas).filter((x) => x);\n const schema = mergeSchemas({\n schemas,\n });\n\n // TODO: @guy please consider to refactor to express extension.\n const app = options.app || express();\n if (!this.config.disableCors) {\n app.use(\n // @ts-ignore todo: it's not clear what's the issue.\n cors({\n origin(origin, callback) {\n callback(null, true);\n },\n credentials: true,\n })\n );\n }\n\n app.use(\n '/graphql',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n graphqlHTTP((request, res, params) => ({\n customFormatErrorFn: (err) => {\n this.logger.error('graphql got an error during running the following query:', params);\n this.logger.error('graphql error ', err);\n return Object.assign(err, {\n // @ts-ignore\n ERR_CODE: err?.originalError?.errors?.[0].ERR_CODE || err.originalError?.constructor?.name,\n // @ts-ignore\n HTTP_CODE: err?.originalError?.errors?.[0].HTTP_CODE || err.originalError?.code,\n });\n },\n schema,\n rootValue: request,\n graphiql,\n validationRules: disableIntrospection ? [NoIntrospection] : undefined,\n }))\n );\n\n const server = createServer(app);\n const subscriptionsPort = options.subscriptionsPortRange || this.config.subscriptionsPortRange;\n const subscriptionServerPort = await this.getPort(subscriptionsPort);\n const { port } = await this.createSubscription(options, subscriptionServerPort);\n this.proxySubscription(server, port);\n\n return server;\n }\n\n /**\n * register a new graphql server.\n */\n registerServer(server: GraphQLServer) {\n this.graphQLServerSlot.register(server);\n return this;\n }\n\n /**\n * register a pubsub client\n */\n registerPubSub(pubsub: PubSubEngine) {\n const pubSubSlots = this.pubSubSlot.toArray();\n if (pubSubSlots.length) throw new Error('can not register more then one pubsub provider');\n this.pubSubSlot.register(pubsub);\n return this;\n }\n\n /**\n * start a graphql server.\n */\n async listen(port?: number, server?: Server, app?: Express) {\n const serverPort = port || this.config.port;\n const subServer = server || (await this.createServer({ app }));\n\n subServer.listen(serverPort, () => {\n this.logger.info(`API Server over HTTP is now running on http://localhost:${serverPort}`);\n this.logger.info(\n `API Server over web socket with subscriptions is now running on ws://localhost:${serverPort}/${this.config.subscriptionsPath}`\n );\n });\n }\n\n /**\n * register a new graphql module.\n */\n register(schema: Schema) {\n // const module = new GraphQLModule(schema);\n this.moduleSlot.register(schema);\n return this;\n }\n\n private async getPort(range: number[]) {\n const [from, to] = range;\n return Port.getPort(from, to);\n }\n\n /** create Subscription server with different port */\n\n private async createSubscription(options: GraphQLServerOptions, port: number) {\n // Create WebSocket listener server\n const websocketServer = createServer((request, response) => {\n response.writeHead(404);\n response.end();\n });\n\n // Bind it to port and start listening\n websocketServer.listen(port, () =>\n this.logger.debug(`Websocket Server is now running on http://localhost:${port}`)\n );\n\n const localSchema = this.createRootModule(options.schemaSlot);\n const remoteSchemas = await createRemoteSchemas(options.remoteSchemas || this.graphQLServerSlot.values());\n const schemas = [localSchema.schema].concat(remoteSchemas).filter((x) => x);\n const schema = mergeSchemas({\n schemas,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const subServer = new SubscriptionServer(\n {\n execute,\n subscribe,\n schema,\n onConnect: options.onWsConnect,\n },\n {\n server: websocketServer,\n path: this.config.subscriptionsPath,\n }\n );\n return { subServer, port };\n }\n /** proxy ws Subscription server to avoid conflict with different websocket connections */\n\n private proxySubscription(server: Server, port: number) {\n const proxServer = httpProxy.createProxyServer();\n const subscriptionsPath = this.config.subscriptionsPath;\n server.on('upgrade', function (req, socket, head) {\n if (req.url === subscriptionsPath) {\n proxServer.ws(req, socket, head, { target: { host: 'localhost', port } });\n }\n });\n }\n\n private createRootModule(schemaSlot?: SchemaSlot) {\n const modules = this.buildModules(schemaSlot);\n\n return new GraphQLModule({\n imports: modules,\n });\n }\n\n private buildModules(schemaSlot?: SchemaSlot) {\n const schemaSlots = schemaSlot ? schemaSlot.toArray() : this.moduleSlot.toArray();\n return schemaSlots.map(([extensionId, schema]) => {\n const moduleDeps = this.getModuleDependencies(extensionId);\n\n const module = new GraphQLModule({\n typeDefs: schema.typeDefs,\n resolvers: schema.resolvers,\n schemaDirectives: schema.schemaDirectives,\n imports: moduleDeps,\n context: (session) => {\n return {\n ...session,\n verb: session?.headers?.['x-verb'] || Verb.READ,\n };\n },\n });\n\n this.modules.set(extensionId, module);\n\n return module;\n });\n }\n\n private getModuleDependencies(extensionId: string): GraphQLModule[] {\n const extension = this.context.extensions.get(extensionId);\n if (!extension) throw new Error(`aspect ${extensionId} was not found`);\n const deps = this.context.getDependencies(extension);\n const ids = deps.map((dep) => dep.id);\n\n // @ts-ignore check :TODO why types are breaking here.\n return Array.from(this.modules.entries())\n .map(([depId, module]) => {\n const dep = ids.includes(depId);\n if (!dep) return undefined;\n return module;\n })\n .filter((module) => !!module);\n }\n\n static slots = [Slot.withType<Schema>(), Slot.withType<GraphQLServer>(), Slot.withType<PubSubSlot>()];\n\n static defaultConfig = {\n port: 4000,\n subscriptionsPortRange: [2000, 2100],\n disableCors: false,\n subscriptionsPath: '/subscriptions',\n };\n\n static runtime = MainRuntime;\n static dependencies = [LoggerAspect];\n\n static async provider(\n [loggerFactory]: [LoggerMain],\n config: GraphQLConfig,\n [moduleSlot, graphQLServerSlot, pubSubSlot]: [SchemaSlot, GraphQLServerSlot, PubSubSlot],\n context: Harmony\n ) {\n const logger = loggerFactory.createLogger(GraphqlAspect.id);\n const graphqlMain = new GraphqlMain(config, moduleSlot, context, logger, graphQLServerSlot, pubSubSlot);\n return graphqlMain;\n }\n}\n\nGraphqlAspect.addRuntime(GraphqlMain);\n"],"mappings":";;;;;;AAAA,SAAAA,QAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,OAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,6BAAA;EAAA,MAAAF,IAAA,GAAAG,sBAAA,CAAAF,OAAA;EAAAC,4BAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAI,MAAA;EAAA,MAAAJ,IAAA,GAAAC,OAAA;EAAAG,KAAA,YAAAA,CAAA;IAAA,OAAAJ,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAK,KAAA;EAAA,MAAAL,IAAA,GAAAC,OAAA;EAAAI,IAAA,YAAAA,CAAA;IAAA,OAAAL,IAAA;EA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,aAAa,CAACC,YAAY,CAACC,yBAAa,CAACP,EAAE,CAAC;IAC3D,MAAMQ,WAAW,GAAG,IAAI5I,WAAW,CAACE,MAAM,EAAEC,UAAU,EAAEC,OAAO,EAAEC,MAAM,EAAEC,iBAAiB,EAAEC,UAAU,CAAC;IACvG,OAAOqI,WAAW;EACpB;AACF;AAAC7I,OAAA,CAAAC,WAAA,GAAAA,WAAA;AAAAnB,eAAA,CArRYmB,WAAW,WA+PP,CAAC6I,eAAI,CAACC,QAAQ,CAAS,CAAC,EAAED,eAAI,CAACC,QAAQ,CAAgB,CAAC,EAAED,eAAI,CAACC,QAAQ,CAAa,CAAC,CAAC;AAAAjK,eAAA,CA/P1FmB,WAAW,mBAiQC;EACrBsE,IAAI,EAAE,IAAI;EACVH,sBAAsB,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC;EACpC9B,WAAW,EAAE,KAAK;EAClB4C,iBAAiB,EAAE;AACrB,CAAC;AAAApG,eAAA,CAtQUmB,WAAW,aAwQL+I,kBAAW;AAAAlK,eAAA,CAxQjBmB,WAAW,kBAyQA,CAACgJ,sBAAY,CAAC;AActCL,yBAAa,CAACM,UAAU,CAACjJ,WAAW,CAAC"}
1
+ {"version":3,"names":["_schema","data","require","_graphqlDisableIntrospection","_interopRequireDefault","_core","_cli","_harmony","_logger","_express","_expressGraphql","_toolboxNetwork","_graphql","_graphqlSubscriptions","_http","_httpProxy","_subscriptionsTransportWs","_cors","_createRemoteSchemas","_graphql2","obj","__esModule","default","ownKeys","e","r","t","Object","keys","getOwnPropertySymbols","o","filter","getOwnPropertyDescriptor","enumerable","push","apply","_objectSpread","arguments","length","forEach","_defineProperty","getOwnPropertyDescriptors","defineProperties","defineProperty","key","value","_toPropertyKey","configurable","writable","i","_toPrimitive","String","Symbol","toPrimitive","call","TypeError","Number","Verb","exports","GraphqlMain","constructor","config","moduleSlot","context","logger","graphQLServerSlot","pubSubSlot","Map","pubsub","pubSubSlots","values","PubSub","getSchema","aspectId","get","getSchemas","aspectIds","toArray","includes","map","schema","createServer","options","graphiql","disableIntrospection","localSchema","createRootModule","schemaSlot","remoteSchemas","createRemoteSchemas","schemas","concat","x","mergeSchemas","app","express","disableCors","use","cors","origin","callback","credentials","graphqlHTTP","request","res","params","customFormatErrorFn","err","error","assign","ERR_CODE","originalError","errors","name","HTTP_CODE","code","rootValue","validationRules","NoIntrospection","undefined","server","subscriptionsPort","subscriptionsPortRange","subscriptionServerPort","getPort","port","createSubscription","proxySubscription","registerServer","register","registerPubSub","Error","listen","serverPort","subServer","info","subscriptionsPath","range","from","to","Port","websocketServer","response","writeHead","end","debug","SubscriptionServer","execute","subscribe","onConnect","onWsConnect","path","proxServer","httpProxy","createProxyServer","on","req","socket","head","url","ws","target","host","modules","buildModules","GraphQLModule","imports","schemaSlots","extensionId","moduleDeps","getModuleDependencies","module","typeDefs","resolvers","schemaDirectives","session","verb","headers","READ","set","extension","extensions","deps","getDependencies","ids","dep","id","Array","entries","depId","provider","loggerFactory","createLogger","GraphqlAspect","graphqlMain","Slot","withType","MainRuntime","LoggerAspect","addRuntime"],"sources":["graphql.main.runtime.ts"],"sourcesContent":["import { mergeSchemas } from '@graphql-tools/schema';\nimport NoIntrospection from 'graphql-disable-introspection';\nimport { GraphQLModule } from '@graphql-modules/core';\nimport { MainRuntime } from '@teambit/cli';\nimport { Harmony, Slot, SlotRegistry } from '@teambit/harmony';\nimport { Logger, LoggerAspect, LoggerMain } from '@teambit/logger';\nimport express, { Express } from 'express';\nimport { graphqlHTTP } from 'express-graphql';\nimport { Port } from '@teambit/toolbox.network.get-port';\nimport { execute, subscribe } from 'graphql';\nimport { PubSubEngine, PubSub } from 'graphql-subscriptions';\nimport { createServer, Server } from 'http';\nimport httpProxy from 'http-proxy';\nimport { SubscriptionServer } from 'subscriptions-transport-ws';\nimport cors from 'cors';\nimport { GraphQLServer } from './graphql-server';\nimport { createRemoteSchemas } from './create-remote-schemas';\nimport { GraphqlAspect } from './graphql.aspect';\nimport { Schema } from './schema';\n\nexport enum Verb {\n WRITE = 'write',\n READ = 'read',\n}\n\nexport type GraphQLConfig = {\n port: number;\n subscriptionsPortRange: number[];\n subscriptionsPath: string;\n disableCors?: boolean;\n};\n\nexport type GraphQLServerSlot = SlotRegistry<GraphQLServer>;\n\nexport type SchemaSlot = SlotRegistry<Schema>;\n\nexport type PubSubSlot = SlotRegistry<PubSubEngine>;\n\nexport type GraphQLServerOptions = {\n schemaSlot?: SchemaSlot;\n app?: Express;\n graphiql?: boolean;\n disableIntrospection?: boolean;\n remoteSchemas?: GraphQLServer[];\n subscriptionsPortRange?: number[];\n onWsConnect?: Function;\n};\n\nexport class GraphqlMain {\n constructor(\n /**\n * extension config\n */\n readonly config: GraphQLConfig,\n\n /**\n * slot for registering graphql modules\n */\n private moduleSlot: SchemaSlot,\n\n /**\n * harmony context.\n */\n private context: Harmony,\n\n /**\n * logger extension.\n */\n readonly logger: Logger,\n\n private graphQLServerSlot: GraphQLServerSlot,\n\n /**\n * graphql pubsub. allows to emit events to clients.\n */\n private pubSubSlot: PubSubSlot\n ) {}\n\n get pubsub(): PubSubEngine {\n const pubSubSlots = this.pubSubSlot.values();\n if (pubSubSlots.length) return pubSubSlots[0];\n return new PubSub();\n }\n\n private modules = new Map<string, GraphQLModule>();\n\n /**\n * returns the schema for a specific aspect by its id.\n */\n getSchema(aspectId: string) {\n return this.moduleSlot.get(aspectId);\n }\n\n /**\n * get multiple schema by aspect ids.\n */\n getSchemas(aspectIds: string[]) {\n return this.moduleSlot\n .toArray()\n .filter(([aspectId]) => {\n return aspectIds.includes(aspectId);\n })\n .map(([, schema]) => {\n return schema;\n });\n }\n\n async createServer(options: GraphQLServerOptions) {\n const { graphiql = true, disableIntrospection } = options;\n const localSchema = this.createRootModule(options.schemaSlot);\n const remoteSchemas = await createRemoteSchemas(options.remoteSchemas || this.graphQLServerSlot.values());\n const schemas = [localSchema.schema].concat(remoteSchemas).filter((x) => x);\n const schema = mergeSchemas({\n schemas,\n });\n\n // TODO: @guy please consider to refactor to express extension.\n const app = options.app || express();\n if (!this.config.disableCors) {\n app.use(\n // @ts-ignore todo: it's not clear what's the issue.\n cors({\n origin(origin, callback) {\n callback(null, true);\n },\n credentials: true,\n })\n );\n }\n\n app.use(\n '/graphql',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n graphqlHTTP((request, res, params) => ({\n customFormatErrorFn: (err) => {\n this.logger.error('graphql got an error during running the following query:', params);\n this.logger.error('graphql error ', err);\n return Object.assign(err, {\n // @ts-ignore\n ERR_CODE: err?.originalError?.errors?.[0].ERR_CODE || err.originalError?.constructor?.name,\n // @ts-ignore\n HTTP_CODE: err?.originalError?.errors?.[0].HTTP_CODE || err.originalError?.code,\n });\n },\n schema,\n rootValue: request,\n graphiql,\n validationRules: disableIntrospection ? [NoIntrospection] : undefined,\n }))\n );\n\n const server = createServer(app);\n const subscriptionsPort = options.subscriptionsPortRange || this.config.subscriptionsPortRange;\n const subscriptionServerPort = await this.getPort(subscriptionsPort);\n const { port } = await this.createSubscription(options, subscriptionServerPort);\n this.proxySubscription(server, port);\n\n return server;\n }\n\n /**\n * register a new graphql server.\n */\n registerServer(server: GraphQLServer) {\n this.graphQLServerSlot.register(server);\n return this;\n }\n\n /**\n * register a pubsub client\n */\n registerPubSub(pubsub: PubSubEngine) {\n const pubSubSlots = this.pubSubSlot.toArray();\n if (pubSubSlots.length) throw new Error('can not register more then one pubsub provider');\n this.pubSubSlot.register(pubsub);\n return this;\n }\n\n /**\n * start a graphql server.\n */\n async listen(port?: number, server?: Server, app?: Express) {\n const serverPort = port || this.config.port;\n const subServer = server || (await this.createServer({ app }));\n\n subServer.listen(serverPort, () => {\n this.logger.info(`API Server over HTTP is now running on http://localhost:${serverPort}`);\n this.logger.info(\n `API Server over web socket with subscriptions is now running on ws://localhost:${serverPort}/${this.config.subscriptionsPath}`\n );\n });\n }\n\n /**\n * register a new graphql module.\n */\n register(schema: Schema) {\n // const module = new GraphQLModule(schema);\n this.moduleSlot.register(schema);\n return this;\n }\n\n private async getPort(range: number[]) {\n const [from, to] = range;\n return Port.getPort(from, to);\n }\n\n /** create Subscription server with different port */\n\n private async createSubscription(options: GraphQLServerOptions, port: number) {\n // Create WebSocket listener server\n const websocketServer = createServer((request, response) => {\n response.writeHead(404);\n response.end();\n });\n\n // Bind it to port and start listening\n websocketServer.listen(port, () =>\n this.logger.debug(`Websocket Server is now running on http://localhost:${port}`)\n );\n\n const localSchema = this.createRootModule(options.schemaSlot);\n const remoteSchemas = await createRemoteSchemas(options.remoteSchemas || this.graphQLServerSlot.values());\n const schemas = [localSchema.schema].concat(remoteSchemas).filter((x) => x);\n const schema = mergeSchemas({\n schemas,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const subServer = new SubscriptionServer(\n {\n execute,\n subscribe,\n schema,\n onConnect: options.onWsConnect,\n },\n {\n server: websocketServer,\n path: this.config.subscriptionsPath,\n }\n );\n return { subServer, port };\n }\n /** proxy ws Subscription server to avoid conflict with different websocket connections */\n\n private proxySubscription(server: Server, port: number) {\n const proxServer = httpProxy.createProxyServer();\n const subscriptionsPath = this.config.subscriptionsPath;\n server.on('upgrade', function (req, socket, head) {\n if (req.url === subscriptionsPath) {\n proxServer.ws(req, socket, head, { target: { host: 'localhost', port } });\n }\n });\n }\n\n private createRootModule(schemaSlot?: SchemaSlot) {\n const modules = this.buildModules(schemaSlot);\n\n return new GraphQLModule({\n imports: modules,\n });\n }\n\n private buildModules(schemaSlot?: SchemaSlot) {\n const schemaSlots = schemaSlot ? schemaSlot.toArray() : this.moduleSlot.toArray();\n return schemaSlots.map(([extensionId, schema]) => {\n const moduleDeps = this.getModuleDependencies(extensionId);\n\n const module = new GraphQLModule({\n typeDefs: schema.typeDefs,\n resolvers: schema.resolvers,\n schemaDirectives: schema.schemaDirectives,\n imports: moduleDeps,\n context: (session) => {\n return {\n ...session,\n verb: session?.headers?.['x-verb'] || Verb.READ,\n };\n },\n });\n\n this.modules.set(extensionId, module);\n\n return module;\n });\n }\n\n private getModuleDependencies(extensionId: string): GraphQLModule[] {\n const extension = this.context.extensions.get(extensionId);\n if (!extension) throw new Error(`aspect ${extensionId} was not found`);\n const deps = this.context.getDependencies(extension);\n const ids = deps.map((dep) => dep.id);\n\n // @ts-ignore check :TODO why types are breaking here.\n return Array.from(this.modules.entries())\n .map(([depId, module]) => {\n const dep = ids.includes(depId);\n if (!dep) return undefined;\n return module;\n })\n .filter((module) => !!module);\n }\n\n static slots = [Slot.withType<Schema>(), Slot.withType<GraphQLServer>(), Slot.withType<PubSubSlot>()];\n\n static defaultConfig = {\n port: 4000,\n subscriptionsPortRange: [2000, 2100],\n disableCors: false,\n subscriptionsPath: '/subscriptions',\n };\n\n static runtime = MainRuntime;\n static dependencies = [LoggerAspect];\n\n static async provider(\n [loggerFactory]: [LoggerMain],\n config: GraphQLConfig,\n [moduleSlot, graphQLServerSlot, pubSubSlot]: [SchemaSlot, GraphQLServerSlot, PubSubSlot],\n context: Harmony\n ) {\n const logger = loggerFactory.createLogger(GraphqlAspect.id);\n const graphqlMain = new GraphqlMain(config, moduleSlot, context, logger, graphQLServerSlot, pubSubSlot);\n return graphqlMain;\n }\n}\n\nGraphqlAspect.addRuntime(GraphqlMain);\n"],"mappings":";;;;;;AAAA,SAAAA,QAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,OAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,6BAAA;EAAA,MAAAF,IAAA,GAAAG,sBAAA,CAAAF,OAAA;EAAAC,4BAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAI,MAAA;EAAA,MAAAJ,IAAA,GAAAC,OAAA;EAAAG,KAAA,YAAAA,CAAA;IAAA,OAAAJ,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAK,KAAA;EAAA,MAAAL,IAAA,GAAAC,OAAA;EAAAI,IAAA,YAAAA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wC,iBAAiB,EAAE;AACrB,CAAC;AAAAhG,eAAA,CAtQUmB,WAAW,aAwQL0I,kBAAW;AAAA7J,eAAA,CAxQjBmB,WAAW,kBAyQA,CAAC2I,sBAAY,CAAC;AActCL,yBAAa,CAACM,UAAU,CAAC5I,WAAW,CAAC"}
@@ -1,4 +1,4 @@
1
- import React, { ReactNode } from 'react';
1
+ import { ReactNode } from 'react';
2
2
  import { ApolloClient } from '@apollo/client';
3
3
  import type { NormalizedCacheObject } from '@apollo/client';
4
4
  import { GraphqlRenderPlugins } from './render-lifecycle';
@@ -6,8 +6,8 @@ import { GraphqlRenderPlugins } from './render-lifecycle';
6
6
  * Type of gql client.
7
7
  * Used to abstract Apollo client, so consumers could import the type from graphql.ui, and not have to depend on @apollo/client directly
8
8
  * */
9
- export declare type GraphQLClient<T> = ApolloClient<T>;
10
- declare type ClientOptions = {
9
+ export type GraphQLClient<T> = ApolloClient<T>;
10
+ type ClientOptions = {
11
11
  /** Preset in-memory cache with state (e.g. continue state from SSR) */
12
12
  state?: NormalizedCacheObject;
13
13
  /** endpoint for websocket connections */
@@ -27,11 +27,11 @@ export declare class GraphqlUI {
27
27
  getProvider: ({ client, children }: {
28
28
  client: GraphQLClient<any>;
29
29
  children: ReactNode;
30
- }) => React.JSX.Element;
30
+ }) => JSX.Element;
31
31
  readonly renderPlugins: GraphqlRenderPlugins;
32
32
  static runtime: import("@teambit/harmony").RuntimeDefinition;
33
- static dependencies: never[];
34
- static slots: never[];
33
+ static dependencies: any[];
34
+ static slots: any[];
35
35
  static provider(): Promise<GraphqlUI>;
36
36
  }
37
37
  export {};
@@ -1,5 +1,5 @@
1
- import * as compositions_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.harmony_graphql@1.0.106/dist/graphql.composition.js';
2
- import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.harmony_graphql@1.0.106/dist/graphql.docs.mdx';
1
+ import * as compositions_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.harmony_graphql@1.0.108/dist/graphql.composition.js';
2
+ import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.harmony_graphql@1.0.108/dist/graphql.docs.mdx';
3
3
 
4
4
  export const compositions = [compositions_0];
5
5
  export const overview = [overview_0];
@@ -1,8 +1,8 @@
1
- import React, { ReactNode } from 'react';
1
+ import { ReactNode } from 'react';
2
2
  import type { ApolloClient, NormalizedCacheObject } from '@apollo/client';
3
3
  import type { SSR } from '@teambit/ui';
4
4
  import type { GraphqlUI, GraphQLClient } from './graphql.ui.runtime';
5
- declare type RenderContext = {
5
+ type RenderContext = {
6
6
  client: GraphQLClient<any>;
7
7
  };
8
8
  export declare class GraphqlRenderPlugins implements SSR.RenderPlugin<RenderContext, {
@@ -19,21 +19,21 @@ export declare class GraphqlRenderPlugins implements SSR.RenderPlugin<RenderCont
19
19
  onBeforeRender: (ctx: RenderContext, app: ReactNode) => Promise<void>;
20
20
  serialize: (ctx?: RenderContext) => {
21
21
  json: string;
22
- } | undefined;
22
+ };
23
23
  deserialize: (raw?: string) => {
24
- state: NormalizedCacheObject | undefined;
24
+ state: NormalizedCacheObject;
25
25
  };
26
26
  private _client;
27
27
  browserInit: ({ state }?: {
28
- state?: NormalizedCacheObject | undefined;
28
+ state?: NormalizedCacheObject;
29
29
  }) => {
30
30
  client: ApolloClient<NormalizedCacheObject>;
31
31
  };
32
32
  getClient(): ApolloClient<NormalizedCacheObject>;
33
33
  private BrowserGqlProvider;
34
34
  reactContext: ({ renderCtx, children }: {
35
- renderCtx?: RenderContext | undefined;
35
+ renderCtx?: RenderContext;
36
36
  children: ReactNode;
37
- }) => React.JSX.Element;
37
+ }) => JSX.Element;
38
38
  }
39
39
  export {};
@@ -67,11 +67,11 @@ class GraphqlRenderPlugins {
67
67
  _defineProperty(this, "serverInit", ({
68
68
  browser
69
69
  }) => {
70
- const port = (browser === null || browser === void 0 ? void 0 : browser.location.port) || 3000;
70
+ const port = browser?.location.port || 3000;
71
71
  const serverUrl = `http://localhost:${port}/graphql`;
72
72
  const client = this.graphqlUI.createSsrClient({
73
73
  serverUrl,
74
- headers: (0, _lodash().default)(browser === null || browser === void 0 ? void 0 : browser.headers, ALLOWED_HEADERS)
74
+ headers: (0, _lodash().default)(browser?.headers, ALLOWED_HEADERS)
75
75
  });
76
76
  const ctx = {
77
77
  client
@@ -89,7 +89,7 @@ class GraphqlRenderPlugins {
89
89
  });
90
90
  });
91
91
  _defineProperty(this, "serialize", ctx => {
92
- const client = ctx === null || ctx === void 0 ? void 0 : ctx.client;
92
+ const client = ctx?.client;
93
93
  if (!client) return undefined;
94
94
  return {
95
95
  json: JSON.stringify(client.extract())
@@ -132,9 +132,9 @@ class GraphqlRenderPlugins {
132
132
  renderCtx,
133
133
  children
134
134
  }) => {
135
- if (!(renderCtx !== null && renderCtx !== void 0 && renderCtx.client)) throw new TypeError('GQL client is not initialized, make sure `.browserInit()` executes');
135
+ if (!renderCtx?.client) throw new TypeError('GQL client is not initialized, make sure `.browserInit()` executes');
136
136
  return /*#__PURE__*/_react().default.createElement(this.graphqlUI.getProvider, {
137
- client: renderCtx === null || renderCtx === void 0 ? void 0 : renderCtx.client
137
+ client: renderCtx?.client
138
138
  }, children);
139
139
  });
140
140
  _defineProperty(this, "reactContext", _uiFoundationUi().isBrowser ? this.BrowserGqlProvider : ServerGqlProvider);
@@ -149,7 +149,7 @@ function ServerGqlProvider({
149
149
  renderCtx,
150
150
  children
151
151
  }) {
152
- if (!(renderCtx !== null && renderCtx !== void 0 && renderCtx.client)) throw new TypeError('GQL client has not been initialized during SSR, make sure `.serverInit()` executes');
152
+ if (!renderCtx?.client) throw new TypeError('GQL client has not been initialized during SSR, make sure `.serverInit()` executes');
153
153
  const {
154
154
  client
155
155
  } = renderCtx;
@@ -1 +1 @@
1
- {"version":3,"names":["_react","data","_interopRequireDefault","require","_ssr","_server","_lodash","_uiFoundationUi","_graphqlProvider","_graphql","obj","__esModule","default","_defineProperty","key","value","_toPropertyKey","Object","defineProperty","enumerable","configurable","writable","t","i","_toPrimitive","String","r","e","Symbol","toPrimitive","call","TypeError","Number","ALLOWED_HEADERS","GraphqlRenderPlugins","constructor","graphqlUI","GraphqlAspect","id","browser","port","location","serverUrl","client","createSsrClient","headers","pick","ctx","app","getMarkupFromTree","tree","renderFunction","ReactDOMServer","renderToStaticMarkup","undefined","json","JSON","stringify","extract","raw","state","parse","console","error","window","isInsecure","protocol","wsUrl","host","createClient","subscriptionUri","_client","renderCtx","children","createElement","getProvider","isBrowser","BrowserGqlProvider","ServerGqlProvider","getClient","browserInit","exports","GraphQLProvider"],"sources":["render-lifecycle.tsx"],"sourcesContent":["import React, { ReactNode } from 'react';\n// Calling getMarkupFromTree instead of getDataFromTree so we can control the render function\n// This is required since upgrade to @apollo/client v3.6.9 because otherwise the ssr is not working since\n// webpack is not bundling the react-dom/server\nimport { getMarkupFromTree } from '@apollo/client/react/ssr';\nimport ReactDOMServer from 'react-dom/server';\nimport type { ApolloClient, NormalizedCacheObject } from '@apollo/client';\nimport pick from 'lodash.pick';\n\nimport { isBrowser } from '@teambit/ui-foundation.ui.is-browser';\nimport type { SSR } from '@teambit/ui';\n\nimport type { GraphqlUI, GraphQLClient } from './graphql.ui.runtime';\nimport { GraphQLProvider } from './graphql-provider';\nimport { GraphqlAspect } from './graphql.aspect';\n\ntype RenderContext = {\n client: GraphQLClient<any>;\n};\n\nconst ALLOWED_HEADERS = ['cookie'];\n\nexport class GraphqlRenderPlugins implements SSR.RenderPlugin<RenderContext, { state?: NormalizedCacheObject }> {\n constructor(private graphqlUI: GraphqlUI) {}\n\n key = GraphqlAspect.id;\n\n serverInit = ({ browser }: SSR.SsrSession) => {\n const port = browser?.location.port || 3000;\n const serverUrl = `http://localhost:${port}/graphql`;\n\n const client = this.graphqlUI.createSsrClient({\n serverUrl,\n headers: pick(browser?.headers, ALLOWED_HEADERS),\n });\n\n const ctx: RenderContext = { client };\n return ctx;\n };\n\n /**\n * Eagerly and recursively execute all gql queries in the app.\n * Data will be available in gqlClient.extract()\n */\n onBeforeRender = async (ctx: RenderContext, app: ReactNode) => {\n await getMarkupFromTree({ tree: app, renderFunction: ReactDOMServer.renderToStaticMarkup });\n };\n\n serialize = (ctx?: RenderContext) => {\n const client = ctx?.client;\n if (!client) return undefined;\n\n return {\n json: JSON.stringify(client.extract()),\n };\n };\n\n deserialize = (raw?: string) => {\n if (!raw) return { state: undefined };\n let state: NormalizedCacheObject | undefined;\n try {\n state = JSON.parse(raw);\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error('[GraphQL] failed deserializing state from DOM', e);\n }\n\n return { state };\n };\n\n private _client: ApolloClient<NormalizedCacheObject> | undefined = undefined;\n\n browserInit = ({ state }: { state?: NormalizedCacheObject } = {}) => {\n const { location } = window;\n const isInsecure = location.protocol === 'http:';\n const wsUrl = `${isInsecure ? 'ws:' : 'wss:'}//${location.host}/subscriptions`;\n\n const client = this.graphqlUI.createClient('/graphql', { state, subscriptionUri: wsUrl });\n this._client = client;\n\n return { client };\n };\n\n getClient() {\n if (!this._client) return this.browserInit().client;\n return this._client;\n }\n\n private BrowserGqlProvider = ({ renderCtx, children }: { renderCtx?: RenderContext; children: ReactNode }) => {\n if (!renderCtx?.client) throw new TypeError('GQL client is not initialized, make sure `.browserInit()` executes');\n\n return <this.graphqlUI.getProvider client={renderCtx?.client}>{children}</this.graphqlUI.getProvider>;\n };\n\n reactContext = isBrowser ? this.BrowserGqlProvider : ServerGqlProvider;\n}\n\nfunction ServerGqlProvider({ renderCtx, children }: { renderCtx?: RenderContext; children: ReactNode }) {\n if (!renderCtx?.client)\n throw new TypeError('GQL client has not been initialized during SSR, make sure `.serverInit()` executes');\n\n const { client } = renderCtx;\n return <GraphQLProvider client={client}>{children}</GraphQLProvider>;\n}\n"],"mappings":";;;;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AAK;QAAEU,eAAe,EAAEH;MAAM,CAAC,CAAC;MACzF,IAAI,CAACI,OAAO,GAAG5B,MAAM;MAErB,OAAO;QAAEA;MAAO,CAAC;IACnB,CAAC;IAAA9B,eAAA,6BAO4B,CAAC;MAAE2D,SAAS;MAAEC;IAA6D,CAAC,KAAK;MAC5G,IAAI,EAACD,SAAS,aAATA,SAAS,eAATA,SAAS,CAAE7B,MAAM,GAAE,MAAM,IAAIZ,SAAS,CAAC,oEAAoE,CAAC;MAEjH,oBAAO/B,MAAA,GAAAY,OAAA,CAAA8D,aAAA,MAAMtC,SAAS,CAACuC,WAAW;QAAChC,MAAM,EAAE6B,SAAS,aAATA,SAAS,uBAATA,SAAS,CAAE7B;MAAO,GAAE8B,QAAqC,CAAC;IACvG,CAAC;IAAA5D,eAAA,uBAEc+D,2BAAS,GAAG,IAAI,CAACC,kBAAkB,GAAGC,iBAAiB;EAvE3B;EA4D3CC,SAASA,CAAA,EAAG;IACV,IAAI,CAAC,IAAI,CAACR,OAAO,EAAE,OAAO,IAAI,CAACS,WAAW,CAAC,CAAC,CAACrC,MAAM;IACnD,OAAO,IAAI,CAAC4B,OAAO;EACrB;AASF;AAACU,OAAA,CAAA/C,oBAAA,GAAAA,oBAAA;AAED,SAAS4C,iBAAiBA,CAAC;EAAEN,SAAS;EAAEC;AAA6D,CAAC,EAAE;EACtG,IAAI,EAACD,SAAS,aAATA,SAAS,eAATA,SAAS,CAAE7B,MAAM,GACpB,MAAM,IAAIZ,SAAS,CAAC,oFAAoF,CAAC;EAE3G,MAAM;IAAEY;EAAO,CAAC,GAAG6B,SAAS;EAC5B,oBAAOxE,MAAA,GAAAY,OAAA,CAAA8D,aAAA,CAAClE,gBAAA,GAAA0E,eAAe;IAACvC,MAAM,EAAEA;EAAO,GAAE8B,QAA0B,CAAC;AACtE"}
1
+ {"version":3,"names":["_react","data","_interopRequireDefault","require","_ssr","_server","_lodash","_uiFoundationUi","_graphqlProvider","_graphql","obj","__esModule","default","_defineProperty","key","value","_toPropertyKey","Object","defineProperty","enumerable","configurable","writable","t","i","_toPrimitive","String","r","e","Symbol","toPrimitive","call","TypeError","Number","ALLOWED_HEADERS","GraphqlRenderPlugins","constructor","graphqlUI","GraphqlAspect","id","browser","port","location","serverUrl","client","createSsrClient","headers","pick","ctx","app","getMarkupFromTree","tree","renderFunction","ReactDOMServer","renderToStaticMarkup","undefined","json","JSON","stringify","extract","raw","state","parse","console","error","window","isInsecure","protocol","wsUrl","host","createClient","subscriptionUri","_client","renderCtx","children","createElement","getProvider","isBrowser","BrowserGqlProvider","ServerGqlProvider","getClient","browserInit","exports","GraphQLProvider"],"sources":["render-lifecycle.tsx"],"sourcesContent":["import React, { ReactNode } from 'react';\n// Calling getMarkupFromTree instead of getDataFromTree so we can control the render function\n// This is required since upgrade to @apollo/client v3.6.9 because otherwise the ssr is not working since\n// webpack is not bundling the react-dom/server\nimport { getMarkupFromTree } from '@apollo/client/react/ssr';\nimport ReactDOMServer from 'react-dom/server';\nimport type { ApolloClient, NormalizedCacheObject } from '@apollo/client';\nimport pick from 'lodash.pick';\n\nimport { isBrowser } from '@teambit/ui-foundation.ui.is-browser';\nimport type { SSR } from '@teambit/ui';\n\nimport type { GraphqlUI, GraphQLClient } from './graphql.ui.runtime';\nimport { GraphQLProvider } from './graphql-provider';\nimport { GraphqlAspect } from './graphql.aspect';\n\ntype RenderContext = {\n client: GraphQLClient<any>;\n};\n\nconst ALLOWED_HEADERS = ['cookie'];\n\nexport class GraphqlRenderPlugins implements SSR.RenderPlugin<RenderContext, { state?: NormalizedCacheObject }> {\n constructor(private graphqlUI: GraphqlUI) {}\n\n key = GraphqlAspect.id;\n\n serverInit = ({ browser }: SSR.SsrSession) => {\n const port = browser?.location.port || 3000;\n const serverUrl = `http://localhost:${port}/graphql`;\n\n const client = this.graphqlUI.createSsrClient({\n serverUrl,\n headers: pick(browser?.headers, ALLOWED_HEADERS),\n });\n\n const ctx: RenderContext = { client };\n return ctx;\n };\n\n /**\n * Eagerly and recursively execute all gql queries in the app.\n * Data will be available in gqlClient.extract()\n */\n onBeforeRender = async (ctx: RenderContext, app: ReactNode) => {\n await getMarkupFromTree({ tree: app, renderFunction: ReactDOMServer.renderToStaticMarkup });\n };\n\n serialize = (ctx?: RenderContext) => {\n const client = ctx?.client;\n if (!client) return undefined;\n\n return {\n json: JSON.stringify(client.extract()),\n };\n };\n\n deserialize = (raw?: string) => {\n if (!raw) return { state: undefined };\n let state: NormalizedCacheObject | undefined;\n try {\n state = JSON.parse(raw);\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error('[GraphQL] failed deserializing state from DOM', e);\n }\n\n return { state };\n };\n\n private _client: ApolloClient<NormalizedCacheObject> | undefined = undefined;\n\n browserInit = ({ state }: { state?: NormalizedCacheObject } = {}) => {\n const { location } = window;\n const isInsecure = location.protocol === 'http:';\n const wsUrl = `${isInsecure ? 'ws:' : 'wss:'}//${location.host}/subscriptions`;\n\n const client = this.graphqlUI.createClient('/graphql', { state, subscriptionUri: wsUrl });\n this._client = client;\n\n return { client };\n };\n\n getClient() {\n if (!this._client) return this.browserInit().client;\n return this._client;\n }\n\n private BrowserGqlProvider = ({ renderCtx, children }: { renderCtx?: RenderContext; children: ReactNode }) => {\n if (!renderCtx?.client) throw new TypeError('GQL client is not initialized, make sure `.browserInit()` executes');\n\n return <this.graphqlUI.getProvider client={renderCtx?.client}>{children}</this.graphqlUI.getProvider>;\n };\n\n reactContext = isBrowser ? this.BrowserGqlProvider : ServerGqlProvider;\n}\n\nfunction ServerGqlProvider({ renderCtx, children }: { renderCtx?: RenderContext; children: ReactNode }) {\n if (!renderCtx?.client)\n throw new TypeError('GQL client has not been initialized during SSR, make sure `.serverInit()` executes');\n\n const { client } = renderCtx;\n return <GraphQLProvider client={client}>{children}</GraphQLProvider>;\n}\n"],"mappings":";;;;;;AAAA,SAAAA,OAAA;EAAA,MAAAC,IAAA,GAAAC,sBAAA,CAAAC,OAAA;EAAAH,MAAA,YAAAA,CAAA;IAAA,OAAAC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AC5G,IAAI,CAACD,SAAS,EAAE7B,MAAM,EAAE,MAAM,IAAIZ,SAAS,CAAC,oEAAoE,CAAC;MAEjH,oBAAO/B,MAAA,GAAAY,OAAA,CAAA8D,aAAA,MAAMtC,SAAS,CAACuC,WAAW;QAAChC,MAAM,EAAE6B,SAAS,EAAE7B;MAAO,GAAE8B,QAAqC,CAAC;IACvG,CAAC;IAAA5D,eAAA,uBAEc+D,2BAAS,GAAG,IAAI,CAACC,kBAAkB,GAAGC,iBAAiB;EAvE3B;EA4D3CC,SAASA,CAAA,EAAG;IACV,IAAI,CAAC,IAAI,CAACR,OAAO,EAAE,OAAO,IAAI,CAACS,WAAW,CAAC,CAAC,CAACrC,MAAM;IACnD,OAAO,IAAI,CAAC4B,OAAO;EACrB;AASF;AAACU,OAAA,CAAA/C,oBAAA,GAAAA,oBAAA;AAED,SAAS4C,iBAAiBA,CAAC;EAAEN,SAAS;EAAEC;AAA6D,CAAC,EAAE;EACtG,IAAI,CAACD,SAAS,EAAE7B,MAAM,EACpB,MAAM,IAAIZ,SAAS,CAAC,oFAAoF,CAAC;EAE3G,MAAM;IAAEY;EAAO,CAAC,GAAG6B,SAAS;EAC5B,oBAAOxE,MAAA,GAAAY,OAAA,CAAA8D,aAAA,CAAClE,gBAAA,GAAA0E,eAAe;IAACvC,MAAM,EAAEA;EAAO,GAAE8B,QAA0B,CAAC;AACtE"}
package/dist/schema.d.ts CHANGED
@@ -3,7 +3,7 @@ import type { SchemaDirectives } from '@graphql-modules/core';
3
3
  /**
4
4
  * graphql schema for an extension.
5
5
  */
6
- export declare type Schema = {
6
+ export type Schema = {
7
7
  typeDefs?: string | DocumentNode;
8
8
  resolvers?: {
9
9
  [key: string]: any;
@@ -0,0 +1,13 @@
1
+ export class GraphQlError {
2
+ constructor(
3
+ /**
4
+ * http status code of error
5
+ */
6
+ public readonly code: number,
7
+
8
+ /**
9
+ * error message of the error
10
+ */
11
+ public readonly message?: string
12
+ ) {}
13
+ }
@@ -0,0 +1,5 @@
1
+ export interface GraphQLServer {
2
+ uri: string;
3
+
4
+ subscriptionsUri?: string;
5
+ }
@@ -0,0 +1,9 @@
1
+ import { Aspect } from '@teambit/harmony';
2
+
3
+ export const GraphqlAspect = Aspect.create({
4
+ id: 'teambit.harmony/graphql',
5
+ dependencies: [],
6
+ defaultConfig: {},
7
+ });
8
+
9
+ export default GraphqlAspect;
@@ -0,0 +1,328 @@
1
+ import { mergeSchemas } from '@graphql-tools/schema';
2
+ import NoIntrospection from 'graphql-disable-introspection';
3
+ import { GraphQLModule } from '@graphql-modules/core';
4
+ import { MainRuntime } from '@teambit/cli';
5
+ import { Harmony, Slot, SlotRegistry } from '@teambit/harmony';
6
+ import { Logger, LoggerAspect, LoggerMain } from '@teambit/logger';
7
+ import express, { Express } from 'express';
8
+ import { graphqlHTTP } from 'express-graphql';
9
+ import { Port } from '@teambit/toolbox.network.get-port';
10
+ import { execute, subscribe } from 'graphql';
11
+ import { PubSubEngine, PubSub } from 'graphql-subscriptions';
12
+ import { createServer, Server } from 'http';
13
+ import httpProxy from 'http-proxy';
14
+ import { SubscriptionServer } from 'subscriptions-transport-ws';
15
+ import cors from 'cors';
16
+ import { GraphQLServer } from './graphql-server';
17
+ import { createRemoteSchemas } from './create-remote-schemas';
18
+ import { GraphqlAspect } from './graphql.aspect';
19
+ import { Schema } from './schema';
20
+
21
+ export enum Verb {
22
+ WRITE = 'write',
23
+ READ = 'read',
24
+ }
25
+
26
+ export type GraphQLConfig = {
27
+ port: number;
28
+ subscriptionsPortRange: number[];
29
+ subscriptionsPath: string;
30
+ disableCors?: boolean;
31
+ };
32
+
33
+ export type GraphQLServerSlot = SlotRegistry<GraphQLServer>;
34
+
35
+ export type SchemaSlot = SlotRegistry<Schema>;
36
+
37
+ export type PubSubSlot = SlotRegistry<PubSubEngine>;
38
+
39
+ export type GraphQLServerOptions = {
40
+ schemaSlot?: SchemaSlot;
41
+ app?: Express;
42
+ graphiql?: boolean;
43
+ disableIntrospection?: boolean;
44
+ remoteSchemas?: GraphQLServer[];
45
+ subscriptionsPortRange?: number[];
46
+ onWsConnect?: Function;
47
+ };
48
+
49
+ export class GraphqlMain {
50
+ constructor(
51
+ /**
52
+ * extension config
53
+ */
54
+ readonly config: GraphQLConfig,
55
+
56
+ /**
57
+ * slot for registering graphql modules
58
+ */
59
+ private moduleSlot: SchemaSlot,
60
+
61
+ /**
62
+ * harmony context.
63
+ */
64
+ private context: Harmony,
65
+
66
+ /**
67
+ * logger extension.
68
+ */
69
+ readonly logger: Logger,
70
+
71
+ private graphQLServerSlot: GraphQLServerSlot,
72
+
73
+ /**
74
+ * graphql pubsub. allows to emit events to clients.
75
+ */
76
+ private pubSubSlot: PubSubSlot
77
+ ) {}
78
+
79
+ get pubsub(): PubSubEngine {
80
+ const pubSubSlots = this.pubSubSlot.values();
81
+ if (pubSubSlots.length) return pubSubSlots[0];
82
+ return new PubSub();
83
+ }
84
+
85
+ private modules = new Map<string, GraphQLModule>();
86
+
87
+ /**
88
+ * returns the schema for a specific aspect by its id.
89
+ */
90
+ getSchema(aspectId: string) {
91
+ return this.moduleSlot.get(aspectId);
92
+ }
93
+
94
+ /**
95
+ * get multiple schema by aspect ids.
96
+ */
97
+ getSchemas(aspectIds: string[]) {
98
+ return this.moduleSlot
99
+ .toArray()
100
+ .filter(([aspectId]) => {
101
+ return aspectIds.includes(aspectId);
102
+ })
103
+ .map(([, schema]) => {
104
+ return schema;
105
+ });
106
+ }
107
+
108
+ async createServer(options: GraphQLServerOptions) {
109
+ const { graphiql = true, disableIntrospection } = options;
110
+ const localSchema = this.createRootModule(options.schemaSlot);
111
+ const remoteSchemas = await createRemoteSchemas(options.remoteSchemas || this.graphQLServerSlot.values());
112
+ const schemas = [localSchema.schema].concat(remoteSchemas).filter((x) => x);
113
+ const schema = mergeSchemas({
114
+ schemas,
115
+ });
116
+
117
+ // TODO: @guy please consider to refactor to express extension.
118
+ const app = options.app || express();
119
+ if (!this.config.disableCors) {
120
+ app.use(
121
+ // @ts-ignore todo: it's not clear what's the issue.
122
+ cors({
123
+ origin(origin, callback) {
124
+ callback(null, true);
125
+ },
126
+ credentials: true,
127
+ })
128
+ );
129
+ }
130
+
131
+ app.use(
132
+ '/graphql',
133
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
134
+ graphqlHTTP((request, res, params) => ({
135
+ customFormatErrorFn: (err) => {
136
+ this.logger.error('graphql got an error during running the following query:', params);
137
+ this.logger.error('graphql error ', err);
138
+ return Object.assign(err, {
139
+ // @ts-ignore
140
+ ERR_CODE: err?.originalError?.errors?.[0].ERR_CODE || err.originalError?.constructor?.name,
141
+ // @ts-ignore
142
+ HTTP_CODE: err?.originalError?.errors?.[0].HTTP_CODE || err.originalError?.code,
143
+ });
144
+ },
145
+ schema,
146
+ rootValue: request,
147
+ graphiql,
148
+ validationRules: disableIntrospection ? [NoIntrospection] : undefined,
149
+ }))
150
+ );
151
+
152
+ const server = createServer(app);
153
+ const subscriptionsPort = options.subscriptionsPortRange || this.config.subscriptionsPortRange;
154
+ const subscriptionServerPort = await this.getPort(subscriptionsPort);
155
+ const { port } = await this.createSubscription(options, subscriptionServerPort);
156
+ this.proxySubscription(server, port);
157
+
158
+ return server;
159
+ }
160
+
161
+ /**
162
+ * register a new graphql server.
163
+ */
164
+ registerServer(server: GraphQLServer) {
165
+ this.graphQLServerSlot.register(server);
166
+ return this;
167
+ }
168
+
169
+ /**
170
+ * register a pubsub client
171
+ */
172
+ registerPubSub(pubsub: PubSubEngine) {
173
+ const pubSubSlots = this.pubSubSlot.toArray();
174
+ if (pubSubSlots.length) throw new Error('can not register more then one pubsub provider');
175
+ this.pubSubSlot.register(pubsub);
176
+ return this;
177
+ }
178
+
179
+ /**
180
+ * start a graphql server.
181
+ */
182
+ async listen(port?: number, server?: Server, app?: Express) {
183
+ const serverPort = port || this.config.port;
184
+ const subServer = server || (await this.createServer({ app }));
185
+
186
+ subServer.listen(serverPort, () => {
187
+ this.logger.info(`API Server over HTTP is now running on http://localhost:${serverPort}`);
188
+ this.logger.info(
189
+ `API Server over web socket with subscriptions is now running on ws://localhost:${serverPort}/${this.config.subscriptionsPath}`
190
+ );
191
+ });
192
+ }
193
+
194
+ /**
195
+ * register a new graphql module.
196
+ */
197
+ register(schema: Schema) {
198
+ // const module = new GraphQLModule(schema);
199
+ this.moduleSlot.register(schema);
200
+ return this;
201
+ }
202
+
203
+ private async getPort(range: number[]) {
204
+ const [from, to] = range;
205
+ return Port.getPort(from, to);
206
+ }
207
+
208
+ /** create Subscription server with different port */
209
+
210
+ private async createSubscription(options: GraphQLServerOptions, port: number) {
211
+ // Create WebSocket listener server
212
+ const websocketServer = createServer((request, response) => {
213
+ response.writeHead(404);
214
+ response.end();
215
+ });
216
+
217
+ // Bind it to port and start listening
218
+ websocketServer.listen(port, () =>
219
+ this.logger.debug(`Websocket Server is now running on http://localhost:${port}`)
220
+ );
221
+
222
+ const localSchema = this.createRootModule(options.schemaSlot);
223
+ const remoteSchemas = await createRemoteSchemas(options.remoteSchemas || this.graphQLServerSlot.values());
224
+ const schemas = [localSchema.schema].concat(remoteSchemas).filter((x) => x);
225
+ const schema = mergeSchemas({
226
+ schemas,
227
+ });
228
+
229
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
230
+ const subServer = new SubscriptionServer(
231
+ {
232
+ execute,
233
+ subscribe,
234
+ schema,
235
+ onConnect: options.onWsConnect,
236
+ },
237
+ {
238
+ server: websocketServer,
239
+ path: this.config.subscriptionsPath,
240
+ }
241
+ );
242
+ return { subServer, port };
243
+ }
244
+ /** proxy ws Subscription server to avoid conflict with different websocket connections */
245
+
246
+ private proxySubscription(server: Server, port: number) {
247
+ const proxServer = httpProxy.createProxyServer();
248
+ const subscriptionsPath = this.config.subscriptionsPath;
249
+ server.on('upgrade', function (req, socket, head) {
250
+ if (req.url === subscriptionsPath) {
251
+ proxServer.ws(req, socket, head, { target: { host: 'localhost', port } });
252
+ }
253
+ });
254
+ }
255
+
256
+ private createRootModule(schemaSlot?: SchemaSlot) {
257
+ const modules = this.buildModules(schemaSlot);
258
+
259
+ return new GraphQLModule({
260
+ imports: modules,
261
+ });
262
+ }
263
+
264
+ private buildModules(schemaSlot?: SchemaSlot) {
265
+ const schemaSlots = schemaSlot ? schemaSlot.toArray() : this.moduleSlot.toArray();
266
+ return schemaSlots.map(([extensionId, schema]) => {
267
+ const moduleDeps = this.getModuleDependencies(extensionId);
268
+
269
+ const module = new GraphQLModule({
270
+ typeDefs: schema.typeDefs,
271
+ resolvers: schema.resolvers,
272
+ schemaDirectives: schema.schemaDirectives,
273
+ imports: moduleDeps,
274
+ context: (session) => {
275
+ return {
276
+ ...session,
277
+ verb: session?.headers?.['x-verb'] || Verb.READ,
278
+ };
279
+ },
280
+ });
281
+
282
+ this.modules.set(extensionId, module);
283
+
284
+ return module;
285
+ });
286
+ }
287
+
288
+ private getModuleDependencies(extensionId: string): GraphQLModule[] {
289
+ const extension = this.context.extensions.get(extensionId);
290
+ if (!extension) throw new Error(`aspect ${extensionId} was not found`);
291
+ const deps = this.context.getDependencies(extension);
292
+ const ids = deps.map((dep) => dep.id);
293
+
294
+ // @ts-ignore check :TODO why types are breaking here.
295
+ return Array.from(this.modules.entries())
296
+ .map(([depId, module]) => {
297
+ const dep = ids.includes(depId);
298
+ if (!dep) return undefined;
299
+ return module;
300
+ })
301
+ .filter((module) => !!module);
302
+ }
303
+
304
+ static slots = [Slot.withType<Schema>(), Slot.withType<GraphQLServer>(), Slot.withType<PubSubSlot>()];
305
+
306
+ static defaultConfig = {
307
+ port: 4000,
308
+ subscriptionsPortRange: [2000, 2100],
309
+ disableCors: false,
310
+ subscriptionsPath: '/subscriptions',
311
+ };
312
+
313
+ static runtime = MainRuntime;
314
+ static dependencies = [LoggerAspect];
315
+
316
+ static async provider(
317
+ [loggerFactory]: [LoggerMain],
318
+ config: GraphQLConfig,
319
+ [moduleSlot, graphQLServerSlot, pubSubSlot]: [SchemaSlot, GraphQLServerSlot, PubSubSlot],
320
+ context: Harmony
321
+ ) {
322
+ const logger = loggerFactory.createLogger(GraphqlAspect.id);
323
+ const graphqlMain = new GraphqlMain(config, moduleSlot, context, logger, graphQLServerSlot, pubSubSlot);
324
+ return graphqlMain;
325
+ }
326
+ }
327
+
328
+ GraphqlAspect.addRuntime(GraphqlMain);
package/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ export { GraphqlAspect, GraphqlAspect as default } from './graphql.aspect';
2
+
3
+ export type { Schema } from './schema';
4
+ export type { GraphqlMain, SchemaSlot } from './graphql.main.runtime';
5
+ export type { GraphqlUI, GraphQLClient } from './graphql.ui.runtime';
6
+ export type { GraphQLServer } from './graphql-server';
7
+ export { GraphQLProvider } from './graphql-provider';
8
+ export { GraphQlError } from './graphql-error';
package/logging.ts ADDED
@@ -0,0 +1,26 @@
1
+ import { ErrorResponse } from '@apollo/client/link/error';
2
+
3
+ export function logError({ graphQLErrors, networkError, operation }: ErrorResponse) {
4
+ if (graphQLErrors)
5
+ graphQLErrors.forEach(({ message, locations, path }) =>
6
+ // eslint-disable-next-line no-console
7
+ console.error(`[gql] error on "${operation.operationName}" - "${message}"`, locations, path)
8
+ );
9
+
10
+ // eslint-disable-next-line no-console
11
+ if (networkError) console.error('[gql] network error', `"${operation.operationName}"`, networkError);
12
+ }
13
+
14
+ // // // a fetch monkey patch with logs. useful to debug gql
15
+ // function loggingCrossFetch(...p: Parameters<typeof fetch>) {
16
+ // const [url, init] = p;
17
+ // const headers = init?.headers;
18
+ // const body = init?.body;
19
+
20
+ // console.debug('[gql]', 'fetching', url, body, { headers });
21
+ // const promise = crossFetch(...p);
22
+ // promise
23
+ // .then((result) => console.debug('[gql]', 'finished', result))
24
+ // .catch((err) => console.debug('[gql]', 'error', err));
25
+ // return promise;
26
+ // }
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@teambit/graphql",
3
- "version": "1.0.106",
3
+ "version": "1.0.108",
4
4
  "homepage": "https://bit.cloud/teambit/harmony/graphql",
5
5
  "main": "dist/index.js",
6
6
  "componentId": {
7
7
  "scope": "teambit.harmony",
8
8
  "name": "graphql",
9
- "version": "1.0.106"
9
+ "version": "1.0.108"
10
10
  },
11
11
  "dependencies": {
12
12
  "@graphql-modules/core": "0.7.17",
@@ -30,33 +30,31 @@
30
30
  "ws": "7.4.2",
31
31
  "utf-8-validate": "5.0.5",
32
32
  "bufferutil": "4.0.3",
33
- "core-js": "^3.0.0",
34
- "@babel/runtime": "7.20.0",
35
33
  "@teambit/harmony": "0.4.6",
36
34
  "@teambit/ui-foundation.ui.is-browser": "0.0.500",
37
- "@teambit/cli": "0.0.839",
38
- "@teambit/logger": "0.0.932",
35
+ "@teambit/cli": "0.0.840",
36
+ "@teambit/logger": "0.0.933",
39
37
  "@teambit/toolbox.network.get-port": "1.0.4",
40
- "@teambit/ui": "1.0.106"
38
+ "@teambit/ui": "1.0.108"
41
39
  },
42
40
  "devDependencies": {
43
- "@types/react": "^17.0.8",
44
41
  "@types/cors": "2.8.10",
45
42
  "@types/express": "4.17.13",
46
43
  "@types/lodash.pick": "4.4.6",
47
- "@types/react-dom": "^17.0.5",
48
44
  "@types/node-fetch": "2.5.12",
49
45
  "@types/mocha": "9.1.0",
50
- "@types/node": "12.20.4",
51
- "@types/jest": "^26.0.0",
52
- "@types/testing-library__jest-dom": "5.9.5"
46
+ "@types/jest": "^29.2.2",
47
+ "@types/testing-library__jest-dom": "^5.9.5",
48
+ "@teambit/harmony.envs.core-aspect-env": "0.0.13"
53
49
  },
54
50
  "peerDependencies": {
55
51
  "@apollo/client": "^3.6.0",
56
- "graphql": "15.8.0",
57
- "@teambit/legacy": "1.0.624",
58
- "react": "^16.8.0 || ^17.0.0",
59
- "react-dom": "^16.8.0 || ^17.0.0"
52
+ "react": "^17.0.0 || ^18.0.0",
53
+ "react-dom": "^17.0.0 || ^18.0.0",
54
+ "graphql": "^15.8.0",
55
+ "@types/react": "^18.2.12",
56
+ "@types/react-dom": "^18.2.5",
57
+ "@teambit/legacy": "1.0.624"
60
58
  },
61
59
  "license": "Apache-2.0",
62
60
  "optionalDependencies": {},
@@ -70,7 +68,7 @@
70
68
  },
71
69
  "private": false,
72
70
  "engines": {
73
- "node": ">=12.22.0"
71
+ "node": ">=16.0.0"
74
72
  },
75
73
  "repository": {
76
74
  "type": "git",
@@ -79,12 +77,9 @@
79
77
  "keywords": [
80
78
  "bit",
81
79
  "bit-aspect",
80
+ "bit-core-aspect",
82
81
  "components",
83
82
  "collaboration",
84
- "web",
85
- "react",
86
- "react-components",
87
- "angular",
88
- "angular-components"
83
+ "web"
89
84
  ]
90
85
  }
package/schema.ts ADDED
@@ -0,0 +1,11 @@
1
+ import type { DocumentNode } from 'graphql';
2
+ import type { SchemaDirectives } from '@graphql-modules/core';
3
+
4
+ /**
5
+ * graphql schema for an extension.
6
+ */
7
+ export type Schema = {
8
+ typeDefs?: string | DocumentNode;
9
+ resolvers?: { [key: string]: any };
10
+ schemaDirectives?: SchemaDirectives;
11
+ };
package/tsconfig.json CHANGED
@@ -1,38 +1,33 @@
1
1
  {
2
2
  "compilerOptions": {
3
3
  "lib": [
4
- "es2019",
5
- "DOM",
6
- "ES6",
7
- "DOM.Iterable",
8
- "ScriptHost"
4
+ "esnext",
5
+ "dom",
6
+ "dom.Iterable"
9
7
  ],
10
- "target": "es2015",
11
- "module": "CommonJS",
12
- "jsx": "react",
13
- "allowJs": true,
14
- "composite": true,
8
+ "target": "es2020",
9
+ "module": "es2020",
10
+ "jsx": "react-jsx",
15
11
  "declaration": true,
16
12
  "sourceMap": true,
17
- "skipLibCheck": true,
18
13
  "experimentalDecorators": true,
19
- "outDir": "dist",
14
+ "skipLibCheck": true,
20
15
  "moduleResolution": "node",
21
16
  "esModuleInterop": true,
22
- "rootDir": ".",
23
17
  "resolveJsonModule": true,
24
- "emitDeclarationOnly": true,
25
- "emitDecoratorMetadata": true,
26
- "allowSyntheticDefaultImports": true,
27
- "strictPropertyInitialization": false,
28
- "strict": true,
29
- "noImplicitAny": false,
30
- "preserveConstEnums": true
18
+ "allowJs": true,
19
+ "outDir": "dist",
20
+ "emitDeclarationOnly": true
31
21
  },
32
22
  "exclude": [
23
+ "artifacts",
24
+ "public",
33
25
  "dist",
26
+ "node_modules",
27
+ "package.json",
34
28
  "esm.mjs",
35
- "package.json"
29
+ "**/*.cjs",
30
+ "./dist"
36
31
  ],
37
32
  "include": [
38
33
  "**/*",
package/types/asset.d.ts CHANGED
@@ -5,12 +5,12 @@ declare module '*.png' {
5
5
  declare module '*.svg' {
6
6
  import type { FunctionComponent, SVGProps } from 'react';
7
7
 
8
- export const ReactComponent: FunctionComponent<SVGProps<SVGSVGElement> & { title?: string }>;
8
+ export const ReactComponent: FunctionComponent<
9
+ SVGProps<SVGSVGElement> & { title?: string }
10
+ >;
9
11
  const src: string;
10
12
  export default src;
11
13
  }
12
-
13
- // @TODO Gilad
14
14
  declare module '*.jpg' {
15
15
  const value: any;
16
16
  export = value;
@@ -27,3 +27,15 @@ declare module '*.bmp' {
27
27
  const value: any;
28
28
  export = value;
29
29
  }
30
+ declare module '*.otf' {
31
+ const value: any;
32
+ export = value;
33
+ }
34
+ declare module '*.woff' {
35
+ const value: any;
36
+ export = value;
37
+ }
38
+ declare module '*.woff2' {
39
+ const value: any;
40
+ export = value;
41
+ }