@gravity-ui/gateway 4.6.0 → 4.7.1-alpha.0

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 (95) hide show
  1. package/README.md +179 -3
  2. package/{build → dist/commonjs}/components/grpc.d.ts +5 -5
  3. package/{build → dist/commonjs}/components/grpc.js +109 -90
  4. package/{build → dist/commonjs}/components/mixed.d.ts +4 -4
  5. package/{build → dist/commonjs}/components/mixed.js +11 -12
  6. package/{build → dist/commonjs}/components/rest.d.ts +5 -5
  7. package/{build → dist/commonjs}/components/rest.js +42 -35
  8. package/{build → dist/commonjs}/constants.d.ts +2 -2
  9. package/{build → dist/commonjs}/constants.js +29 -19
  10. package/{build → dist/commonjs}/index.d.ts +9 -8
  11. package/{build → dist/commonjs}/index.js +35 -46
  12. package/{build → dist/commonjs}/models/common.d.ts +19 -8
  13. package/{build → dist/commonjs}/models/context.d.ts +0 -1
  14. package/dist/commonjs/package.json +3 -0
  15. package/dist/commonjs/utils/axios.d.ts +4 -0
  16. package/{build → dist/commonjs}/utils/axios.js +3 -4
  17. package/{build → dist/commonjs}/utils/common.d.ts +4 -3
  18. package/{build → dist/commonjs}/utils/common.js +19 -8
  19. package/{build → dist/commonjs}/utils/create-context-api.d.ts +2 -2
  20. package/{build → dist/commonjs}/utils/create-context-api.js +5 -6
  21. package/{build → dist/commonjs}/utils/grpc-reflection.js +15 -35
  22. package/{build → dist/commonjs}/utils/grpc.d.ts +1 -1
  23. package/{build → dist/commonjs}/utils/grpc.js +10 -11
  24. package/dist/commonjs/utils/overrideEndpoints/index.d.ts +2 -0
  25. package/dist/commonjs/utils/overrideEndpoints/index.js +4 -0
  26. package/{build → dist/commonjs}/utils/overrideEndpoints/overrideEndpoints.d.ts +1 -1
  27. package/{build → dist/commonjs}/utils/overrideEndpoints/overrideEndpoints.js +1 -2
  28. package/dist/commonjs/utils/package-root.d.ts +1 -0
  29. package/dist/commonjs/utils/package-root.js +44 -0
  30. package/{build → dist/commonjs}/utils/parse-error.d.ts +5 -5
  31. package/{build → dist/commonjs}/utils/parse-error.js +19 -19
  32. package/{build → dist/commonjs}/utils/proto-path-resolver.d.ts +1 -1
  33. package/{build → dist/commonjs}/utils/proto-path-resolver.js +24 -15
  34. package/{build → dist/commonjs}/utils/redact-sensitive-headers.d.ts +1 -2
  35. package/{build → dist/commonjs}/utils/redact-sensitive-headers.js +1 -2
  36. package/dist/commonjs/utils/source-dir.d.ts +1 -0
  37. package/dist/commonjs/utils/source-dir.js +41 -0
  38. package/{build → dist/commonjs}/utils/typed-api.d.ts +1 -1
  39. package/{build → dist/commonjs}/utils/typed-api.js +1 -2
  40. package/{build → dist/commonjs}/utils/validate.js +6 -10
  41. package/dist/esm/components/grpc.d.ts +24 -0
  42. package/dist/esm/components/grpc.js +691 -0
  43. package/dist/esm/components/mixed.d.ts +11 -0
  44. package/dist/esm/components/mixed.js +62 -0
  45. package/dist/esm/components/rest.d.ts +8 -0
  46. package/dist/esm/components/rest.js +357 -0
  47. package/dist/esm/constants.d.ts +53 -0
  48. package/dist/esm/constants.js +82 -0
  49. package/dist/esm/index.d.ts +13 -0
  50. package/dist/esm/index.js +274 -0
  51. package/dist/esm/models/common.d.ts +289 -0
  52. package/dist/esm/models/common.js +5 -0
  53. package/dist/esm/models/context.d.ts +22 -0
  54. package/dist/esm/models/context.js +1 -0
  55. package/dist/esm/models/error.d.ts +12 -0
  56. package/dist/esm/models/error.js +1 -0
  57. package/dist/esm/package.json +3 -0
  58. package/{build → dist/esm}/utils/axios.d.ts +1 -1
  59. package/dist/esm/utils/axios.js +24 -0
  60. package/dist/esm/utils/common.d.ts +16 -0
  61. package/dist/esm/utils/common.js +48 -0
  62. package/dist/esm/utils/create-context-api.d.ts +4 -0
  63. package/dist/esm/utils/create-context-api.js +38 -0
  64. package/dist/esm/utils/grpc-reflection.d.ts +28 -0
  65. package/dist/esm/utils/grpc-reflection.js +72 -0
  66. package/dist/esm/utils/grpc.d.ts +15 -0
  67. package/dist/esm/utils/grpc.js +72 -0
  68. package/dist/esm/utils/overrideEndpoints/index.d.ts +2 -0
  69. package/dist/esm/utils/overrideEndpoints/index.js +2 -0
  70. package/dist/esm/utils/overrideEndpoints/overrideEndpoints.d.ts +17 -0
  71. package/dist/esm/utils/overrideEndpoints/overrideEndpoints.js +96 -0
  72. package/dist/esm/utils/package-root.d.ts +1 -0
  73. package/dist/esm/utils/package-root.js +8 -0
  74. package/dist/esm/utils/parse-error.d.ts +30 -0
  75. package/dist/esm/utils/parse-error.js +214 -0
  76. package/dist/esm/utils/proto-path-resolver.d.ts +2 -0
  77. package/dist/esm/utils/proto-path-resolver.js +23 -0
  78. package/dist/esm/utils/redact-sensitive-headers.d.ts +3 -0
  79. package/dist/esm/utils/redact-sensitive-headers.js +12 -0
  80. package/dist/esm/utils/source-dir.d.ts +1 -0
  81. package/dist/esm/utils/source-dir.js +4 -0
  82. package/dist/esm/utils/typed-api.d.ts +2 -0
  83. package/dist/esm/utils/typed-api.js +3 -0
  84. package/dist/esm/utils/validate.d.ts +4 -0
  85. package/dist/esm/utils/validate.js +47 -0
  86. package/package.json +41 -16
  87. package/build/utils/overrideEndpoints/index.d.ts +0 -2
  88. package/build/utils/overrideEndpoints/index.js +0 -4
  89. /package/bin/{patch.js → patch.cjs} +0 -0
  90. /package/{build → dist/commonjs}/models/common.js +0 -0
  91. /package/{build → dist/commonjs}/models/context.js +0 -0
  92. /package/{build → dist/commonjs}/models/error.d.ts +0 -0
  93. /package/{build → dist/commonjs}/models/error.js +0 -0
  94. /package/{build → dist/commonjs}/utils/grpc-reflection.d.ts +0 -0
  95. /package/{build → dist/commonjs}/utils/validate.d.ts +0 -0
