@naturalcycles/js-lib 14.105.0 → 14.107.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,3 +24,16 @@ export declare function _isHttpErrorObject(o: any): o is ErrorObject<HttpErrorDa
24
24
  * Note: any instance of AppError is also automatically an ErrorObject
25
25
  */
26
26
  export declare function _isErrorObject(o: any): o is ErrorObject;
27
+ /**
28
+ * Convenience function to safely add properties to Error's `data` object
29
+ * (even if it wasn't previously existing)
30
+ *
31
+ * @example
32
+ *
33
+ * try {} catch (err) {
34
+ * _errorDataAppend(err, {
35
+ * httpStatusCode: 401,
36
+ * })
37
+ * }
38
+ */
39
+ export declare function _errorDataAppend(err: Error, data: ErrorData): void;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports._isErrorObject = exports._isHttpErrorObject = exports._isHttpErrorResponse = exports._errorObjectToError = exports._errorObjectToAppError = exports._errorToErrorObject = exports._anyToErrorObject = exports._anyToError = void 0;
3
+ exports._errorDataAppend = exports._isErrorObject = exports._isHttpErrorObject = exports._isHttpErrorResponse = exports._errorObjectToError = exports._errorObjectToAppError = exports._errorToErrorObject = exports._anyToErrorObject = exports._anyToError = void 0;
4
4
  const __1 = require("..");
5
5
  /**
6
6
  * Useful to ensure that error in `catch (err) { ... }`
@@ -108,3 +108,23 @@ function _isErrorObject(o) {
108
108
  return (!!o && typeof o.name === 'string' && typeof o.message === 'string' && typeof o.data === 'object');
109
109
  }
110
110
  exports._isErrorObject = _isErrorObject;
111
+ /**
112
+ * Convenience function to safely add properties to Error's `data` object
113
+ * (even if it wasn't previously existing)
114
+ *
115
+ * @example
116
+ *
117
+ * try {} catch (err) {
118
+ * _errorDataAppend(err, {
119
+ * httpStatusCode: 401,
120
+ * })
121
+ * }
122
+ */
123
+ function _errorDataAppend(err, data) {
124
+ ;
125
+ err.data = {
126
+ ...err.data,
127
+ ...data,
128
+ };
129
+ }
130
+ exports._errorDataAppend = _errorDataAppend;
package/dist/index.d.ts CHANGED
@@ -53,12 +53,15 @@ import { JsonStringifyFunction, StringifyAnyOptions, _stringifyAny } from './str
53
53
  export * from './time/time.util';
54
54
  export * from './is.util';
55
55
  import { Class, ConditionalExcept, ConditionalPick, Merge, Promisable, ReadonlyDeep, Simplify } from './typeFest';
56
- import { AsyncMapper, AsyncPredicate, BaseDBEntity, CreatedUpdated, CreatedUpdatedId, ObjectWithId, AnyObjectWithId, Saved, Unsaved, UnsavedId, BatchResult, InstanceId, IsoDate, IsoDateString, IsoDateTimeString, KeyValueTuple, Mapper, ObjectMapper, ObjectPredicate, Predicate, PromiseMap, AnyObject, AnyEnum, NumberEnum, StringEnum, AnyFunction, Reviver, SavedDBEntity, StringMap, UnixTimestampNumber, UnixTimestampMillisNumber, UnixTimestamp, Integer, ValueOf, ValuesOf, AbortableMapper, AbortableAsyncPredicate, AbortableAsyncMapper, AbortablePredicate, NullishValue, FalsyValue, END, SKIP, _noop, _objectKeys, _passNothingPredicate, _passthroughMapper, _passthroughPredicate, _passUndefinedMapper, _stringMapEntries, _stringMapValues } from './types';
56
+ import { AsyncMapper, AsyncPredicate, BaseDBEntity, CreatedUpdated, CreatedUpdatedId, ObjectWithId, AnyObjectWithId, Saved, Unsaved, UnsavedId, BatchResult, InstanceId, IsoDate, IsoDateString, IsoDateTimeString, KeyValueTuple, Mapper, ObjectMapper, ObjectPredicate, Predicate, PromiseMap, AnyObject, AnyEnum, NumberEnum, StringEnum, AnyFunction, Reviver, SavedDBEntity, StringMap, UnixTimestampNumber, UnixTimestampMillisNumber, UnixTimestamp, Integer, ValueOf, ValuesOf, AbortableMapper, AbortableAsyncPredicate, AbortableAsyncMapper, AbortablePredicate, NullishValue, FalsyValue } from './types';
57
+ export * from './types';
57
58
  export * from './unit/size.util';
