ag-common 0.0.762 → 0.0.763

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 (61) hide show
  1. package/dist/api/helpers/apigw.d.ts +1 -1
  2. package/dist/api/helpers/apigw.js +6 -8
  3. package/dist/api/helpers/index.d.ts +0 -2
  4. package/dist/api/helpers/index.js +0 -2
  5. package/dist/api/types/index.d.ts +0 -32
  6. package/dist/ui/components/index.d.ts +0 -1
  7. package/dist/ui/components/index.js +0 -1
  8. package/dist/ui/helpers/dom.js +2 -0
  9. package/dist/ui/helpers/index.d.ts +0 -1
  10. package/dist/ui/helpers/index.js +0 -1
  11. package/dist/ui/helpers/routes.d.ts +0 -11
  12. package/dist/ui/helpers/useContextMenu.js +3 -0
  13. package/dist/ui/helpers/useIsInViewport.js +1 -0
  14. package/dist/ui/helpers/useOnScroll.js +2 -3
  15. package/package.json +1 -2
  16. package/dist/api/helpers/openApiHelpers.d.ts +0 -43
  17. package/dist/api/helpers/openApiHelpers.js +0 -163
  18. package/dist/api/helpers/validateOpenApi.d.ts +0 -25
  19. package/dist/api/helpers/validateOpenApi.js +0 -127
  20. package/dist/api/openapi-postfix.d.ts +0 -1
  21. package/dist/api/openapi-postfix.js +0 -42
  22. package/dist/api/openapi-prefix.d.ts +0 -1
  23. package/dist/api/openapi-prefix.js +0 -88
  24. package/dist/ui/components/OpenApiCodeBlock/OpenApiCodeBlock.d.ts +0 -3
  25. package/dist/ui/components/OpenApiCodeBlock/OpenApiCodeBlock.js +0 -69
  26. package/dist/ui/components/OpenApiCodeBlock/curl/helpers/body.d.ts +0 -6
  27. package/dist/ui/components/OpenApiCodeBlock/curl/helpers/body.js +0 -30
  28. package/dist/ui/components/OpenApiCodeBlock/curl/helpers/getCurlLines.d.ts +0 -2
  29. package/dist/ui/components/OpenApiCodeBlock/curl/helpers/getCurlLines.js +0 -31
  30. package/dist/ui/components/OpenApiCodeBlock/curl/helpers/security.d.ts +0 -11
  31. package/dist/ui/components/OpenApiCodeBlock/curl/helpers/security.js +0 -28
  32. package/dist/ui/components/OpenApiCodeBlock/curl/index.d.ts +0 -6
  33. package/dist/ui/components/OpenApiCodeBlock/curl/index.js +0 -35
  34. package/dist/ui/components/OpenApiCodeBlock/fetch/helpers/call.d.ts +0 -3
  35. package/dist/ui/components/OpenApiCodeBlock/fetch/helpers/call.js +0 -23
  36. package/dist/ui/components/OpenApiCodeBlock/fetch/helpers/getFetchLines.d.ts +0 -2
  37. package/dist/ui/components/OpenApiCodeBlock/fetch/helpers/getFetchLines.js +0 -19
  38. package/dist/ui/components/OpenApiCodeBlock/fetch/helpers/req.d.ts +0 -3
  39. package/dist/ui/components/OpenApiCodeBlock/fetch/helpers/req.js +0 -78
  40. package/dist/ui/components/OpenApiCodeBlock/fetch/index.d.ts +0 -6
  41. package/dist/ui/components/OpenApiCodeBlock/fetch/index.js +0 -24
  42. package/dist/ui/components/OpenApiCodeBlock/helpers/common.d.ts +0 -20
  43. package/dist/ui/components/OpenApiCodeBlock/helpers/common.js +0 -89
  44. package/dist/ui/components/OpenApiCodeBlock/helpers/joinJsx.d.ts +0 -4
  45. package/dist/ui/components/OpenApiCodeBlock/helpers/joinJsx.js +0 -25
  46. package/dist/ui/components/OpenApiCodeBlock/index.d.ts +0 -2
  47. package/dist/ui/components/OpenApiCodeBlock/index.js +0 -17
  48. package/dist/ui/components/OpenApiCodeBlock/types.d.ts +0 -60
  49. package/dist/ui/components/OpenApiCodeBlock/types.js +0 -2
  50. package/dist/ui/helpers/callOpenApi/cached.d.ts +0 -34
  51. package/dist/ui/helpers/callOpenApi/cached.js +0 -92
  52. package/dist/ui/helpers/callOpenApi/direct.d.ts +0 -9
  53. package/dist/ui/helpers/callOpenApi/direct.js +0 -137
  54. package/dist/ui/helpers/callOpenApi/helpers.d.ts +0 -9
  55. package/dist/ui/helpers/callOpenApi/helpers.js +0 -60
  56. package/dist/ui/helpers/callOpenApi/hook.d.ts +0 -27
  57. package/dist/ui/helpers/callOpenApi/hook.js +0 -82
  58. package/dist/ui/helpers/callOpenApi/index.d.ts +0 -5
  59. package/dist/ui/helpers/callOpenApi/index.js +0 -20
  60. package/dist/ui/helpers/callOpenApi/types.d.ts +0 -19
  61. package/dist/ui/helpers/callOpenApi/types.js +0 -2
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Sends a message to a specific WebSocket connection
3
3
  */
