@makerx/graphql-core 2.2.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/{User.cjs → User.js} +2 -1
  2. package/User.js.map +1 -0
  3. package/User.mjs +1 -0
  4. package/User.mjs.map +1 -0
  5. package/{context.cjs → context.js} +2 -1
  6. package/context.js.map +1 -0
  7. package/context.mjs +1 -0
  8. package/context.mjs.map +1 -0
  9. package/index.d.ts +0 -1
  10. package/{index.cjs → index.js} +7 -12
  11. package/index.js.map +1 -0
  12. package/index.mjs +1 -3
  13. package/index.mjs.map +1 -0
  14. package/{logging.cjs → logging.js} +2 -1
  15. package/logging.js.map +1 -0
  16. package/logging.mjs +1 -0
  17. package/logging.mjs.map +1 -0
  18. package/package.json +27 -16
  19. package/{schema-util.cjs → schema-util.js} +1 -0
  20. package/schema-util.js.map +1 -0
  21. package/schema-util.mjs +1 -0
  22. package/schema-util.mjs.map +1 -0
  23. package/shield.d.ts +3 -2
  24. package/{shield.cjs → shield.js} +1 -0
  25. package/shield.js.map +1 -0
  26. package/shield.mjs +1 -0
  27. package/shield.mjs.map +1 -0
  28. package/subscriptions/{context.cjs → context.js} +3 -2
  29. package/subscriptions/context.js.map +1 -0
  30. package/subscriptions/context.mjs +1 -0
  31. package/subscriptions/context.mjs.map +1 -0
  32. package/subscriptions/index.js +12 -0
  33. package/subscriptions/index.js.map +1 -0
  34. package/subscriptions/index.mjs +4 -0
  35. package/subscriptions/index.mjs.map +1 -0
  36. package/subscriptions/{server.cjs → server.js} +3 -2
  37. package/subscriptions/server.js.map +1 -0
  38. package/subscriptions/server.mjs +1 -0
  39. package/subscriptions/server.mjs.map +1 -0
  40. package/subscriptions/{utils.cjs → utils.js} +1 -0
  41. package/subscriptions/utils.js.map +1 -0
  42. package/subscriptions/utils.mjs +1 -0
  43. package/subscriptions/utils.mjs.map +1 -0
  44. package/testing.js +68 -0
  45. package/testing.js.map +1 -0
  46. package/testing.mjs +60 -0
  47. package/testing.mjs.map +1 -0
  48. package/{utils.cjs → utils.js} +1 -0
  49. package/utils.js.map +1 -0
  50. package/utils.mjs +1 -0
  51. package/utils.mjs.map +1 -0
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var utils = require('./utils.cjs');
3
+ var utils = require('./utils.js');
4
4
 
5
5
  class User {
6
6
  constructor(claims, accessToken) {
@@ -47,3 +47,4 @@ class User {
47
47
  }
48
48
 
49
49
  exports.User = User;
50
+ //# sourceMappingURL=User.js.map
package/User.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"User.js","sources":["../src/User.ts"],"sourcesContent":["import type { JwtPayload } from './context'\nimport { isNotNil } from './utils'\n\nexport class User {\n public readonly token: string\n public readonly claims: JwtPayload\n\n constructor(claims: JwtPayload, accessToken: string) {\n this.claims = claims\n this.token = accessToken\n }\n\n get email(): string | undefined {\n return (\n this.claims.email ??\n (this.claims.emails as string[] | undefined)?.[0] ??\n this.claims.preferred_username ??\n this.claims.unique_name ??\n this.claims.upn\n )\n }\n\n get name(): string | undefined {\n if (this.claims.name) return this.claims.name\n const otherNames = [this.claims.given_name, this.claims.family_name].filter(isNotNil)\n if (otherNames.length > 0) return otherNames.join(' ')\n return undefined\n }\n\n get id(): string {\n return this.firstOrThrow('oid', 'sub')\n }\n\n get scopes(): string[] {\n return this.claims.scp ? this.claims.scp.split(' ') : []\n }\n\n get roles(): string[] {\n return this.claims.roles ?? []\n }\n\n private first(...claims: Array<keyof JwtPayload>): string | undefined {\n for (const key of claims) {\n if (this.claims[key]) return this.claims[key] as string\n }\n return undefined\n }\n\n private firstOrThrow(...claims: Array<keyof JwtPayload>): string {\n const first = this.first(...claims)\n if (!first) throw new Error(`claims do not include any of: ${claims.join(', ')}`)\n return first\n }\n}\n"],"names":["isNotNil"],"mappings":";;;;MAGa,IAAI,CAAA;IAIf,WAAY,CAAA,MAAkB,EAAE,WAAmB,EAAA;AACjD,QAAA,IAAI,C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AI,CAAC,MAAM,CAAC,GAAG,CAAC;AAAE,gBAAA,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAW,CAAA;SACxD;AACD,QAAA,OAAO,SAAS,CAAA;KACjB;IAEO,YAAY,CAAC,GAAG,MAA+B,EAAA;QACrD,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,MAAM,CAAC,CAAA;AACnC,QAAA,IAAI,CAAC,KAAK;AAAE,YAAA,MAAM,IAAI,KAAK,CAAC,CAAA,8BAAA,EAAiC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAE,CAAA,CAAC,CAAA;AACjF,QAAA,OAAO,KAAK,CAAA;KACb;AACF;;;;"}
package/User.mjs CHANGED
@@ -45,3 +45,4 @@ class User {
45
45
  }
46
46
 
47
47
  export { User };
48
+ //# sourceMappingURL=User.mjs.map
package/User.mjs.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"User.mjs","sources":["../src/User.ts"],"sourcesContent":["import type { JwtPayload } from './context'\nimport { isNotNil } from './utils'\n\nexport class User {\n public readonly token: string\n public readonly claims: JwtPayload\n\n constructor(claims: JwtPayload, accessToken: string) {\n this.claims = claims\n this.token = accessToken\n }\n\n get email(): string | undefined {\n return (\n this.claims.email ??\n (this.claims.emails as string[] | undefined)?.[0] ??\n this.claims.preferred_username ??\n this.claims.unique_name ??\n this.claims.upn\n )\n }\n\n get name(): string | undefined {\n if (this.claims.name) return this.claims.name\n const otherNames = [this.claims.given_name, this.claims.family_name].filter(isNotNil)\n if (otherNames.length > 0) return otherNames.join(' ')\n return undefined\n }\n\n get id(): string {\n return this.firstOrThrow('oid', 'sub')\n }\n\n get scopes(): string[] {\n return this.claims.scp ? this.claims.scp.split(' ') : []\n }\n\n get roles(): string[] {\n return this.claims.roles ?? []\n }\n\n private first(...claims: Array<keyof JwtPayload>): string | undefined {\n for (const key of claims) {\n if (this.claims[key]) return this.claims[key] as string\n }\n return undefined\n }\n\n private firstOrThrow(...claims: Array<keyof JwtPayload>): string {\n const first = this.first(...claims)\n if (!first) throw new Error(`claims do not include any of: ${claims.join(', ')}`)\n return first\n }\n}\n"],"names":[],"mappings":";;MAGa,IAAI,CAAA;IAIf,WAAY,CAAA,MAAkB,EAAE,WAAmB,EAAA;AACjD,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;AACpB,QAAA,IAAI,CAAC,KAAK,GAAG,WAAW,CAAA;KACzB;AAED,IAAA,IAAI,KAAK,GAAA;AACP,QAAA,QACE,IAAI,CAAC,MAAM,CAAC,KAAK;AAChB,YAAA,IAAI,CAAC,MAAM,CAAC,MAA+B,GAAG,CAAC,CAAC;YACjD,IAAI,CAAC,MAAM,CAAC,kBAAkB;YAC9B,IAAI,CAAC,MAAM,CAAC,WAAW;AACvB,YAAA,IAAI,CAAC,MAAM,CAAC,GAAG,EAChB;KACF;AAED,IAAA,IAAI,IAAI,GAAA;AACN,QAAA,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI;AAAE,YAAA,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,CAAA;QAC7C,MAAM,UAAU,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAA;AACrF,QAAA,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC;AAAE,YAAA,OAAO,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AACtD,QAAA,OAAO,SAAS,CAAA;KACjB;AAED,IAAA,IAAI,EAAE,GAAA;QACJ,OAAO,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;KACvC;AAED,IAAA,IAAI,MAAM,GAAA;QACR,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,CAAA;KACzD;AAED,IAAA,IAAI,KAAK,GAAA;AACP,QAAA,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,IAAI,EAAE,CAAA;KAC/B;IAEO,KAAK,CAAC,GAAG,MAA+B,EAAA;AAC9C,QAAA,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE;AACxB,YAAA,IAAI,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC;AAAE,gBAAA,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAW,CAAA;SACxD;AACD,QAAA,OAAO,SAAS,CAAA;KACjB;IAEO,YAAY,CAAC,GAAG,MAA+B,EAAA;QACrD,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,MAAM,CAAC,CAAA;AACnC,QAAA,IAAI,CAAC,KAAK;AAAE,YAAA,MAAM,IAAI,KAAK,CAAC,CAAA,8BAAA,EAAiC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAE,CAAA,CAAC,CAAA;AACjF,QAAA,OAAO,KAAK,CAAA;KACb;AACF;;;;"}
@@ -2,7 +2,7 @@
2
2
 
3
3
  var crypto = require('crypto');
4
4
  var lodash = require('lodash');
5
- var User = require('./User.cjs');
5
+ var User = require('./User.js');
6
6
 