58
59
  import { is } from './vendor/is';
59
- import { CommonLogLevel, CommonLogFunction, CommonLogger, commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, CommonLogWithLevelFunction, commonLoggerCreate } from './log/commonLogger';
60
+ import { CommonLogLevel, CommonLogFunction, CommonLogger, CommonLogWithLevelFunction } from './log/commonLogger';
61
+ export * from './log/commonLogger';
60
62
  export * from './string/safeJsonStringify';
61
- import { PQueue, PQueueCfg } from './promise/pQueue';
63
+ import { PQueueCfg } from './promise/pQueue';
64
+ export * from './promise/pQueue';
62
65
  export * from './seq/seq';
63
66
  export * from './math/stack.util';
64
67
  export * from './string/leven';
@@ -71,4 +74,4 @@ import { LocalTimeConfig, LocalTimeFormatter, LocalTimeUnit, LocalTimeComponents
71
74
  import { DateIntervalConfig, DateIntervalString } from './datetime/dateInterval';
72
75
  import { TimeIntervalConfig, TimeIntervalString } from './datetime/timeInterval';
73
76
  export type { DateIntervalConfig, DateIntervalString, TimeIntervalConfig, TimeIntervalString, LocalDateConfig, LocalDateFormatter, LocalDateUnit, LocalDateUnitStrict, Inclusiveness, LocalTimeConfig, LocalTimeFormatter, LocalTimeUnit, ISODayOfWeek, LocalTimeComponents, AbortableMapper, AbortablePredicate, AbortableAsyncPredicate, AbortableAsyncMapper, PQueueCfg, MemoCache, AsyncMemoCache, PromiseDecoratorCfg, PromiseDecoratorResp, ErrorData, ErrorObject, HttpErrorData, HttpErrorResponse, Admin401ErrorData, Admin403ErrorData, StringMap, PromiseMap, AnyObject, AnyEnum, NumberEnum, StringEnum, AnyFunction, ValuesOf, ValueOf, KeyValueTuple, ObjectMapper, ObjectPredicate, InstanceId, IsoDate, IsoDateString, IsoDateTimeString, Reviver, FalsyValue, NullishValue, PMapOptions, Mapper, AsyncMapper, Predicate, AsyncPredicate, BatchResult, DeferredPromise, PRetryOptions, PTimeoutOptions, TryCatchOptions, StringifyAnyOptions, JsonStringifyFunction, Merge, ReadonlyDeep, Promisable, Simplify, ConditionalPick, ConditionalExcept, Class, UnixTimestampNumber, UnixTimestampMillisNumber, UnixTimestamp, Integer, BaseDBEntity, SavedDBEntity, Saved, Unsaved, UnsavedId, CreatedUpdated, CreatedUpdatedId, ObjectWithId, AnyObjectWithId, JsonSchema, JsonSchemaAny, JsonSchemaOneOf, JsonSchemaAllOf, JsonSchemaAnyOf, JsonSchemaNot, JsonSchemaRef, JsonSchemaConst, JsonSchemaEnum, JsonSchemaString, JsonSchemaNumber, JsonSchemaBoolean, JsonSchemaNull, JsonSchemaRootObject, JsonSchemaObject, JsonSchemaArray, JsonSchemaTuple, JsonSchemaBuilder, CommonLogLevel, CommonLogWithLevelFunction, CommonLogFunction, CommonLogger, };
74
- export { is, _createPromiseDecorator, _stringMapValues, _stringMapEntries, _objectKeys, pMap, _passthroughMapper, _passUndefinedMapper, _passthroughPredicate, _passNothingPredicate, _noop, ErrorMode, pDefer, AggregatedError, pRetry, pRetryFn, pTimeout, pTimeoutFn, _tryCatch, _TryCatch, _stringifyAny, jsonSchema, JsonSchemaAnyBuilder, commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, commonLoggerCreate, PQueue, END, SKIP, };
77
+ export { is, _createPromiseDecorator, pMap, ErrorMode, pDefer, AggregatedError, pRetry, pRetryFn, pTimeout, pTimeoutFn, _tryCatch, _TryCatch, _stringifyAny, jsonSchema, JsonSchemaAnyBuilder, };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SKIP = exports.END = exports.PQueue = exports.commonLoggerCreate = exports.commonLoggerPrefix = exports.commonLoggerPipe = exports.commonLogLevelNumber = exports.commonLoggerNoop = exports.commonLoggerMinLevel = exports.JsonSchemaAnyBuilder = exports.jsonSchema = exports._stringifyAny = exports._TryCatch = exports._tryCatch = exports.pTimeoutFn = exports.pTimeout = exports.pRetryFn = exports.pRetry = exports.AggregatedError = exports.pDefer = exports.ErrorMode = exports._noop = exports._passNothingPredicate = exports._passthroughPredicate = exports._passUndefinedMapper = exports._passthroughMapper = exports.pMap = exports._objectKeys = exports._stringMapEntries = exports._stringMapValues = exports._createPromiseDecorator = exports.is = void 0;
3
+ exports.JsonSchemaAnyBuilder = exports.jsonSchema = exports._stringifyAny = exports._TryCatch = exports._tryCatch = exports.pTimeoutFn = exports.pTimeout = exports.pRetryFn = exports.pRetry = exports.AggregatedError = exports.pDefer = exports.ErrorMode = exports.pMap = exports._createPromiseDecorator = exports.is = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  tslib_1.__exportStar(require("./array/array.util"), exports);
6
6
  tslib_1.__exportStar(require("./lazy"), exports);
@@ -67,30 +67,13 @@ const stringifyAny_1 = require("./string/stringifyAny");
67
67
  Object.defineProperty(exports, "_stringifyAny", { enumerable: true, get: function () { return stringifyAny_1._stringifyAny; } });
68
68
  tslib_1.__exportStar(require("./time/time.util"), exports);
69
69
  tslib_1.__exportStar(require("./is.util"), exports);
70
- const types_1 = require("./types");
71
- Object.defineProperty(exports, "END", { enumerable: true, get: function () { return types_1.END; } });
72
- Object.defineProperty(exports, "SKIP", { enumerable: true, get: function () { return types_1.SKIP; } });
73
- Object.defineProperty(exports, "_noop", { enumerable: true, get: function () { return types_1._noop; } });
74
- Object.defineProperty(exports, "_objectKeys", { enumerable: true, get: function () { return types_1._objectKeys; } });
75
- Object.defineProperty(exports, "_passNothingPredicate", { enumerable: true, get: function () { return types_1._passNothingPredicate; } });
76
- Object.defineProperty(exports, "_passthroughMapper", { enumerable: true, get: function () { return types_1._passthroughMapper; } });
77
- Object.defineProperty(exports, "_passthroughPredicate", { enumerable: true, get: function () { return types_1._passthroughPredicate; } });
78
- Object.defineProperty(exports, "_passUndefinedMapper", { enumerable: true, get: function () { return types_1._passUndefinedMapper; } });
79
- Object.defineProperty(exports, "_stringMapEntries", { enumerable: true, get: function () { return types_1._stringMapEntries; } });
80
- Object.defineProperty(exports, "_stringMapValues", { enumerable: true, get: function () { return types_1._stringMapValues; } });
70
+ tslib_1.__exportStar(require("./types"), exports);
81
71
  tslib_1.__exportStar(require("./unit/size.util"), exports);
82
72
  const is_1 = require("./vendor/is");
83
73
  Object.defineProperty(exports, "is", { enumerable: true, get: function () { return is_1.is; } });
84
- const commonLogger_1 = require("./log/commonLogger");
85
- Object.defineProperty(exports, "commonLoggerMinLevel", { enumerable: true, get: function () { return commonLogger_1.commonLoggerMinLevel; } });
86
- Object.defineProperty(exports, "commonLoggerNoop", { enumerable: true, get: function () { return commonLogger_1.commonLoggerNoop; } });
87
- Object.defineProperty(exports, "commonLogLevelNumber", { enumerable: true, get: function () { return commonLogger_1.commonLogLevelNumber; } });
88
- Object.defineProperty(exports, "commonLoggerPipe", { enumerable: true, get: function () { return commonLogger_1.commonLoggerPipe; } });
89
- Object.defineProperty(exports, "commonLoggerPrefix", { enumerable: true, get: function () { return commonLogger_1.commonLoggerPrefix; } });
90
- Object.defineProperty(exports, "commonLoggerCreate", { enumerable: true, get: function () { return commonLogger_1.commonLoggerCreate; } });
74
+ tslib_1.__exportStar(require("./log/commonLogger"), exports);
91
75
  tslib_1.__exportStar(require("./string/safeJsonStringify"), exports);
92
- const pQueue_1 = require("./promise/pQueue");
93
- Object.defineProperty(exports, "PQueue", { enumerable: true, get: function () { return pQueue_1.PQueue; } });
76
+ tslib_1.__exportStar(require("./promise/pQueue"), exports);
94
77
  tslib_1.__exportStar(require("./seq/seq"), exports);
95
78
  tslib_1.__exportStar(require("./math/stack.util"), exports);
96
79
  tslib_1.__exportStar(require("./string/leven"), exports);
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.pDefer = void 0;
4
+ /* eslint-disable @typescript-eslint/promise-function-async */
4
5
  /**
5
6
  * Returns DeferredPromise - a Promise that has .resolve() and .reject() methods.
6
7
  */
@@ -2,6 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.pDelay = void 0;
4
4
  async function pDelay(ms = 0, value) {
5
- return new Promise(resolve => setTimeout(() => resolve(value), ms));
5
+ return await new Promise(resolve => setTimeout(() => resolve(value), ms));
6
6
  }
7
7
  exports.pDelay = pDelay;
@@ -5,6 +5,6 @@ exports.pHang = void 0;
5
5
  * Returns Promise that never resolves ("hanging").
6
6
  */
7
7
  async function pHang() {
8
- return new Promise(() => void 0);
8
+ return await new Promise(() => void 0);
9
9
  }
10
10
  exports.pHang = pHang;
@@ -94,7 +94,7 @@ async function pMap(iterable, mapper, opt = {}) {
94
94
  }
95
95
  return ret;
96
96
  }