4
- export declare function sendWebSocketMessage<T>({ connectionId, message, endpoint, }: {
4
+ export declare function sendWebSocketMessage<T>(p: {
5
5
  connectionId: string;
6
6
  message: T;
7
7
  endpoint: string;
@@ -18,15 +18,13 @@ const common_1 = require("../../common");
18
18
  /**
19
19
  * Sends a message to a specific WebSocket connection
20
20
  */
21
- function sendWebSocketMessage(_a) {
22
- return __awaiter(this, arguments, void 0, function* ({ connectionId, message, endpoint, }) {
23
- const wsClient = new client_apigatewaymanagementapi_1.ApiGatewayManagementApiClient({
24
- endpoint,
25
- });
21
+ function sendWebSocketMessage(p) {
22
+ return __awaiter(this, void 0, void 0, function* () {
23
+ const wsClient = new client_apigatewaymanagementapi_1.ApiGatewayManagementApiClient(p);
26
24
  try {
27
25
  const s = yield wsClient.send(new client_apigatewaymanagementapi_1.PostToConnectionCommand({
28
- ConnectionId: connectionId,
29
- Data: JSON.stringify(message),
26
+ ConnectionId: p.connectionId,
27
+ Data: JSON.stringify(p.message),
30
28
  }));
31
29
  if (s.$metadata.httpStatusCode === 200) {
32
30
  return true;
@@ -34,7 +32,7 @@ function sendWebSocketMessage(_a) {
34
32
  throw new Error('Error:' + JSON.stringify(s));
35
33
  }
36
34
  catch (e) {
37
- (0, common_1.warn)('Failed to send WebSocket message:', e.message);
35
+ (0, common_1.warn)('Failed to send WebSocket message:', p, e);
38
36
  return false;
39
37
  }
40
38
  });
@@ -3,12 +3,10 @@ export * from './apigw';
3
3
  export * from './aws';
4
4
  export * from './dynamo';
5
5
  export * from './enforceDynamoProvisionCap';
6
- export * from './openApiHelpers';
7
6
  export * from './s3';
8
7
  export * from './ses';
9
8
  export * from './sqs';
10
9
  export * from './ssm';
11
10
  export * from './ssmInfra';
12
11
  export * from './sts';
13
- export * from './validateOpenApi';
14
12
  export * from './validations';
@@ -19,12 +19,10 @@ __exportStar(require("./apigw"), exports);
19
19
  __exportStar(require("./aws"), exports);
20
20
  __exportStar(require("./dynamo"), exports);
21
21
  __exportStar(require("./enforceDynamoProvisionCap"), exports);
22
- __exportStar(require("./openApiHelpers"), exports);
23
22
  __exportStar(require("./s3"), exports);
24
23
  __exportStar(require("./ses"), exports);
25
24
  __exportStar(require("./sqs"), exports);
26
25
  __exportStar(require("./ssm"), exports);
27
26
  __exportStar(require("./ssmInfra"), exports);
28
27
  __exportStar(require("./sts"), exports);
29
- __exportStar(require("./validateOpenApi"), exports);
30
28
  __exportStar(require("./validations"), exports);
@@ -1,4 +1,3 @@
1
- import type { aws_dynamodb as dynamodb, aws_iam as iam, aws_lambda as lambda } from 'aws-cdk-lib';
2
1
  export interface Key {
3
2
  [key: string]: string | number;
4
3
  }
@@ -15,35 +14,4 @@ export interface DYNAMOKEYS {
15
14
  PK3?: string;
16
15
  PK4?: string;
17
16
  }
18
- export interface ILambdaConfig {
19
- dynamo?: {
20
- reads?: dynamodb.ITable[];
21
- writes?: dynamodb.ITable[];
22
- };
23
- policies?: iam.PolicyStatement[];
24
- env?: Record<string, string>;
25
- layers?: lambda.ILayerVersion[];
26
- /**
27
- * use the name of the lambda authorizer passed in in the openApiImpl config
28
- */
29
- authorizerName?: string;
30
- /**
31
- * timeout in seconds. defaults to 30
32
- */
33
- timeoutS?: number;
34
- /**
35
- * lambda memory. defaults to 128
36
- */
37
- memory?: number;
38
- /**
39
- * reserved lambda concurrency. defaults to 5. if null, doesnt apply
40
- */
41
- reservedConcurrentExecutions?: number | null;
42
- }
43
- /**
44
- * 'default' will be applied to all functions
45
- */
46
- export type ILambdaConfigs = Partial<Record<string, ILambdaConfig & {
47
- default?: ILambdaConfig;
48
- }>>;
49
17
  export type * from './aws';
@@ -20,7 +20,6 @@ export * from './Loader';
20
20
  export * from './Markdown';
21
21
  export * from './MinSidebar';
22
22
  export * from './Modal';
23
- export * from './OpenApiCodeBlock';
24
23
  export * from './PieChart';
25
24
  export * from './ProgressBar';
26
25
  export * from './Prompt';
@@ -36,7 +36,6 @@ __exportStar(require("./Loader"), exports);
36
36
  __exportStar(require("./Markdown"), exports);
37
37
  __exportStar(require("./MinSidebar"), exports);
38
38
  __exportStar(require("./Modal"), exports);
39
- __exportStar(require("./OpenApiCodeBlock"), exports);
40
39
  __exportStar(require("./PieChart"), exports);
41
40
  __exportStar(require("./ProgressBar"), exports);
42
41
  __exportStar(require("./Prompt"), exports);
@@ -22,6 +22,7 @@ exports.convertRemToPixels = convertRemToPixels;
22
22
  * @param p
23
23
  * @returns
24
24
  */
25
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
25
26
  const filterDataProps = (p) => {
26
27
  const x = Object.entries(p)
27
28
  .filter((r) => r[0].startsWith('data-'))
@@ -37,6 +38,7 @@ const isRightClick = (event) => {
37
38
  isRightMB = event.which == 3;
38
39
  else if ('button' in event)
39
40
  // IE, Opera
41
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
40
42
  isRightMB = event.button == 2;
41
43
  return isRightMB;
42
44
  };
@@ -1,5 +1,4 @@
1
1
  export * from './axiosHelper';
2
- export * from './callOpenApi';
3
2
  export type * from './cognito';
4
3
  export * from './cookie';
5
4
  export * from './date';
@@ -15,7 +15,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./axiosHelper"), exports);
18
- __exportStar(require("./callOpenApi"), exports);
19
18
  __exportStar(require("./cookie"), exports);
20
19
  __exportStar(require("./date"), exports);
21
20
  __exportStar(require("./debounce"), exports);
@@ -20,23 +20,12 @@ export interface CacheItem<T> {
20
20
  prefillData: AxiosWrapperLite<T>;
21
21
  ttlSeconds: number;
22
22
  }
23
- export interface IInitialStateCommon {
24
- openApiCache?: CacheItem<any>[];
25
- }
26
23
  export interface IRequestCommon {
27
24
  url: URLLite;
28
25
  query: Record<string, string>;
29
26
  lang: TLang;
30
27
  userAgent: string;
31
28
  }
32
- export interface IStateCommon<TRequest extends IRequestCommon> extends IInitialStateCommon {
33
- request: TRequest;
34
- pushPath: (path: string) => Promise<void>;
35
- /**
36
- * set for ssr
37
- */
38
- cookieDocument: string | undefined;
39
- }
40
29
  export declare const getRenderLanguage: (host?: string | null) => TLang;
41
30
  export declare const getClientReqHref: () => IRequestCommon;
42
31
  /**
@@ -9,6 +9,9 @@ const useContextMenu = ({ ref, }) => {
9
9
  const [showMenu, setShowMenu] = (0, react_1.useState)(false);
10
10
  const handleContextMenu = (0, react_1.useCallback)((e) => {
11
11
  var _a;
12
+ if (!e.target) {
13
+ return;
14
+ }
12
15
  if (!((_a = ref.current) === null || _a === void 0 ? void 0 : _a.contains(e.target))) {
13
16
  return;
14
17
  }
@@ -8,6 +8,7 @@ function useIsInViewport(ref) {
8
8
  const observer = new IntersectionObserver((entries) => {
9
9
  setIsInViewport(entries[0].isIntersecting);
10
10
  });
11
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
11
12
  if (ref.current) {
12
13
  observer.observe(ref.current);
13
14
  }
@@ -18,12 +18,11 @@ function useOnScroll({ onScroll, element, } = {}) {
18
18
  (0, useGranularHook_1.useGranularEffect)(() => {
19
19
  var _a;
20
20
  const listener = (e) => {
21
- var _a, _b;
22
21
  if (!(element === null || element === void 0 ? void 0 : element.current)) {
23
22
  return null;
24
23
  }
25
- const y = (_a = element.current.scrollTop) !== null && _a !== void 0 ? _a : window.scrollY;
26
- const x = (_b = element.current.scrollLeft) !== null && _b !== void 0 ? _b : window.scrollX;
24
+ const y = element.current.scrollTop;
25
+ const x = element.current.scrollLeft;
27
26
  const r = {
28
27
  y,
29
28
  x,
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.0.762",
2
+ "version": "0.0.763",
3
3
  "name": "ag-common",
4
4
  "main": "./dist/index.js",
5
5
  "types": "./dist/index.d.ts",
@@ -34,7 +34,6 @@
34
34
  "jsonwebtoken": "^9.0.2",
35
35
  "jwks-rsa": "^3.2.0",
36
36
  "node-cache": "^5.1.2",
37
- "openapi-request-validator": "^12.1.3",
38
37
  "react": "^19.1.1",
39
38
  "react-dom": "^19.1.1",
40
39
  "typescript": "^5.9.2"
@@ -1,43 +0,0 @@
1
- import type { aws_certificatemanager as certmgr } from 'aws-cdk-lib';
2
- import { aws_apigateway as apigw, aws_route53 as route53 } from 'aws-cdk-lib';
3
- import type { Construct } from 'constructs';
4
- import type { ILambdaConfigs } from '../types';
5
- export declare const openApiImpl: (p: {
6
- stack: Construct;
7
- /**
8
- * pass in generated openapi file
9
- * eg schema: require('common/openapi.generated').default;
10
- */
11
- schema: unknown;
12
- NODE_ENV: string;
13
- endpointsBase: string;
14
- /**
15
- * 'default' will be applied to all functions
16
- */
17
- lambdaConfig: ILambdaConfigs;
18
- shortStackName: string;
19
- /**
20
- * defaults:
21
- * allowOrigins: apigw.Cors.ALL_ORIGINS,
22
- allowHeaders: apigw.Cors.DEFAULT_HEADERS,
23
- */
24
- cors?: {
25
- allowOrigins: string[];
26
- allowHeaders: string[];
27
- };
28
- /**
29
- * dictionary of named authorizer functions. these names are to be used in the lambdaConfig param
30
- */
31
- authorizers?: Record<string, apigw.TokenAuthorizer>;
32
- /**
33
- * A record will be created in hosted zone for the apigw on this path. if undefined, record wont be created
34
- */
35
- r53?: {
36
- /** will create apigw domainname
37
- * eg api.mydomain.com */
38
- apiUrl: string;
39
- /** if provided will add r53 record to apigw domainame */
40
- hostedZone?: route53.IHostedZone;
41
- certificate: certmgr.ICertificate;
42
- };
43
- }) => void;
@@ -1,163 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.openApiImpl = void 0;
4
- const aws_cdk_lib_1 = require("aws-cdk-lib");
5
- const array_1 = require("../../common/helpers/array");
6
- const log_1 = require("../../common/helpers/log");
7
- const getPaths = (schema) => Object.entries(schema.paths).map(([fullPath, verbs]) => ({
8
- fullPath,
9
- pathList: fullPath.split('/').filter((s) => s),
10
- verbs: Object.keys(verbs),
11
- }));
12
- const setUpApiGw = ({ stack, NODE_ENV, shortStackName, r53, cors = {
13
- allowOrigins: aws_cdk_lib_1.aws_apigateway.Cors.ALL_ORIGINS,
14
- allowHeaders: aws_cdk_lib_1.aws_apigateway.Cors.DEFAULT_HEADERS,
15
- }, }) => {
16
- const api = new aws_cdk_lib_1.aws_apigateway.RestApi(stack, `${shortStackName}-api-${NODE_ENV}`, {
17
- defaultCorsPreflightOptions: Object.assign({}, (cors || {})),
18
- });
19
- if (r53) {
20
- const dn = new aws_cdk_lib_1.aws_apigateway.DomainName(stack, 'domain', {
21
- domainName: r53.apiUrl,
22
- certificate: r53.certificate,
23
- endpointType: aws_cdk_lib_1.aws_apigateway.EndpointType.EDGE,
24
- securityPolicy: aws_cdk_lib_1.aws_apigateway.SecurityPolicy.TLS_1_2,
25
- mapping: api,
26
- });
27
- if (r53.hostedZone) {
28
- new aws_cdk_lib_1.aws_route53.ARecord(stack, 'ARecord', {
29
- comment: '(cdk)',
30
- recordName: r53.apiUrl.substring(0, r53.apiUrl.indexOf('.')),
31
- zone: r53.hostedZone,
32
- target: aws_cdk_lib_1.aws_route53.RecordTarget.fromAlias(new aws_cdk_lib_1.aws_route53_targets.ApiGatewayDomain(dn)),
33
- });
34
- }
35
- }
36
- return api;
37
- };
38
- const setupLambda = ({ lambdaConfig, pathV, verb, seenPermissions, authorizers, }) => {
39
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
40
- const pathCompute = pathV + '/' + verb;
41
- const lp = lambdaConfig[pathCompute];
42
- if (lp) {
43
- seenPermissions[pathCompute] = true;
44
- }
45
- else {
46
- seenPermissions[pathCompute] = false;
47
- }
48
- const def = lambdaConfig.default;
49
- if (def) {
50
- seenPermissions.default = true;
51
- }
52
- //
53
- const readTables = (0, array_1.distinctBy)([...((_b = (_a = def === null || def === void 0 ? void 0 : def.dynamo) === null || _a === void 0 ? void 0 : _a.reads) !== null && _b !== void 0 ? _b : []), ...((_d = (_c = lp === null || lp === void 0 ? void 0 : lp.dynamo) === null || _c === void 0 ? void 0 : _c.reads) !== null && _d !== void 0 ? _d : [])], (s) => s.tableName);
54
- const writeTables = (0, array_1.distinctBy)([...((_f = (_e = def === null || def === void 0 ? void 0 : def.dynamo) === null || _e === void 0 ? void 0 : _e.writes) !== null && _f !== void 0 ? _f : []), ...((_h = (_g = lp === null || lp === void 0 ? void 0 : lp.dynamo) === null || _g === void 0 ? void 0 : _g.writes) !== null && _h !== void 0 ? _h : [])], (s) => s.tableName);
55
- const policies = [...((_j = def === null || def === void 0 ? void 0 : def.policies) !== null && _j !== void 0 ? _j : []), ...((_k = lp === null || lp === void 0 ? void 0 : lp.policies) !== null && _k !== void 0 ? _k : [])].filter(array_1.notEmpty);
56
- const layers = [...((_l = def === null || def === void 0 ? void 0 : def.layers) !== null && _l !== void 0 ? _l : []), ...((_m = lp === null || lp === void 0 ? void 0 : lp.layers) !== null && _m !== void 0 ? _m : [])].filter(array_1.notEmpty);
57
- const memory = (_p = (_o = lp === null || lp === void 0 ? void 0 : lp.memory) !== null && _o !== void 0 ? _o : def === null || def === void 0 ? void 0 : def.memory) !== null && _p !== void 0 ? _p : 128;
58
- // null forces undefined, undefined forces 5
59
- let reservedConcurrentExecutions = lp === null || lp === void 0 ? void 0 : lp.reservedConcurrentExecutions;
60
- if (reservedConcurrentExecutions === undefined) {
61
- reservedConcurrentExecutions = def === null || def === void 0 ? void 0 : def.reservedConcurrentExecutions;
62
- }
63
- if (reservedConcurrentExecutions === undefined) {
64
- reservedConcurrentExecutions = 5;
65
- }
66
- reservedConcurrentExecutions = reservedConcurrentExecutions !== null && reservedConcurrentExecutions !== void 0 ? reservedConcurrentExecutions : undefined;
67
- //
68
- const timeout = aws_cdk_lib_1.Duration.seconds((_r = (_q = lp === null || lp === void 0 ? void 0 : lp.timeoutS) !== null && _q !== void 0 ? _q : def === null || def === void 0 ? void 0 : def.timeoutS) !== null && _r !== void 0 ? _r : 30);
69
- let authorizerName = lp === null || lp === void 0 ? void 0 : lp.authorizerName;
70
- if (authorizerName === undefined) {
71
- authorizerName = def === null || def === void 0 ? void 0 : def.authorizerName;
72
- }
73
- if (authorizerName && (!authorizers || !authorizers[authorizerName])) {
74
- throw new Error('unseen auth name:' + authorizerName);
75
- }
76
- const authorizer = !authorizerName
77
- ? undefined
78
- : authorizers === null || authorizers === void 0 ? void 0 : authorizers[authorizerName];
79
- const env = Object.assign(Object.assign({}, ((_s = def === null || def === void 0 ? void 0 : def.env) !== null && _s !== void 0 ? _s : {})), ((_t = lp === null || lp === void 0 ? void 0 : lp.env) !== null && _t !== void 0 ? _t : {}));
80
- const environment = env;
81
- return {
82
- environment,
83
- readTables,
84
- writeTables,
85
- policies,
86
- layers,
87
- authorizer,
88
- memory,
89
- timeout,
90
- reservedConcurrentExecutions,
91
- };
92
- };
93
- const addApiPaths = (api, pathList, apiRoots) => {
94
- let pathBuild = '';
95
- let apiPath = api.root;
96
- pathList.forEach((path) => {
97
- pathBuild += '/' + path;
98
- if (apiRoots[pathBuild]) {
99
- apiPath = apiRoots[pathBuild];
100
- }
101
- else {
102
- apiRoots[pathBuild] = apiPath.addResource(path);
103
- apiPath = apiRoots[pathBuild];
104
- }
105
- });
106
- if (!apiPath) {
107
- throw new Error('no apipath');
108
- }
109
- return apiPath;
110
- };
111
- const lambdaNameSafe = (raw) => raw.replace(/[^a-zA-Z0-9-.]/gim, '-').replace(/(-){2,}/gim, '-');
112
- const openApiImpl = (p) => {
113
- if (!p.schema) {
114
- throw new Error('no openapi schema found');
115
- }
116
- const { stack, NODE_ENV, endpointsBase, lambdaConfig } = p;
117
- const paths = getPaths(p.schema);
118
- const api = setUpApiGw(p);
119
- const apiRoots = {};
120
- const seenPermissions = {};
121
- paths.forEach(({ fullPath, verbs, pathList }) => {
122
- const apiPath = addApiPaths(api, pathList, apiRoots);
123
- verbs.forEach((verb) => {
124
- const lc = setupLambda({
125
- lambdaConfig,
126
- pathV: fullPath,
127
- verb,
128
- seenPermissions,
129
- authorizers: p.authorizers,
130
- });
131
- const lambdaName = lambdaNameSafe(`${p.shortStackName}-${fullPath}-${verb}-${NODE_ENV}`);
132
- const entry = `${endpointsBase}${fullPath}/${verb.toUpperCase()}.ts`;
133
- const lambdaV = new aws_cdk_lib_1.aws_lambda_nodejs.NodejsFunction(stack, lambdaName, {
134
- functionName: lambdaName,
135
- runtime: aws_cdk_lib_1.aws_lambda.Runtime.NODEJS_18_X,
136
- handler: 'handler',
137
- environment: lc.environment,
138
- memorySize: lc.memory,
139
- timeout: lc.timeout,
140
- description: '(cdk)',
141
- entry,
142
- reservedConcurrentExecutions: lc.reservedConcurrentExecutions,
143
- logRetention: aws_cdk_lib_1.aws_logs.RetentionDays.FIVE_DAYS,
144
- layers: lc.layers,
145
- });
146
- lc.readTables.forEach((t) => t.grantReadData(lambdaV));
147
- lc.writeTables.forEach((t) => t.grantReadWriteData(lambdaV));
148
- lc.policies.forEach((p1) => lambdaV.addToRolePolicy(p1));
149
- //
150
- apiPath.addMethod(verb.toUpperCase(), new aws_cdk_lib_1.aws_apigateway.LambdaIntegration(lambdaV, {}), { authorizer: lc.authorizer });
151
- });
152
- });
153
- Object.keys(lambdaConfig).forEach((k) => {
154
- if (!seenPermissions[k]) {
155
- (0, log_1.warn)(`unused permissions for '${k}', did you mean one of these paths?=`, Object.entries(seenPermissions)
156
- .filter(([, b]) => !b)
157
- .map(([f]) => f)
158
- .join('\n'));
159
- throw new Error('unused permissions!:' + k);
160
- }
161
- });
162
- };
163
- exports.openApiImpl = openApiImpl;
@@ -1,25 +0,0 @@
1
- import type { TLang } from '../../common/helpers/i18n';
2
- import type { User } from '../../ui/helpers/jwt';
3
- import type { APIGatewayEvent, APIGatewayProxyResult } from '../types';
4
- import type { TGetAndValidateToken } from './validations';
5
- export type NextType<T> = ({ event, body, params, userProfile, lang, }: {
6
- params: Record<string, string>;
7
- event: APIGatewayEvent;
8
- body: T;
9
- userProfile?: User;
10
- lang: TLang;
11
- }) => Promise<APIGatewayProxyResult>;
12
- export declare function validateOpenApi<T>({ event, next, authorized, schema, COGNITO_USER_POOL_ID, jwksRegion, getAndValidateTokenOverride, }: {
13
- getAndValidateTokenOverride?: TGetAndValidateToken;
14
- COGNITO_USER_POOL_ID: string;
15
- /** pass in openapi schema. eg require('common/openapi.generated').default; */
16
- schema: any;
17
- event: APIGatewayEvent;
18
- next: NextType<T>;
19
- /** default false */
20
- authorized?: true | false | 'optional';
21
- /**
22
- * default ap-southeast-2
23
- */
24
- jwksRegion?: string;
25
- }): Promise<APIGatewayProxyResult>;
@@ -1,127 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.validateOpenApi = validateOpenApi;
16
- const openapi_request_validator_1 = __importDefault(require("openapi-request-validator"));
17
- const i18n_1 = require("../../common/helpers/i18n");
18
- const log_1 = require("../../common/helpers/log");
19
- const object_1 = require("../../common/helpers/object");
20
- const api_1 = require("./api");
21
- const validations_1 = require("./validations");
22
- //
23
- const getOperation = ({ path, method, resource, schema, }) => {
24
- var _a;
25
- const resourcePath = Object.keys(schema.paths).find((rp) => rp === resource);
26
- if (!resourcePath) {
27
- throw new Error('incorrect path');
28
- }
29
- const operation = (_a = schema.paths[resourcePath]) === null || _a === void 0 ? void 0 : _a[method];
30
- if (!operation) {
31
- const msg = `no operation found for ${method}/${path}`;
32
- (0, log_1.warn)(`${msg} ${Object.keys(schema.paths)}`);
33
- throw new Error(msg);
34
- }
35
- /*
36
- var path= '/events/12345/topics/2216026039415263/like'
37
- var resourcePath ='/events/{eventCode}/topics/{topicId}/like'
38
- */
39
- const re = new RegExp(resourcePath
40
- .replace(/\//gim, `\\/`)
41
- .replace(/\{(.+?)\}/gim, '(?<$1>[^\\\\]+)'), 'i').exec(path);
42
- const pathParams = (re === null || re === void 0 ? void 0 : re.groups) && (0, object_1.copy)(re.groups);
43
- return { operation, pathParams };
44
- };
45
- function validateOpenApi(_a) {
46
- return __awaiter(this, arguments, void 0, function* ({ event, next, authorized, schema, COGNITO_USER_POOL_ID, jwksRegion = 'ap-southeast-2', getAndValidateTokenOverride, }) {
47
- var _b, _c, _d, _e, _f, _g, _h;
48
- if (!schema) {
49
- throw new Error('schema undefined!');
50
- }
51
- if (!COGNITO_USER_POOL_ID) {
52
- throw new Error('COGNITO_USER_POOL_ID undefined');
53
- }
54
- const request = {
55
- method: event.httpMethod,
56
- path: event.path,
57
- params: undefined,
58
- query: event.queryStringParameters,
59
- body: (0, object_1.tryJsonParse)(event.body, event.body),
60
- headers: (0, object_1.objectKeysToLowerCase)(event.headers),
61
- };
62
- const method = event.requestContext.httpMethod.toLowerCase();
63
- const pathParameters = (_b = event.pathParameters) !== null && _b !== void 0 ? _b : {};
64
- const queryStringParameters = (_c = event.queryStringParameters) !== null && _c !== void 0 ? _c : {};
65
- //
66
- const opm = getOperation({
67
- path: event.path,
68
- method,
69
- resource: event.resource,
70
- schema,
71
- });
72
- if (!opm.operation) {
73
- const msg = `no request handler found! for ${method} ${event.path} - cant validate`;
74
- (0, log_1.error)(msg);
75
- return (0, api_1.returnCode)(400, msg);
76
- }
77
- if (!opm.operation.requestBody && !opm.operation.parameters) {
78
- if (!!event.body || Object.keys(pathParameters).length > 0) {
79
- (0, log_1.warn)(`bad req, unexpected params`);
80
- return (0, api_1.returnCode)(400, 'bad data');
81
- }
82
- // no validation necessary
83
- }
84
- else {
85
- try {
86
- request.params = opm.pathParams;
87
- (0, log_1.debug)('req=', JSON.stringify(Object.assign(Object.assign({}, request), { body: ((_e = (_d = request.body) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0) > 2000
88
- ? '(truncating long body)'
89
- : request.body }), null, 2));
90
- const resp = new openapi_request_validator_1.default(Object.assign(Object.assign({}, opm.operation), { schemas: schema.components.schemas })).validateRequest(request);
91
- if (resp) {
92
- (0, log_1.warn)('bad request');
93
- (0, log_1.debug)('opm=', JSON.stringify(opm, null, 2));
94
- (0, log_1.debug)('resp=', JSON.stringify(resp, null, 2));
95
- return (0, api_1.returnCode)(400, `error:${(_g = (_f = resp === null || resp === void 0 ? void 0 : resp.errors) === null || _f === void 0 ? void 0 : _f[0]) === null || _g === void 0 ? void 0 : _g.message}`);
96
- }
97
- (0, log_1.debug)(`validated request:`, event.path);
98
- }
99
- catch (e) {
100
- (0, log_1.error)('e=', e, JSON.stringify(opm));
101
- }
102
- }
103
- let userProfile;
104
- let error;
105
- const authHeader = event.headers.Authorization || event.headers.authorization;
106
- if (authorized === true || (authorized === 'optional' && authHeader)) {
107
- const vf = getAndValidateTokenOverride !== null && getAndValidateTokenOverride !== void 0 ? getAndValidateTokenOverride : validations_1.getAndValidateToken;
108
- ({ error, userProfile } = yield vf({
109
- tokenRaw: authHeader,
110
- COGNITO_USER_POOL_ID,
111
- jwksRegion,
112
- }));
113
- if (error) {
114
- return error;
115
- }
116
- }
117
- const params = Object.assign(Object.assign({}, (pathParameters || {})), (queryStringParameters || {}));
118
- const res = yield next({
119
- params,
120
- event,
121
- body: (0, object_1.tryJsonParse)(event.body, event.body),
122
- userProfile,
123
- lang: (0, i18n_1.getValidatedLang)((_h = event.headers['x-lang']) !== null && _h !== void 0 ? _h : ''),
124
- });
125
- return res;
126
- });
127
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,42 +0,0 @@
1
- "use strict";
2
- const fs = require('fs');
3
- const process = require('process');
4
- const pathV = require('path');
5
- const cwd = process.cwd();
6
- const resolvePath = (p) => pathV.resolve(cwd, p);
7
- function run() {
8
- if (!fs.existsSync('./dist') || !fs.existsSync('./dist/api')) {
9
- console.log('no dist/api directory, cant run openapi postfix');
10
- return;
11
- }
12
- console.log('running openapi postfixes');
13
- const files = fs
14
- .readdirSync(resolvePath('./dist/api'))
15
- .filter((r) => r.endsWith('.js') || r.endsWith('.d.ts'))
16
- .map((s) => `./dist/api/${s}`)
17
- .filter(fs.existsSync)
18
- .map((file) => ({ file, content: fs.readFileSync(file).toString() }));
19
- let found = false;
20
- files.forEach(({ file, content }) => {
21
- if (content.includes('url_1')) {
22
- console.log('removing url_1 from ' + file);
23
- content = content.replace(/url_1\./gim, '');
24
- found = true;
25
- }
26
- if (content.includes('this.configuration.queryParamsStringify(')) {
27
- console.log('fixing queryparams default from ' + file);
28
- content = content.replace(/this.configuration.queryParamsStringify\(/gim, '(this.configuration.queryParamsStringify||querystring)(');
29
- found = true;
30
- }
31
- if (content.includes(`import("axios").`)) {
32
- console.log('fixing axios import from ' + file);
33
- content = content.replace(/import\("axios"\)\./gim, '');
34
- found = true;
35
- }
36
- fs.writeFileSync(file, content);
37
- });
38
- if (!found) {
39
- console.log('error: no files were fixed');
40
- }
41
- }
42
- run();
@@ -1 +0,0 @@
1
- export {};