@loadmill/universal 0.3.45 → 0.3.48

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.
package/src/log/server.ts DELETED
@@ -1,120 +0,0 @@
1
- import 'source-map-support/register';
2
- import log4js from 'log4js';
3
- import stackTrace from 'stack-trace';
4
- import CircularJSON from 'circular-json';
5
- import { wrapCallSite } from 'source-map-support';
6
- import { myId } from '../my-id';
7
-
8
- const isDev = process.env.NODE_ENV !== 'production';
9
- const level = process.env.LOG_LEVEL || 'info';
10
- const LOG_NEW_LINES = process.env.LOG_NEW_LINES ? process.env.LOG_NEW_LINES === 'true' : isDev;
11
-
12
- log4js.configure({
13
- disableClustering: true,
14
-
15
- appenders: {
16
- out: {
17
- type: 'console',
18
- },
19
- },
20
-
21
- categories: {
22
- default: {
23
- level,
24
- appenders: ['out'],
25
- },
26
-
27
- [myId]: {
28
- level,
29
- appenders: ['out'],
30
- },
31
- },
32
- });
33
-
34
- const log = log4js.getLogger(myId);
35
- log.level = level;
36
-
37
- const loggingMethods = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];
38
-
39
- // Adds logging-source information (for ALL loggers!) if and only if logging
40
- // will actually take place, i.e. if the current log level permits:
41
- loggingMethods.forEach((method) => {
42
- const original = log.constructor.prototype[method];
43
-
44
- log.constructor.prototype[method] = function methodRef(this: any) {
45
- // eslint-disable-next-line
46
- let newArguments: any = arguments;
47
-
48
- try {
49
- if (
50
- (log4js.levels as any)
51
- .getLevel(method)
52
- .isGreaterThanOrEqualTo(this.level)
53
- ) {
54
- // logging WILL take place:
55
- const trace = stackTrace.get(methodRef);
56
-
57
- const { file, line, funcName } = extractSourceInfo(trace[0]);
58
-
59
- // See https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
60
- newArguments = new Array(arguments.length);
61
- for (let i = 0; i < newArguments.length; ++i) {
62
- // eslint-disable-next-line
63
- newArguments[i] = processArgument(arguments[i]);
64
- }
65
-
66
- newArguments.push(`[${file}:${line}#${funcName}]`);
67
- }
68
- } catch (e) {
69
- // like nothing ever happened...
70
- // eslint-disable-next-line
71
- return original.apply(this, arguments);
72
- }
73
-
74
- return original.apply(this, newArguments);
75
- };
76
- });
77
-
78
- function extractSourceInfo(originalFrame) {
79
- // This line uses the source maps:
80
- const frame = wrapCallSite(originalFrame);
81
-
82
- const originalFile = frame.getFileName();
83
-
84
- // remove leading "../"s:
85
- const srcIndex = originalFile.indexOf('src');
86
- const file = srcIndex >= 0 ? originalFile.slice(srcIndex) : originalFile;
87
-
88
- const line = frame.getLineNumber();
89
- const funcName =
90
- frame.getMethodName() || frame.getFunctionName() || '<anonymous>';
91
-
92
- return {
93
- file,
94
- line,
95
- funcName,
96
- };
97
- }
98
-
99
- function processArgument(argument: any) {
100
- const isError = argument instanceof Error;
101
-
102
- if (typeof argument !== 'string' && !isError) {
103
- argument = stringify(argument);
104
- }
105
-
106
- return isError || !argument || LOG_NEW_LINES
107
- ? argument
108
- : argument.replace(/(?:\r\n|\r|\n)/g, '^');
109
- }
110
-
111
- function stringify(argument: any) {
112
- return LOG_NEW_LINES
113
- ? CircularJSON.stringify(argument, null, 4)
114
- : CircularJSON.stringify(argument);
115
- }
116
-
117
- // @ts-ignore
118
- log.cli = (...args) => log.info(...args);
119
-
120
- export default log;
@@ -1,58 +0,0 @@
1
- const isEmpty = obj => [Object, Array].includes((obj || {}).constructor) && !Object.entries((obj || {})).length;
2
-
3
- export function stripSingleton(singleton, defaultValue: any = {}) {
4
- if (!isEmpty(singleton)) {
5
- return singleton[firstKey(singleton)];
6
- } else {
7
- return defaultValue;
8
- }
9
- }
10
-
11
- export function firstKey(obj) {
12
- return Object.keys(obj)[0];
13
- }
14
-
15
- export function objToSingletonArray(obj: {}, sort = true) {
16
- const result = Object.keys(obj).map(key => ({ [key]: obj[key] }));
17
-
18
- if (sort) {
19
- result.sort(firstKeyComparator);
20
- }
21
-
22
- return result;
23
- }
24
-
25
- export function firstKeyComparator(o1, o2) {
26
- const k1 = firstKey(o1);
27
- const k2 = firstKey(o2);
28
-
29
- return k1 < k2 ? -1 : k1 > k2 ? 1 : 0;
30
- }
31
- /**
32
- * {"a":1, "b":2} => [{"a":1}, {"b":2}]
33
- */
34
- export function fromObjectToArrayOfObjects(obj: object): { [name: string]: string }[] {
35
- if (!obj) {
36
- obj = {};
37
- }
38
-
39
- return Object.entries(obj)
40
- .map(([name, value]) => {
41
- return { [name]: value };
42
- });
43
- }
44
-
45
- /**
46
- * Deletes all occurrences of a given property from the given object (nested)
47
- * { a:1, b: {a: 1, b: 2} } => { b: { b: 2 } }
48
- */
49
- export function deleteProp(obj: object, propToDelete: string) {
50
- for (const prop of Object.keys(obj)) {
51
-
52
- delete obj[propToDelete];
53
-
54
- if (typeof obj[prop] === 'object') {
55
- deleteProp(obj[prop], propToDelete);
56
- }
57
- }
58
- }
package/src/math-utils.ts DELETED
@@ -1,31 +0,0 @@
1
- import quickselect from 'quickselect';
2
-
3
- export function calcAvg(
4
- value1: number,
5
- weight1: number,
6
- value2: number,
7
- weight2: number
8
- ) {
9
- const totalWeight = weight1 + weight2;
10
-
11
- if (!totalWeight) {
12
- return 0;
13
- }
14
-
15
- const weighted1 = (weight1 / totalWeight) * value1;
16
- const weighted2 = (weight2 / totalWeight) * value2;
17
-
18
- return weighted1 + weighted2;
19
- }
20
-
21
- export function findMedian(array, compare?) {
22
- const len = array.length;
23
- if (len <= 1) {
24
- return array[0];
25
- }
26
-
27
- const k = Math.ceil(len / 2);
28
- quickselect(array, k, 0, len - 1, compare);
29
-
30
- return array[k - 1];
31
- }
package/src/my-id.ts DELETED
@@ -1,3 +0,0 @@
1
- import uuid from 'uuid';
2
-
3
- export const myId = uuid.v4();
@@ -1,28 +0,0 @@
1
- export function numberify(num?: number | string | null, defaultValue = 0) {
2
- if (num == null) {
3
- return defaultValue;
4
- } else {
5
- return Number(num);
6
- }
7
- }
8
-
9
- export function formatNumber(value: number, fractionDigits: number) {
10
- if (fractionDigits === 0) {
11
- return value + '';
12
- }
13
-
14
- // Throw away insignificant digits:
15
- const factor = Math.pow(10, fractionDigits);
16
- value = Math.round(value * factor) / factor;
17
-
18
- if (Number.isInteger(value)) {
19
- return value + '';
20
- } else {
21
- return (
22
- value
23
- .toFixed(fractionDigits)
24
- // Remove trailing zeros:
25
- .replace(/0*$/, '')
26
- );
27
- }
28
- }
package/src/object-map.ts DELETED
@@ -1,71 +0,0 @@
1
- const isEmpty = obj => [Object, Array].includes((obj || {}).constructor) && !Object.entries((obj || {})).length;
2
-
3
- export class ObjectMap<T = any> {
4
- nextId: number = 0;
5
- obj: { [key: string]: T } = {};
6
-
7
- constructor(generateKey?) {
8
- if (generateKey) {
9
- this.generateKey = generateKey;
10
- }
11
- }
12
-
13
- generateKey = () => '' + this.nextId++;
14
-
15
- size = () => {
16
- return Object.keys(this.obj).length;
17
- };
18
-
19
- clear = () => {
20
- this.obj = {};
21
- };
22
-
23
- isEmpty = () => {
24
- return isEmpty(this.obj);
25
- };
26
-
27
- get = (key) => {
28
- return this.obj[key];
29
- };
30
-
31
- forEach = (fn) => Object.keys(this.obj).forEach((key, i) => fn(this.obj[key], key, i));
32
-
33
- pop = (key) => {
34
- const value = this.obj[key];
35
- this.remove(key);
36
- return value;
37
- };
38
-
39
- getOrMake = (key, provider = () => ({} as T)) => {
40
- const value = this.obj[key];
41
-
42
- return value != null ? value : (this.obj[key] = provider());
43
- };
44
-
45
- put = (key, value: T) => {
46
- this.obj[key] = value;
47
- };
48
-
49
- putIfAbsent = (key, value: T) => {
50
- return this.getOrMake(key, () => value);
51
- };
52
-
53
- add = (value: T) => {
54
- const key = this.generateKey();
55
- this.put(key, value);
56
- return key;
57
- };
58
-
59
- remove = (key) => {
60
- delete this.obj[key];
61
- };
62
-
63
- mark = (keyAndValue: T) => {
64
- const previous = this.get(keyAndValue);
65
- this.put(keyAndValue, keyAndValue);
66
-
67
- return previous == null;
68
- };
69
-
70
- hasKey = (key) => this.get(key) != null;
71
- }
@@ -1,3 +0,0 @@
1
- export function delay(timeout: number) {
2
- return new Promise(resolve => setTimeout(resolve, timeout));
3
- }
@@ -1,66 +0,0 @@
1
- // split("foo 'bar baz'")
2
- // ["foo", "bar baz"]
3
- export const split = (line: string) => {
4
- let field: string;
5
- if (line == null) {
6
- line = '';
7
- }
8
- const words: string[] = [];
9
- field = '';
10
-
11
- const regex = /\s*(?:([^\s\\'"]+)|'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)"|(\\.?)|(\S))(\s|$)?/;
12
-
13
- _scan(line, regex, (match) => {
14
- let dq, escape, garbage, seperator, sq, word;
15
- word = match[1], sq = match[2], dq = match[3], escape = match[4], garbage = match[5], seperator = match[6];
16
- if (garbage != null) {
17
- throw new Error('Unmatched quote');
18
- }
19
- if (!word && !sq && !dq && !escape) {
20
- field = '';
21
- } else {
22
- field += word || (sq || dq || escape).replace(/\\(?=.)/, '');
23
- }
24
- if (seperator != null) {
25
- words.push(field);
26
- return field = '';
27
- }
28
- });
29
- if (field != null) {
30
- words.push(field);
31
- }
32
- return words;
33
- };
34
-
35
- const _scan = (string, pattern, callback) => {
36
- let result = '';
37
- while (string.length > 0) {
38
- const match = string.match(pattern);
39
- if (match) {
40
- result += string.slice(0, match.index);
41
- result += callback(match);
42
- string = string.slice(match.index + match[0].length);
43
- } else {
44
- result += string;
45
- string = '';
46
- }
47
- }
48
- return result;
49
- };
50
-
51
- // escape("What's up, yo?") => 'What\\\'s\\ up,\\ yo\\?'
52
- export const escape = (s: string): string => {
53
- if (s == null) {
54
- s = '';
55
- }
56
- if (s == null) {
57
- return '\'\'';
58
- }
59
- return s.replace(/([^A-Za-z0-9_\-.,:/@\n])/g, '\\$1').replace(/\n/g, '\'\n\'');
60
- };
61
-
62
- export const nodeBtoa = (str = '') => Buffer.from(str).toString('base64');
63
-
64
- export const isNonEmptyString = (s: unknown): boolean => {
65
- return !!s && typeof s === 'string';
66
- };
@@ -1,18 +0,0 @@
1
- /**
2
- * example usage of this function:
3
- * arr = [{ id: 1 }, { id: 2 }]
4
- * b = { uid: 2 }
5
- * const found = ensure(arr.find((a) => a.id === b.uid)); // TS thinks `find` might return undefined.
6
- * We know it will never be undefined, so we use `ensure` to tell TS that arg is defined and has value.
7
- * @param arg a value which should be defined and initialized
8
- * @param msg custom error message
9
- * @returns arg if it is defined, otherwise throws TypeError
10
- * @throws TypeError if arg is null or undefined
11
- */
12
- export function ensure<T>(arg?: T | null, msg: string = 'This value was supposed to be defined'): T {
13
- if (arg == null) {
14
- throw new TypeError(msg);
15
- }
16
-
17
- return arg;
18
- }
package/src/uri-utils.ts DELETED
@@ -1,72 +0,0 @@
1
- import URI from 'urijs';
2
-
3
- const SUPPORTED_PROTOCOLS = ['http', 'https', 'ws', 'wss'];
4
-
5
- const isUrlStartsWithSupportedProtocol = (url: string, delimiter = ':') =>
6
- SUPPORTED_PROTOCOLS.some(protocol =>
7
- url.startsWith(protocol + delimiter)
8
- );
9
-
10
- export function withProtocol(url: string) {
11
- if (url && !isUrlStartsWithSupportedProtocol(url)) {
12
- url = 'http://' + url;
13
- }
14
- return url;
15
- }
16
-
17
- export function parseQuery(query: string) {
18
- return URI.parseQuery(query) as any;
19
- }
20
-
21
- export function getDomain(url) {
22
- const parsedUri = new URI(url);
23
- return normalizeDomain(parsedUri.host());
24
- }
25
-
26
- export function normalizeDomain(domain?: string) {
27
- return (
28
- stripProtocol(domain || '')
29
- .toLowerCase()
30
- // No trailing `/`:
31
- .replace(/\/$/, '')
32
- );
33
- }
34
-
35
- export function stripProtocol(urlish: string) {
36
- if (isUrlStartsWithSupportedProtocol(urlish, '://')) {
37
- const url = new URI(urlish);
38
- const protocolLength = url.protocol().length;
39
- return urlish.substring(protocolLength + 3, urlish.length);
40
- }
41
-
42
- return urlish;
43
- }
44
-
45
- export function encodePart(urlPart: string) {
46
- return URI.encode(urlPart);
47
- }
48
-
49
- export function decodePart(urlPart: string) {
50
- return URI.decode(urlPart);
51
- }
52
-
53
- export function isVerified(domain: string, verifiedDomains: string[]) {
54
- return !!verifiedDomains.find((verifiedDomain) =>
55
- isSubDomain(domain, verifiedDomain)
56
- );
57
- }
58
-
59
- export function getFullUrl (url: string) {
60
- return new URL(withProtocol(url)).href;
61
- }
62
-
63
- /**
64
- * Assumes both domains are properly normalized.
65
- *
66
- * @param domain1 Potential sub-domain of `domain2`.
67
- * @param domain2 Potential parent domain of `domain1`.
68
- * @returns True if domain1 is equal to or a sub-domain of domain2.
69
- */
70
- function isSubDomain(domain1: string, domain2: string): boolean {
71
- return domain1 === domain2 || domain1.endsWith('.' + domain2);
72
- }
@@ -1,35 +0,0 @@
1
- const { expect } = require('chai');
2
- const { describe, it } = require('mocha');
3
- const { parameterUtils } = require('../../core/dist/parameters');
4
- const arrayUtils = require('../dist/array-utils');
5
-
6
- describe('array-utils', () => {
7
- describe('swap', () => {
8
- it('Validate swap top down', () => {
9
- const arr1 = [0, 1, 2, 3];
10
- arrayUtils.swap(arr1, 3, 0);
11
- expect(arr1).deep.equal([3, 0, 1, 2]);
12
- });
13
-
14
- it('Validate swap bottom up', () => {
15
- const arr2 = [0, 1, 2, 3];
16
- arrayUtils.swap(arr2, 0, 3);
17
- expect(arr2).deep.equal([1, 2, 3, 0]);
18
- });
19
-
20
- it('Validate swap with an array of objects', () => {
21
- const arr3 = [{ order: 0 }, { order: 1 }, { order: 2 }, { order: 3 }];
22
- arrayUtils.swap(arr3, 3, 0);
23
- expect(arr3).deep.equal([{ order: 3 }, { order: 0 }, { order: 1 }, { order: 2 }]);
24
- });
25
-
26
- it('uniqByKeepLast function', () => {
27
- let params = [{ a: 1 }, { a: 2 }, { a: 3 }];
28
- expect(arrayUtils.uniqByKeepLast(params, parameterUtils.getParameterName)).to.eql([{ a: 3 }]);
29
- params = [{ a: 1 }, { b: 2 }];
30
- expect(arrayUtils.uniqByKeepLast(params, parameterUtils.getParameterName)).to.eql([{ a: 1 }, { b:2 }]);
31
- params = [{ a: 1 }, { b: 2 }, { a: 4 }];
32
- expect(arrayUtils.uniqByKeepLast(params, parameterUtils.getParameterName)).to.eql([{ b:2 }, { a:4 }]);
33
- });
34
- });
35
- });
@@ -1,39 +0,0 @@
1
- const { expect } = require('chai');
2
- const { describe, it } = require('mocha');
3
-
4
- const { getCronLabel, isAllowedExpression } = require('../dist/cron-utils');
5
-
6
- describe('cron-utils', () => {
7
- it('getCronLabel', () => {
8
- expect(getCronLabel('1')).equals('');
9
- expect(getCronLabel('No scheduling')).equals('No scheduling');
10
- expect(getCronLabel('*/10 * * * *')).equals('Every 10 minutes');
11
- expect(getCronLabel('0 */1 * * *')).equals('Every 1 Hour');
12
- expect(getCronLabel('0 2 * * *')).equals('Every night');
13
- expect(getCronLabel('0 1 * * 1')).equals('Once a Week');
14
- expect(getCronLabel('0 1 * * 2')).equals('Once a Week');
15
- expect(getCronLabel('0 3 * * 2')).equals('Once a Week');
16
- expect(getCronLabel('0 10 * * 2')).equals('Once a Week');
17
- expect(getCronLabel('0 15 * * 2')).equals('Once a Week');
18
- expect(getCronLabel('0 23 * * 2')).equals('Once a Week');
19
- expect(getCronLabel('0 0 * * 6')).equals('Once a Week');
20
- expect(getCronLabel('0 23 * * 7')).equals('');
21
- expect(getCronLabel('0 24 * * 2')).equals('');
22
- expect(getCronLabel('0 */1 * * 2')).equals('');
23
- expect(getCronLabel('1 3 * * 2')).equals('');
24
- expect(getCronLabel('0 /3 * * 2')).equals('');
25
- });
26
-
27
- it('isAllowedExpression', () => {
28
- expect(isAllowedExpression('1')).equals(false);
29
- expect(isAllowedExpression('No scheduling')).equals(true);
30
- expect(isAllowedExpression('*/10 * * * *')).equals(true);
31
- expect(isAllowedExpression('0 */1 * * *')).equals(true);
32
- expect(isAllowedExpression('0 2 * * *')).equals(true);
33
- expect(isAllowedExpression('0 1 * * 1')).equals(true);
34
- expect(isAllowedExpression('0 1 * * 2')).equals(true);
35
- expect(isAllowedExpression('0 3 * * 2')).equals(true);
36
- expect(isAllowedExpression('1 3 * * 2')).equals(false);
37
- expect(isAllowedExpression('0 /3 * * 2')).equals(false);
38
- });
39
- });