ag-common 0.0.7 → 0.0.11

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.
@@ -28,7 +28,7 @@ const putDynamo = (item, tableName) => __awaiter(void 0, void 0, void 0, functio
28
28
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
29
29
  Item: item,
30
30
  };
31
- (0, log_1.info)(`running dynamo put=${JSON.stringify(params)}`);
31
+ (0, log_1.info)(`running dynamo put=${JSON.stringify(params, null, 2)}`);
32
32
  // write the todo to the database
33
33
  const put = yield exports.dynamoDb.put(params).promise();
34
34
  if (put.$response.error &&
@@ -138,7 +138,7 @@ const getItemDynamo = ({ tableName, pkName, pkValue, }) => __awaiter(void 0, voi
138
138
  try {
139
139
  const res = yield exports.dynamoDb.get(params).promise();
140
140
  const ret = res.Item;
141
- (0, log_1.debug)(`got dynamo getitem=${JSON.stringify(params)}`);
141
+ (0, log_1.debug)(`got dynamo getitem=${JSON.stringify(params, null, 2)}`);
142
142
  return ret;
143
143
  }
144
144
  catch (e) {
@@ -158,14 +158,19 @@ const getItemsDynamo = ({ tableName, items, }) => __awaiter(void 0, void 0, void
158
158
  },
159
159
  },
160
160
  };
161
+ const dbRaw = new aws_sdk_1.default.DynamoDB({ apiVersion: '2012-10-08' });
161
162
  try {
162
- const res = yield exports.dynamoDb.batchGet(params).promise();
163
- (0, log_1.debug)(`got dynamo getitems=${JSON.stringify(res)}`);
164
- let ret = ((_f = (_e = res.Responses) === null || _e === void 0 ? void 0 : _e[tableName]) === null || _f === void 0 ? void 0 : _f.map((s) => s)) || [];
163
+ const res = yield dbRaw.batchGetItem(params).promise();
164
+ (0, log_1.debug)(`got dynamo getitems=${JSON.stringify(res, null, 2)}`);
165
+ let ret = ((_f = (_e = res.Responses) === null || _e === void 0 ? void 0 : _e[tableName]) === null || _f === void 0 ? void 0 : _f.map((s) => aws_sdk_1.default.DynamoDB.Converter.unmarshall(s))) || [];
165
166
  return ret;
166
167
  }
167
168
  catch (e) {
168
- (0, log_1.error)(e);
169
+ let msg = `error with getitems query:` +
170
+ JSON.stringify(params, null, 2) +
171
+ '\n' +
172
+ e.toString();
173
+ (0, log_1.error)(msg);
169
174
  throw e;
170
175
  }
171
176
  });
@@ -68,12 +68,12 @@ const getAndValidateToken = ({ tokenRaw, COGNITO_USER_POOL_ID, }) => __awaiter(v
68
68
  error: (0, api_1.returnCode)(403, 'auth failed'),
69
69
  };
70
70
  }
71
- token = tokenRaw.substr(tokenRaw.indexOf(' ') + 1);
71
+ token = tokenRaw.substring(tokenRaw.indexOf(' ') + 1);
72
72
  let subject;