@@ -0,0 +1,48 @@
1
+ import _ from 'lodash';
2
+ export function isExtendedActionEndpoint(endpoint) {
3
+ return (endpoint === null || endpoint === void 0 ? void 0 : endpoint.path) !== undefined;
4
+ }
5
+ export function isExtendedGrpcActionEndpoint(endpoint) {
6
+ return ((endpoint === null || endpoint === void 0 ? void 0 : endpoint.grpcOptions) !== undefined ||
7
+ (endpoint === null || endpoint === void 0 ? void 0 : endpoint.insecure) !== undefined ||
8
+ (endpoint === null || endpoint === void 0 ? void 0 : endpoint.secureWithoutRootCert) !== undefined);
9
+ }
10
+ export function isExtendedRestActionEndpoint(endpoint) {
11
+ return (endpoint === null || endpoint === void 0 ? void 0 : endpoint.axiosConfig) !== undefined;
12
+ }
13
+ export function getKeys(obj) {
14
+ return Object.keys(obj);
15
+ }
16
+ /**
17
+ * This function should only use to sanitize debugHeaders that are creating in our code
18
+ */
19
+ export function sanitizeDebugHeaders(debugHeaders) {
20
+ return _.omit(debugHeaders, ['x-api-request-body']);
21
+ }
22
+ export function getHeadersFromMetadata(metadata, prefix = '') {
23
+ return Object.entries(metadata).reduce((headers, [key, values]) => {
24
+ headers[`${prefix}${key}`] = values.filter((value) => typeof value === 'string').join(' ');
25
+ return headers;
26
+ }, {});
27
+ }
28
+ export function handleError(ErrorConstructor, error, ctx, message, extra) {
29
+ if (error instanceof Error) {
30
+ ctx.logError(message, ErrorConstructor.wrap(error), extra);
31
+ }
32
+ else if (typeof error === 'string') {
33
+ ctx.logError(message, { error }, extra);
34
+ }
35
+ else {
36
+ ctx.logError(message, error, extra);
37
+ }
38
+ }
39
+ export const getProxyHeadersArgs = (serviceName, actionName, grpcConfig) => {
40
+ const protopath = grpcConfig && 'protoPath' in grpcConfig ? grpcConfig.protoPath : undefined;
41
+ const protokey = grpcConfig === null || grpcConfig === void 0 ? void 0 : grpcConfig.protoKey;
42
+ return {
43
+ service: serviceName,
44
+ action: actionName,
45
+ protopath,
46
+ protokey,
47
+ };
48
+ };
@@ -0,0 +1,4 @@
1
+ import { ApiActionConfig, ApiByScope, ContextApiWithRoot, GatewayRequest, GatewayResponse, SchemasByScope } from '../models/common.js';
2
+ import { GatewayContext } from '../models/context.js';
3
+ export type RequestContext<Context extends GatewayContext> = Omit<ApiActionConfig<Context, never>, 'args'>;
4
+ export declare function generateContextApi<TFullSchema extends SchemasByScope, Context extends GatewayContext, Req extends GatewayRequest<Context>, Res extends GatewayResponse>(baseApi: ApiByScope<TFullSchema, Context, Req, Res>, requestContext: RequestContext<Context>): ContextApiWithRoot<TFullSchema>;
@@ -0,0 +1,38 @@
1
+ import _ from 'lodash';
2
+ import { getKeys } from './common.js';
3
+ function createContextApiForScope(api, requestContext) {
4
+ return _.reduce(api, (acc, service, serviceName) => {
5
+ acc[serviceName] = _.reduce(service, (accService, action, actionName) => {
6
+ accService[actionName] = (args) => action(Object.assign(Object.assign({}, requestContext), { args })).then((response) => response.responseData ||
7
+ response
8
+ .stream);
9
+ return accService;
10
+ }, {});
11
+ return acc;
12
+ }, {});
13
+ }
14
+ export function generateContextApi(baseApi, requestContext) {
15
+ var _a;
16
+ const contextApi = _.reduce(baseApi, (contextApi, scope, scopeName) => {
17
+ contextApi[scopeName] = createContextApiForScope(scope, requestContext);
18
+ return contextApi;
19
+ }, {});
20
+ const api = contextApi;
21
+ const rootScope = contextApi.root;
22
+ if (rootScope) {
23
+ for (const rootService of getKeys(rootScope)) {
24
+ const curScope = (_a = api[rootService]) !== null && _a !== void 0 ? _a : {};
25
+ for (const rootAction of getKeys(rootScope[rootService])) {
26
+ const rootServiceFunc = rootScope[rootService][rootAction];
27
+ if (curScope[rootAction]) {
28
+ for (const curScopeAction of getKeys(curScope[rootAction])) {
29
+ rootServiceFunc[curScopeAction] = curScope[rootAction][curScopeAction];
30
+ }
31
+ }
32
+ curScope[rootAction] = rootServiceFunc;
33
+ }
34
+ api[rootService] = curScope;
35
+ }
36
+ }
37
+ return api;
38
+ }
@@ -0,0 +1,28 @@
1
+ import type { ChannelCredentials } from '@grpc/grpc-js';
2
+ type DescriptorExtensionProto = string[] | {
3
+ includeProtoRoots: string[];
4
+ filenames: string[];
5
+ };
6
+ /**
7
+ * @param actionEndpoint
8
+ * @param protoKey
9
+ * @param credentials
10
+ * @param grpcOptions
11
+ * @param descriptorExtensionProto
12
+ * @returns Promise<protobufjs.Root>.
13
+ * use toDescriptor for use with protoLoader.
14
+ * use toJSON for get a JSON descriptor.
15
+ */
16
+ export declare function getCachedReflectionRoot(actionEndpoint: string, protoKey: string, credentials: ChannelCredentials, grpcOptions?: object, descriptorExtensionProto?: DescriptorExtensionProto): Promise<any>;
17
+ /**
18
+ * @param actionEndpoint
19
+ * @param protoKey
20
+ * @param credentials
21
+ * @param grpcOptions
22
+ * @param addToCache
23
+ * @returns Promise<protobufjs.Root>.
24
+ * use toDescriptor for use with protoLoader.
25
+ * use toJSON for get a JSON descriptor.
26
+ */
27
+ export declare function getReflectionRoot(actionEndpoint: string, protoKey: string, credentials: ChannelCredentials, grpcOptions?: object, addToCache?: boolean): Promise<any>;
28
+ export {};
@@ -0,0 +1,72 @@
1
+ import _ from 'lodash';
2
+ import protobufjs from 'protobufjs';
3
+ import { patchProtoPathResolver } from './proto-path-resolver.js';
4
+ const reflectionClientsMap = {};
5
+ async function getCachedClient(actionEndpoint, credentials, grpcOptions, descriptorExtensionProto) {
6
+ const cacheKey = [actionEndpoint, JSON.stringify([grpcOptions, descriptorExtensionProto])];
7
+ let clientWithCache = _.get(reflectionClientsMap, cacheKey);
8
+ if (!clientWithCache) {
9
+ const grpcReflection = await import('grpc-reflection-js');
10
+ let descriptorRoot;
11
+ if (descriptorExtensionProto) {
12
+ descriptorRoot = protobufjs.Root.fromJSON(
13
+ // @ts-expect-error no typings for default export
14
+ (await import('protobufjs/ext/descriptor/index.js')).default);
15
+ if (Array.isArray(descriptorExtensionProto)) {
16
+ descriptorRoot.loadSync(descriptorExtensionProto);
17
+ }
18
+ else {
19
+ patchProtoPathResolver(descriptorRoot, descriptorExtensionProto.includeProtoRoots);
20
+ descriptorRoot.loadSync(descriptorExtensionProto.filenames);
21
+ }
22
+ }
23
+ const client = new grpcReflection.Client(actionEndpoint, credentials, grpcOptions, undefined,
24
+ // @ts-ignore this parameter is present only in the patched version
25
+ descriptorRoot);
26
+ clientWithCache = { client, reflectionRootPromiseMap: {} };
27
+ _.set(reflectionClientsMap, cacheKey, clientWithCache);
28
+ }
29
+ return clientWithCache;
30
+ }
31
+ /**
32
+ * @param actionEndpoint
33
+ * @param protoKey
34
+ * @param credentials
35
+ * @param grpcOptions
36
+ * @param descriptorExtensionProto
37
+ * @returns Promise<protobufjs.Root>.
38
+ * use toDescriptor for use with protoLoader.
39
+ * use toJSON for get a JSON descriptor.
40
+ */
41
+ export async function getCachedReflectionRoot(actionEndpoint, protoKey, credentials, grpcOptions, descriptorExtensionProto) {
42
+ const { client, reflectionRootPromiseMap } = await getCachedClient(actionEndpoint, credentials, grpcOptions, descriptorExtensionProto);
43
+ const cacheKey = [actionEndpoint, protoKey];
44
+ let cachedRootPromise = _.get(reflectionRootPromiseMap, cacheKey);
45
+ if (!cachedRootPromise) {
46
+ cachedRootPromise = client.fileContainingSymbol(protoKey);
47
+ _.set(reflectionRootPromiseMap, cacheKey, cachedRootPromise);
48
+ cachedRootPromise.catch(() => {
49
+ _.set(reflectionRootPromiseMap, cacheKey, undefined);
50
+ });
51
+ }
52
+ const loadedRoot = await cachedRootPromise;
53
+ return loadedRoot;
54
+ }
55
+ /**
56
+ * @param actionEndpoint
57
+ * @param protoKey
58
+ * @param credentials
59
+ * @param grpcOptions
60
+ * @param addToCache
61
+ * @returns Promise<protobufjs.Root>.
62
+ * use toDescriptor for use with protoLoader.
63
+ * use toJSON for get a JSON descriptor.
64
+ */
65
+ export async function getReflectionRoot(actionEndpoint, protoKey, credentials, grpcOptions, addToCache) {
66
+ const { client, reflectionRootPromiseMap } = await getCachedClient(actionEndpoint, credentials, grpcOptions);
67
+ const loadedRoot = await client.fileContainingSymbol(protoKey);
68
+ if (addToCache) {
69
+ _.set(reflectionRootPromiseMap, [actionEndpoint, protoKey], Promise.resolve(loadedRoot));
70
+ }
71
+ return loadedRoot;
72
+ }
@@ -0,0 +1,15 @@
1
+ import * as grpc from '@grpc/grpc-js';
2
+ import { ClientDuplexStream, ClientReadableStream, ClientUnaryCall, ClientWritableStream } from '@grpc/grpc-js';
3
+ import protobufjs from 'protobufjs';
4
+ export declare function decodeAnyMessageRecursively(root: protobufjs.Root, message?: unknown, decodeAnyMessageProtoLoaderOptions?: protobufjs.IConversionOptions): unknown;
5
+ export declare function isRetryableGrpcError(error?: grpc.ServiceError): boolean;
6
+ export declare function isRecreateServiceError(error?: grpc.ServiceError): boolean;
7
+ export type ListenForAbortArgs = {
8
+ signal?: AbortSignal;
9
+ config: {
10
+ abortOnClientDisconnect?: boolean;
11
+ };
12
+ call: ClientUnaryCall | ClientReadableStream<unknown> | ClientWritableStream<unknown> | ClientDuplexStream<unknown, unknown>;
13
+ reject: (err: Error) => void;
14
+ };
15
+ export declare function listenForAbort({ signal, config, call, reject }: ListenForAbortArgs): () => void;
@@ -0,0 +1,72 @@
1
+ /* eslint-disable camelcase */
2
+ import { DEFAULT_PROTO_LOADER_OPTIONS, RECREATE_SERVICE_CODES, RETRYABLE_STATUS_CODES, } from '../constants.js';
3
+ import { GrpcError } from './parse-error.js';
4
+ function isEncodedMessage(message) {
5
+ return Boolean(message.type_url && message.value);
6
+ }
7
+ export function decodeAnyMessageRecursively(root, message, decodeAnyMessageProtoLoaderOptions) {
8
+ if (!message || typeof message !== 'object') {
9
+ return message;
10
+ }
11
+ if (Array.isArray(message)) {
12
+ return message.map((innerMessage) => decodeAnyMessageRecursively(root, innerMessage, decodeAnyMessageProtoLoaderOptions));
13
+ }
14
+ if (typeof message === 'object' && !isEncodedMessage(message)) {
15
+ return Object.entries(message).reduce((res, [key, value]) => {
16
+ res[key] = decodeAnyMessageRecursively(root, value, decodeAnyMessageProtoLoaderOptions);
17
+ return res;
18
+ }, {});
19
+ }
20
+ const lastSlashIndex = message.type_url.lastIndexOf('/');
21
+ if (lastSlashIndex < 0) {
22
+ return message;
23
+ }
24
+ const typeName = message.type_url.substring(lastSlashIndex + 1);
25
+ try {
26
+ const type = root.lookupType(typeName);
27
+ const decodedMessage = type.toObject(type.decode(message.value), Object.assign(Object.assign({}, DEFAULT_PROTO_LOADER_OPTIONS), decodeAnyMessageProtoLoaderOptions));
28
+ if (typeof decodedMessage === 'object' &&
29
+ !Array.isArray(decodedMessage) &&
30
+ !decodedMessage['@type']) {
31
+ Object.assign(decodedMessage, { '@type': message.type_url });
32
+ }
33
+ return decodeAnyMessageRecursively(root, decodedMessage, decodeAnyMessageProtoLoaderOptions);
34
+ }
35
+ catch (error) {
36
+ console.error(`Failed to lookup ${typeName}`, error);
37
+ return message;
38
+ }
39
+ }
40
+ export function isRetryableGrpcError(error) {
41
+ if (!error) {
42
+ return false;
43
+ }
44
+ return RETRYABLE_STATUS_CODES.includes(error.code);
45
+ }
46
+ export function isRecreateServiceError(error) {
47
+ if (!error) {
48
+ return false;
49
+ }
50
+ return RECREATE_SERVICE_CODES.includes(error.code);
51
+ }
52
+ export function listenForAbort({ signal, config, call, reject }) {
53
+ if (!signal || !config.abortOnClientDisconnect) {
54
+ return () => null;
55
+ }
56
+ const handleAbortSignal = () => {
57
+ call.cancel();
58
+ reject(new GrpcError('Request was cancelled.', {
59
+ status: 499,
60
+ code: 'REQUEST_WAS_CANCELLED',
61
+ message: 'Request was cancelled because the original connection was disconnected.',
62
+ }));
63
+ };
64
+ if (signal.aborted) {
65
+ handleAbortSignal();
66
+ return () => null;
67
+ }
68
+ signal.addEventListener('abort', handleAbortSignal);
69
+ return () => {
70
+ signal.removeEventListener('abort', handleAbortSignal);
71
+ };
72
+ }
@@ -0,0 +1,2 @@
1
+ import { overrideEndpoints } from './overrideEndpoints.js';
2
+ export default overrideEndpoints;
@@ -0,0 +1,2 @@
1
+ import { overrideEndpoints } from './overrideEndpoints.js';
2
+ export default overrideEndpoints;
@@ -0,0 +1,17 @@
1
+ import { ActionEndpoint, SchemasByScope } from '../../index.js';
2
+ export interface OverrideParams {
3
+ [serviceKeyScope: string]: {
4
+ [endpointName: string]: ActionEndpoint;
5
+ };
6
+ }
7
+ /**
8
+ * Overrides endpoints in the schema according to overrideParams
9
+ * @param originalSchema Schema for the gateway
10
+ * @param overrideParams Definitions of endpoints for services in the format {[<scope>.<service key>]: {[<endpointName>]: ActionEndpoint}}
11
+ * If <scope> is not specified, root is assumed.
12
+ * Example: '{serviceName: {endpoint: "https://example.com"}}'
13
+ * @param installation
14
+ * @param env
15
+ * @return new overridden schema
16
+ */
17
+ export declare function overrideEndpoints<T extends SchemasByScope>(originalSchema: T, overrideParams: OverrideParams, installation: string | undefined, env: string | undefined): T;
@@ -0,0 +1,96 @@
1
+ import _ from 'lodash';
2
+ function parseOverrideEndpointsParams(params) {
3
+ const parsedParams = [];
4
+ for (const [serviceKeyScope, serviceKeyValues] of Object.entries(params)) {
5
+ for (const [endpointName, config] of Object.entries(serviceKeyValues)) {
6
+ let scope = 'root';
7
+ let serviceKey = serviceKeyScope;
8
+ const pointInd = serviceKey.indexOf('.');
9
+ if (pointInd >= 0) {
10
+ scope = serviceKey.slice(0, pointInd);
11
+ serviceKey = serviceKey.slice(pointInd + 1);
12
+ }
13
+ parsedParams.push({
14
+ scope,
15
+ serviceKey,
16
+ endpointName,
17
+ config,
18
+ });
19
+ }
20
+ }
21
+ return parsedParams;
22
+ }
23
+ function getKeys(obj) {
24
+ return Object.keys(obj);
25
+ }
26
+ function deepCopy(obj) {
27
+ const res = Object.assign({}, obj);
28
+ getKeys(res).forEach((key) => {
29
+ if (typeof res[key] === 'object' && !Array.isArray(res[key]) && res[key] !== null) {
30
+ res[key] = deepCopy(res[key]);
31
+ }
32
+ });
33
+ return res;
34
+ }
35
+ /**
36
+ * Overrides endpoints in the schema according to overrideParams
37
+ * @param originalSchema Schema for the gateway
38
+ * @param overrideParams Definitions of endpoints for services in the format {[<scope>.<service key>]: {[<endpointName>]: ActionEndpoint}}
39
+ * If <scope> is not specified, root is assumed.
40
+ * Example: '{serviceName: {endpoint: "https://example.com"}}'
41
+ * @param installation
42
+ * @param env
43
+ * @return new overridden schema
44
+ */
45
+ export function overrideEndpoints(originalSchema, overrideParams, installation, env) {
46
+ if (!installation) {
47
+ console.warn('overrideEndpoints: installation empty');
48
+ return originalSchema;
49
+ }
50
+ if (!env) {
51
+ console.warn('overrideEndpoints: env empty');
52
+ return originalSchema;
53
+ }
54
+ const schema = deepCopy(originalSchema);
55
+ const parsedParams = parseOverrideEndpointsParams(overrideParams);
56
+ parsedParams.forEach((overrideConfig) => {
57
+ var _a;
58
+ const curService = (_a = schema[overrideConfig.scope]) === null || _a === void 0 ? void 0 : _a[overrideConfig.serviceKey];
59
+ if (!curService || !curService.actions || !curService.endpoints) {
60
+ console.warn('overrideEndpoints: incorrect service ' +
61
+ overrideConfig.scope +
62
+ '.' +
63
+ overrideConfig.serviceKey);
64
+ return;
65
+ }
66
+ const endpoints = curService.endpoints;
67
+ const envEndpoints = _.get(endpoints, [installation, env]);
68
+ if (!envEndpoints) {
69
+ console.warn('overrideEndpoints: ' + [installation, env] + ' not exists in envEndpoints');
70
+ return;
71
+ }
72
+ if (overrideConfig.endpointName) {
73
+ if (!envEndpoints[overrideConfig.endpointName]) {
74
+ console.warn('overrideEndpoints: incorrect endpointName ' + overrideConfig.endpointName);
75
+ }
76
+ overrideEndpoint(envEndpoints, overrideConfig.endpointName, overrideConfig);
77
+ }
78
+ });
79
+ return schema;
80
+ }
81
+ function isExtendedEndpointConfig(config) {
82
+ return typeof config === 'object';
83
+ }
84
+ function overrideEndpoint(envEndpoints, endpointName, overrideConfig) {
85
+ const config = envEndpoints[endpointName];
86
+ if (isExtendedEndpointConfig(config)) {
87
+ if (typeof overrideConfig.config === 'string') {
88
+ config.path = overrideConfig.config;
89
+ }
90
+ else {
91
+ Object.assign(config, overrideConfig.config);
92
+ }
93
+ return;
94
+ }
95
+ envEndpoints[endpointName] = overrideConfig.config;
96
+ }
@@ -0,0 +1 @@
1
+ export declare const packageRoot: string;
@@ -0,0 +1,8 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { sourceDir } from './source-dir.js';
4
+ let packageRootTest = path.resolve(sourceDir, '../package.json');
5
+ if (!fs.existsSync(packageRootTest)) {
6
+ packageRootTest = path.resolve(sourceDir, '../../package.json');
7
+ }
8
+ export const packageRoot = path.dirname(packageRootTest);
@@ -0,0 +1,30 @@
1
+ import * as grpc from '@grpc/grpc-js';
2
+ import protobufjs from 'protobufjs';
3
+ import { Lang } from '../constants.js';
4
+ import { GatewayError } from '../models/common.js';
5
+ import { AppErrorConstructor } from '../models/error.js';
6
+ export declare function parseMixedError(e: Error & {
7
+ code?: string;
8
+ }): {
9
+ status: number;
10
+ message: string;
11
+ code: string;
12
+ debug: {
13
+ originalError: Error & {
14
+ code?: string;
15
+ };
16
+ stack: string | undefined;
17
+ };
18
+ };
19
+ export declare function parseRestError(error: any, lang?: string): GatewayError;
20
+ export declare function parseGrpcError(error: grpc.ServiceError, packageRoot: protobufjs.Root, lang?: Lang, decodeAnyMessageProtoLoaderOptions?: protobufjs.IConversionOptions): GatewayError;
21
+ export declare class GrpcError extends Error {
22
+ private parsedError;
23
+ private rawError;
24
+ constructor(message: string, parsedError: GatewayError, rawError?: grpc.ServiceError);
25
+ getGatewayError(): GatewayError;
26
+ getRawError(): grpc.ServiceError | undefined;
27
+ getAppError(ErrorConstructor: AppErrorConstructor): Error;
28
+ }
29
+ export declare function isGrpcError(error: Error | GrpcError): error is GrpcError;
30
+ export declare function grpcErrorFactory(error: Error): GrpcError;
@@ -0,0 +1,214 @@
1
+ import _ from 'lodash';
2
+ import { Lang } from '../constants.js';
3
+ import { decodeAnyMessageRecursively } from './grpc.js';
4
+ const DEFAULT_GATEWAY_CODE = 'GATEWAY_REQUEST_ERROR';
5
+ const DEFAULT_GATEWAY_MESSAGE = 'Gateway request error';
6
+ export function parseMixedError(e) {
7
+ return {
8
+ status: 500,
9
+ message: String(e.message || DEFAULT_GATEWAY_MESSAGE),
10
+ code: String(e.code || DEFAULT_GATEWAY_CODE),
11
+ debug: {
12
+ originalError: e,
13
+ stack: e.stack,
14
+ },
15
+ };
16
+ }
17
+ function getErrorTitle(error) {
18
+ const prop = _.propertyOf(error);
19
+ const details = prop('details[0]');
20
+ if (details) {
21
+ return prop('details[0].type') || prop('details[0].code') || prop('code');
22
+ }
23
+ return prop('type') || prop('code');
24
+ }
25
+ function getErrorMessage(error) {
26
+ const prop = _.propertyOf(error);
27
+ const message = prop('message');
28
+ const detail = prop('detail');
29
+ const detailsMessage = prop('details[0].message');
30
+ if (message) {
31
+ return message;
32
+ }
33
+ if (detailsMessage) {
34
+ return detailsMessage;
35
+ }
36
+ if (detail) {
37
+ return prop('detail.Description') || prop('detail.Body') || detail;
38
+ }
39
+ return '';
40
+ }
41
+ function getStatusByGrpcCode(code) {
42
+ switch (code) {
43
+ case 0:
44
+ return 200;
45
+ case 1:
46
+ return 499;
47
+ case 2:
48
+ return 500;
49
+ case 3:
50
+ return 400;
51
+ case 4:
52
+ return 504;
53
+ case 5:
54
+ return 404;
55
+ case 6:
56
+ return 409;
57
+ case 7:
58
+ return 403;
59
+ case 8:
60
+ return 429;
61
+ case 9:
62
+ return 400;
63
+ case 10:
64
+ return 409;
65
+ case 11:
66
+ return 400;
67
+ case 12:
68
+ return 501;
69
+ case 13:
70
+ return 500;
71
+ case 14:
72
+ return 503;
73
+ case 15:
74
+ return 500;
75
+ case 16:
76
+ return 401;
77
+ default:
78
+ return 500;
79
+ }
80
+ }
81
+ export function parseRestError(error, lang) {
82
+ const prop = _.propertyOf(error);
83
+ let status = 500;
84
+ let title;
85
+ let description;
86
+ let details;
87
+ let type;
88
+ let code;
89
+ let debug;
90
+ if (prop('response')) {
91
+ const responseData = prop('response.data');
92
+ const statusTitle = `${prop('response.status')} ${prop('response.statusText')}`;
93
+ const errorTitle = getErrorTitle(responseData);
94
+ status = prop('response.status');
95
+ code = prop('response.data.code');
96
+ type = prop('response.data.type');
97
+ details = prop('response.data.details');
98
+ debug = prop('response.data.debug');
99
+ title = errorTitle ? errorTitle : statusTitle;
100
+ description = getErrorMessage(responseData);
101
+ if (status === 403) {
102
+ title = lang === Lang.Ru ? 'Доступ запрещен' : 'Access denied';
103
+ }
104
+ }
105
+ else {
106
+ code = prop('code');
107
+ title = lang === Lang.Ru ? 'Ошибка' : 'Error';
108
+ if (code === 'ECONNABORTED' || code === 'ETIMEDOUT') {
109
+ status = 504;
110
+ description = lang === Lang.Ru ? 'Превышено время ожидания ответа' : 'Timeout exceeded';
111
+ }
112
+ else if (code === 'ERR_CANCELED') {
113
+ status = 499;
114
+ description = lang === Lang.Ru ? 'Запрос был отменен.' : 'Request was cancelled.';
115
+ }
116
+ else {
117
+ status = 500;
118
+ description =
119
+ lang === Lang.Ru
120
+ ? 'Произошла непредвиденная ошибка. Попробуйте обновить страницу через некоторое время.'
121
+ : 'An unexpected error has occurred. Try to refresh the page in a few moments.';
122
+ }
123
+ }
124
+ return {
125
+ status,
126
+ message: String(description || DEFAULT_GATEWAY_MESSAGE),
127
+ code: String(code || DEFAULT_GATEWAY_CODE),
128
+ details: Object.assign({ type,
129
+ title,
130
+ description }, (typeof details === 'object' && !Array.isArray(details) ? details : { details })),
131
+ debug,
132
+ };
133
+ }
134
+ function decodeGrpcStatusMessage(metadata, packageRoot, decodeAnyMessageProtoLoaderOptions) {
135
+ const statusMessageBin = metadata.get('grpc-status-details-bin')[0];
136
+ if (!statusMessageBin) {
137
+ return undefined;
138
+ }
139
+ return decodeAnyMessageRecursively(packageRoot, {
140
+ type_url: 'type.googleapis.com/google.rpc.Status',
141
+ value: statusMessageBin,
142
+ }, decodeAnyMessageProtoLoaderOptions);
143
+ }
144
+ export function parseGrpcError(error, packageRoot, lang = Lang.Ru, decodeAnyMessageProtoLoaderOptions) {
145
+ let title = lang === Lang.Ru ? 'Ошибка' : 'Error';
146
+ if (error.code === 7) {
147
+ // Always redefine title for Access denied errors
148
+ title = lang === Lang.Ru ? 'Доступ запрещен' : 'Access denied';
149
+ }
150
+ let code = error.code;
151
+ let description = error.details;
152
+ let details;
153
+ if (error.metadata) {
154
+ try {
155
+ const statusMessage = decodeGrpcStatusMessage(error.metadata, packageRoot, decodeAnyMessageProtoLoaderOptions);
156
+ if (statusMessage) {
157
+ code = statusMessage.code;
158
+ description = statusMessage.message;
159
+ details = statusMessage.details;
160
+ }
161
+ }
162
+ catch (e) { }
163
+ }
164
+ // Always redefine description for Timeout exceeded errors
165
+ if (error.code === 4) {
166
+ description = lang === Lang.Ru ? 'Превышено время ожидания ответа' : 'Timeout exceeded';
167
+ }
168
+ // Use default description if description is undefined, but not for Access denied errors
169
+ if (!description) {
170
+ description =
171
+ lang === Lang.Ru
172
+ ? 'Произошла непредвиденная ошибка. Попробуйте обновить страницу через некоторое время.'
173
+ : 'An unexpected error has occurred. Try to refresh the page in a few moments.';
174
+ }
175
+ const status = getStatusByGrpcCode(error.code);
176
+ return {
177
+ status,
178
+ message: String(description || DEFAULT_GATEWAY_MESSAGE),
179
+ code: DEFAULT_GATEWAY_CODE,
180
+ details: Object.assign({ title,
181
+ description, grpcCode: code }, (typeof details === 'object' && !Array.isArray(details) ? details : { details })),
182
+ };
183
+ }
184
+ export class GrpcError extends Error {
185
+ constructor(message, parsedError, rawError) {
186
+ super(message);
187
+ this.parsedError = parsedError;
188
+ this.rawError = rawError;
189
+ }
190
+ getGatewayError() {
191
+ return this.parsedError;
192
+ }
193
+ getRawError() {
194
+ return this.rawError;
195
+ }
196
+ getAppError(ErrorConstructor) {
197
+ return new ErrorConstructor(this.parsedError.message, {
198
+ code: this.parsedError.code,
199
+ details: this.parsedError.details,
200
+ debug: this.parsedError.debug,
201
+ });
202
+ }
203
+ }
204
+ export function isGrpcError(error) {
205
+ return error.getGatewayError !== undefined;
206
+ }
207
+ export function grpcErrorFactory(error) {
208
+ return new GrpcError(error.message, {
209
+ status: 500,
210
+ code: '',
211
+ message: error.message,
212
+ details: {},
213
+ });
214
+ }
@@ -0,0 +1,2 @@
1
+ import protobufjs from 'protobufjs';
2
+ export declare function patchProtoPathResolver(root: protobufjs.Root, includeDirs: string[]): void;