7
7
  const createContextFactory = ({ requestLogger, augmentRequestInfo, claimsToLog, createUser, requestInfoToLog, augmentContext, }) => {
8
8
  // the function that creates the GraphQL context
@@ -75,3 +75,4 @@ const defaultCreateUser = ({ req, claims }) => {
75
75
 
76
76
  exports.createContextFactory = createContextFactory;
77
77
  exports.defaultCreateUser = defaultCreateUser;
78
+ //# sourceMappingURL=context.js.map
package/context.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sources":["../src/context.ts"],"sourcesContent":["import type { Logger } from '@makerx/node-common'\nimport { randomUUID } from 'crypto'\nimport type { Request } from 'express'\nimport { pick } from 'lodash'\nimport { User } from './User'\n\nexport interface GraphQLContext<\n TLogger extends Logger = Logger,\n TRequestInfo extends BaseRequestInfo = RequestInfo,\n TUser = User | undefined,\n> {\n logger: TLogger\n requestInfo: TRequestInfo\n user: TUser\n started: number\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyGraphqlContext = GraphQLContext<any, any, any>\n\nexport interface BaseRequestInfo extends Record<string, unknown> {\n requestId: string\n protocol: 'http' | 'https' | 'ws'\n host: string\n method: string\n url: string\n origin: string\n referer?: string\n correlationId?: string\n arrLogId?: string\n clientIp?: string\n}\n\nexport interface LambdaContext {\n functionName?: string\n awsRequestId?: string\n}\nexport type LambdaEvent = never\nexport type LambdaRequestInfo = BaseRequestInfo & LambdaContext\nexport type RequestInfo = BaseRequestInfo | LambdaRequestInfo\n\n// standard claims https://datatracker.ietf.org/doc/html/rfc7519#section-4.1\nexport interface JwtPayload {\n [key: string]: unknown\n name?: string | undefined\n email?: string | undefined\n given_name?: string | undefined\n family_name?: string | undefined\n preferred_username?: string | undefined\n upn?: string | undefined\n unique_name?: string | undefined\n oid?: string | undefined\n iss?: string | undefined\n sub?: string | undefined\n aud?: string | string[] | undefined\n roles?: string[] | undefined\n scp?: string | undefined\n exp?: number | undefined\n nbf?: number | undefined\n iat?: number | undefined\n jti?: string | undefined\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type InferUserFromContext<TContext extends AnyGraphqlContext> =\n TContext extends GraphQLContext<any, any, infer TUser> ? TUser : never\nexport type CreateUser<T = User | undefined> = (input: Omit<ContextInput, 'createUser'>) => Promise<T> | T\nexport interface ContextInput {\n req: Request\n claims?: JwtPayload\n context?: LambdaContext\n event?: LambdaEvent\n}\nexport type CreateContext<TContext = GraphQLContext> = (input: ContextInput) => Promise<TContext>\nexport type CreateRequestLogger = (requestMetadata: Record<string, unknown>) => Logger\nexport type AugmentRequestInfo = (input: ContextInput) => Record<string, unknown>\n\nexport interface CreateContextConfig<TContext extends AnyGraphqlContext = GraphQLContext> {\n requestLogger: CreateRequestLogger | Logger\n augmentRequestInfo?: AugmentRequestInfo\n claimsToLog?: string[]\n createUser: CreateUser<InferUserFromContext<TContext>>\n requestInfoToLog?: Array<keyof RequestInfo>\n augmentContext?: (context: TContext) => Record<string, unknown> | Promise<Record<string, unknown>>\n}\n\nexport const createContextFactory = <TContext extends AnyGraphqlContext = GraphQLContext>({\n requestLogger,\n augmentRequestInfo,\n claimsToLog,\n createUser,\n requestInfoToLog,\n augmentContext,\n}: CreateContextConfig<TContext>): CreateContext<TContext> => {\n // the function that creates the GraphQL context\n return async (input: ContextInput) => {\n const { req, claims, context } = input\n\n // build base request info from the request\n const baseRequestInfo: BaseRequestInfo = {\n requestId: req.headers['x-request-id']?.toString() ?? randomUUID(),\n protocol: req.protocol as 'http' | 'https',\n host: req.hostname ?? '',\n method: req.method ?? '',\n url: req.originalUrl,\n origin: req.get('Origin') ?? '',\n referer: req.headers.referer?.toString() ?? '',\n arrLogId: req.headers['x-arr-log-id']?.toString() ?? undefined,\n clientIp: req.headers['x-forwarded-for']?.toString() ?? req.socket.remoteAddress,\n correlationId: req.headers['x-correlation-id']?.toString() ?? undefined,\n }\n\n // add lambda info from the context, if present\n let lambdaRequestInfo: LambdaRequestInfo | undefined\n if (context) {\n const { awsRequestId, functionName } = context\n lambdaRequestInfo = {\n awsRequestId,\n functionName,\n ...baseRequestInfo,\n }\n }\n\n // augment request info with the supplied function, if present\n let requestInfo: RequestInfo = lambdaRequestInfo ?? baseRequestInfo\n if (augmentRequestInfo)\n requestInfo = {\n ...requestInfo,\n ...augmentRequestInfo(input),\n }\n\n // create request logger\n let logger: Logger\n if (typeof requestLogger === 'function') {\n // build request logger metadata\n const requestLoggerMetadata: Record<string, unknown> = {}\n // add request info to log\n if (requestInfoToLog?.length) requestLoggerMetadata.request = pick(requestInfo, requestInfoToLog)\n // add user claims to log\n if (claims && claimsToLog?.length) requestLoggerMetadata.user = pick(claims, claimsToLog)\n // build the request logger\n logger = requestLogger(requestLoggerMetadata)\n } else logger = requestLogger\n\n const graphqlContext: GraphQLContext = {\n requestInfo,\n logger,\n user: createUser ? await createUser(input) : undefined,\n started: Date.now(),\n }\n\n const augmentedGraphQLContext = augmentContext\n ? { ...graphqlContext, ...(await augmentContext(graphqlContext as TContext)) }\n : graphqlContext\n\n return augmentedGraphQLContext as TContext\n }\n}\n\nexport const defaultCreateUser: CreateUser<User | undefined> = ({ req, claims }) => {\n if (!claims) return Promise.resolve(undefined)\n const accessToken = req.headers.authorization?.startsWith('Bearer') ? req.headers.authorization?.substring(7) ?? '' : ''\n return Promise.resolve(new User(claims, accessToken))\n}\n"],"names":["randomUUID","pick","User"],"mappings":";;;;;;AAqFa,MAAA,oBAAoB,GAAG,CAAsD,EACxF,aAAa,EACb,kBAAkB,EAClB,WAAW,EACX,UAAU,EACV,gBAAgB,EAChB,cAAc,GACgB,KAA6B;;AAE3D,IAAA,OAAO,OAAO,KAAmB,KAAI;QACnC,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,KAAK,CAAA;;AAGtC,QAAA,MAAM,eAAe,GAAoB;AACvC,YAAA,SAAS,EAAE,GAAG,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,QAAQ,EAAE,IAAIA,iBAAU,EAAE;YAClE,QAAQ,EAAE,GAAG,CAAC,QAA4B;AAC1C,YAAA,IAAI,EAAE,GAAG,CAAC,QAAQ,IAAI,EAAE;AACxB,YAAA,MAAM,EAAE,GAAG,CAAC,MAAM,IAAI,EAAE;YACxB,GAAG,EAAE,GAAG,CAAC,WAAW;YACpB,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE;YAC/B,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE;YAC9C,QAAQ,EAAE,GAAG,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,QAAQ,EAAE,IAAI,SAAS;AAC9D,YAAA,QAAQ,EAAE,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAC,EAAE,QAAQ,EAAE,IAAI,GAAG,CAAC,MAAM,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,EAAE,IAAI,MAAM,cAAc,CAAC,cAA0B,CAAC,GAAG;cAC5E,cAAc,CAAA;AAElB,QAAA,OAAO,uBAAmC,CAAA;AAC5C,KAAC,CAAA;AACH,EAAC;AAEY,MAAA,iBAAiB,GAAiC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,KAAI;AACjF,IAAA,IAAI,CAAC,MAAM;AAAE,QAAA,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;AAC9C,IAAA,MAAM,WAAW,GAAG,GAAG,CAAC,OAAO,CAAC,aAAa,EAAE,UAAU,CAAC,QAAQ,CAAC,GAAG,GAAG,CAAC,OAAO,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,CAAA;AACxH,IAAA,OAAO,OAAO,CAAC,OAAO,CAAC,IAAIC,SAAI,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAAA;AACvD;;;;;"}
package/context.mjs CHANGED
@@ -72,3 +72,4 @@ const defaultCreateUser = ({ req, claims }) => {
72
72
  };
73
73
 
74
74
  export { createContextFactory, defaultCreateUser };
75
+ //# sourceMappingURL=context.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.mjs","sources":["../src/context.ts"],"sourcesContent":["import type { Logger } from '@makerx/node-common'\nimport { randomUUID } from 'crypto'\nimport type { Request } from 'express'\nimport { pick } from 'lodash'\nimport { User } from './User'\n\nexport interface GraphQLContext<\n TLogger extends Logger = Logger,\n TRequestInfo extends BaseRequestInfo = RequestInfo,\n TUser = User | undefined,\n> {\n logger: TLogger\n requestInfo: TRequestInfo\n user: TUser\n started: number\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyGraphqlContext = GraphQLContext<any, any, any>\n\nexport interface BaseRequestInfo extends Record<string, unknown> {\n requestId: string\n protocol: 'http' | 'https' | 'ws'\n host: string\n method: string\n url: string\n origin: string\n referer?: string\n correlationId?: string\n arrLogId?: string\n clientIp?: string\n}\n\nexport interface LambdaContext {\n functionName?: string\n awsRequestId?: string\n}\nexport type LambdaEvent = never\nexport type LambdaRequestInfo = BaseRequestInfo & LambdaContext\nexport type RequestInfo = BaseRequestInfo | LambdaRequestInfo\n\n// standard claims https://datatracker.ietf.org/doc/html/rfc7519#section-4.1\nexport interface JwtPayload {\n [key: string]: unknown\n name?: string | undefined\n email?: string | undefined\n given_name?: string | undefined\n family_name?: string | undefined\n preferred_username?: string | undefined\n upn?: string | undefined\n unique_name?: string | undefined\n oid?: string | undefined\n iss?: string | undefined\n sub?: string | undefined\n aud?: string | string[] | undefined\n roles?: string[] | undefined\n scp?: string | undefined\n exp?: number | undefined\n nbf?: number | undefined\n iat?: number | undefined\n jti?: string | undefined\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type InferUserFromContext<TContext extends AnyGraphqlContext> =\n TContext extends GraphQLContext<any, any, infer TUser> ? TUser : never\nexport type CreateUser<T = User | undefined> = (input: Omit<ContextInput, 'createUser'>) => Promise<T> | T\nexport interface ContextInput {\n req: Request\n claims?: JwtPayload\n context?: LambdaContext\n event?: LambdaEvent\n}\nexport type CreateContext<TContext = GraphQLContext> = (input: ContextInput) => Promise<TContext>\nexport type CreateRequestLogger = (requestMetadata: Record<string, unknown>) => Logger\nexport type AugmentRequestInfo = (input: ContextInput) => Record<string, unknown>\n\nexport interface CreateContextConfig<TContext extends AnyGraphqlContext = GraphQLContext> {\n requestLogger: CreateRequestLogger | Logger\n augmentRequestInfo?: AugmentRequestInfo\n claimsToLog?: string[]\n createUser: CreateUser<InferUserFromContext<TContext>>\n requestInfoToLog?: Array<keyof RequestInfo>\n augmentContext?: (context: TContext) => Record<string, unknown> | Promise<Record<string, unknown>>\n}\n\nexport const createContextFactory = <TContext extends AnyGraphqlContext = GraphQLContext>({\n requestLogger,\n augmentRequestInfo,\n claimsToLog,\n createUser,\n requestInfoToLog,\n augmentContext,\n}: CreateContextConfig<TContext>): CreateContext<TContext> => {\n // the function that creates the GraphQL context\n return async (input: ContextInput) => {\n const { req, claims, context } = input\n\n // build base request info from the request\n const baseRequestInfo: BaseRequestInfo = {\n requestId: req.headers['x-request-id']?.toString() ?? randomUUID(),\n protocol: req.protocol as 'http' | 'https',\n host: req.hostname ?? '',\n method: req.method ?? '',\n url: req.originalUrl,\n origin: req.get('Origin') ?? '',\n referer: req.headers.referer?.toString() ?? '',\n arrLogId: req.headers['x-arr-log-id']?.toString() ?? undefined,\n clientIp: req.headers['x-forwarded-for']?.toString() ?? req.socket.remoteAddress,\n correlationId: req.headers['x-correlation-id']?.toString() ?? undefined,\n }\n\n // add lambda info from the context, if present\n let lambdaRequestInfo: LambdaRequestInfo | undefined\n if (context) {\n const { awsRequestId, functionName } = context\n lambdaRequestInfo = {\n awsRequestId,\n functionName,\n ...baseRequestInfo,\n }\n }\n\n // augment request info with the supplied function, if present\n let requestInfo: RequestInfo = lambdaRequestInfo ?? baseRequestInfo\n if (augmentRequestInfo)\n requestInfo = {\n ...requestInfo,\n ...augmentRequestInfo(input),\n }\n\n // create request logger\n let logger: Logger\n if (typeof requestLogger === 'function') {\n // build request logger metadata\n const requestLoggerMetadata: Record<string, unknown> = {}\n // add request info to log\n if (requestInfoToLog?.length) requestLoggerMetadata.request = pick(requestInfo, requestInfoToLog)\n // add user claims to log\n if (claims && claimsToLog?.length) requestLoggerMetadata.user = pick(claims, claimsToLog)\n // build the request logger\n logger = requestLogger(requestLoggerMetadata)\n } else logger = requestLogger\n\n const graphqlContext: GraphQLContext = {\n requestInfo,\n logger,\n user: createUser ? await createUser(input) : undefined,\n started: Date.now(),\n }\n\n const augmentedGraphQLContext = augmentContext\n ? { ...graphqlContext, ...(await augmentContext(graphqlContext as TContext)) }\n : graphqlContext\n\n return augmentedGraphQLContext as TContext\n }\n}\n\nexport const defaultCreateUser: CreateUser<User | undefined> = ({ req, claims }) => {\n if (!claims) return Promise.resolve(undefined)\n const accessToken = req.headers.authorization?.startsWith('Bearer') ? req.headers.authorization?.substring(7) ?? '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C,CAAA;AAC9C,IAAA,MAAM,WAAW,GAAG,GAAG,CAAC,OAAO,CAAC,aAAa,EAAE,UAAU,CAAC,QAAQ,CAAC,GAAG,GAAG,CAAC,OAAO,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,CAAA;AACxH,IAAA,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAAA;AACvD;;;;"}
package/index.d.ts CHANGED
@@ -2,7 +2,6 @@ export * from './context';
2
2
  export * from './User';
3
3
  export * from './utils';
4
4
  export * from './logging';
5
- export * from './subscriptions';
6
5
  export * from './schema-util';
7
6
  export * from './shield';
8
7
  export * from './models';
@@ -1,14 +1,11 @@
1
1
  'use strict';
2
2
 
3
- var context = require('./context.cjs');
4
- var User = require('./User.cjs');
5
- var utils = require('./utils.cjs');
6
- var logging = require('./logging.cjs');
7
- var schemaUtil = require('./schema-util.cjs');
8
- var shield = require('./shield.cjs');
9
- var utils$1 = require('./subscriptions/utils.cjs');
10
- var context$1 = require('./subscriptions/context.cjs');
11
- var server = require('./subscriptions/server.cjs');
3
+ var context = require('./context.js');
4
+ var User = require('./User.js');
5
+ var utils = require('./utils.js');
6
+ var logging = require('./logging.js');
7
+ var schemaUtil = require('./schema-util.js');
8
+ var shield = require('./shield.js');
12
9
 
13
10
 
14
11
 
@@ -24,6 +21,4 @@ exports.requireExplicitResolversForScalars = schemaUtil.requireExplicitResolvers
24
21
  exports.combineRuleWithAll = shield.combineRuleWithAll;
25
22
  exports.createRule = shield.createRule;
26
23
  exports.createShieldSchema = shield.createShieldSchema;
27
- exports.extractTokenFromConnectionParams = utils$1.extractTokenFromConnectionParams;
28
- exports.createSubscriptionContextFactory = context$1.createSubscriptionContextFactory;
29
- exports.useSubscriptionsServer = server.useSubscriptionsServer;
24
+ //# sourceMappingURL=index.js.map
package/index.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;"}
package/index.mjs CHANGED
@@ -4,6 +4,4 @@ export { isIntrospectionQuery, isNil, isNotNil } from './utils.mjs';
4
4
  export { logGraphQLOperation, logSubscriptionOperation } from './logging.mjs';
5
5
  export { requireExplicitResolversForScalars } from './schema-util.mjs';
6
6
  export { combineRuleWithAll, createRule, createShieldSchema } from './shield.mjs';
7
- export { extractTokenFromConnectionParams } from './subscriptions/utils.mjs';
8
- export { createSubscriptionContextFactory } from './subscriptions/context.mjs';
9
- export { useSubscriptionsServer } from './subscriptions/server.mjs';
7
+ //# sourceMappingURL=index.mjs.map
package/index.mjs.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;"}
@@ -3,7 +3,7 @@
3
3
  var nodeCommon = require('@makerx/node-common');
4
4
  var graphql = require('graphql');
5
5
  var lodash = require('lodash');
6
- var utils = require('./utils.cjs');
6
+ var utils = require('./utils.js');
7
7
 
8
8
  /**
9
9
  * Logs a GraphQL operation in a consistent format with the option of including any additional data.
@@ -44,3 +44,4 @@ const logSubscriptionOperation = ({ args, result, message, logLevel, }) => {
44
44
 
45
45
  exports.logGraphQLOperation = logGraphQLOperation;
46
46
  exports.logSubscriptionOperation = logSubscriptionOperation;
47
+ //# sourceMappingURL=logging.js.map
package/logging.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logging.js","sources":["../src/logging.ts"],"sourcesContent":["import type { Logger } from '@makerx/node-common'\nimport { isLocalDev } from '@makerx/node-common'\nimport type { ExecutionArgs, GraphQLFormattedError } from 'graphql'\nimport { OperationTypeNode, print } from 'graphql'\nimport type { ExecutionResult } from 'graphql-ws'\nimport { omitBy } from 'lodash'\nimport type { GraphQLContext } from './context'\nimport { isIntrospectionQuery, isNil } from './utils'\n\ntype LogFunction = Logger['info']\nexport type LoggerLogFunctions<T extends Logger> = {\n [Property in keyof T]: LogFunction\n}\n\n/**\n * Info for logging a GraphQL operation in a consistent format with the option of including any additional data.\n */\nexport interface GraphQLLogOperationInfo<TLogger extends Logger = Logger> extends Record<string, unknown> {\n /**\n * The message to log, defaults to 'GraphQL operation'.\n */\n message?: string\n /**\n * The timestamp when the operation started, if supplied, the duration will be logged.\n */\n started?: number\n /**\n * The type of GraphQL operation.\n */\n type?: OperationTypeNode | null\n /**\n * The name of the GraphQL operation.\n */\n operationName?: string | null\n /**\n * The formatted GraphQL query.\n */\n query?: string | null\n /**\n * The GraphQL variables.\n */\n variables?: Record<string, unknown> | null\n /**\n * The result of the GraphQL operation.\n * Generally, we don't log the data or extensions, just errors.\n */\n result?: {\n data?: Record<string, unknown> | null\n errors?: readonly GraphQLFormattedError[] | null\n extensions?: Record<string, unknown> | null\n hasNext?: boolean\n }\n /**\n * Whether the operation is an introspection query.\n */\n isIntrospectionQuery?: boolean\n /**\n * Whether the operation is part of an incremental response.\n */\n isIncrementalResponse?: boolean\n /**\n * Whether the operation is a subsequent payload of an incremental response.\n */\n isSubsequentPayload?: boolean\n /**\n * The logger to use.\n */\n logger: TLogger\n /**\n * The logger function to use, defaults to 'info'.\n */\n logLevel?: keyof LoggerLogFunctions<TLogger>\n}\n\n/**\n * Logs a GraphQL operation in a consistent format with the option of including any additional data.\n * Top level and result entries with null or undefined values will be omitted.\n */\nexport const logGraphQLOperation = <TLogger extends Logger = Logger>({\n message = 'GraphQL operation',\n started,\n type,\n operationName,\n query,\n variables,\n result,\n logger,\n logLevel = 'info',\n ...rest\n}: GraphQLLogOperationInfo<TLogger>) => {\n const isIntrospection = query && isIntrospectionQuery(query)\n if (isLocalDev && isIntrospection) return\n logger[logLevel as keyof Logger](\n message,\n omitBy(\n {\n type,\n operationName,\n query,\n variables: variables && Object.keys(variables).length > 0 ? variables : undefined,\n duration: started ? Date.now() - started : undefined,\n result: result ? omitBy(result, isNil) : undefined,\n isIntrospectionQuery: isIntrospection || undefined,\n ...omitBy(rest, isNil),\n },\n isNil,\n ),\n )\n}\n\nexport const logSubscriptionOperation = <TLogger extends Logger = Logger>({\n args,\n result,\n message,\n logLevel,\n}: {\n args: ExecutionArgs\n result?: ExecutionResult\n message?: string\n logLevel?: keyof LoggerLogFunctions<TLogger>\n}) => {\n const logger = (args.contextValue as GraphQLContext).logger as TLogger\n if (!logger) return\n\n const { operationName, variableValues, document } = args\n const { data, ...resultWithoutData } = result ?? {}\n\n logGraphQLOperation({\n message,\n type: OperationTypeNode.SUBSCRIPTION,\n operationName,\n query: print(document),\n variables: variableValues,\n result: resultWithoutData,\n logger,\n logLevel,\n })\n}\n"],"names":["isIntrospectionQuery","isLocalDev","omitBy","isNil","OperationTypeNode","print"],"mappings":";;;;;;;AA0EA;;;AAGG;AACI,MAAM,mBAAmB,GAAG,CAAkC,EACnE,OAAO,GAAG,mBAAmB,EAC7B,OAAO,EACP,IAAI,EACJ,aAAa,EACb,KAAK,EACL,SAAS,EACT,MAAM,EACN,MAAM,EACN,QAAQ,GAAG,MAAM,EACjB,GAAG,IAAI,EAC0B,KAAI;IACrC,MAAM,eAAe,GAAG,KAAK,IAAIA,0BAAoB,CAAC,KAAK,CAAC,CAAA;IAC5D,IAAIC,qBAAU,IAAI,eAAe;QAAE,OAAM;AACzC,IAAA,MAAM,CAAC,QAAwB,CAAC,CAC9B,OAAO,EACPC,aAAM,CACJ;QACE,IAAI;QACJ,aAAa;QACb,KAAK;QACL,SAAS,EAAE,SAAS,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,GAAG,CAAC,GAAG,SAAS,GAAG,SAAS;AACjF,QAAA,QAAQ,EAAE,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,OAAO,GAAG,SAAS;AACpD,QAAA,MAAM,EAAE,MAAM,GAAGA,aAAM,CAAC,MAAM,EAAEC,WAAK,CAAC,GAAG,SAAS;QAClD,oBAAoB,EAAE,eAAe,IAAI,SAAS;AAClD,QAAA,GAAGD,aAAM,CAAC,IAAI,EAAEC,WAAK,CAAC;KACvB,EACDA,WAAK,CACN,CACF,CAAA;AACH,EAAC;AAEM,MAAM,wBAAwB,GAAG,CAAkC,EACxE,IAAI,EACJ,MAAM,EACN,OAAO,EACP,QAAQ,GAMT,KAAI;AACH,IAAA,MAAM,MAAM,GAAI,IAAI,CAAC,YAA+B,CAAC,MAAiB,CAAA;AACtE,IAAA,IAAI,CAAC,MAAM;QAAE,OAAM;IAEnB,MAAM,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAA;IACxD,MAAM,EAAE,IAAI,EAAE,GAAG,iBAAiB,EAAE,GAAG,MAAM,IAAI,EAAE,CAAA;AAEnD,IAAA,mBAAmB,CAAC;QAClB,OAAO;QACP,IAAI,EAAEC,yBAAiB,CAAC,YAAY;QACpC,aAAa;AACb,QAAA,KAAK,EAAEC,aAAK,CAAC,QAAQ,CAAC;AACtB,QAAA,SAAS,EAAE,cAAc;AACzB,QAAA,MAAM,EAAE,iBAAiB;QACzB,MAAM;QACN,QAAQ;AACT,KAAA,CAAC,CAAA;AACJ;;;;;"}
package/logging.mjs CHANGED
@@ -41,3 +41,4 @@ const logSubscriptionOperation = ({ args, result, message, logLevel, }) => {
41
41
  };
42
42
 
43
43
  export { logGraphQLOperation, logSubscriptionOperation };
44
+ //# sourceMappingURL=logging.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logging.mjs","sources":["../src/logging.ts"],"sourcesContent":["import type { Logger } from '@makerx/node-common'\nimport { isLocalDev } from '@makerx/node-common'\nimport type { ExecutionArgs, GraphQLFormattedError } from 'graphql'\nimport { OperationTypeNode, print } from 'graphql'\nimport type { ExecutionResult } from 'graphql-ws'\nimport { omitBy } from 'lodash'\nimport type { GraphQLContext } from './context'\nimport { isIntrospectionQuery, isNil } from './utils'\n\ntype LogFunction = Logger['info']\nexport type LoggerLogFunctions<T extends Logger> = {\n [Property in keyof T]: LogFunction\n}\n\n/**\n * Info for logging a GraphQL operation in a consistent format with the option of including any additional data.\n */\nexport interface GraphQLLogOperationInfo<TLogger extends Logger = Logger> extends Record<string, unknown> {\n /**\n * The message to log, defaults to 'GraphQL operation'.\n */\n message?: string\n /**\n * The timestamp when the operation started, if supplied, the duration will be logged.\n */\n started?: number\n /**\n * The type of GraphQL operation.\n */\n type?: OperationTypeNode | null\n /**\n * The name of the GraphQL operation.\n */\n operationName?: string | null\n /**\n * The formatted GraphQL query.\n */\n query?: string | null\n /**\n * The GraphQL variables.\n */\n variables?: Record<string, unknown> | null\n /**\n * The result of the GraphQL operation.\n * Generally, we don't log the data or extensions, just errors.\n */\n result?: {\n data?: Record<string, unknown> | null\n errors?: readonly GraphQLFormattedError[] | null\n extensions?: Record<string, unknown> | null\n hasNext?: boolean\n }\n /**\n * Whether the operation is an introspection query.\n */\n isIntrospectionQuery?: boolean\n /**\n * Whether the operation is part of an incremental response.\n */\n isIncrementalResponse?: boolean\n /**\n * Whether the operation is a subsequent payload of an incremental response.\n */\n isSubsequentPayload?: boolean\n /**\n * The logger to use.\n */\n logger: TLogger\n /**\n * The logger function to use, defaults to 'info'.\n */\n logLevel?: keyof LoggerLogFunctions<TLogger>\n}\n\n/**\n * Logs a GraphQL operation in a consistent format with the option of including any additional data.\n * Top level and result entries with null or undefined values will be omitted.\n */\nexport const logGraphQLOperation = <TLogger extends Logger = Logger>({\n message = 'GraphQL operation',\n started,\n type,\n operationName,\n query,\n variables,\n result,\n logger,\n logLevel = 'info',\n ...rest\n}: GraphQLLogOperationInfo<TLogger>) => {\n const isIntrospection = query && isIntrospectionQuery(query)\n if (isLocalDev && isIntrospection) return\n logger[logLevel as keyof Logger](\n message,\n omitBy(\n {\n type,\n operationName,\n query,\n variables: variables && Object.keys(variables).length > 0 ? variables : undefined,\n duration: started ? Date.now() - started : undefined,\n result: result ? omitBy(result, isNil) : undefined,\n isIntrospectionQuery: isIntrospection || undefined,\n ...omitBy(rest, isNil),\n },\n isNil,\n ),\n )\n}\n\nexport const logSubscriptionOperation = <TLogger extends Logger = Logger>({\n args,\n result,\n message,\n logLevel,\n}: {\n args: ExecutionArgs\n result?: ExecutionResult\n message?: string\n logLevel?: keyof LoggerLogFunctions<TLogger>\n}) => {\n const logger = (args.contextValue as GraphQLContext).logger as TLogger\n if (!logger) return\n\n const { operationName, variableValues, document } = args\n const { data, ...resultWithoutData } = result ?? {}\n\n logGraphQLOperation({\n message,\n type: OperationTypeNode.SUBSCRIPTION,\n operationName,\n query: print(document),\n variables: variableValues,\n result: resultWithoutData,\n logger,\n logLevel,\n })\n}\n"],"names":[],"mappings":";;;;;AA0EA;;;AAGG;AACI,MAAM,mBAAmB,GAAG,CAAkC,EACnE,OAAO,GAAG,mBAAmB,EAC7B,OAAO,EACP,IAAI,EACJ,aAAa,EACb,KAAK,EACL,SAAS,EACT,MAAM,EACN,MAAM,EACN,QAAQ,GAAG,MAAM,EACjB,GAAG,IAAI,EAC0B,KAAI;IACrC,MAAM,eAAe,GAAG,KAAK,IAAI,oBAAoB,CAAC,KAAK,CAAC,CAAA;IAC5D,IAAI,UAAU,IAAI,eAAe;QAAE,OAAM;AACzC,IAAA,MAAM,CAAC,QAAwB,CAAC,CAC9B,OAAO,EACP,MAAM,CACJ;QACE,IAAI;QACJ,aAAa;QACb,KAAK;QACL,SAAS,EAAE,SAAS,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,GAAG,CAAC,GAAG,SAAS,GAAG,SAAS;AACjF,QAAA,QAAQ,EAAE,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,OAAO,GAAG,SAAS;AACpD,QAAA,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,GAAG,SAAS;QAClD,oBAAoB,EAAE,eAAe,IAAI,SAAS;AAClD,QAAA,GAAG,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC;KACvB,EACD,KAAK,CACN,CACF,CAAA;AACH,EAAC;AAEM,MAAM,wBAAwB,GAAG,CAAkC,EACxE,IAAI,EACJ,MAAM,EACN,OAAO,EACP,QAAQ,GAMT,KAAI;AACH,IAAA,MAAM,MAAM,GAAI,IAAI,CAAC,YAA+B,CAAC,MAAiB,CAAA;AACtE,IAAA,IAAI,CAAC,MAAM;QAAE,OAAM;IAEnB,MAAM,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAA;IACxD,MAAM,EAAE,IAAI,EAAE,GAAG,iBAAiB,EAAE,GAAG,MAAM,IAAI,EAAE,CAAA;AAEnD,IAAA,mBAAmB,CAAC;QAClB,OAAO;QACP,IAAI,EAAE,iBAAiB,CAAC,YAAY;QACpC,aAAa;AACb,QAAA,KAAK,EAAE,KAAK,CAAC,QAAQ,CAAC;AACtB,QAAA,SAAS,EAAE,cAAc;AACzB,QAAA,MAAM,EAAE,iBAAiB;QACzB,MAAM;QACN,QAAQ;AACT,KAAA,CAAC,CAAA;AACJ;;;;"}
package/package.json CHANGED
@@ -1,26 +1,16 @@
1
1
  {
2
- "main": "index.js",
3
- "types": "index.d.ts",
2
+ "scripts": {},
3
+ "files": [
4
+ "**"
5
+ ],
4
6
  "name": "@makerx/graphql-core",
5
- "version": "2.2.0",
7
+ "version": "2.2.1",
6
8
  "private": false,
7
9
  "description": "A set of core GraphQL utilities that MakerX uses to build GraphQL APIs",
8
10
  "author": "MakerX",
9
11
  "license": "MIT",
10
- "type": "module",
11
- "module": "index.mjs",
12
- "exports": {
13
- ".": {
14
- "types": "./index.d.ts",
15
- "module": "./index.mjs",
16
- "import": "./index.mjs",
17
- "require": "./index.cjs",
18
- "default": "./index.mjs"
19
- },
20
- "./package.json": "./package.json"
21
- },
22
12
  "engines": {
23
- "node": ">=18.0"
13
+ "node": ">=20.0"
24
14
  },
25
15
  "bugs": {
26
16
  "url": "https://github.com/MakerXStudio/graphql-core/issues"
@@ -52,5 +42,26 @@
52
42
  "ws": {
53
43
  "optional": true
54
44
  }
45
+ },
46
+ "main": "./index.js",
47
+ "module": "./index.mjs",
48
+ "types": "./index.d.ts",
49
+ "type": "module",
50
+ "exports": {
51
+ ".": {
52
+ "types": "./index.d.ts",
53
+ "import": "./index.mjs",
54
+ "require": "./index.js"
55
+ },
56
+ "./testing": {
57
+ "types": "./testing.d.ts",
58
+ "import": "./testing.mjs",
59
+ "require": "./testing.js"
60
+ },
61
+ "./subscriptions": {
62
+ "types": "./subscriptions/index.d.ts",
63
+ "import": "./subscriptions/index.mjs",
64
+ "require": "./subscriptions/index.js"
65
+ }
55
66
  }
56
67
  }
@@ -28,3 +28,4 @@ function requireExplicitResolversForScalars(schema, ...scalarsToIgnore) {
28
28
  }
29
29
 
30
30
  exports.requireExplicitResolversForScalars = requireExplicitResolversForScalars;
31
+ //# sourceMappingURL=schema-util.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-util.js","sources":["../src/schema-util.ts"],"sourcesContent":["import type { GraphQLSchema } from 'graphql'\nimport { GraphQLScalarType } from 'graphql'\n\n/**\n * It is possible to register a custom scalar with apollo server without defining an explicit resolver (a default resolver is used in\n * this case), but it is rarely desirable. This function, when provided with your built schema, will ensure any registered scalar types\n * provide at least a base level of validation by failing to parse a Symbol instance. The default resolver does not pass this test\n * meaning any scalars that are falling back to the default resolver will fail.\n * @param schema A schema object, the result of calling `makeExecutableSchema` from `@graphql-tools/schema`\n */\nexport function requireExplicitResolversForScalars(schema: GraphQLSchema, ...scalarsToIgnore: string[]) {\n const testSymbol = Symbol('testSymbol')\n const scalars = Object.values(schema.getTypeMap()).filter((t): t is GraphQLScalarType => t instanceof GraphQLScalarType)\n for (const scalar of scalars) {\n if (scalar.name === 'Void' || scalar.name === 'JSON' || scalarsToIgnore.includes(scalar.name)) continue\n try {\n scalar.parseValue(testSymbol)\n } catch {\n // We expect that a good parser should throw when parsing a random symbol\n continue\n }\n throw new Error(\n `Scalar ${scalar.name} does not appear to have an explicit resolver, or is not performing sufficient validation when parsing input. ` +\n \"If you're satisfied with this scalar you can ignore it in the call to `requireExplicitResolversForScalars`.\",\n )\n }\n}\n"],"names":["GraphQLScalarType"],"mappings":";;;;AAGA;;;;;;AAMG;SACa,kCAAkC,CAAC,MAAqB,EAAE,GAAG,eAAyB,EAAA;AACpG,IAAA,MAAM,UAAU,GAAG,MAAM,CAAC,YAAY,CAAC,CAAA;IACvC,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAA6B,CAAC,YAAYA,yBAAiB,CAAC,CAAA;AACxH,IAAA,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;AAC5B,QAAA,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,IAAI,eAAe,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC;YAAE,SAAQ;AACvG,QAAA,IAAI;AACF,YAAA,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC,CAAA;SAC9B;AAAC,QAAA,MAAM;;YAEN,SAAQ;SACT;AACD,QAAA,MAAM,IAAI,KAAK,CACb,UAAU,MAAM,CAAC,IAAI,CAAgH,8GAAA,CAAA;AACnI,YAAA,6GAA6G,CAChH,CAAA;KACF;AACH;;;;"}
package/schema-util.mjs CHANGED
@@ -26,3 +26,4 @@ function requireExplicitResolversForScalars(schema, ...scalarsToIgnore) {
26
26
  }
27
27
 
28
28
  export { requireExplicitResolversForScalars };
29
+ //# sourceMappingURL=schema-util.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-util.mjs","sources":["../src/schema-util.ts"],"sourcesContent":["import type { GraphQLSchema } from 'graphql'\nimport { GraphQLScalarType } from 'graphql'\n\n/**\n * It is possible to register a custom scalar with apollo server without defining an explicit resolver (a default resolver is used in\n * this case), but it is rarely desirable. This function, when provided with your built schema, will ensure any registered scalar types\n * provide at least a base level of validation by failing to parse a Symbol instance. The default resolver does not pass this test\n * meaning any scalars that are falling back to the default resolver will fail.\n * @param schema A schema object, the result of calling `makeExecutableSchema` from `@graphql-tools/schema`\n */\nexport function requireExplicitResolversForScalars(schema: GraphQLSchema, ...scalarsToIgnore: string[]) {\n const testSymbol = Symbol('testSymbol')\n const scalars = Object.values(schema.getTypeMap()).filter((t): t is GraphQLScalarType => t instanceof GraphQLScalarType)\n for (const scalar of scalars) {\n if (scalar.name === 'Void' || scalar.name === 'JSON' || scalarsToIgnore.includes(scalar.name)) continue\n try {\n scalar.parseValue(testSymbol)\n } catch {\n // We expect that a good parser should throw when parsing a random symbol\n continue\n }\n throw new Error(\n `Scalar ${scalar.name} does not appear to have an explicit resolver, or is not performing sufficient validation when parsing input. ` +\n \"If you're satisfied with this scalar you can ignore it in the call to `requireExplicitResolversForScalars`.\",\n )\n }\n}\n"],"names":[],"mappings":";;AAGA;;;;;;AAMG;SACa,kCAAkC,CAAC,MAAqB,EAAE,GAAG,eAAyB,EAAA;AACpG,IAAA,MAAM,UAAU,GAAG,MAAM,CAAC,YAAY,CAAC,CAAA;IACvC,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAA6B,CAAC,YAAY,iBAAiB,CAAC,CAAA;AACxH,IAAA,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;AAC5B,QAAA,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,IAAI,eAAe,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC;YAAE,SAAQ;AACvG,QAAA,IAAI;AACF,YAAA,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC,CAAA;SAC9B;AAAC,QAAA,MAAM;;YAEN,SAAQ;SACT;AACD,QAAA,MAAM,IAAI,KAAK,CACb,UAAU,MAAM,CAAC,IAAI,CAAgH,8GAAA,CAAA;AACnI,YAAA,6GAA6G,CAChH,CAAA;KACF;AACH;;;;"}
package/shield.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import type { and, chain, or, race } from 'graphql-shield';
2
- import type { ShieldRule } from 'graphql-shield/typings/types';
2
+ import { allow } from 'graphql-shield';
3
3
  import type { Primitive } from './models';
4
4
  type RuleCombinator = typeof chain | typeof race | typeof or | typeof and;
5
- export declare const createRule: <TContext, TParent = unknown, TArgs = unknown>(logic: (parent: TParent, args: TArgs, ctx: TContext) => boolean | Promise<boolean> | Error, cache?: 'contextual' | 'strict') => import("graphql-shield/typings/rules").Rule;
5
+ export type ShieldRule = ReturnType<(typeof allow)['getRules']>[number];
6
+ export declare const createRule: <TContext, TParent = unknown, TArgs = unknown>(logic: (parent: TParent, args: TArgs, ctx: TContext) => boolean | Promise<boolean> | Error, cache?: 'contextual' | 'strict') => ShieldRule;
6
7
  /**
7
8
  * Combines a given rule with all existing defined rules using the provided combinator
8
9
  * @param schema The existing shield schema with rules
@@ -50,3 +50,4 @@ function createShieldSchema(schema, fallbackRule = graphqlShield.allow) {
50
50
  exports.combineRuleWithAll = combineRuleWithAll;
51
51
  exports.createRule = createRule;
52
52
  exports.createShieldSchema = createShieldSchema;
53
+ //# sourceMappingURL=shield.js.map
package/shield.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shield.js","sources":["../src/shield.ts"],"sourcesContent":["import type { and, chain, or, race } from 'graphql-shield'\nimport { allow, rule, shield } from 'graphql-shield'\nimport type { IRules } from 'graphql-shield'\nimport type { Primitive } from './models'\n\ntype RuleCombinator = typeof chain | typeof race | typeof or | typeof and\n// For whatever reason, graphql-shield doesn't export this type, but we can extract if from\n// what it does export.\nexport type ShieldRule = ReturnType<(typeof allow)['getRules']>[number]\nexport const createRule = <TContext, TParent = unknown, TArgs = unknown>(\n logic: (parent: TParent, args: TArgs, ctx: TContext) => boolean | Promise<boolean> | Error,\n cache: 'contextual' | 'strict' = 'strict',\n): ShieldRule => rule({ cache })(async (parent, args, ctx) => logic(parent, args, ctx))\n\n/**\n * Combines a given rule with all existing defined rules using the provided combinator\n * @param schema The existing shield schema with rules\n * @param rule The rule to be combined with existing rules\n * @param combinator The combinator to use. Eg. and | or | chain | race\n *\n * Usage:\n *\n * const updatedSchema = combineRuleWithAll(shieldSchema, rules.accountNotBlocked, chain)\n */\nexport function combineRuleWithAll<T>(schema: ShieldSchema<T>, rule: ShieldRule, combinator: RuleCombinator): ShieldSchema<T> {\n return Object.fromEntries(\n Object.entries(schema).map(([key, value]) => {\n if (value.constructor.name !== 'Object') {\n return [key, combinator(rule, value)]\n }\n return [key, combineRuleWithAll(value, rule, combinator)]\n }),\n ) as ShieldSchema<T>\n}\n\n/**\n * Creates graphql shield middleware making use of generics to type the definition of the rules.\n * @param schema A mapping of schema objects to the shield rules that define the access to that object\n * @param fallbackRule A fallback rule to apply to any object or property which doesn't have a defined rule.\n *\n * Usage:\n * import { Resolvers } from '../generated/types'\n *\n * const shieldSchema = createShieldSchema<Resolvers>({\n * Query: {\n * getThings: allow,\n * dontGetThings: deny,\n * }\n * })\n *\n * let schema = makeExecutableSchema({...})\n *\n * schema = applyMiddleware(schema, shieldSchema)\n */\nexport function createShieldSchema<TRootResolvers>(schema: ShieldSchema<TRootResolvers>, fallbackRule: ShieldRule = allow) {\n return shield(schema as IRules, {\n allowExternalErrors: true,\n fallbackRule: fallbackRule,\n })\n}\n\nexport type ShieldSchema<TResolver> = TResolver extends Primitive\n ? ShieldRule\n : {\n [key in keyof TResolver]?: ShieldSchema<TResolver[key]> | ShieldRule\n } & {\n '*'?: ShieldRule\n }\n"],"names":["rule","allow","shield"],"mappings":";;;;AASa,MAAA,UAAU,GAAG,CACxB,KAA0F,EAC1F,KAAA,GAAiC,QAAQ,KAC1BA,kBAAI,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,OAAO,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,KAAK,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,CAAC,EAAC;AAEvF;;;;;;;;;AASG;SACa,kBAAkB,CAAI,MAAuB,EAAE,IAAgB,EAAE,UAA0B,EAAA;IACzG,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,KAAI;QAC1C,IAAI,KAAK,CAAC,WAAW,CAAC,IAAI,KAAK,QAAQ,EAAE;YACvC,OAAO,CAAC,GAAG,EAAE,UAAU,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAA;SACtC;AACD,QAAA,OAAO,CAAC,GAAG,EAAE,kBAAkB,CAAC,KAAK,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC,CAAA;KAC1D,CAAC,CACgB,CAAA;AACtB,CAAC;AAED;;;;;;;;;;;;;;;;;;AAkBG;SACa,kBAAkB,CAAiB,MAAoC,EAAE,eAA2BC,mBAAK,EAAA;IACvH,OAAOC,oBAAM,CAAC,MAAgB,EAAE;AAC9B,QAAA,mBAAmB,EAAE,IAAI;AACzB,QAAA,YAAY,EAAE,YAAY;AAC3B,KAAA,CAAC,CAAA;AACJ;;;;;;"}
package/shield.mjs CHANGED
@@ -46,3 +46,4 @@ function createShieldSchema(schema, fallbackRule = allow) {
46
46
  }
47
47
 
48
48
  export { combineRuleWithAll, createRule, createShieldSchema };
49
+ //# sourceMappingURL=shield.mjs.map
package/shield.mjs.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shield.mjs","sources":["../src/shield.ts"],"sourcesContent":["import type { and, chain, or, race } from 'graphql-shield'\nimport { allow, rule, shield } from 'graphql-shield'\nimport type { IRules } from 'graphql-shield'\nimport type { Primitive } from './models'\n\ntype RuleCombinator = typeof chain | typeof race | typeof or | typeof and\n// For whatever reason, graphql-shield doesn't export this type, but we can extract if from\n// what it does export.\nexport type ShieldRule = ReturnType<(typeof allow)['getRules']>[number]\nexport const createRule = <TContext, TParent = unknown, TArgs = unknown>(\n logic: (parent: TParent, args: TArgs, ctx: TContext) => boolean | Promise<boolean> | Error,\n cache: 'contextual' | 'strict' = 'strict',\n): ShieldRule => rule({ cache })(async (parent, args, ctx) => logic(parent, args, ctx))\n\n/**\n * Combines a given rule with all existing defined rules using the provided combinator\n * @param schema The existing shield schema with rules\n * @param rule The rule to be combined with existing rules\n * @param combinator The combinator to use. Eg. and | or | chain | race\n *\n * Usage:\n *\n * const updatedSchema = combineRuleWithAll(shieldSchema, rules.accountNotBlocked, chain)\n */\nexport function combineRuleWithAll<T>(schema: ShieldSchema<T>, rule: ShieldRule, combinator: RuleCombinator): ShieldSchema<T> {\n return Object.fromEntries(\n Object.entries(schema).map(([key, value]) => {\n if (value.constructor.name !== 'Object') {\n return [key, combinator(rule, value)]\n }\n return [key, combineRuleWithAll(value, rule, combinator)]\n }),\n ) as ShieldSchema<T>\n}\n\n/**\n * Creates graphql shield middleware making use of generics to type the definition of the rules.\n * @param schema A mapping of schema objects to the shield rules that define the access to that object\n * @param fallbackRule A fallback rule to apply to any object or property which doesn't have a defined rule.\n *\n * Usage:\n * import { Resolvers } from '../generated/types'\n *\n * const shieldSchema = createShieldSchema<Resolvers>({\n * Query: {\n * getThings: allow,\n * dontGetThings: deny,\n * }\n * })\n *\n * let schema = makeExecutableSchema({...})\n *\n * schema = applyMiddleware(schema, shieldSchema)\n */\nexport function createShieldSchema<TRootResolvers>(schema: ShieldSchema<TRootResolvers>, fallbackRule: ShieldRule = allow) {\n return shield(schema as IRules, {\n allowExternalErrors: true,\n fallbackRule: fallbackRule,\n })\n}\n\nexport type ShieldSchema<TResolver> = TResolver extends Primitive\n ? ShieldRule\n : {\n [key in keyof TResolver]?: ShieldSchema<TResolver[key]> | ShieldRule\n } & {\n '*'?: ShieldRule\n }\n"],"names":[],"mappings":";;AASa,MAAA,UAAU,GAAG,CACxB,KAA0F,EAC1F,KAAA,GAAiC,QAAQ,KAC1B,IAAI,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,OAAO,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,KAAK,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,CAAC,EAAC;AAEvF;;;;;;;;;AASG;SACa,kBAAkB,CAAI,MAAuB,EAAE,IAAgB,EAAE,UAA0B,EAAA;IACzG,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,KAAI;QAC1C,IAAI,KAAK,CAAC,WAAW,CAAC,IAAI,KAAK,QAAQ,EAAE;YACvC,OAAO,CAAC,GAAG,EAAE,UAAU,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAA;SACtC;AACD,QAAA,OAAO,CAAC,GAAG,EAAE,kBAAkB,CAAC,KAAK,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC,CAAA;KAC1D,CAAC,CACgB,CAAA;AACtB,CAAC;AAED;;;;;;;;;;;;;;;;;;AAkBG;SACa,kBAAkB,CAAiB,MAAoC,EAAE,eAA2B,KAAK,EAAA;IACvH,OAAO,MAAM,CAAC,MAAgB,EAAE;AAC9B,QAAA,mBAAmB,EAAE,IAAI;AACzB,QAAA,YAAY,EAAE,YAAY;AAC3B,KAAA,CAAC,CAAA;AACJ;;;;"}
@@ -2,8 +2,8 @@
2
2
 
3
3
  var crypto = require('crypto');
4
4
  var lodash = require('lodash');
5
- var User = require('../User.cjs');
6
- var utils = require('./utils.cjs');
5
+ var User = require('../User.js');
6
+ var utils = require('./utils.js');
7
7
 
8
8
  const createSubscriptionContextFactory = ({ requestLogger, augmentRequestInfo, claimsToLog, createUser = defaultCreateUser, requestInfoToLog, augmentContext, }) => {
9
9
  // the function that creates the GraphQL context
@@ -61,3 +61,4 @@ const defaultCreateUser = ({ claims, connectionParams }) => {
61
61
  };
62
62
 
63
63
  exports.createSubscriptionContextFactory = createSubscriptionContextFactory;
64
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sources":["../../src/subscriptions/context.ts"],"sourcesContent":["import type { Logger } from '@makerx/node-common'\nimport { randomUUID } from 'crypto'\nimport type { IncomingMessage } from 'http'\nimport { pick } from 'lodash'\nimport { User } from '../User'\nimport type { CreateRequestLogger, GraphQLContext, JwtPayload, RequestInfo } from '../context'\nimport { extractTokenFromConnectionParams } from './utils'\n\nexport interface SubscriptionContextInput {\n connectRequest: IncomingMessage\n connectionParams?: Readonly<Record<string, unknown>>\n claims?: JwtPayload\n}\n\nexport type CreateSubscriptionUser<T = User | undefined> = (input: SubscriptionContextInput) => Promise<T>\nexport type CreateSubscriptionContext<TContext = GraphQLContext> = (input: SubscriptionContextInput) => Promise<TContext>\nexport type AugmentSubscriptionRequestInfo = (input: SubscriptionContextInput) => Record<string, unknown>\n\nexport interface CreateSubscriptionContextConfig<TContext = GraphQLContext> {\n requestLogger: CreateRequestLogger | Logger\n augmentRequestInfo?: AugmentSubscriptionRequestInfo\n claimsToLog?: string[]\n createUser?: CreateSubscriptionUser\n requestInfoToLog?: Array<keyof RequestInfo>\n augmentContext?: (context: TContext) => Record<string, unknown> | Promise<Record<string, unknown>>\n}\n\nexport const createSubscriptionContextFactory = <TContext extends GraphQLContext = GraphQLContext>({\n requestLogger,\n augmentRequestInfo,\n claimsToLog,\n createUser = defaultCreateUser,\n requestInfoToLog,\n augmentContext,\n}: CreateSubscriptionContextConfig<TContext>): CreateSubscriptionContext<TContext> => {\n // the function that creates the GraphQL context\n return async (input: SubscriptionContextInput) => {\n const { connectRequest: req, claims } = input\n\n const xForwardedFor = req.headers['x-forwarded-for']\n const host = Array.isArray(xForwardedFor) ? xForwardedFor[0] : xForwardedFor ?? req.headers.host\n\n // build request info from the connect request and socket\n const requestInfo: RequestInfo = {\n requestId: req.headers['x-request-id']?.toString() ?? randomUUID(),\n protocol: 'ws',\n host: host ?? '',\n method: req.method ?? '',\n url: req.url ?? '',\n origin: req.headers['origin'] ?? '',\n referer: req.headers.referer?.toString() ?? '',\n arrLogId: req.headers['x-arr-log-id']?.toString() ?? undefined,\n clientIp: req.headers['x-forwarded-for']?.toString() ?? req.socket.remoteAddress,\n correlationId: req.headers['x-correlation-id']?.toString() ?? undefined,\n ...augmentRequestInfo?.(input),\n }\n\n // create request logger\n let logger: Logger\n if (typeof requestLogger === 'function') {\n // build request logger metadata\n const requestLoggerMetadata: Record<string, unknown> = {}\n // add request info to log\n if (requestInfoToLog?.length) requestLoggerMetadata.request = pick(requestInfo, requestInfoToLog)\n // add user claims to log\n if (claims && claimsToLog?.length) requestLoggerMetadata.user = pick(claims, claimsToLog)\n // build the request logger\n logger = requestLogger(requestLoggerMetadata)\n } else logger = requestLogger\n\n const graphqlContext: GraphQLContext = {\n requestInfo,\n logger,\n user: await createUser(input),\n started: Date.now(),\n }\n\n const augmentedGraphQLContext = augmentContext\n ? { ...graphqlContext, ...(await augmentContext(graphqlContext as TContext)) }\n : graphqlContext\n\n return augmentedGraphQLContext as TContext\n }\n}\n\nconst defaultCreateUser: CreateSubscriptionUser<User | undefined> = ({ claims, connectionParams }) => {\n if (!claims) return Promise.resolve(undefined)\n const accessToken = extractTokenFromConnectionParams(connectionParams)\n return Promise.resolve(new User(claims, accessToken ?? ''))\n}\n"],"names":["randomUUID","pick","extractTokenFromConnectionParams","User"],"mappings":";;;;;;;MA2Ba,gCAAgC,GAAG,CAAmD,EACjG,aAAa,EACb,kBAAkB,EAClB,WAAW,EACX,UAAU,GAAG,iBAAiB,EAC9B,gBAAgB,EAChB,cAAc,GAC4B,KAAyC;;AAEnF,IAAA,OAAO,OAAO,KAA+B,KAAI;QAC/C,MAAM,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,KAAK,CAAA;QAE7C,MAAM,aAAa,GAAG,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAA;QACpD,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,GAAG,aAAa,IAAI,GAAG,CAAC,OAAO,CAAC,IAAI,CAAA;;AAGhG,QAA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M,MAAM,GAAG,aAAa,CAAA;AAE7B,QAAA,MAAM,cAAc,GAAmB;YACrC,WAAW;YACX,MAAM;AACN,YAAA,IAAI,EAAE,MAAM,UAAU,CAAC,KAAK,CAAC;AAC7B,YAAA,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE;SACpB,CAAA;QAED,MAAM,uBAAuB,GAAG,cAAc;AAC5C,cAAE,EAAE,GAAG,cAAc,EAAE,IAAI,MAAM,cAAc,CAAC,cAA0B,CAAC,GAAG;cAC5E,cAAc,CAAA;AAElB,QAAA,OAAO,uBAAmC,CAAA;AAC5C,KAAC,CAAA;AACH,EAAC;AAED,MAAM,iBAAiB,GAA6C,CAAC,EAAE,MAAM,EAAE,gBAAgB,EAAE,KAAI;AACnG,IAAA,IAAI,CAAC,MAAM;AAAE,QAAA,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;AAC9C,IAAA,MAAM,WAAW,GAAGC,sCAAgC,CAAC,gBAAgB,CAAC,CAAA;AACtE,IAAA,OAAO,OAAO,CAAC,OAAO,CAAC,IAAIC,SAAI,CAAC,MAAM,EAAE,WAAW,IAAI,EAAE,CAAC,CAAC,CAAA;AAC7D,CAAC;;;;"}
@@ -59,3 +59,4 @@ const defaultCreateUser = ({ claims, connectionParams }) => {
59
59
  };
60
60
 
61
61
  export { createSubscriptionContextFactory };
62
+ //# sourceMappingURL=context.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.mjs","sources":["../../src/subscriptions/context.ts"],"sourcesContent":["import type { Logger } from '@makerx/node-common'\nimport { randomUUID } from 'crypto'\nimport type { IncomingMessage } from 'http'\nimport { pick } from 'lodash'\nimport { User } from '../User'\nimport type { CreateRequestLogger, GraphQLContext, JwtPayload, RequestInfo } from '../context'\nimport { extractTokenFromConnectionParams } from './utils'\n\nexport interface SubscriptionContextInput {\n connectRequest: IncomingMessage\n connectionParams?: Readonly<Record<string, unknown>>\n claims?: JwtPayload\n}\n\nexport type CreateSubscriptionUser<T = User | undefined> = (input: SubscriptionContextInput) => Promise<T>\nexport type CreateSubscriptionContext<TContext = GraphQLContext> = (input: SubscriptionContextInput) => Promise<TContext>\nexport type AugmentSubscriptionRequestInfo = (input: SubscriptionContextInput) => Record<string, unknown>\n\nexport interface CreateSubscriptionContextConfig<TContext = GraphQLContext> {\n requestLogger: CreateRequestLogger | Logger\n augmentRequestInfo?: AugmentSubscriptionRequestInfo\n claimsToLog?: string[]\n createUser?: CreateSubscriptionUser\n requestInfoToLog?: Array<keyof RequestInfo>\n augmentContext?: (context: TContext) => Record<string, unknown> | Promise<Record<string, unknown>>\n}\n\nexport const createSubscriptionContextFactory = <TContext extends GraphQLContext = GraphQLContext>({\n requestLogger,\n augmentRequestInfo,\n claimsToLog,\n createUser = defaultCreateUser,\n requestInfoToLog,\n augmentContext,\n}: CreateSubscriptionContextConfig<TContext>): CreateSubscriptionContext<TContext> => {\n // the function that creates the GraphQL context\n return async (input: SubscriptionContextInput) => {\n const { connectRequest: req, claims } = input\n\n const xForwardedFor = req.headers['x-forwarded-for']\n const host = Array.isArray(xForwardedFor) ? xForwardedFor[0] : xForwardedFor ?? req.headers.host\n\n // build request info from the connect request and socket\n const requestInfo: RequestInfo = {\n requestId: req.headers['x-request-id']?.toString() ?? randomUUID(),\n protocol: 'ws',\n host: host ?? '',\n method: req.method ?? '',\n url: req.url ?? '',\n origin: req.headers['origin'] ?? '',\n referer: req.headers.referer?.toString() ?? '',\n arrLogId: req.headers['x-arr-log-id']?.toString() ?? undefined,\n clientIp: req.headers['x-forwarded-for']?.toString() ?? req.socket.remoteAddress,\n correlationId: req.headers['x-correlation-id']?.toString() ?? undefined,\n ...augmentRequestInfo?.(input),\n }\n\n // create request logger\n let logger: Logger\n if (typeof requestLogger === 'function') {\n // build request logger metadata\n const requestLoggerMetadata: Record<string, unknown> = {}\n // add request info to log\n if (requestInfoToLog?.length) requestLoggerMetadata.request = pick(requestInfo, requestInfoToLog)\n // add user claims to log\n if (claims && claimsToLog?.length) requestLoggerMetadata.user = pick(claims, claimsToLog)\n // build the request logger\n logger = requestLogger(requestLoggerMetadata)\n } else logger = requestLogger\n\n const graphqlContext: GraphQLContext = {\n requestInfo,\n logger,\n user: await createUser(input),\n started: Date.now(),\n }\n\n const augmentedGraphQLContext = augmentContext\n ? { ...graphqlContext, ...(await augmentContext(graphqlContext as TContext)) }\n : graphqlContext\n\n return augmentedGraphQLContext as TContext\n }\n}\n\nconst defaultCreateUser: CreateSubscriptionUser<User | undefined> = ({ claims, connectionParams }) => {\n if (!claims) return Promise.resolve(undefined)\n const accessToken = extractTokenFromConnectionParams(connectionParams)\n return Promise.resolve(new User(claims, accessToken ?? ''))\n}\n"],"names":[],"mappings":";;;;;MA2Ba,gCAAgC,GAAG,CAAmD,EACjG,aAAa,EACb,kBAAkB,EAClB,WAAW,EACX,UAAU,GAAG,iBAAiB,EAC9B,gBAAgB,EAChB,cAAc,GAC4B,KAAyC;;AAEnF,IAAA,OAAO,OAAO,KAA+B,KAAI;QAC/C,MAAM,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,KAAK,CAAA;QAE7C,MAAM,aAAa,GAAG,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAA;QACpD,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,GAAG,aAAa,IAAI,GAAG,CAAC,OAAO,CAAC,IAAI,CAAA;;AAGhG,QAAA,MAAM,WAAW,GAAgB;AAC/B,YAAA,SAAS,EAAE,GAAG,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,QAAQ,EAAE,IAAI,UAAU,EAAE;AAClE,YAAA,QAAQ,EAAE,IAAI;YACd,IAAI,EAAE,IAAI,IAAI,EAAE;AAChB,YAAA,MAAM,EAAE,GAAG,CAAC,MAAM,IAAI,EAAE;AACxB,YAAA,GAAG,EAAE,GAAG,CAAC,GAAG,IAAI,EAAE;YAClB,MAAM,EAAE,GAA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CAAA;AAElB,QAAA,OAAO,uBAAmC,CAAA;AAC5C,KAAC,CAAA;AACH,EAAC;AAED,MAAM,iBAAiB,GAA6C,CAAC,EAAE,MAAM,EAAE,gBAAgB,EAAE,KAAI;AACnG,IAAA,IAAI,CAAC,MAAM;AAAE,QAAA,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;AAC9C,IAAA,MAAM,WAAW,GAAG,gCAAgC,CAAC,gBAAgB,CAAC,CAAA;AACtE,IAAA,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE,WAAW,IAAI,EAAE,CAAC,CAAC,CAAA;AAC7D,CAAC;;;;"}
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+
3
+ var context = require('./context.js');
4
+ var server = require('./server.js');
5
+ var utils = require('./utils.js');
6
+
7
+
8
+
9
+ exports.createSubscriptionContextFactory = context.createSubscriptionContextFactory;
10
+ exports.useSubscriptionsServer = server.useSubscriptionsServer;
11
+ exports.extractTokenFromConnectionParams = utils.extractTokenFromConnectionParams;
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;"}
@@ -0,0 +1,4 @@
1
+ export { createSubscriptionContextFactory } from './context.mjs';
2
+ export { useSubscriptionsServer } from './server.mjs';
3
+ export { extractTokenFromConnectionParams } from './utils.mjs';
4
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}
@@ -4,8 +4,8 @@ var graphqlWs = require('graphql-ws');
4
4
  var ws$1 = require('graphql-ws/lib/use/ws');
5
5
  var lodash = require('lodash');
6
6
  var ws = require('ws');
7
- var logging = require('../logging.cjs');
8
- var utils = require('./utils.cjs');
7
+ var logging = require('../logging.js');
8
+ var utils = require('./utils.js');
9
9
 
10
10
  function useSubscriptionsServer({ schema, httpServer, createSubscriptionContext, logger, operationLogLevel = 'info', path = '/graphql', verifyToken, requireAuth, jwtClaimsToLog = ['oid', 'iss'], }) {
11
11
  if (requireAuth && !verifyToken)
@@ -86,3 +86,4 @@ function useSubscriptionsServer({ schema, httpServer, createSubscriptionContext,
86
86
  }
87
87
 
88
88
  exports.useSubscriptionsServer = useSubscriptionsServer;
89
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","sources":["../../src/subscriptions/server.ts"],"sourcesContent":["import type { Logger } from '@makerx/node-common'\nimport type { GraphQLSchema } from 'graphql'\nimport { CloseCode } from 'graphql-ws'\nimport { useServer } from 'graphql-ws/lib/use/ws'\nimport type { Server } from 'http'\nimport { pick } from 'lodash'\nimport { WebSocketServer } from 'ws'\nimport type { JwtPayload } from '../context'\nimport { logSubscriptionOperation } from '../logging'\nimport type { CreateSubscriptionContext } from './context'\nimport { extractTokenFromConnectionParams, getHost } from './utils'\n\nexport function useSubscriptionsServer<TLogger extends Logger = Logger>({\n schema,\n httpServer,\n createSubscriptionContext,\n logger,\n operationLogLevel = 'info',\n path = '/graphql',\n verifyToken,\n requireAuth,\n jwtClaimsToLog = ['oid', 'iss'],\n}: {\n schema: GraphQLSchema\n httpServer: Server\n createSubscriptionContext: CreateSubscriptionContext\n logger: TLogger\n operationLogLevel?: keyof TLogger\n path?: string\n verifyToken?: (host: string, token: string) => Promise<JwtPayload>\n requireAuth?: boolean\n jwtClaimsToLog?: string[]\n}) {\n if (requireAuth && !verifyToken) throw new Error('verifyToken must be supplied when requireAuth is true')\n\n const wsServer = new WebSocketServer({\n server: httpServer,\n path,\n })\n\n return useServer(\n {\n schema,\n onError(_ctx, message, errors) {\n logger.error('GraphQL subscriptions server error', { message, errors })\n },\n onConnect: async (ctx) => {\n const connectionEstablished = 'Subscription connection established'\n if (!verifyToken) {\n logger.info(connectionEstablished)\n return true\n }\n\n const token = extractTokenFromConnectionParams(ctx.connectionParams)\n if (!token) {\n if (requireAuth) {\n logger.error('No authorization parameter was supplied via websocket connection params')\n return false\n }\n logger.info(connectionEstablished)\n return true\n }\n\n try {\n const claims = await verifyToken(getHost(ctx.extra.request), token)\n ctx.extra.claims = claims as unknown as undefined\n logger.info(connectionEstablished, {\n claims: pick(claims, jwtClaimsToLog),\n })\n return true\n } catch (error) {\n logger.error('Failed to verify subscription connection auth token', { error })\n return false\n }\n },\n onSubscribe: async (ctx) => {\n if (!verifyToken) return\n const token = extractTokenFromConnectionParams(ctx.connectionParams)\n if (!token) {\n if (requireAuth) {\n logger.error('No authorization parameter was supplied via websocket connection params')\n ctx.extra.socket.close(CloseCode.Forbidden, 'Forbidden')\n }\n return\n }\n try {\n await verifyToken(getHost(ctx.extra.request), token)\n } catch (error) {\n logger.warn('Subscription connection auth token is no longer valid', { claims: pick(ctx.extra.claims, jwtClaimsToLog), error })\n ctx.extra.socket.close(CloseCode.Forbidden, 'Forbidden')\n }\n },\n onDisconnect({ extra: { claims } }) {\n logger.info('Subscription connection disconnected', { claims: pick(claims, jwtClaimsToLog) })\n },\n context: async (ctx) => {\n return createSubscriptionContext({\n connectRequest: ctx.extra.request,\n connectionParams: ctx.connectionParams,\n claims: ctx.extra.claims as JwtPayload | undefined,\n })\n },\n onOperation(_ctx, _message, args) {\n logSubscriptionOperation({ args, logLevel: operationLogLevel })\n },\n onNext(_ctx, _message, args, { data, ...result }) {\n logSubscriptionOperation({ args, logLevel: operationLogLevel, result })\n },\n },\n wsServer,\n )\n}\n"],"names":["WebSocketServer","useServer","extractTokenFromConnectionParams","getHost","pick","CloseCode","logSubscriptionOperation"],"mappings":";;;;;;;;;AAYgB,SAAA,sBAAsB,CAAkC,EACtE,MAAM,EACN,UAAU,EACV,yBAAyB,EACzB,MAAM,EACN,iBAAiB,GAAG,MAAM,EAC1B,IAAI,GAAG,UAAU,EACjB,WAAW,EACX,WAAW,EACX,cAAc,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,GAWhC,EAAA;IACC,IAAI,WAAW,IAA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GAAG,KAAI;AACrB,YAAA,OAAO,yBAAyB,CAAC;AAC/B,gBAAA,cAAc,EAAE,GAAG,CAAC,KAAK,CAAC,OAAO;gBACjC,gBAAgB,EAAE,GAAG,CAAC,gBAAgB;AACtC,gBAAA,MAAM,EAAE,GAAG,CAAC,KAAK,CAAC,MAAgC;AACnD,aAAA,CAAC,CAAA;SACH;AACD,QAAA,WAAW,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAA;YAC9BE,gCAAwB,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,iBAAiB,EAAE,CAAC,CAAA;SAChE;AACD,QAAA,MAAM,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,EAAA;YAC9CA,gCAAwB,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,EAAE,CAAC,CAAA;SACxE;KACF,EACD,QAAQ,CACT,CAAA;AACH;;;;"}
@@ -84,3 +84,4 @@ function useSubscriptionsServer({ schema, httpServer, createSubscriptionContext,
84
84
  }
85
85
 
86
86
  export { useSubscriptionsServer };
87
+ //# sourceMappingURL=server.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.mjs","sources":["../../src/subscriptions/server.ts"],"sourcesContent":["import type { Logger } from '@makerx/node-common'\nimport type { GraphQLSchema } from 'graphql'\nimport { CloseCode } from 'graphql-ws'\nimport { useServer } from 'graphql-ws/lib/use/ws'\nimport type { Server } from 'http'\nimport { pick } from 'lodash'\nimport { WebSocketServer } from 'ws'\nimport type { JwtPayload } from '../context'\nimport { logSubscriptionOperation } from '../logging'\nimport type { CreateSubscriptionContext } from './context'\nimport { extractTokenFromConnectionParams, getHost } from './utils'\n\nexport function useSubscriptionsServer<TLogger extends Logger = Logger>({\n schema,\n httpServer,\n createSubscriptionContext,\n logger,\n operationLogLevel = 'info',\n path = '/graphql',\n verifyToken,\n requireAuth,\n jwtClaimsToLog = ['oid', 'iss'],\n}: {\n schema: GraphQLSchema\n httpServer: Server\n createSubscriptionContext: CreateSubscriptionContext\n logger: TLogger\n operationLogLevel?: keyof TLogger\n path?: string\n verifyToken?: (host: string, token: string) => Promise<JwtPayload>\n requireAuth?: boolean\n jwtClaimsToLog?: string[]\n}) {\n if (requireAuth && !verifyToken) throw new Error('verifyToken must be supplied when requireAuth is true')\n\n const wsServer = new WebSocketServer({\n server: httpServer,\n path,\n })\n\n return useServer(\n {\n schema,\n onError(_ctx, message, errors) {\n logger.error('GraphQL subscriptions server error', { message, errors })\n },\n onConnect: async (ctx) => {\n const connectionEstablished = 'Subscription connection established'\n if (!verifyToken) {\n logger.info(connectionEstablished)\n return true\n }\n\n const token = extractTokenFromConnectionParams(ctx.connectionParams)\n if (!token) {\n if (requireAuth) {\n logger.error('No authorization parameter was supplied via websocket connection params')\n return false\n }\n logger.info(connectionEstablished)\n return true\n }\n\n try {\n const claims = await verifyToken(getHost(ctx.extra.request), token)\n ctx.extra.claims = claims as unknown as undefined\n logger.info(connectionEstablished, {\n claims: pick(claims, jwtClaimsToLog),\n })\n return true\n } catch (error) {\n logger.error('Failed to verify subscription connection auth token', { error })\n return false\n }\n },\n onSubscribe: async (ctx) => {\n if (!verifyToken) return\n const token = extractTokenFromConnectionParams(ctx.connectionParams)\n if (!token) {\n if (requireAuth) {\n logger.error('No authorization parameter was supplied via websocket connection params')\n ctx.extra.socket.close(CloseCode.Forbidden, 'Forbidden')\n }\n return\n }\n try {\n await verifyToken(getHost(ctx.extra.request), token)\n } catch (error) {\n logger.warn('Subscription connection auth token is no longer valid', { claims: pick(ctx.extra.claims, jwtClaimsToLog), error })\n ctx.extra.socket.close(CloseCode.Forbidden, 'Forbidden')\n }\n },\n onDisconnect({ extra: { claims } }) {\n logger.info('Subscription connection disconnected', { claims: pick(claims, jwtClaimsToLog) })\n },\n context: async (ctx) => {\n return createSubscriptionContext({\n connectRequest: ctx.extra.request,\n connectionParams: ctx.connectionParams,\n claims: ctx.extra.claims as JwtPayload | undefined,\n })\n },\n onOperation(_ctx, _message, args) {\n logSubscriptionOperation({ args, logLevel: operationLogLevel })\n },\n onNext(_ctx, _message, args, { data, ...result }) {\n logSubscriptionOperation({ args, logLevel: operationLogLevel, result })\n },\n },\n wsServer,\n )\n}\n"],"names":[],"mappings":";;;;;;;AAYgB,SAAA,sBAAsB,CAAkC,EACtE,MAAM,EACN,UAAU,EACV,yBAAyB,EACzB,MAAM,EACN,iBAAiB,GAAG,MAAM,EAC1B,IAAI,GAAG,UAAU,EACjB,WAAW,EACX,WAAW,EACX,cAAc,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,GAWhC,EAAA;IACC,IAAI,WAAW,IAAI,CAAC,WAAW;AAAE,QAAA,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAA;AAEzG,IAAA,MAAM,QAAQ,GAAG,IAAI,eAAe,CAAC;AACnC,QAAA,MAAM,EAAE,UAAU;QAClB,IAAI;AACL,KAAA,CAAC,CAAA;AAEF,IAAA,OAAO,SAAS,CACd;QACE,MAAM;AACN,QAAA,OAAO,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,EAAA;YAC3B,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAA;SACxE;AACD,QAAA,SAAS,EAAE,OAAO,GAAG,KAAI;YACvB,MAAM,qBAAqB,GAAG,qCAAqC,CAAA;YACnE,IAAI,CAAC,WAAW,EAAE;AAChB,gBAAA,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAA;AAClC,gBAAA,OAAO,IAAI,CAAA;aACZ;YAED,MAAM,KAAK,GAAG,gCAAgC,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAA;YACpE,IAAI,CAAC,KAAK,EAAE;gBACV,IAAI,WAAW,EAAE;AACf,oBAAA,MAAM,CAAC,KAAK,CAAC,yEAAyE,CAAC,CAAA;AACvF,oBAAA,OAAO,KAAK,CAAA;iBAC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G,CAAC,KAAK,CAAC,MAAM,EAAE,cAAc,CAAC,EAAE,KAAK,EAAE,CAAC,CAAA;AAC/H,gBAAA,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,SAAS,EAAE,WAAW,CAAC,CAAA;aACzD;SACF;AACD,QAAA,YAAY,CAAC,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,EAAA;AAChC,YAAA,MAAM,CAAC,IAAI,CAAC,sCAAsC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,cAAc,CAAC,EAAE,CAAC,CAAA;SAC9F;AACD,QAAA,OAAO,EAAE,OAAO,GAAG,KAAI;AACrB,YAAA,OAAO,yBAAyB,CAAC;AAC/B,gBAAA,cAAc,EAAE,GAAG,CAAC,KAAK,CAAC,OAAO;gBACjC,gBAAgB,EAAE,GAAG,CAAC,gBAAgB;AACtC,gBAAA,MAAM,EAAE,GAAG,CAAC,KAAK,CAAC,MAAgC;AACnD,aAAA,CAAC,CAAA;SACH;AACD,QAAA,WAAW,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAA;YAC9B,wBAAwB,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,iBAAiB,EAAE,CAAC,CAAA;SAChE;AACD,QAAA,MAAM,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,EAAA;YAC9C,wBAAwB,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,EAAE,CAAC,CAAA;SACxE;KACF,EACD,QAAQ,CACT,CAAA;AACH;;;;"}
@@ -21,3 +21,4 @@ function getHost(request) {
21
21
 
22
22
  exports.extractTokenFromConnectionParams = extractTokenFromConnectionParams;
23
23
  exports.getHost = getHost;
24
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sources":["../../src/subscriptions/utils.ts"],"sourcesContent":["import type { IncomingMessage } from 'http'\n\n/**\n * Extracts a token from a connection parameter named `authorization` or `Authorization`.\n * The expected format of the parameter value is: Bearer <token>, consistent with an HTTP Authorization header.\n * Apollo Sandbox sets an `Authorization` connection parameter when you specify an HTTP Authorization header via the UI.\n * @param connectionParams\n * @returns\n */\nexport function extractTokenFromConnectionParams(connectionParams?: Readonly<Record<string, unknown>>) {\n const bearerTokenValue = (connectionParams?.authorization ?? connectionParams?.Authorization) as string | undefined\n if (!bearerTokenValue?.startsWith('Bearer ')) return undefined\n return bearerTokenValue.substring(7)\n}\n\nexport function getHost(request: IncomingMessage) {\n const proxyHostHeader = request.headers['x-forwarded-host']\n const host = Array.isArray(proxyHostHeader) ? proxyHostHeader[0] ?? undefined : proxyHostHeader ?? request.headers.host ?? undefined\n return host ?? 'subscriptions'\n}\n"],"names":[],"mappings":";;AAEA;;;;;;AAMG;AACG,SAAU,gCAAgC,CAAC,gBAAoD,EAAA;IACnG,MAAM,gBAAgB,IAAI,gBAAgB,EAAE,aAAa,IAAI,gBAAgB,EAAE,aAAa,CAAuB,CAAA;AACnH,IAAA,IAAI,CAAC,gBAAgB,EAAE,UAAU,CAAC,SAAS,CAAC;AAAE,QAAA,OAAO,SAAS,CAAA;AAC9D,IAAA,OAAO,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAA;AACtC,CAAC;AAEK,SAAU,OAAO,CAAC,OAAwB,EAAA;IAC9C,MAAM,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAA;AAC3D,IAAA,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,IAAI,SAAS,GAAG,eAAe,IAAI,OAAO,CAAC,OAAO,CAAC,IAAI,IAAI,SAAS,CAAA;IACpI,OAAO,IAAI,IAAI,eAAe,CAAA;AAChC;;;;;"}
@@ -18,3 +18,4 @@ function getHost(request) {
18
18
  }
19
19
 
20
20
  export { extractTokenFromConnectionParams, getHost };
21
+ //# sourceMappingURL=utils.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.mjs","sources":["../../src/subscriptions/utils.ts"],"sourcesContent":["import type { IncomingMessage } from 'http'\n\n/**\n * Extracts a token from a connection parameter named `authorization` or `Authorization`.\n * The expected format of the parameter value is: Bearer <token>, consistent with an HTTP Authorization header.\n * Apollo Sandbox sets an `Authorization` connection parameter when you specify an HTTP Authorization header via the UI.\n * @param connectionParams\n * @returns\n */\nexport function extractTokenFromConnectionParams(connectionParams?: Readonly<Record<string, unknown>>) {\n const bearerTokenValue = (connectionParams?.authorization ?? connectionParams?.Authorization) as string | undefined\n if (!bearerTokenValue?.startsWith('Bearer ')) return undefined\n return bearerTokenValue.substring(7)\n}\n\nexport function getHost(request: IncomingMessage) {\n const proxyHostHeader = request.headers['x-forwarded-host']\n const host = Array.isArray(proxyHostHeader) ? proxyHostHeader[0] ?? undefined : proxyHostHeader ?? request.headers.host ?? undefined\n return host ?? 'subscriptions'\n}\n"],"names":[],"mappings":"AAEA;;;;;;AAMG;AACG,SAAU,gCAAgC,CAAC,gBAAoD,EAAA;IACnG,MAAM,gBAAgB,IAAI,gBAAgB,EAAE,aAAa,IAAI,gBAAgB,EAAE,aAAa,CAAuB,CAAA;AACnH,IAAA,IAAI,CAAC,gBAAgB,EAAE,UAAU,CAAC,SAAS,CAAC;AAAE,QAAA,OAAO,SAAS,CAAA;AAC9D,IAAA,OAAO,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAA;AACtC,CAAC;AAEK,SAAU,OAAO,CAAC,OAAwB,EAAA;IAC9C,MAAM,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAA;AAC3D,IAAA,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,IAAI,SAAS,GAAG,eAAe,IAAI,OAAO,CAAC,OAAO,CAAC,IAAI,IAAI,SAAS,CAAA;IACpI,OAAO,IAAI,IAAI,eAAe,CAAA;AAChC;;;;"}
package/testing.js ADDED
@@ -0,0 +1,68 @@
1
+ 'use strict';
2
+
3
+ var core = require('@apollo/client/core');
4
+ var context = require('@apollo/client/link/context');
5
+ var nodeCommon = require('@makerx/node-common');
6
+
7
+ const bearerTokenLink = (accessToken) => context.setContext((_, { headers }) => {
8
+ if (accessToken)
9
+ return {
10
+ headers: {
11
+ ...headers,
12
+ authorization: `Bearer ${accessToken}`,
13
+ },
14
+ };
15
+ return {
16
+ headers,
17
+ };
18
+ });
19
+ const clientCredentialsLink = (clientCredentialsConfig) => {
20
+ let promise;
21
+ return context.setContext(async () => {
22
+ if (!promise)
23
+ promise = nodeCommon.getClientCredentialsToken(clientCredentialsConfig);
24
+ let tokenResponse = await promise;
25
+ if (tokenResponse.isExpired) {
26
+ promise = nodeCommon.getClientCredentialsToken(clientCredentialsConfig);
27
+ tokenResponse = await promise;
28
+ }
29
+ return {
30
+ headers: {
31
+ authorization: `Bearer ${tokenResponse.access_token}`,
32
+ },
33
+ };
34
+ });
35
+ };
36
+ const httpLink = (url) => core.createHttpLink({
37
+ uri: url,
38
+ });
39
+ const createTestClient = (url, accessToken, options) => new core.ApolloClient({
40
+ link: core.from([bearerTokenLink(accessToken), httpLink(url)]),
41
+ cache: new core.InMemoryCache(),
42
+ defaultOptions: {
43
+ query: {
44
+ errorPolicy: 'all',
45
+ },
46
+ },
47
+ ...options,
48
+ });
49
+ const createTestClientWithClientCredentials = (url, clientCredentialsConfig, options) => new core.ApolloClient({
50
+ link: core.from([clientCredentialsLink(clientCredentialsConfig), httpLink(url)]),
51
+ cache: new core.InMemoryCache(),
52
+ defaultOptions: {
53
+ query: {
54
+ errorPolicy: 'all',
55
+ },
56
+ },
57
+ ...options,
58
+ });
59
+
60
+ exports.createTestClient = createTestClient;
61
+ exports.createTestClientWithClientCredentials = createTestClientWithClientCredentials;
62
+ Object.keys(core).forEach(function (k) {
63
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
64
+ enumerable: true,
65
+ get: function () { return core[k]; }
66
+ });
67
+ });
68
+ //# sourceMappingURL=testing.js.map
package/testing.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.js","sources":["../src/testing.ts"],"sourcesContent":["import type { NormalizedCacheObject } from '@apollo/client/core'\nimport { ApolloClient, createHttpLink, from, InMemoryCache } from '@apollo/client/core'\nimport type { ApolloClientOptions } from '@apollo/client/core/ApolloClient'\nimport { setContext } from '@apollo/client/link/context'\nimport type { AccessTokenResponse, ClientCredentialsConfig } from '@makerx/node-common'\nimport { getClientCredentialsToken } from '@makerx/node-common'\n\nexport * from '@apollo/client/core'\n\nconst bearerTokenLink = (accessToken?: string) =>\n setContext((_, { headers }) => {\n if (accessToken)\n return {\n headers: {\n ...headers,\n authorization: `Bearer ${accessToken}`,\n },\n }\n return {\n headers,\n }\n })\n\nconst clientCredentialsLink = (clientCredentialsConfig: ClientCredentialsConfig) => {\n let promise: Promise<AccessTokenResponse> | undefined\n return setContext(async () => {\n if (!promise) promise = getClientCredentialsToken(clientCredentialsConfig)\n let tokenResponse = await promise\n if (tokenResponse.isExpired) {\n promise = getClientCredentialsToken(clientCredentialsConfig)\n tokenResponse = await promise\n }\n return {\n headers: {\n authorization: `Bearer ${tokenResponse.access_token}`,\n },\n }\n })\n}\n\nconst httpLink = (url: string) =>\n createHttpLink({\n uri: url,\n })\n\nexport const createTestClient = (\n url: string,\n accessToken?: string,\n options?: Partial<ApolloClientOptions<NormalizedCacheObject>>,\n): ApolloClient<NormalizedCacheObject> =>\n new ApolloClient({\n link: from([bearerTokenLink(accessToken), httpLink(url)]),\n cache: new InMemoryCache(),\n defaultOptions: {\n query: {\n errorPolicy: 'all',\n },\n },\n ...options,\n })\n\nexport const createTestClientWithClientCredentials = (\n url: string,\n clientCredentialsConfig: ClientCredentialsConfig,\n options?: Partial<ApolloClientOptions<NormalizedCacheObject>>,\n): ApolloClient<NormalizedCacheObject> =>\n new ApolloClient({\n link: from([clientCredentialsLink(clientCredentialsConfig), httpLink(url)]),\n cache: new InMemoryCache(),\n defaultOptions: {\n query: {\n errorPolicy: 'all',\n },\n },\n ...options,\n })\n"],"names":["setContext","getClientCredentialsToken","createHttpLink","ApolloClient","from","InMemoryCache"],"mappings":";;;;;;AASA,MAAM,eAAe,GAAG,CAAC,WAAoB,KAC3CA,kBAAU,CAAC,CAAC,CAAC,EAAE,EAAE,OAAO,EAAE,KAAI;AAC5B,IAAA,IAAI,WAAW;QACb,OAAO;AACL,YAAA,OAAO,EAAE;AACP,gBAAA,GAAG,OAAO;gBACV,aAAa,EAAE,CAAU,OAAA,EAAA,WAAW,CAAE,CAAA;AACvC,aAAA;SACF,CAAA;IACH,OAAO;QACL,OAAO;KACR,CAAA;AACH,CAAC,CAAC,CAAA;AAEJ,MAAM,qBAAqB,GAAG,CAAC,uBAAgD,KAAI;AACjF,IAAA,IAAI,OAAiD,CAAA;AACrD,IAAA,OAAOA,kBAAU,CAAC,YAAW;AAC3B,QAAA,IAAI,CAAC,OAAO;AAAE,YAAA,OAAO,GAAGC,oCAAyB,CAAC,uBAAuB,CAAC,CAAA;AAC1E,QAAA,IAAI,aAAa,GAAG,MAAM,OAAO,CAAA;AACjC,QAAA,IAAI,aAAa,CAAC,SAAS,EAAE;AAC3B,YAAA,OAAO,GAAGA,oCAAyB,CAAC,uBAAuB,CAAC,CAAA;YAC5D,aAAa,GAAG,MAAM,OAAO,CAAA;SAC9B;QACD,OAAO;AACL,YAAA,OAAO,EAAE;AACP,gBAAA,aAAa,EAAE,CAAA,OAAA,EAAU,aAAa,CAAC,YAAY,CAAE,CAAA;AACtD,aAAA;SACF,CAAA;AACH,KAAC,CAAC,CAAA;AACJ,CAAC,CAAA;AAED,MAAM,QAAQ,GAAG,CAAC,GAAW,KAC3BC,mBAAc,CAAC;AACb,IAAA,GAAG,EAAE,GAAG;AACT,CAAA,CAAC,CAAA;AAEG,MAAM,gBAAgB,GAAG,CAC9B,GAAW,EACX,WAAoB,EACpB,OAA6D,KAE7D,IAAIC,iBAAY,CAAC;AACf,IAAA,IAAI,EAAEC,SAAI,CAAC,CAAC,eAAe,CAAC,WAAW,CAAC,EAAE,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;IACzD,KAAK,EAAE,IAAIC,kBAAa,EAAE;AAC1B,IAAA,cAAc,EAAE;AACd,QAAA,KAAK,EAAE;AACL,YAAA,WAAW,EAAE,KAAK;AACnB,SAAA;AACF,KAAA;AACD,IAAA,GAAG,OAAO;AACX,CAAA,EAAC;AAEG,MAAM,qCAAqC,GAAG,CACnD,GAAW,EACX,uBAAgD,EAChD,OAA6D,KAE7D,IAAIF,iBAAY,CAAC;AACf,IAAA,IAAI,EAAEC,SAAI,CAAC,CAAC,qBAAqB,CAAC,uBAAuB,CAAC,EAAE,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3E,KAAK,EAAE,IAAIC,kBAAa,EAAE;AAC1B,IAAA,cAAc,EAAE;AACd,QAAA,KAAK,EAAE;AACL,YAAA,WAAW,EAAE,KAAK;AACnB,SAAA;AACF,KAAA;AACD,IAAA,GAAG,OAAO;AACX,CAAA;;;;;;;;;;;"}
package/testing.mjs ADDED
@@ -0,0 +1,60 @@
1
+ import { ApolloClient, from, InMemoryCache, createHttpLink } from '@apollo/client/core';
2
+ export * from '@apollo/client/core';
3
+ import { setContext } from '@apollo/client/link/context';
4
+ import { getClientCredentialsToken } from '@makerx/node-common';
5
+
6
+ const bearerTokenLink = (accessToken) => setContext((_, { headers }) => {
7
+ if (accessToken)
8
+ return {
9
+ headers: {
10
+ ...headers,
11
+ authorization: `Bearer ${accessToken}`,
12
+ },
13
+ };
14
+ return {
15
+ headers,
16
+ };
17
+ });
18
+ const clientCredentialsLink = (clientCredentialsConfig) => {
19
+ let promise;
20
+ return setContext(async () => {
21
+ if (!promise)
22
+ promise = getClientCredentialsToken(clientCredentialsConfig);
23
+ let tokenResponse = await promise;
24
+ if (tokenResponse.isExpired) {
25
+ promise = getClientCredentialsToken(clientCredentialsConfig);
26
+ tokenResponse = await promise;
27
+ }
28
+ return {
29
+ headers: {
30
+ authorization: `Bearer ${tokenResponse.access_token}`,
31
+ },
32
+ };
33
+ });
34
+ };
35
+ const httpLink = (url) => createHttpLink({
36
+ uri: url,
37
+ });
38
+ const createTestClient = (url, accessToken, options) => new ApolloClient({
39
+ link: from([bearerTokenLink(accessToken), httpLink(url)]),
40
+ cache: new InMemoryCache(),
41
+ defaultOptions: {
42
+ query: {
43
+ errorPolicy: 'all',
44
+ },
45
+ },
46
+ ...options,
47
+ });
48
+ const createTestClientWithClientCredentials = (url, clientCredentialsConfig, options) => new ApolloClient({
49
+ link: from([clientCredentialsLink(clientCredentialsConfig), httpLink(url)]),
50
+ cache: new InMemoryCache(),
51
+ defaultOptions: {
52
+ query: {
53
+ errorPolicy: 'all',
54
+ },
55
+ },
56
+ ...options,
57
+ });
58
+
59
+ export { createTestClient, createTestClientWithClientCredentials };
60
+ //# sourceMappingURL=testing.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.mjs","sources":["../src/testing.ts"],"sourcesContent":["import type { NormalizedCacheObject } from '@apollo/client/core'\nimport { ApolloClient, createHttpLink, from, InMemoryCache } from '@apollo/client/core'\nimport type { ApolloClientOptions } from '@apollo/client/core/ApolloClient'\nimport { setContext } from '@apollo/client/link/context'\nimport type { AccessTokenResponse, ClientCredentialsConfig } from '@makerx/node-common'\nimport { getClientCredentialsToken } from '@makerx/node-common'\n\nexport * from '@apollo/client/core'\n\nconst bearerTokenLink = (accessToken?: string) =>\n setContext((_, { headers }) => {\n if (accessToken)\n return {\n headers: {\n ...headers,\n authorization: `Bearer ${accessToken}`,\n },\n }\n return {\n headers,\n }\n })\n\nconst clientCredentialsLink = (clientCredentialsConfig: ClientCredentialsConfig) => {\n let promise: Promise<AccessTokenResponse> | undefined\n return setContext(async () => {\n if (!promise) promise = getClientCredentialsToken(clientCredentialsConfig)\n let tokenResponse = await promise\n if (tokenResponse.isExpired) {\n promise = getClientCredentialsToken(clientCredentialsConfig)\n tokenResponse = await promise\n }\n return {\n headers: {\n authorization: `Bearer ${tokenResponse.access_token}`,\n },\n }\n })\n}\n\nconst httpLink = (url: string) =>\n createHttpLink({\n uri: url,\n })\n\nexport const createTestClient = (\n url: string,\n accessToken?: string,\n options?: Partial<ApolloClientOptions<NormalizedCacheObject>>,\n): ApolloClient<NormalizedCacheObject> =>\n new ApolloClient({\n link: from([bearerTokenLink(accessToken), httpLink(url)]),\n cache: new InMemoryCache(),\n defaultOptions: {\n query: {\n errorPolicy: 'all',\n },\n },\n ...options,\n })\n\nexport const createTestClientWithClientCredentials = (\n url: string,\n clientCredentialsConfig: ClientCredentialsConfig,\n options?: Partial<ApolloClientOptions<NormalizedCacheObject>>,\n): ApolloClient<NormalizedCacheObject> =>\n new ApolloClient({\n link: from([clientCredentialsLink(clientCredentialsConfig), httpLink(url)]),\n cache: new InMemoryCache(),\n defaultOptions: {\n query: {\n errorPolicy: 'all',\n },\n },\n ...options,\n })\n"],"names":[],"mappings":";;;;;AASA,MAAM,eAAe,GAAG,CAAC,WAAoB,KAC3C,UAAU,CAAC,CAAC,CAAC,EAAE,EAAE,OAAO,EAAE,KAAI;AAC5B,IAAA,IAAI,WAAW;QACb,OAAO;AACL,YAAA,OAAO,EAAE;AACP,gBAAA,GAAG,OAAO;gBACV,aAAa,EAAE,CAAU,OAAA,EAAA,WAAW,CAAE,CAAA;AACvC,aAAA;SACF,CAAA;IACH,OAAO;QACL,OAAO;KACR,CAAA;AACH,CAAC,CAAC,CAAA;AAEJ,MAAM,qBAAqB,GAAG,CAAC,uBAAgD,KAAI;AACjF,IAAA,IAAI,OAAiD,CAAA;AACrD,IAAA,OAAO,UAAU,CAAC,YAAW;AAC3B,QAAA,IAAI,CAAC,OAAO;AAAE,YAAA,OAAO,GAAG,yBAAyB,CAAC,uBAAuB,CAAC,CAAA;AAC1E,QAAA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@@ const isNotNil = (value) => !isNil(value);
7
7
  exports.isIntrospectionQuery = isIntrospectionQuery;
8
8
  exports.isNil = isNil;
9
9
  exports.isNotNil = isNotNil;
10
+ //# sourceMappingURL=utils.js.map
package/utils.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sources":["../src/utils.ts"],"sourcesContent":["export const isIntrospectionQuery = (query?: string) => query?.includes('__schema')\nexport const isNil = (value: unknown): value is null | undefined => value === null || value === undefined\nexport const isNotNil = <T>(value: T): value is Exclude<T, undefined | null> => !isNil(value)\n"],"names":[],"mappings":";;AAAO,MAAM,oBAAoB,GAAG,CAAC,KAAc,KAAK,KAAK,EAAE,QAAQ,CAAC,UAAU,EAAC;AACtE,MAAA,KAAK,GAAG,CAAC,KAAc,KAAgC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,UAAS;AAClG,MAAM,QAAQ,GAAG,CAAI,KAAQ,KAA4C,CAAC,KAAK,CAAC,KAAK;;;;;;"}
package/utils.mjs CHANGED
@@ -3,3 +3,4 @@ const isNil = (value) => value === null || value === undefined;
3
3
  const isNotNil = (value) => !isNil(value);
4
4
 
5
5
  export { isIntrospectionQuery, isNil, isNotNil };
6
+ //# sourceMappingURL=utils.mjs.map
package/utils.mjs.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.mjs","sources":["../src/utils.ts"],"sourcesContent":["export const isIntrospectionQuery = (query?: string) => query?.includes('__schema')\nexport const isNil = (value: unknown): value is null | undefined => value === null || value === undefined\nexport const isNotNil = <T>(value: T): value is Exclude<T, undefined | null> => !isNil(value)\n"],"names":[],"mappings":"AAAO,MAAM,oBAAoB,GAAG,CAAC,KAAc,KAAK,KAAK,EAAE,QAAQ,CAAC,UAAU,EAAC;AACtE,MAAA,KAAK,GAAG,CAAC,KAAc,KAAgC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,UAAS;AAClG,MAAM,QAAQ,GAAG,CAAI,KAAQ,KAA4C,CAAC,KAAK,CAAC,KAAK;;;;"}