97
- return new Promise((resolve, reject) => {
97
+ return await new Promise((resolve, reject) => {
98
98
  const next = () => {
99
99
  if (isSettled) {
100
100
  return;
@@ -39,18 +39,18 @@ class PQueue {
39
39
  * Resolves immediately in case the queue is Idle.
40
40
  * Idle means 0 queue and 0 inFlight.
41
41
  */
42
- onIdle() {
42
+ async onIdle() {
43
43
  if (this.queue.length === 0 && this.inFlight === 0)
44
- return Promise.resolve();
44
+ return;
45
45
  const listener = (0, pDefer_1.pDefer)();
46
46
  this.onIdleListeners.push(listener);
47
- return listener;
47
+ return await listener;
48
48
  }
49
49
  /**
50
50
  * Push PromiseReturningFunction to the Queue.
51
51
  * Returns a Promise that resolves (or rejects) with the return value from the Promise.
52
52
  */
53
- push(fn_) {
53
+ async push(fn_) {
54
54
  const { concurrency } = this.cfg;
55
55
  const resolveOnStart = this.cfg.resolveOn === 'start';
56
56
  const fn = fn_;
@@ -99,7 +99,7 @@ class PQueue {
99
99
  this.queue.push(fn);
100
100
  this.debug(`inFlight ${this.inFlight}/${concurrency}, queue++ ${this.queue.length}`);
101
101
  }
102
- return fn.defer;
102
+ return await fn.defer;
103
103
  }
104
104
  }
105
105
  exports.PQueue = PQueue;
@@ -11,7 +11,7 @@ const UNIQUE_VALUE = Symbol('unique');
11
11
  * Based on: https://makandracards.com/makandra/46681-javascript-how-to-query-the-state-of-a-native-promise
12
12
  */
13
13
  async function pState(p) {
14
- return Promise.race([p, Promise.resolve(UNIQUE_VALUE)]).then(v => {
14
+ return await Promise.race([p, Promise.resolve(UNIQUE_VALUE)]).then(v => {
15
15
  return v === UNIQUE_VALUE ? 'pending' : 'resolved';
16
16
  }, () => 'rejected');
17
17
  }
package/dist/types.d.ts CHANGED
@@ -194,3 +194,15 @@ export declare function _stringMapEntries<T>(m: StringMap<T>): [k: string, v: T]
194
194
  export declare function _objectKeys<T extends AnyObject>(obj: T): (keyof T)[];
195
195
  export declare type NullishValue = null | undefined;
196
196
  export declare type FalsyValue = false | '' | 0 | null | undefined;
197
+ /**
198
+ * Utility function that helps to cast *existing variable* to needed type T.
199
+ *
200
+ * @example
201
+ * try {} catch (err) {
202
+ * // err is unknown here
203
+ * _typeCast<AppError>(err)
204
+ * // now err is of type AppError
205
+ * err.data = {} // can be done, because it was casted
206
+ * }
207
+ */
208
+ export declare function _typeCast<T>(v: any): asserts v is T;
package/dist/types.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports._objectKeys = exports._stringMapEntries = exports._stringMapValues = exports._passNothingPredicate = exports._passthroughPredicate = exports._noop = exports._passUndefinedMapper = exports._passthroughMapper = exports.SKIP = exports.END = void 0;
3
+ exports._typeCast = exports._objectKeys = exports._stringMapEntries = exports._stringMapValues = exports._passNothingPredicate = exports._passthroughPredicate = exports._noop = exports._passUndefinedMapper = exports._passthroughMapper = exports.SKIP = exports.END = void 0;
4
4
  /**
5
5
  * Symbol to indicate END of Sequence.
6
6
  */
@@ -48,3 +48,16 @@ function _objectKeys(obj) {
48
48
  return Object.keys(obj);
49
49
  }
50
50
  exports._objectKeys = _objectKeys;
51
+ /**
52
+ * Utility function that helps to cast *existing variable* to needed type T.
53
+ *
54
+ * @example
55
+ * try {} catch (err) {
56
+ * // err is unknown here
57
+ * _typeCast<AppError>(err)
58
+ * // now err is of type AppError
59
+ * err.data = {} // can be done, because it was casted
60
+ * }
61
+ */
62
+ function _typeCast(v) { }
63
+ exports._typeCast = _typeCast;
@@ -96,3 +96,19 @@ export function _isHttpErrorObject(o) {
96
96
  export function _isErrorObject(o) {
97
97
  return (!!o && typeof o.name === 'string' && typeof o.message === 'string' && typeof o.data === 'object');
98
98
  }
99
+ /**
100
+ * Convenience function to safely add properties to Error's `data` object
101
+ * (even if it wasn't previously existing)
102
+ *
103
+ * @example
104
+ *
105
+ * try {} catch (err) {
106
+ * _errorDataAppend(err, {
107
+ * httpStatusCode: 401,
108
+ * })
109
+ * }
110
+ */
111
+ export function _errorDataAppend(err, data) {
112
+ ;
113
+ err.data = Object.assign(Object.assign({}, err.data), data);
114
+ }
package/dist-esm/index.js CHANGED
@@ -49,12 +49,12 @@ export * from './string/string.util';
49
49
  import { _stringifyAny } from './string/stringifyAny';
50
50
  export * from './time/time.util';
51
51
  export * from './is.util';
52
- import { END, SKIP, _noop, _objectKeys, _passNothingPredicate, _passthroughMapper, _passthroughPredicate, _passUndefinedMapper, _stringMapEntries, _stringMapValues, } from './types';
52
+ export * from './types';
53
53
  export * from './unit/size.util';
54
54
  import { is } from './vendor/is';
55
- import { commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, commonLoggerCreate, } from './log/commonLogger';
55
+ export * from './log/commonLogger';
56
56
  export * from './string/safeJsonStringify';
57
- import { PQueue } from './promise/pQueue';
57
+ export * from './promise/pQueue';
58
58
  export * from './seq/seq';
59
59
  export * from './math/stack.util';
60
60
  export * from './string/leven';
@@ -63,4 +63,4 @@ export * from './datetime/localTime';
63
63
  export * from './datetime/dateInterval';
64
64
  export * from './datetime/timeInterval';
65
65
  import { ISODayOfWeek, } from './datetime/localTime';
66
- export { is, _createPromiseDecorator, _stringMapValues, _stringMapEntries, _objectKeys, pMap, _passthroughMapper, _passUndefinedMapper, _passthroughPredicate, _passNothingPredicate, _noop, ErrorMode, pDefer, AggregatedError, pRetry, pRetryFn, pTimeout, pTimeoutFn, _tryCatch, _TryCatch, _stringifyAny, jsonSchema, JsonSchemaAnyBuilder, commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, commonLoggerCreate, PQueue, END, SKIP, };
66
+ export { is, _createPromiseDecorator, pMap, ErrorMode, pDefer, AggregatedError, pRetry, pRetryFn, pTimeout, pTimeoutFn, _tryCatch, _TryCatch, _stringifyAny, jsonSchema, JsonSchemaAnyBuilder, };
@@ -1,3 +1,4 @@
1
+ /* eslint-disable @typescript-eslint/promise-function-async */
1
2
  /**
2
3
  * Returns DeferredPromise - a Promise that has .resolve() and .reject() methods.
3
4
  */
@@ -1,3 +1,3 @@
1
1
  export async function pDelay(ms = 0, value) {
2
- return new Promise(resolve => setTimeout(() => resolve(value), ms));
2
+ return await new Promise(resolve => setTimeout(() => resolve(value), ms));
3
3
  }
@@ -2,5 +2,5 @@
2
2
  * Returns Promise that never resolves ("hanging").
3
3
  */
4
4
  export async function pHang() {
5
- return new Promise(() => void 0);
5
+ return await new Promise(() => void 0);
6
6
  }
@@ -103,7 +103,7 @@ export async function pMap(iterable, mapper, opt = {}) {
103
103
  }
104
104
  return ret;
105
105
  }
106
- return new Promise((resolve, reject) => {
106
+ return await new Promise((resolve, reject) => {
107
107
  const next = () => {
108
108
  if (isSettled) {
109
109
  return;
@@ -31,18 +31,18 @@ export class PQueue {
31
31
  * Resolves immediately in case the queue is Idle.
32
32
  * Idle means 0 queue and 0 inFlight.
33
33
  */
34
- onIdle() {
34
+ async onIdle() {
35
35
  if (this.queue.length === 0 && this.inFlight === 0)
36
- return Promise.resolve();
36
+ return;
37
37
  const listener = pDefer();
38
38
  this.onIdleListeners.push(listener);
39
- return listener;
39
+ return await listener;
40
40
  }
41
41
  /**
42
42
  * Push PromiseReturningFunction to the Queue.
43
43
  * Returns a Promise that resolves (or rejects) with the return value from the Promise.
44
44
  */
45
- push(fn_) {
45
+ async push(fn_) {
46
46
  const { concurrency } = this.cfg;
47
47
  const resolveOnStart = this.cfg.resolveOn === 'start';
48
48
  const fn = fn_;
@@ -91,6 +91,6 @@ export class PQueue {
91
91
  this.queue.push(fn);
92
92
  this.debug(`inFlight ${this.inFlight}/${concurrency}, queue++ ${this.queue.length}`);
93
93
  }
94
- return fn.defer;
94
+ return await fn.defer;
95
95
  }
96
96
  }
@@ -8,7 +8,7 @@ const UNIQUE_VALUE = Symbol('unique');
8
8
  * Based on: https://makandracards.com/makandra/46681-javascript-how-to-query-the-state-of-a-native-promise
9
9
  */
10
10
  export async function pState(p) {
11
- return Promise.race([p, Promise.resolve(UNIQUE_VALUE)]).then(v => {
11
+ return await Promise.race([p, Promise.resolve(UNIQUE_VALUE)]).then(v => {
12
12
  return v === UNIQUE_VALUE ? 'pending' : 'resolved';
13
13
  }, () => 'rejected');
14
14
  }
package/dist-esm/types.js CHANGED
@@ -37,3 +37,15 @@ export function _stringMapEntries(m) {
37
37
  export function _objectKeys(obj) {
38
38
  return Object.keys(obj);
39
39
  }
40
+ /**
41
+ * Utility function that helps to cast *existing variable* to needed type T.
42
+ *
43
+ * @example
44
+ * try {} catch (err) {
45
+ * // err is unknown here
46
+ * _typeCast<AppError>(err)
47
+ * // now err is of type AppError
48
+ * err.data = {} // can be done, because it was casted
49
+ * }
50
+ */
51
+ export function _typeCast(v) { }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@naturalcycles/js-lib",
3
- "version": "14.105.0",
3
+ "version": "14.107.0",
4
4
  "scripts": {
5
5
  "prepare": "husky install",
6
6
  "build-prod": "build-prod-esm-cjs",
@@ -12,10 +12,11 @@
12
12
  },
13
13
  "devDependencies": {
14
14
  "@naturalcycles/bench-lib": "^1.5.0",
15
- "@naturalcycles/dev-lib": "^12.0.0",
15
+ "@naturalcycles/dev-lib": "^13.0.1",
16
16
  "@naturalcycles/nodejs-lib": "^12.33.4",
17
17
  "@naturalcycles/time-lib": "^3.5.1",
18
- "@types/node": "^17.0.4",
18
+ "@types/node": "^18.0.0",
19
+ "expect-type": "^0.13.0",
19
20
  "jest": "^28.0.3",
20
21
  "patch-package": "^6.2.1",
21
22
  "prettier": "^2.1.2",
@@ -145,3 +145,22 @@ export function _isErrorObject(o: any): o is ErrorObject {
145
145
  !!o && typeof o.name === 'string' && typeof o.message === 'string' && typeof o.data === 'object'
146
146
  )
147
147
  }
148
+
149
+ /**
150
+ * Convenience function to safely add properties to Error's `data` object
151
+ * (even if it wasn't previously existing)
152
+ *
153
+ * @example
154
+ *
155
+ * try {} catch (err) {
156
+ * _errorDataAppend(err, {
157
+ * httpStatusCode: 401,
158
+ * })
159
+ * }
160
+ */
161
+ export function _errorDataAppend(err: Error, data: ErrorData): void {
162
+ ;(err as any).data = {
163
+ ...(err as any).data,
164
+ ...data,
165
+ }
166
+ }
package/src/index.ts CHANGED
@@ -137,33 +137,20 @@ import {
137
137
  AbortablePredicate,
138
138
  NullishValue,
139
139
  FalsyValue,
140
- END,
141
- SKIP,
142
- _noop,
143
- _objectKeys,
144
- _passNothingPredicate,
145
- _passthroughMapper,
146
- _passthroughPredicate,
147
- _passUndefinedMapper,
148
- _stringMapEntries,
149
- _stringMapValues,
150
140
  } from './types'
141
+ export * from './types'
151
142
  export * from './unit/size.util'
152
143
  import { is } from './vendor/is'
153
144
  import {
154
145
  CommonLogLevel,
155
146
  CommonLogFunction,
156
147
  CommonLogger,
157
- commonLoggerMinLevel,
158
- commonLoggerNoop,
159
- commonLogLevelNumber,
160
- commonLoggerPipe,
161
- commonLoggerPrefix,
162
148
  CommonLogWithLevelFunction,
163
- commonLoggerCreate,
164
149
  } from './log/commonLogger'
150
+ export * from './log/commonLogger'
165
151
  export * from './string/safeJsonStringify'
166
- import { PQueue, PQueueCfg } from './promise/pQueue'
152
+ import { PQueueCfg } from './promise/pQueue'
153
+ export * from './promise/pQueue'
167
154
  export * from './seq/seq'
168
155
  export * from './math/stack.util'
169
156
  export * from './string/leven'
@@ -296,15 +283,7 @@ export type {
296
283
  export {
297
284
  is,
298
285
  _createPromiseDecorator,
299
- _stringMapValues,
300
- _stringMapEntries,
301
- _objectKeys,
302
286
  pMap,
303
- _passthroughMapper,
304
- _passUndefinedMapper,
305
- _passthroughPredicate,
306
- _passNothingPredicate,
307
- _noop,
308
287
  ErrorMode,
309
288
  pDefer,
310
289
  AggregatedError,
@@ -317,13 +296,4 @@ export {
317
296
  _stringifyAny,
318
297
  jsonSchema,
319
298
  JsonSchemaAnyBuilder,
320
- commonLoggerMinLevel,
321
- commonLoggerNoop,
322
- commonLogLevelNumber,
323
- commonLoggerPipe,
324
- commonLoggerPrefix,
325
- commonLoggerCreate,
326
- PQueue,
327
- END,
328
- SKIP,
329
299
  }
@@ -6,6 +6,8 @@ export interface DeferredPromise<T = void> extends Promise<T> {
6
6
  reject(e?: Error): void
7
7
  }
8
8
 
9
+ /* eslint-disable @typescript-eslint/promise-function-async */
10
+
9
11
  /**
10
12
  * Returns DeferredPromise - a Promise that has .resolve() and .reject() methods.
11
13
  */
@@ -1,3 +1,3 @@
1
1
  export async function pDelay<T>(ms: number = 0, value?: T): Promise<T> {
2
- return new Promise<T>(resolve => setTimeout(() => resolve(value as T), ms))
2
+ return await new Promise<T>(resolve => setTimeout(() => resolve(value as T), ms))
3
3
  }
@@ -2,5 +2,5 @@
2
2
  * Returns Promise that never resolves ("hanging").
3
3
  */
4
4
  export async function pHang(): Promise<never> {
5
- return new Promise<never>(() => void 0)
5
+ return await new Promise<never>(() => void 0)
6
6
  }
@@ -120,7 +120,7 @@ export async function pMap<IN, OUT>(
120
120
  return ret as OUT[]
121
121
  }
122
122
 
123
- return new Promise<OUT[]>((resolve, reject) => {
123
+ return await new Promise<OUT[]>((resolve, reject) => {
124
124
  const next = () => {
125
125
  if (isSettled) {
126
126
  return
@@ -94,19 +94,19 @@ export class PQueue {
94
94
  * Resolves immediately in case the queue is Idle.
95
95
  * Idle means 0 queue and 0 inFlight.
96
96
  */
97
- onIdle(): Promise<void> {
98
- if (this.queue.length === 0 && this.inFlight === 0) return Promise.resolve()
97
+ async onIdle(): Promise<void> {
98
+ if (this.queue.length === 0 && this.inFlight === 0) return
99
99
 
100
100
  const listener = pDefer()
101
101
  this.onIdleListeners.push(listener)
102
- return listener
102
+ return await listener
103
103
  }
104
104
 
105
105
  /**
106
106
  * Push PromiseReturningFunction to the Queue.
107
107
  * Returns a Promise that resolves (or rejects) with the return value from the Promise.
108
108
  */
109
- push<R>(fn_: PromiseReturningFunction<R>): Promise<R> {
109
+ async push<R>(fn_: PromiseReturningFunction<R>): Promise<R> {
110
110
  const { concurrency } = this.cfg
111
111
  const resolveOnStart = this.cfg.resolveOn === 'start'
112
112
 
@@ -155,6 +155,6 @@ export class PQueue {
155
155
  this.debug(`inFlight ${this.inFlight}/${concurrency}, queue++ ${this.queue.length}`)
156
156
  }
157
157
 
158
- return fn.defer
158
+ return await fn.defer
159
159
  }
160
160
  }
@@ -9,7 +9,7 @@ const UNIQUE_VALUE = Symbol('unique')
9
9
  * Based on: https://makandracards.com/makandra/46681-javascript-how-to-query-the-state-of-a-native-promise
10
10
  */
11
11
  export async function pState(p: Promise<any>): Promise<'resolved' | 'rejected' | 'pending'> {
12
- return Promise.race([p, Promise.resolve(UNIQUE_VALUE)]).then(
12
+ return await Promise.race([p, Promise.resolve(UNIQUE_VALUE)]).then(
13
13
  v => {
14
14
  return v === UNIQUE_VALUE ? 'pending' : 'resolved'
15
15
  },
package/src/types.ts CHANGED
@@ -267,3 +267,16 @@ export function _objectKeys<T extends AnyObject>(obj: T): (keyof T)[] {
267
267
 
268
268
  export type NullishValue = null | undefined
269
269
  export type FalsyValue = false | '' | 0 | null | undefined
270
+
271
+ /**
272
+ * Utility function that helps to cast *existing variable* to needed type T.
273
+ *
274
+ * @example
275
+ * try {} catch (err) {
276
+ * // err is unknown here
277
+ * _typeCast<AppError>(err)
278
+ * // now err is of type AppError
279
+ * err.data = {} // can be done, because it was casted
280
+ * }
281
+ */
282
+ export function _typeCast<T>(v: any): asserts v is T {}