ag-common 0.0.124 → 0.0.125

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.
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.openApiImpl = void 0;
4
4
  /* eslint-disable no-new */
5
5
  const aws_cdk_lib_1 = require("aws-cdk-lib");
6
- const __1 = require("../..");
7
6
  const array_1 = require("../../common/helpers/array");
8
7
  const log_1 = require("../../common/helpers/log");
9
8
  // eslint-disable-next-line
@@ -51,8 +50,8 @@ const setupLambda = ({ lambdaConfig, pathV, verb, seenPermissions, }) => {
51
50
  //
52
51
  const readTables = (0, array_1.distinctBy)([...(((_a = def === null || def === void 0 ? void 0 : def.dynamo) === null || _a === void 0 ? void 0 : _a.reads) || []), ...(((_b = lp === null || lp === void 0 ? void 0 : lp.dynamo) === null || _b === void 0 ? void 0 : _b.reads) || [])], (s) => s.shortName);
53
52
  const writeTables = (0, array_1.distinctBy)([...(((_c = def === null || def === void 0 ? void 0 : def.dynamo) === null || _c === void 0 ? void 0 : _c.writes) || []), ...(((_d = lp === null || lp === void 0 ? void 0 : lp.dynamo) === null || _d === void 0 ? void 0 : _d.writes) || [])], (s) => s.shortName);
54
- const policies = [...(def.policies || []), ...((lp === null || lp === void 0 ? void 0 : lp.policies) || [])].filter(__1.notEmpty);
55
- const layers = [...(def.layers || []), ...((lp === null || lp === void 0 ? void 0 : lp.layers) || [])].filter(__1.notEmpty);
53
+ const policies = [...(def.policies || []), ...((lp === null || lp === void 0 ? void 0 : lp.policies) || [])].filter(array_1.notEmpty);
54
+ const layers = [...(def.layers || []), ...((lp === null || lp === void 0 ? void 0 : lp.layers) || [])].filter(array_1.notEmpty);
56
55
  const env = Object.assign(Object.assign({}, (def.env || {})), ((lp === null || lp === void 0 ? void 0 : lp.env) || {}));
57
56
  const tables = [...readTables, ...writeTables];
58
57
  const environment = env;
@@ -1,7 +1,10 @@
1
- export declare const Chevron: ({ down, width, className, colour, onToggle, }: {
1
+ export declare const Chevron: ({ width, className, colour, onToggle, point, }: {
2
+ /**
3
+ * default right
4
+ */
5
+ point: 'up' | 'down' | 'left' | 'right';
2
6
  colour?: string | undefined;
3
7
  className?: string | undefined;
4
8
  width?: string | undefined;
5
- down: boolean;
6
9
  onToggle?: (() => void) | undefined;
7
10
  }) => JSX.Element;
@@ -20,6 +20,26 @@ const IconStyled = (0, styled_components_1.default)(Icon_1.Icon) `
20
20
  `;
21
21
  const ChevronIcon = (react_1.default.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 -256 1792 1792" },
22
22
  react_1.default.createElement("path", { d: "M1679.339 301.56q0 53-37 90l-651 651q-38 38-91 38-54 0-90-38l-651-651q-38-36-38-90 0-53 38-91l74-75q39-37 91-37 53 0 90 37l486 486 486-486q37-37 90-37 52 0 91 37l75 75q37 39 37 91z" })));
23
- const Chevron = ({ down, width = '1.2rem', className, colour = 'black', onToggle, }) => (react_1.default.createElement(SChevron, { className: className, onClick: () => onToggle === null || onToggle === void 0 ? void 0 : onToggle(), onTouchStart: () => onToggle === null || onToggle === void 0 ? void 0 : onToggle(), onKeyPress: (e) => e.key === 'Enter' && (onToggle === null || onToggle === void 0 ? void 0 : onToggle()) },
24
- react_1.default.createElement(IconStyled, { flip: down, fill: colour, width: width, height: width }, ChevronIcon)));
23
+ const Chevron = ({ width = '1.2rem', className, colour = 'black', onToggle, point = 'right', }) => {
24
+ let rotate = 0;
25
+ switch (point) {
26
+ case 'down': {
27
+ rotate = 180;
28
+ break;
29
+ }
30
+ case 'left': {
31
+ rotate = 270;
32
+ break;
33
+ }
34
+ case 'up': {
35
+ rotate = 0;
36
+ break;
37
+ }
38
+ case 'right': {
39
+ rotate = 90;
40
+ }
41
+ }
42
+ return (react_1.default.createElement(SChevron, { className: className, onClick: () => onToggle === null || onToggle === void 0 ? void 0 : onToggle(), onTouchStart: () => onToggle === null || onToggle === void 0 ? void 0 : onToggle(), onKeyPress: (e) => e.key === 'Enter' && (onToggle === null || onToggle === void 0 ? void 0 : onToggle()) },
43
+ react_1.default.createElement(IconStyled, { rotate: rotate, fill: colour, width: width, height: width }, ChevronIcon)));
44
+ };
25
45
  exports.Chevron = Chevron;
@@ -5,7 +5,7 @@ interface IIcon {
5
5
  outline?: string;
6
6
  width?: string;
7
7
  height?: string;
8
- flip?: boolean;
8
+ rotate?: number;
9
9
  canHover?: boolean;
10
10
  margin?: string;
11
11
  padding?: string;
@@ -69,9 +69,9 @@ exports.IconF = styled_components_1.default.span `
69
69
 
70
70
  width: ${({ width }) => width || '100%'};
71
71
  height: ${({ height }) => height || '100%'};
72
- ${({ flip }) => flip &&
72
+ ${({ rotate }) => rotate &&
73
73
  (0, styled_components_1.css) `
74
- transform: rotate(180deg);
74
+ transform: rotate(${rotate}deg);
75
75
  `};
76
76
 
77
77
  svg {
@@ -85,7 +85,7 @@ const PromptModal = ({ wrapper, res, bottomText, topText, okText = 'OK', cancelT
85
85
  react_1.default.createElement(Content, null,
86
86
  topText && react_1.default.createElement(TopText, null, topText),
87
87
  react_1.default.createElement(BottomText, null, bottomText),
88
- react_1.default.createElement(TextInput_1.TextInput, { value: text, onChange: (c) => setText(c), placeholder: placeholder, focus: true }),
88
+ react_1.default.createElement(TextInput_1.TextInput, { value: text, onChange: (c) => setText(c), placeholder: placeholder, focus: true, onKeyPress: (e) => e.key === 'Enter' && ret(text) }),
89
89
  react_1.default.createElement(Bottom, { noGrow: true },
90
90
  react_1.default.createElement(Button_1.Button, { onClick: () => ret(text) }, okText),
91
91
  react_1.default.createElement(Button_1.Button, { invert: true, onClick: () => ret(undefined) }, cancelText))))));
@@ -0,0 +1,28 @@
1
+ import { ICallOpenApi } from './types';
2
+ import { CacheItems } from '../routes';
3
+ import { AxiosWrapperLite } from '../jwt';
4
+ export declare type TCallOpenApiCached<T, TDefaultApi> = ICallOpenApi<T, TDefaultApi> & {
5
+ /**
6
+ * if falsey, will run callOpenApi directly
7
+ */
8
+ cacheKey: string;
9
+ /**
10
+ * will shortcut and return the appropriate axioswrapper data if cachekey is found
11
+ */
12
+ ssrCacheItems?: CacheItems;
13
+ /**
14
+ * default ttl in seconds for cache - default 120s
15
+ */
16
+ cacheTtl?: number;
17
+ /**
18
+ * (ssr) if true, wont run callopenapi if data is not cached
19
+ */
20
+ onlyCached?: boolean;
21
+ };
22
+ /**
23
+ * sync call to callOpenApiCache.
24
+ * @param p
25
+ * @returns undefined if no cache item
26
+ */
27
+ export declare const callOpenApiCachedRaw: <T, TDefaultApi>(p: TCallOpenApiCached<T, TDefaultApi>) => AxiosWrapperLite<T> | undefined;
28
+ export declare const callOpenApiCached: <T, TDefaultApi>(p: TCallOpenApiCached<T, TDefaultApi>) => Promise<AxiosWrapperLite<T>>;
@@ -0,0 +1,72 @@
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.callOpenApiCached = exports.callOpenApiCachedRaw = void 0;
16
+ const cookie_1 = require("../cookie");
17
+ const node_cache_1 = __importDefault(require("node-cache"));
18
+ const direct_1 = require("./direct");
19
+ const string_1 = require("../../../common/helpers/string");
20
+ let callOpenApiCache;
21
+ function getCacheKey({ cacheKey, overrideAuth, }) {
22
+ const authkeyPrefix = (overrideAuth === null || overrideAuth === void 0 ? void 0 : overrideAuth.id_token) || (0, cookie_1.getCookieWrapper)({ cname: 'id_token' });
23
+ let cacheKeyRet;
24
+ if (cacheKey) {
25
+ const pref = !authkeyPrefix ? '' : (0, string_1.toBase64)(authkeyPrefix);
26
+ cacheKeyRet = cacheKey + '||' + pref;
27
+ }
28
+ return cacheKeyRet;
29
+ }
30
+ /**
31
+ * sync call to callOpenApiCache.
32
+ * @param p
33
+ * @returns undefined if no cache item
34
+ */
35
+ const callOpenApiCachedRaw = (p) => {
36
+ var _a, _b, _c;
37
+ const userPrefixedCacheKey = getCacheKey(p);
38
+ if (!userPrefixedCacheKey) {
39
+ return undefined;
40
+ }
41
+ if (!callOpenApiCache) {
42
+ callOpenApiCache = new node_cache_1.default({ stdTTL: p.cacheTtl || 120 });
43
+ }
44
+ const ssrCached = (_a = p.ssrCacheItems) === null || _a === void 0 ? void 0 : _a.find((s) => s.cacheKey === p.cacheKey);
45
+ if (!callOpenApiCache.get(userPrefixedCacheKey) &&
46
+ ((_b = ssrCached === null || ssrCached === void 0 ? void 0 : ssrCached.prefillData) === null || _b === void 0 ? void 0 : _b.data)) {
47
+ callOpenApiCache.set(userPrefixedCacheKey, (_c = ssrCached.prefillData) === null || _c === void 0 ? void 0 : _c.data);
48
+ }
49
+ const cached = callOpenApiCache.get(userPrefixedCacheKey);
50
+ if (cached) {
51
+ return { data: cached };
52
+ }
53
+ return undefined;
54
+ };
55
+ exports.callOpenApiCachedRaw = callOpenApiCachedRaw;
56
+ const callOpenApiCached = (p) => __awaiter(void 0, void 0, void 0, function* () {
57
+ const raw = (0, exports.callOpenApiCachedRaw)(p);
58
+ if (raw) {
59
+ return raw;
60
+ }
61
+ const resp = yield (0, direct_1.callOpenApi)(p);
62
+ if (resp.error) {
63
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
64
+ return { error: resp.error, data: undefined };
65
+ }
66
+ const userPrefixedCacheKey = getCacheKey(p);
67
+ if (callOpenApiCache && userPrefixedCacheKey) {
68
+ callOpenApiCache.set(userPrefixedCacheKey, resp.data);
69
+ }
70
+ return resp;
71
+ });
72
+ exports.callOpenApiCached = callOpenApiCached;
@@ -1,3 +1,3 @@
1
- import { AxiosWrapper } from './jwt';
2
1
  import { ICallOpenApi } from './types';
3
- export declare const callOpenApi: <T, TDefaultApi>({ func, apiUrl, overrideAuth, refreshToken, logout, newDefaultApi, headers, }: ICallOpenApi<T, TDefaultApi>) => Promise<AxiosWrapper<T>>;
2
+ import { AxiosWrapperLite } from '../jwt';
3
+ export declare const callOpenApi: <T, TDefaultApi>({ func, apiUrl, overrideAuth, refreshToken, logout, newDefaultApi, headers, }: ICallOpenApi<T, TDefaultApi>) => Promise<AxiosWrapperLite<T>>;
@@ -10,9 +10,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.callOpenApi = void 0;
13
- const cookie_1 = require("./cookie");
14
- const sleep_1 = require("../../common/helpers/sleep");
15
- const array_1 = require("../../common/helpers/array");
13
+ const cookie_1 = require("../cookie");
14
+ const sleep_1 = require("../../../common/helpers/sleep");
15
+ const array_1 = require("../../../common/helpers/array");
16
16
  const callOpenApi = ({ func, apiUrl, overrideAuth, refreshToken, logout, newDefaultApi, headers, }) => __awaiter(void 0, void 0, void 0, function* () {
17
17
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
18
18
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -22,14 +22,16 @@ const callOpenApi = ({ func, apiUrl, overrideAuth, refreshToken, logout, newDefa
22
22
  basePath: apiUrl,
23
23
  baseOptions: { headers: Object.assign({ authorization: '' }, (headers || {})) },
24
24
  };
25
- const isAuthed = !!(0, cookie_1.getCookieWrapper)({ cname: 'id_token' });
26
25
  if (overrideAuth === null || overrideAuth === void 0 ? void 0 : overrideAuth.id_token) {
27
26
  config.baseOptions.headers.authorization = `Bearer ${overrideAuth === null || overrideAuth === void 0 ? void 0 : overrideAuth.id_token}`;
28
27
  }
29
- else if (isAuthed) {
30
- const updated = yield refreshToken();
31
- if ((_a = updated === null || updated === void 0 ? void 0 : updated.jwt) === null || _a === void 0 ? void 0 : _a.id_token) {
32
- config.baseOptions.headers.authorization = `Bearer ${(_b = updated === null || updated === void 0 ? void 0 : updated.jwt) === null || _b === void 0 ? void 0 : _b.id_token}`;
28
+ else {
29
+ const isAuthed = !!(0, cookie_1.getCookieWrapper)({ cname: 'id_token' });
30
+ if (isAuthed) {
31
+ const updated = yield refreshToken();
32
+ if ((_a = updated === null || updated === void 0 ? void 0 : updated.jwt) === null || _a === void 0 ? void 0 : _a.id_token) {
33
+ config.baseOptions.headers.authorization = `Bearer ${(_b = updated === null || updated === void 0 ? void 0 : updated.jwt) === null || _b === void 0 ? void 0 : _b.id_token}`;
34
+ }
33
35
  }
34
36
  }
35
37
  const cl = newDefaultApi(config);
@@ -65,10 +67,6 @@ const callOpenApi = ({ func, apiUrl, overrideAuth, refreshToken, logout, newDefa
65
67
  return {
66
68
  error: ae,
67
69
  data: undefined,
68
- datetime: new Date().getTime(),
69
- loading: false,
70
- reFetch: () => __awaiter(void 0, void 0, void 0, function* () { }),
71
- url: func.toString(),
72
70
  };
73
71
  }
74
72
  if (status !== 500 || errorCount === errorMax) {
@@ -79,6 +77,6 @@ const callOpenApi = ({ func, apiUrl, overrideAuth, refreshToken, logout, newDefa
79
77
  // eslint-disable-next-line no-await-in-loop
80
78
  yield (0, sleep_1.sleep)(2000);
81
79
  }
82
- return Object.assign(Object.assign({ data }, (error && { error })), { loading: false, reFetch: () => __awaiter(void 0, void 0, void 0, function* () { return func(cl); }), url: func.toString(), datetime: new Date().getTime() });
80
+ return Object.assign({ data }, (error && { error }));
83
81
  });
84
82
  exports.callOpenApi = callOpenApi;
@@ -1,10 +1,15 @@
1
- import { AxiosWrapper } from './jwt';
1
+ import { AxiosWrapper } from '../jwt';
2
2
  import { ICallOpenApi } from './types';
3
- import { CacheItems } from './routes';
3
+ import { CacheItems } from '../routes';
4
4
  declare type AxiosWrapperWrap<T> = AxiosWrapper<T | undefined> & {
5
5
  loaded: boolean;
6
6
  loadcount: number;
7
7
  };
8
+ /**
9
+ * hooks+cached call to callOpenApi
10
+ * @param p
11
+ * @returns
12
+ */
8
13
  export declare const useCallOpenApi: <T, TDefaultApi>(p: ICallOpenApi<T, TDefaultApi> & {
9
14
  cacheKey: string;
10
15
  /**
@@ -8,24 +8,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
11
  Object.defineProperty(exports, "__esModule", { value: true });
15
12
  exports.useCallOpenApi = void 0;
16
13
  const react_1 = require("react");
17
- const callOpenApi_1 = require("./callOpenApi");
18
- const node_cache_1 = __importDefault(require("node-cache"));
19
- let useCallOpenApiCache;
14
+ const cached_1 = require("./cached");
15
+ /**
16
+ * hooks+cached call to callOpenApi
17
+ * @param p
18
+ * @returns
19
+ */
20
20
  const useCallOpenApi = (p) => {
21
21
  var _a;
22
- if (!useCallOpenApiCache) {
23
- useCallOpenApiCache = new node_cache_1.default({ stdTTL: p.cacheTtl || 120 });
24
- }
25
- const ssrCached = (_a = p.ssrCacheItems) === null || _a === void 0 ? void 0 : _a.find((s) => s.cacheKey === p.cacheKey);
26
- if (!useCallOpenApiCache.get(p.cacheKey) && ssrCached) {
27
- useCallOpenApiCache.set(p.cacheKey, ssrCached);
28
- }
29
22
  const defv = {
30
23
  data: undefined,
31
24
  url: '',
@@ -35,16 +28,13 @@ const useCallOpenApi = (p) => {
35
28
  loaded: false,
36
29
  reFetch: () => __awaiter(void 0, void 0, void 0, function* () { }),
37
30
  };
38
- const cached = useCallOpenApiCache.get(p.cacheKey);
39
- const [data, setData] = (0, react_1.useState)(Object.assign(Object.assign({}, defv), { data: cached, loaded: !!cached }));
31
+ const cachedData = (_a = (0, cached_1.callOpenApiCachedRaw)(Object.assign(Object.assign({}, p), { onlyCached: true }))) === null || _a === void 0 ? void 0 : _a.data;
32
+ const [data, setData] = (0, react_1.useState)(Object.assign(Object.assign(Object.assign({}, defv), (cachedData && { data: cachedData })), { loaded: !!cachedData }));
40
33
  (0, react_1.useEffect)(() => {
41
34
  function run() {
42
35
  return __awaiter(this, void 0, void 0, function* () {
43
- const resp = yield (0, callOpenApi_1.callOpenApi)(p);
44
- if (useCallOpenApiCache) {
45
- useCallOpenApiCache.set(p.cacheKey, resp.data);
46
- }
47
- setData((d) => (Object.assign(Object.assign({}, resp), { loaded: true, loading: false, loadcount: d.loadcount + 1 })));
36
+ const resp = yield (0, cached_1.callOpenApiCached)(p);
37
+ setData((d) => (Object.assign(Object.assign({}, resp), { loaded: true, loading: false, loadcount: d.loadcount + 1, reFetch: () => __awaiter(this, void 0, void 0, function* () { }), url: '', datetime: new Date().getTime() })));
48
38
  });
49
39
  }
50
40
  const { error, loaded, loading, loadcount } = data;
@@ -54,7 +44,7 @@ const useCallOpenApi = (p) => {
54
44
  }
55
45
  setData((d) => (Object.assign(Object.assign({}, d), { loading: true })));
56
46
  void run();
57
- }, [cached, data, p, setData]);
47
+ }, [data, p, setData]);
58
48
  return Object.assign(Object.assign({}, data), { reFetch: () => __awaiter(void 0, void 0, void 0, function* () {
59
49
  setData(defv);
60
50
  }) });
@@ -0,0 +1,4 @@
1
+ export * from './direct';
2
+ export * from './cached';
3
+ export * from './hook';
4
+ export * from './types';
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ __exportStar(require("./direct"), exports);
14
+ __exportStar(require("./cached"), exports);
15
+ __exportStar(require("./hook"), exports);
16
+ __exportStar(require("./types"), exports);
@@ -1,5 +1,5 @@
1
1
  import { AxiosResponse } from 'axios';
2
- import { User } from './jwt';
2
+ import { User } from '../jwt';
3
3
  export interface OverrideAuth {
4
4
  id_token?: string;
5
5
  }
@@ -9,17 +9,12 @@ export * from './dom';
9
9
  export * from './extractAttributes';
10
10
  export * from './jwt';
11
11
  export * from './lang';
12
- export * from './mutex';
13
- export * from './mutexData';
14
12
  export * from './plural';
15
13
  export * from './routes';
16
- export * from './types';
17
- export * from './useCallOpenApi';
18
14
  export * from './useContextMenu';
19
15
  export * from './useLocalStorage';
20
16
  export * from './useLockBodyScroll';
21
17
  export * from './useOnClickOutside';
22
18
  export * from './useOnScroll';
23
- export * from './useOpenApiStore';
24
19
  export * from './useQueryString';
25
20
  export * from './useResize';
@@ -21,17 +21,12 @@ __exportStar(require("./dom"), exports);
21
21
  __exportStar(require("./extractAttributes"), exports);
22
22
  __exportStar(require("./jwt"), exports);
23
23
  __exportStar(require("./lang"), exports);
24
- __exportStar(require("./mutex"), exports);
25
- __exportStar(require("./mutexData"), exports);
26
24
  __exportStar(require("./plural"), exports);
27
25
  __exportStar(require("./routes"), exports);
28
- __exportStar(require("./types"), exports);
29
- __exportStar(require("./useCallOpenApi"), exports);
30
26
  __exportStar(require("./useContextMenu"), exports);
31
27
  __exportStar(require("./useLocalStorage"), exports);
32
28
  __exportStar(require("./useLockBodyScroll"), exports);
33
29
  __exportStar(require("./useOnClickOutside"), exports);
34
30
  __exportStar(require("./useOnScroll"), exports);
35
- __exportStar(require("./useOpenApiStore"), exports);
36
31
  __exportStar(require("./useQueryString"), exports);
37
32
  __exportStar(require("./useResize"), exports);
@@ -57,6 +57,10 @@ export interface AxiosWrapper<T> {
57
57
  url: string;
58
58
  datetime: number;
59
59
  }
60
+ export interface AxiosWrapperLite<T> {
61
+ data: T;
62
+ error?: AxiosError;
63
+ }
60
64
  export interface AuthedUserContext {
61
65
  loading: boolean;
62
66
  isAuthenticated: boolean;
@@ -1,6 +1,6 @@
1
1
  import { TLang } from '../../common/helpers/i18n';
2
2
  import { ICognitoAuth } from './cognito';
3
- import { AxiosWrapper } from './jwt';
3
+ import { AxiosWrapperLite } from './jwt';
4
4
  export interface LocationSubset {
5
5
  pathname: string;
6
6
  hash: string;
@@ -11,7 +11,7 @@ export interface LocationSubset {
11
11
  export declare type CacheItems = CacheItem<any>[];
12
12
  export interface CacheItem<T> {
13
13
  cacheKey: string;
14
- prefillData: AxiosWrapper<T>;
14
+ prefillData: AxiosWrapperLite<T>;
15
15
  ttlSeconds: number;
16
16
  }
17
17
  export interface IInitialStateCommon {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ag-common",
3
- "version": "0.0.124",
3
+ "version": "0.0.125",
4
4
  "main": "./dist/index.js",
5
5
  "types": "./dist/index.d.ts",
6
6
  "author": "Andrei Gec <@andreigec> (https://gec.dev/)",
@@ -1,22 +0,0 @@
1
- export interface IMutex {
2
- capture(key: string): Promise<() => void>;
3
- isLocked: (key: string) => boolean;
4
- }
5
- export interface IMutexOptions {
6
- intervalMs?: number;
7
- autoUnlockTimeoutMs?: number;
8
- Promise?: PromiseConstructor;
9
- }
10
- declare type TResolve = (value: (() => void) | PromiseLike<() => void>) => void;
11
- declare type TReject = (reason?: string) => void;
12
- export declare class Mutex implements IMutex {
13
- static defaultIntervalMs: number;
14
- static defaultAutoUnlockTimeoutMs: number;
15
- protected storage: Record<string, number>;
16
- protected options: IMutexOptions;
17
- constructor(options?: IMutexOptions);
18
- capture(key: string): Promise<() => void>;
19
- isLocked: (key: string) => boolean;
20
- protected checkMutexAndLock(key: string, resolve: TResolve, reject: TReject): void;
21
- }
22
- export {};
@@ -1,53 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Mutex = void 0;
4
- let setTimeout;
5
- let clearTimeout;
6
- if (typeof global !== 'undefined') {
7
- setTimeout = global.setTimeout;
8
- clearTimeout = global.clearTimeout;
9
- }
10
- else {
11
- setTimeout = window.setTimeout;
12
- clearTimeout = window.clearTimeout;
13
- }
14
- class Mutex {
15
- constructor(options = {}) {
16
- this.storage = {};
17
- this.options = {};
18
- this.isLocked = (key) => !!this.storage[key];
19
- this.options = {
20
- Promise: options.Promise || Promise,
21
- intervalMs: (options && options.intervalMs) || Mutex.defaultIntervalMs,
22
- autoUnlockTimeoutMs: (options && options.autoUnlockTimeoutMs) ||
23
- Mutex.defaultAutoUnlockTimeoutMs,
24
- };
25
- }
26
- capture(key) {
27
- const P = this.options.Promise || Promise;
28
- return new P((resolve, reject) => {
29
- this.checkMutexAndLock(key, resolve, reject);
30
- });
31
- }
32
- checkMutexAndLock(key, resolve, reject) {
33
- if (!this.storage[key]) {
34
- const value = Date.now();
35
- this.storage[key] = value;
36
- const timeout = setTimeout(() => {
37
- delete this.storage[key];
38
- }, this.options.autoUnlockTimeoutMs);
39
- resolve(() => {
40
- clearTimeout(timeout);
41
- if (this.storage[key] === value) {
42
- delete this.storage[key];
43
- }
44
- });
45
- }
46
- else {
47
- setTimeout(this.checkMutexAndLock.bind(this, key, resolve, reject), this.options.intervalMs);
48
- }
49
- }
50
- }
51
- exports.Mutex = Mutex;
52
- Mutex.defaultIntervalMs = 50;
53
- Mutex.defaultAutoUnlockTimeoutMs = 3000;
@@ -1,17 +0,0 @@
1
- export declare class MutexData<T> {
2
- subscriptions: {
3
- [a: string]: {
4
- [subId: string]: (ts: number) => void;
5
- };
6
- };
7
- subscribe(key: string, subId: string, func: (ts: number) => void): void;
8
- unsubscribe(key: string, subId: string): void;
9
- getData(key: string): T;
10
- pingSubscribers(key: string): void;
11
- setData({ ttlSeconds, key, data, }: {
12
- key: string;
13
- data: T;
14
- ttlSeconds?: number;
15
- }): void;
16
- delete(key: string, updateSubscribers?: boolean): void;
17
- }
@@ -1,55 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MutexData = void 0;
4
- /* eslint-disable class-methods-use-this */
5
- const _1 = require(".");
6
- const log_1 = require("../../common/helpers/log");
7
- const useLocalStorage_1 = require("./useLocalStorage");
8
- class MutexData {
9
- constructor() {
10
- this.subscriptions = {};
11
- }
12
- subscribe(key, subId, func) {
13
- if (!this.subscriptions[key]) {
14
- this.subscriptions[key] = { [subId]: func };
15
- }
16
- this.subscriptions[key][subId] = func;
17
- }
18
- unsubscribe(key, subId) {
19
- delete this.subscriptions[key][subId];
20
- }
21
- getData(key) {
22
- return (0, useLocalStorage_1.getLocalStorageItem)(`mutex-${key}`, undefined, 3600);
23
- }
24
- pingSubscribers(key) {
25
- if (!this.subscriptions[key]) {
26
- (0, log_1.debug)('no subscribers');
27
- return;
28
- }
29
- Object.keys(this.subscriptions[key]).forEach((subKey) => {
30
- const ts = new Date().getTime();
31
- if (!this.subscriptions[key][subKey] ||
32
- typeof this.subscriptions[key][subKey] !== 'function') {
33
- this.unsubscribe(key, subKey);
34
- }
35
- else {
36
- this.subscriptions[key][subKey](ts);
37
- }
38
- });
39
- }
40
- setData({ ttlSeconds = 3600, key, data, }) {
41
- (0, useLocalStorage_1.setLocalStorageItem)(`mutex-${key}`, data, ttlSeconds);
42
- if (Object.keys(this.subscriptions).length > 0) {
43
- this.pingSubscribers(key);
44
- }
45
- }
46
- delete(key, updateSubscribers = false) {
47
- (0, _1.clearLocalStorageItem)(`mutex-${key}`);
48
- if (updateSubscribers) {
49
- if (Object.keys(this.subscriptions).length > 0) {
50
- this.pingSubscribers(key);
51
- }
52
- }
53
- }
54
- }
55
- exports.MutexData = MutexData;
@@ -1,24 +0,0 @@
1
- import { CacheItems } from './routes';
2
- import { AxiosWrapper } from './jwt';
3
- import { ICallOpenApi } from './types';
4
- export declare const deleteMutexData: (key: string) => void;
5
- export declare const setMutexData: ({ key, data, ttlSeconds, }: {
6
- key: string;
7
- data: any;
8
- ttlSeconds: number;
9
- }) => void;
10
- export declare const getMutexData: <T>(key: string) => AxiosWrapper<T>;
11
- /**
12
- *
13
- * @param overrideAuth - auth automatically picked up from id_token cookie, can override value here, but not required
14
- * @returns
15
- */
16
- export declare const useOpenApiStore: <T, TDefaultApi>(p: ICallOpenApi<T, TDefaultApi> & {
17
- ttlSeconds?: number | undefined;
18
- cacheKey: string;
19
- /**
20
- * will shortcut and return the appropriate axioswrapper data if cachekey is found
21
- */
22
- ssrCacheItems?: CacheItems | undefined;
23
- }) => AxiosWrapper<T>;
24
- export declare const setOpenApiCache: (items: CacheItems) => void;
@@ -1,147 +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
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.setOpenApiCache = exports.useOpenApiStore = exports.getMutexData = exports.setMutexData = exports.deleteMutexData = void 0;
13
- const react_1 = require("react");
14
- const mutex_1 = require("./mutex");
15
- const mutexData_1 = require("./mutexData");
16
- const callOpenApi_1 = require("./callOpenApi");
17
- const log_1 = require("../../common/helpers/log");
18
- const mutex = new mutex_1.Mutex({
19
- autoUnlockTimeoutMs: 10000,
20
- intervalMs: 100,
21
- Promise: Promise,
22
- });
23
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
24
- const mutexData = new mutexData_1.MutexData();
25
- const deleteMutexData = (key) => mutexData.delete(key);
26
- exports.deleteMutexData = deleteMutexData;
27
- const setMutexData = ({ key, data, ttlSeconds = 3600, }) => {
28
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
29
- const wrap = {
30
- data,
31
- loading: false,
32
- reFetch: () => __awaiter(void 0, void 0, void 0, function* () {
33
- (0, log_1.info)('mocked');
34
- }),
35
- datetime: new Date().getTime(),
36
- error: undefined,
37
- url: '',
38
- };
39
- mutexData.setData({ key, data: wrap, ttlSeconds });
40
- };
41
- exports.setMutexData = setMutexData;
42
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
43
- const getMutexData = (key) => mutexData.getData(key);
44
- exports.getMutexData = getMutexData;
45
- function mLock(p) {
46
- return __awaiter(this, void 0, void 0, function* () {
47
- let unlock;
48
- try {
49
- unlock = yield mutex.capture(p.key);
50
- if (mutexData.getData(p.key)) {
51
- return;
52
- }
53
- const newData = yield (0, callOpenApi_1.callOpenApi)(p);
54
- if (!newData) {
55
- return;
56
- }
57
- if (newData.error) {
58
- (0, log_1.error)('api error:', newData.error);
59
- }
60
- else {
61
- mutexData.setData({
62
- key: p.key,
63
- data: newData,
64
- ttlSeconds: p.ttlSeconds,
65
- });
66
- }
67
- mutexData.pingSubscribers(p.key);
68
- }
69
- catch (e) {
70
- (0, log_1.error)('mutex error:', e);
71
- }
72
- finally {
73
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
74
- // @ts-ignore
75
- if (unlock) {
76
- unlock();
77
- }
78
- }
79
- });
80
- }
81
- const getTs = () => new Date().getTime();
82
- /**
83
- *
84
- * @param overrideAuth - auth automatically picked up from id_token cookie, can override value here, but not required
85
- * @returns
86
- */
87
- const useOpenApiStore = (p) => {
88
- var _a;
89
- const { cacheKey, disabled } = p;
90
- if (!cacheKey) {
91
- throw new Error('no cache key');
92
- }
93
- const [key, setKey] = (0, react_1.useState)(cacheKey);
94
- (0, react_1.useEffect)(() => {
95
- setKey(cacheKey);
96
- }, [cacheKey]);
97
- const [, setTs] = (0, react_1.useState)(0);
98
- (0, react_1.useEffect)(() => {
99
- const myHash = getTs().toString();
100
- mutexData.subscribe(key, myHash, setTs);
101
- return () => mutexData.unsubscribe(key, myHash);
102
- }, [key]);
103
- (0, react_1.useEffect)(() => {
104
- if (!disabled && !mutexData.getData(key)) {
105
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
106
- mLock(Object.assign({ key }, p));
107
- }
108
- }, [disabled, key, p]);
109
- if (disabled) {
110
- return {
111
- loading: false,
112
- error: undefined,
113
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
114
- data: undefined,
115
- datetime: new Date().getTime(),
116
- reFetch: () => __awaiter(void 0, void 0, void 0, function* () { }),
117
- url: '',
118
- };
119
- }
120
- const ssrCached = (_a = p.ssrCacheItems) === null || _a === void 0 ? void 0 : _a.find((s) => s.cacheKey === cacheKey);
121
- if (typeof window === 'undefined' && ssrCached) {
122
- return ssrCached.prefillData;
123
- }
124
- const current = mutexData.getData(key);
125
- if (!current) {
126
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
127
- return { loading: true };
128
- }
129
- return Object.assign(Object.assign({}, current), { reFetch: () => __awaiter(void 0, void 0, void 0, function* () {
130
- mutexData.setData({
131
- key,
132
- data: Object.assign(Object.assign({}, current), { loading: true }),
133
- ttlSeconds: p.ttlSeconds,
134
- });
135
- mutexData.pingSubscribers(key);
136
- const newData = yield (0, callOpenApi_1.callOpenApi)(p);
137
- mutexData.setData({ key, data: newData, ttlSeconds: p.ttlSeconds });
138
- mutexData.pingSubscribers(key);
139
- }) });
140
- };
141
- exports.useOpenApiStore = useOpenApiStore;
142
- const setOpenApiCache = (items) => {
143
- items.forEach(({ cacheKey, prefillData, ttlSeconds }) => {
144
- mutexData.setData({ key: cacheKey, data: prefillData, ttlSeconds });
145
- });
146
- };
147
- exports.setOpenApiCache = setOpenApiCache;