73
73
  try {
74
74
  yield jwtVerify({ token, COGNITO_USER_POOL_ID });
75
75
  const decoded = (0, jsonwebtoken_1.decode)(token);
76
- (0, log_1.debug)(`decoded=${JSON.stringify(decoded)}`);
76
+ (0, log_1.debug)(`decoded=${JSON.stringify(decoded, null, 2)}`);
77
77
  subject = decoded === null || decoded === void 0 ? void 0 : decoded.sub;
78
78
  if (!subject) {
79
79
  const mess = 'user should have responded with subject (sub) field';
@@ -27,10 +27,8 @@ const chunk = (array, max) => {
27
27
  let row = [];
28
28
  for (const k in array) {
29
29
  const item = array[k];
30
- if (row.length < max) {
31
- row = [...row, item];
32
- }
33
- else {
30
+ row.push(item);
31
+ if (row.length >= max) {
34
32
  rows.push(row);
35
33
  row = [];
36
34
  }
@@ -1,5 +1,8 @@
1
+ export declare type TLogType = 'TRACE' | 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'FATAL';
2
+ export declare const GetLogLevel: (l: TLogType) => number;
3
+ export declare const trace: (...args: any[]) => void;
4
+ export declare const debug: (...args: any[]) => void;
1
5
  export declare const info: (...args: any[]) => void;
2
6
  export declare const warn: (...args: any[]) => void;
3
7
  export declare const error: (...args: any[]) => void;
4
- export declare const debug: (...args: any[]) => void;
5
- export declare const trace: (...args: any[]) => void;
8
+ export declare const fatal: (...args: any[]) => void;
@@ -1,25 +1,153 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.trace = exports.debug = exports.error = exports.warn = exports.info = void 0;
3
+ exports.fatal = exports.error = exports.warn = exports.info = exports.debug = exports.trace = exports.GetLogLevel = void 0;
4
4
  /* eslint-disable @typescript-eslint/no-explicit-any */
5
+ const _1 = require(".");
6
+ const GetLogLevel = (l) => ['TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'].findIndex((s) => s === l);
7
+ exports.GetLogLevel = GetLogLevel;
5
8
  /* eslint-disable no-console */
6
- const info = (...args) => {
7
- console.log(...args);
9
+ function dateF() {
10
+ const d = new Date();
11
+ const str = `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`;
12
+ return str;
13
+ }
14
+ function nicify(...args) {
15
+ const ret = [];
16
+ args.forEach((a) => {
17
+ a.forEach((v) => {
18
+ if (v !== null &&
19
+ typeof v !== 'undefined' &&
20
+ v.toString().indexOf('Error:') !== -1 &&
21
+ v.stack) {
22
+ ret.push(`${v.stack}`);
23
+ }
24
+ else if (typeof v === 'string') {
25
+ if (v.trim() !== 'undefined') {
26
+ ret.push(`${v.trim()}`);
27
+ }
28
+ }
29
+ else if (typeof v === 'object') {
30
+ ret.push(JSON.parse(JSON.stringify(v)));
31
+ }
32
+ else {
33
+ ret.push(v);
34
+ }
35
+ });
36
+ });
37
+ return ret;
38
+ }
39
+ function logprocess(type, date, args) {
40
+ var _a;
41
+ const ds = date ? `[${date}]` : '';
42
+ const retm = [ds, type, ...args].filter(_1.notEmpty).join('\t');
43
+ const min = (0, exports.GetLogLevel)((_a = process.env.LOG_LEVEL) === null || _a === void 0 ? void 0 : _a.toUpperCase()) || 'WARN';
44
+ const typesLogLevel = (0, exports.GetLogLevel)(type);
45
+ // env ignores it
46
+ if (typesLogLevel < min) {
47
+ return;
48
+ }
49
+ switch (type) {
50
+ case 'TRACE': {
51
+ console.trace(retm);
52
+ break;
53
+ }
54
+ case 'DEBUG': {
55
+ console.debug(retm);
56
+ break;
57
+ }
58
+ case 'INFO': {
59
+ console.log(retm);
60
+ break;
61
+ }
62
+ case 'WARN': {
63
+ console.warn(retm);
64
+ break;
65
+ }
66
+ case 'ERROR': {
67
+ console.error(retm);
68
+ break;
69
+ }
70
+ case 'FATAL': {
71
+ console.error(retm);
72
+ break;
73
+ }
74
+ default: {
75
+ console.log(retm);
76
+ break;
77
+ }
78
+ }
79
+ }
80
+ function printStackTrace(...args) {
81
+ const callstack = [];
82
+ let isCallstackPopulated = false;
83
+ try {
84
+ throw new Error('Test');
85
+ }
86
+ catch (e) {
87
+ const er = e;
88
+ if (er.stack) {
89
+ // Firefox / chrome
90
+ const lines = er.stack.split('\n');
91
+ for (let i = 0, len = lines.length; i < len; i += 1) {
92
+ callstack.push(` ${lines[i]} `);
93
+ }
94
+ // Remove call to logStackTrace()
95
+ callstack.shift();
96
+ isCallstackPopulated = true;
97
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
98
+ // @ts-ignore
99
+ }
100
+ else if (window.opera && er.message) {
101
+ // Opera
102
+ const lines = er.message.split('\n');
103
+ for (let i = 0, len = lines.length; i < len; i += 1) {
104
+ if (lines[i].match(/^\s*[A-Za-z0-9\-_$]+\(/)) {
105
+ let entry = lines[i];
106
+ // Append next line also since it has the file info
107
+ if (lines[i + 1]) {
108
+ entry += ` at ${lines[i + 1]}`;
109
+ i += 1;
110
+ }
111
+ callstack.push(entry);
112
+ }
113
+ }
114
+ // Remove call to logStackTrace()
115
+ callstack.shift();
116
+ isCallstackPopulated = true;
117
+ }
118
+ }
119
+ if (!isCallstackPopulated) {
120
+ // IE and Safari
121
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
122
+ // @ts-ignore
123
+ let currentFunction = args.callee.caller;
124
+ while (currentFunction) {
125
+ const fn = currentFunction.toString();
126
+ const fname = fn.substring(fn.indexOf('function') + 8, fn.indexOf('(')) ||
127
+ 'anonymous';
128
+ callstack.push(fname);
129
+ currentFunction = currentFunction.caller;
130
+ }
131
+ }
132
+ return callstack.join('\n');
133
+ }
134
+ const trace = (...args) => {
135
+ const argsNice = nicify(args);
136
+ args.push(printStackTrace());
137
+ logprocess('TRACE', dateF(), argsNice);
8
138
  };
139
+ exports.trace = trace;
140
+ const debug = (...args) => logprocess('DEBUG', dateF(), nicify(args));
141
+ exports.debug = debug;
142
+ const info = (...args) => logprocess('INFO', dateF(), nicify(args));
9
143
  exports.info = info;
10
- const warn = (...args) => {
11
- console.warn(...args);
12
- };
144
+ const warn = (...args) => logprocess('WARN', dateF(), nicify(args));
13
145
  exports.warn = warn;
14
- const error = (...args) => {
15
- console.error(...args);
16
- };
146
+ const error = (...args) => logprocess('ERROR', dateF(), nicify(args));
17
147
  exports.error = error;
18
- const debug = (...args) => {
19
- console.debug(...args);
148
+ const fatal = (...args) => {
149
+ const argsNice = nicify(args);
150
+ args.push(printStackTrace());
151
+ logprocess('FATAL', dateF(), argsNice);
20
152
  };
21
- exports.debug = debug;
22
- const trace = (...args) => {
23
- console.trace(...args);
24
- };
25
- exports.trace = trace;
153
+ exports.fatal = fatal;
@@ -6,4 +6,13 @@ export interface ISite {
6
6
  siteUrl: string;
7
7
  niceSiteUrl: string;
8
8
  }
9
+ /**
10
+ * removes protocol, and trailing slashes
11
+ */
9
12
  export declare const niceUrl: (siteUrl: string) => string | ISite;
13
+ /**
14
+ * string -> String
15
+ * @param str
16
+ * @returns
17
+ */
18
+ export declare function toTitleCase(str: string): string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.niceUrl = exports.truncate = exports.trim = exports.trimSide = exports.csvJSON = void 0;
3
+ exports.toTitleCase = exports.niceUrl = exports.truncate = exports.trim = exports.trimSide = exports.csvJSON = void 0;
4
4
  const csvJSON = (csv) => {
5
5
  const lines = csv.split('\n');
6
6
  const result = [];
@@ -47,12 +47,15 @@ function truncate(str, n, ellip) {
47
47
  return str.length > n ? str.substr(0, n - 1) + ellip : str;
48
48
  }
49
49
  exports.truncate = truncate;
50
+ /**
51
+ * removes protocol, and trailing slashes
52
+ */
50
53
  const niceUrl = (siteUrl) => {
51
54
  if (!siteUrl) {
52
55
  return siteUrl;
53
56
  }
54
57
  let niceSiteUrl = siteUrl
55
- .substr(siteUrl.indexOf(':') + 1)
58
+ .substring(siteUrl.indexOf(':') + 1)
56
59
  .replace('sc-domain:', '')
57
60
  .replace('https://', '')
58
61
  .replace('http://', '');
@@ -60,3 +63,15 @@ const niceUrl = (siteUrl) => {
60
63
  return { siteUrl, niceSiteUrl };
61
64
  };
62
65
  exports.niceUrl = niceUrl;
66
+ /**
67
+ * string -> String
68
+ * @param str
69
+ * @returns
70
+ */
71
+ function toTitleCase(str) {
72
+ if (!str) {
73
+ return str;
74
+ }
75
+ return str.replace(/\w\S*/g, (txt) => txt && txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase());
76
+ }
77
+ exports.toTitleCase = toTitleCase;
@@ -21,7 +21,7 @@ const LoginButton = ({ className, text = text_1.getstarted, invert, title, saveP
21
21
  const lp = loginPath(!savePath || typeof window === 'undefined'
22
22
  ? undefined
23
23
  : {
24
- redirect: window.location.href.substr(window.location.origin.length),
24
+ redirect: window.location.href.substring(window.location.origin.length),
25
25
  });
26
26
  return (react_1.default.createElement(Button_1.Button, { lang: lang, title: title, invert: invert, className: className, onKeyPress: () => __awaiter(void 0, void 0, void 0, function* () {
27
27
  yield pushPath(lp);
@@ -0,0 +1,11 @@
1
+ import { AxiosResponse } from 'axios';
2
+ export declare const axiosHelper: <TOut>({ verb, url, data, headers, timeout, retryMax, }: {
3
+ headers?: {
4
+ [a: string]: string;
5
+ } | undefined;
6
+ verb: 'put' | 'post' | 'get' | 'patch' | 'delete';
7
+ url: string;
8
+ data?: unknown;
9
+ timeout?: number | undefined;
10
+ retryMax?: number | undefined;
11
+ }) => Promise<AxiosResponse<TOut, any>>;
@@ -0,0 +1,82 @@
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.axiosHelper = void 0;
16
+ const axios_1 = __importDefault(require("axios"));
17
+ const object_1 = require("../../common/helpers/object");
18
+ const axiosHelper = ({ verb, url, data, headers, timeout = 30000, retryMax = 0, }) => __awaiter(void 0, void 0, void 0, function* () {
19
+ let retry = 0;
20
+ do {
21
+ try {
22
+ const setHeaders = Object.assign({ accept: 'application/json' }, headers);
23
+ if (verb === 'get') {
24
+ const ret = yield axios_1.default.get(url, {
25
+ headers: setHeaders,
26
+ timeout,
27
+ timeoutErrorMessage: `${url} timeout`,
28
+ });
29
+ return ret;
30
+ }
31
+ let noBody = false;
32
+ let func = axios_1.default.post;
33
+ if (verb === 'put') {
34
+ func = axios_1.default.put;
35
+ }
36
+ else if (verb === 'post') {
37
+ func = axios_1.default.post;
38
+ }
39
+ else if (verb === 'patch') {
40
+ func = axios_1.default.patch;
41
+ }
42
+ else if (verb === 'delete') {
43
+ func = axios_1.default.delete;
44
+ noBody = true;
45
+ }
46
+ let ret;
47
+ if (noBody) {
48
+ ret = yield func(url, {
49
+ headers: setHeaders,
50
+ timeout,
51
+ timeoutErrorMessage: `${url} timeout`,
52
+ });
53
+ }
54
+ else {
55
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
56
+ if (data && (0, object_1.isJson)(data)) {
57
+ setHeaders['Content-Type'] = 'application/json';
58
+ }
59
+ ret = yield func(url, data, { headers: setHeaders });
60
+ }
61
+ return ret;
62
+ }
63
+ catch (e) {
64
+ const em = e;
65
+ // jwt expired or bad response
66
+ // 403 returned for old token - will be refreshed
67
+ if (em.code === '401' || em.code === '403') {
68
+ // eslint-disable-next-line no-console
69
+ console.log('auth expired, reset');
70
+ // retry current page
71
+ window.location.reload();
72
+ retry = retryMax;
73
+ }
74
+ if (retry >= retryMax) {
75
+ throw em;
76
+ }
77
+ }
78
+ retry += 1;
79
+ } while (retry <= retryMax);
80
+ throw new Error('unexpected');
81
+ });
82
+ exports.axiosHelper = axiosHelper;
@@ -26,7 +26,7 @@ function getCookie({ cname, cookieDocument, }) {
26
26
  const ca = ca1.split(';').map((t) => t.trim());
27
27
  for (const c of ca) {
28
28
  if (c.indexOf(name) === 0) {
29
- return c.substring(name.length, c.length);
29
+ return c.substr(name.length, c.length);
30
30
  }
31
31
  }
32
32
  return undefined;
@@ -1,3 +1,4 @@
1
+ export * from './axiosHelper';
1
2
  export * from './browserHelpers';
2
3
  export * from './callOpenApi';
3
4
  export * from './cookie';
@@ -10,6 +10,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
10
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
+ __exportStar(require("./axiosHelper"), exports);
13
14
  __exportStar(require("./browserHelpers"), exports);
14
15
  __exportStar(require("./callOpenApi"), exports);
15
16
  __exportStar(require("./cookie"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ag-common",
3
- "version": "0.0.7",
3
+ "version": "0.0.11",
4
4
  "main": "./dist/index.js",
5
5
  "types": "./dist/index.d.ts",
6
6
  "author": "Andrei Gec <@andreigec> (https://gec.dev/)",