@naturalcycles/js-lib 14.95.0 → 14.96.1

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,8 +24,8 @@ export declare class LocalDate {
24
24
  /**
25
25
  * Returns null if invalid.
26
26
  */
27
- static parseOrNull(d: LocalDateConfig): LocalDate | null;
28
- static isValid(iso: string): boolean;
27
+ static parseOrNull(d: LocalDateConfig | undefined | null): LocalDate | null;
28
+ static isValid(iso: string | undefined | null): boolean;
29
29
  static today(): LocalDate;
30
30
  static todayUTC(): LocalDate;
31
31
  static sort(items: LocalDate[], mutate?: boolean, descending?: boolean): LocalDate[];
@@ -46,6 +46,8 @@ class LocalDate {
46
46
  * Returns null if invalid.
47
47
  */
48
48
  static parseOrNull(d) {
49
+ if (!d)
50
+ return null;
49
51
  if (d instanceof LocalDate)
50
52
  return d;
51
53
  // todo: explore more performant options
@@ -27,8 +27,8 @@ export declare class LocalTime {
27
27
  /**
28
28
  * Returns null if invalid
29
29
  */
30
- static parseOrNull(d: LocalTimeConfig): LocalTime | null;
31
- static isValid(d: LocalTimeConfig): boolean;
30
+ static parseOrNull(d: LocalTimeConfig | undefined | null): LocalTime | null;
31
+ static isValid(d: LocalTimeConfig | undefined | null): boolean;
32
32
  static now(): LocalTime;
33
33
  static fromComponents(c: {
34
34
  year: number;
@@ -5,18 +5,6 @@ const assert_1 = require("../error/assert");
5
5
  const time_util_1 = require("../time/time.util");
6
6
  const localDate_1 = require("./localDate");
7
7
  /* eslint-disable no-dupe-class-members */
8
- // Design choices:
9
- // No milliseconds
10
- // No timezone support, ISO8601 is parsed as LocalDateTime, discarding Timezone information
11
- // Formats as unix timestamp, ISO8601 or "pretty string"
12
- // toString and .toJSON formats as unix timestamp
13
- // No "unixMillis", just pure unixtimestamp
14
- // .valueOf returns unix timestamp (no millis)
15
- // Prevents dayjs(undefined) being dayjs.now()
16
- // Validates on parse, throws if invalid. Doesn't allow invalid objects
17
- // No arbitrary .format('') (which is slow to parse) vs well-defined (opinionated) formats
18
- // Separate LocalTime, powered by native js Date, and LocalDate - a smaller functionality class when
19
- // you only need "whole dates", no time, no timezone worry
20
8
  /**
21
9
  * @experimental
22
10
  */
@@ -48,6 +36,8 @@ class LocalTime {
48
36
  * Returns null if invalid
49
37
  */
50
38
  static parseOrNull(d) {
39
+ if (!d)
40
+ return null;
51
41
  if (d instanceof LocalTime)
52
42
  return d;
53
43
  let date;
@@ -10,7 +10,7 @@ function _debounce(func, wait, opt = {}) {
10
10
  let lastInvokeTime = 0;
11
11
  const maxing = 'maxWait' in opt;
12
12
  const { leading = false, trailing = true } = opt;
13
- const maxWait = maxing ? Math.max(+opt.maxWait || 0, wait) : opt.maxWait;
13
+ const maxWait = maxing ? Math.max(Number(opt.maxWait) || 0, wait) : opt.maxWait;
14
14
  function invokeFunc(time) {
15
15
  const args = lastArgs;
16
16
  const thisArg = lastThis;
@@ -5,25 +5,31 @@ import { AppError } from './app.error';
5
5
  * Allows to write shorter code that avoids `try/catch`.
6
6
  * Useful e.g. in unit tests.
7
7
  *
8
- * Similar to pTuple, but for sync functions.
8
+ * Similar to pTry, but for sync functions.
9
9
  *
10
10
  * For convenience, second argument type is non-optional,
11
11
  * so you can use it without `!`. But you SHOULD always check `if (err)` first!
12
12
  *
13
+ * ERR is typed as Error, not `unknown`. While unknown would be more correct,
14
+ * according to recent TypeScript, Error gives more developer convenience.
15
+ * In our code we NEVER throw non-errors.
16
+ * Only possibility of non-error is in the 3rd-party library code, in these cases it
17
+ * can be manually cast to `unknown` for extra safety.
18
+ *
13
19
  * @example
14
20
  *
15
21
  * const [err, v] = _try(() => someFunction())
16
22
  * if (err) ...do something...
17
23
  * v // go ahead and use v
18
24
  */
19
- export declare function _try<ERR = unknown, RETURN = void>(fn: () => RETURN): [err: ERR | null, value: RETURN];
25
+ export declare function _try<ERR = Error, RETURN = void>(fn: () => RETURN): [err: ERR | null, value: RETURN];
20
26
  /**
21
27
  * Like _try, but for Promises.
22
28
  *
23
29
  * Also, intentionally types second return item as non-optional,
24
30
  * but you should check for `err` presense first!
25
31
  */
26
- export declare function pTry<ERR = unknown, RETURN = void>(promise: Promise<RETURN>): Promise<[err: ERR | null, value: Awaited<RETURN>]>;
32
+ export declare function pTry<ERR = Error, RETURN = void>(promise: Promise<RETURN>): Promise<[err: ERR | null, value: Awaited<RETURN>]>;
27
33
  /**
28
34
  * It is thrown when Error was expected, but didn't happen
29
35
  * ("pass" happened instead).
package/dist/error/try.js CHANGED
@@ -7,11 +7,17 @@ const app_error_1 = require("./app.error");
7
7
  * Allows to write shorter code that avoids `try/catch`.
8
8
  * Useful e.g. in unit tests.
9
9
  *
10
- * Similar to pTuple, but for sync functions.
10
+ * Similar to pTry, but for sync functions.
11
11
  *
12
12
  * For convenience, second argument type is non-optional,
13
13
  * so you can use it without `!`. But you SHOULD always check `if (err)` first!
14
14
  *
15
+ * ERR is typed as Error, not `unknown`. While unknown would be more correct,
16
+ * according to recent TypeScript, Error gives more developer convenience.
17
+ * In our code we NEVER throw non-errors.
18
+ * Only possibility of non-error is in the 3rd-party library code, in these cases it
19
+ * can be manually cast to `unknown` for extra safety.
20
+ *
15
21
  * @example
16
22
  *
17
23
  * const [err, v] = _try(() => someFunction())
@@ -49,7 +55,7 @@ exports.pTry = pTry;
49
55
  */
50
56
  class UnexpectedPassError extends app_error_1.AppError {
51
57
  constructor() {
52
- super('_expectedError passed unexpectedly');
58
+ super('expected error was not thrown');
53
59
  }
54
60
  }
55
61
  exports.UnexpectedPassError = UnexpectedPassError;
@@ -5,7 +5,7 @@ export interface TryCatchOptions {
5
5
  * The value returned from the function will be returned from the wrapped method (!).
6
6
  * onError function may be asynchronous.
7
7
  */
8
- onError?: (err: unknown) => any;
8
+ onError?: (err: Error) => any;
9
9
  /**
10
10
  * @default false
11
11
  */
@@ -30,7 +30,7 @@ function _tryCatch(fn, opt = {}) {
30
30
  }
31
31
  if (onError) {
32
32
  try {
33
- return await onError(err); // eslint-disable-line @typescript-eslint/return-await
33
+ return await onError((0, index_1._anyToError)(err)); // eslint-disable-line @typescript-eslint/return-await
34
34
  }
35
35
  catch { }
36
36
  }
package/dist/index.d.ts CHANGED
@@ -45,7 +45,6 @@ export * from './promise/pProps';
45
45
  import { pRetry, pRetryFn, PRetryOptions } from './promise/pRetry';
46
46
  export * from './promise/pState';
47
47
  import { pTimeout, pTimeoutFn, PTimeoutOptions } from './promise/pTimeout';
48
- export * from './promise/pTuple';
49
48
  export * from './string/case';
50
49
  export * from './string/json.util';
51
50
  export * from './string/string.util';
package/dist/index.js CHANGED
@@ -59,7 +59,6 @@ tslib_1.__exportStar(require("./promise/pState"), exports);
59
59
  const pTimeout_1 = require("./promise/pTimeout");
60
60
  Object.defineProperty(exports, "pTimeout", { enumerable: true, get: function () { return pTimeout_1.pTimeout; } });
61
61
  Object.defineProperty(exports, "pTimeoutFn", { enumerable: true, get: function () { return pTimeout_1.pTimeoutFn; } });
62
- tslib_1.__exportStar(require("./promise/pTuple"), exports);
63
62
  tslib_1.__exportStar(require("./string/case"), exports);
64
63
  tslib_1.__exportStar(require("./string/json.util"), exports);
65
64
  tslib_1.__exportStar(require("./string/string.util"), exports);
@@ -17,7 +17,7 @@ function _safeJsonStringify(obj, replacer, spaces, cycleReplacer) {
17
17
  }
18
18
  }
19
19
  exports._safeJsonStringify = _safeJsonStringify;
20
- /* eslint-disable @typescript-eslint/no-unused-expressions, no-bitwise */
20
+ /* eslint-disable @typescript-eslint/no-unused-expressions, no-bitwise, no-implicit-coercion */
21
21
  function serializer(replacer, cycleReplacer) {
22
22
  const stack = [];
23
23
  const keys = [];
@@ -43,6 +43,8 @@ export class LocalDate {
43
43
  * Returns null if invalid.
44
44
  */
45
45
  static parseOrNull(d) {
46
+ if (!d)
47
+ return null;
46
48
  if (d instanceof LocalDate)
47
49
  return d;
48
50
  // todo: explore more performant options
@@ -2,18 +2,6 @@ import { _assert } from '../error/assert';
2
2
  import { _ms } from '../time/time.util';
3
3
  import { LocalDate } from './localDate';
4
4
  /* eslint-disable no-dupe-class-members */
5
- // Design choices:
6
- // No milliseconds
7
- // No timezone support, ISO8601 is parsed as LocalDateTime, discarding Timezone information
8
- // Formats as unix timestamp, ISO8601 or "pretty string"
9
- // toString and .toJSON formats as unix timestamp
10
- // No "unixMillis", just pure unixtimestamp
11
- // .valueOf returns unix timestamp (no millis)
12
- // Prevents dayjs(undefined) being dayjs.now()
13
- // Validates on parse, throws if invalid. Doesn't allow invalid objects
14
- // No arbitrary .format('') (which is slow to parse) vs well-defined (opinionated) formats
15
- // Separate LocalTime, powered by native js Date, and LocalDate - a smaller functionality class when
16
- // you only need "whole dates", no time, no timezone worry
17
5
  /**
18
6
  * @experimental
19
7
  */
@@ -45,6 +33,8 @@ export class LocalTime {
45
33
  * Returns null if invalid
46
34
  */
47
35
  static parseOrNull(d) {
36
+ if (!d)
37
+ return null;
48
38
  if (d instanceof LocalTime)
49
39
  return d;
50
40
  let date;
@@ -7,7 +7,7 @@ export function _debounce(func, wait, opt = {}) {
7
7
  let lastInvokeTime = 0;
8
8
  const maxing = 'maxWait' in opt;
9
9
  const { leading = false, trailing = true } = opt;
10
- const maxWait = maxing ? Math.max(+opt.maxWait || 0, wait) : opt.maxWait;
10
+ const maxWait = maxing ? Math.max(Number(opt.maxWait) || 0, wait) : opt.maxWait;
11
11
  function invokeFunc(time) {
12
12
  const args = lastArgs;
13
13
  const thisArg = lastThis;
@@ -4,11 +4,17 @@ import { AppError } from './app.error';
4
4
  * Allows to write shorter code that avoids `try/catch`.
5
5
  * Useful e.g. in unit tests.
6
6
  *
7
- * Similar to pTuple, but for sync functions.
7
+ * Similar to pTry, but for sync functions.
8
8
  *
9
9
  * For convenience, second argument type is non-optional,
10
10
  * so you can use it without `!`. But you SHOULD always check `if (err)` first!
11
11
  *
12
+ * ERR is typed as Error, not `unknown`. While unknown would be more correct,
13
+ * according to recent TypeScript, Error gives more developer convenience.
14
+ * In our code we NEVER throw non-errors.
15
+ * Only possibility of non-error is in the 3rd-party library code, in these cases it
16
+ * can be manually cast to `unknown` for extra safety.
17
+ *
12
18
  * @example
13
19
  *
14
20
  * const [err, v] = _try(() => someFunction())
@@ -44,7 +50,7 @@ export async function pTry(promise) {
44
50
  */
45
51
  export class UnexpectedPassError extends AppError {
46
52
  constructor() {
47
- super('_expectedError passed unexpectedly');
53
+ super('expected error was not thrown');
48
54
  }
49
55
  }
50
56
  /**
@@ -1,4 +1,4 @@
1
- import { _since, _stringifyAny } from '../index';
1
+ import { _anyToError, _since, _stringifyAny } from '../index';
2
2
  /**
3
3
  * Decorates a function with "try/catch", so it'll never reject/throw.
4
4
  * Only applies to async functions (or, turns sync function into async).
@@ -27,7 +27,7 @@ export function _tryCatch(fn, opt = {}) {
27
27
  }
28
28
  if (onError) {
29
29
  try {
30
- return await onError(err); // eslint-disable-line @typescript-eslint/return-await
30
+ return await onError(_anyToError(err)); // eslint-disable-line @typescript-eslint/return-await
31
31
  }
32
32
  catch (_a) { }
33
33
  }
package/dist-esm/index.js CHANGED
@@ -42,7 +42,6 @@ export * from './promise/pProps';
42
42
  import { pRetry, pRetryFn } from './promise/pRetry';
43
43
  export * from './promise/pState';
44
44
  import { pTimeout, pTimeoutFn } from './promise/pTimeout';
45
- export * from './promise/pTuple';
46
45
  export * from './string/case';
47
46
  export * from './string/json.util';
48
47
  export * from './string/string.util';
@@ -13,7 +13,7 @@ export function _safeJsonStringify(obj, replacer, spaces, cycleReplacer) {
13
13
  return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces);
14
14
  }
15
15
  }
16
- /* eslint-disable @typescript-eslint/no-unused-expressions, no-bitwise */
16
+ /* eslint-disable @typescript-eslint/no-unused-expressions, no-bitwise, no-implicit-coercion */
17
17
  function serializer(replacer, cycleReplacer) {
18
18
  const stack = [];
19
19
  const keys = [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@naturalcycles/js-lib",
3
- "version": "14.95.0",
3
+ "version": "14.96.1",
4
4
  "scripts": {
5
5
  "prepare": "husky install",
6
6
  "build-prod": "build-prod-esm-cjs",
@@ -55,7 +55,8 @@ export class LocalDate {
55
55
  /**
56
56
  * Returns null if invalid.
57
57
  */
58
- static parseOrNull(d: LocalDateConfig): LocalDate | null {
58
+ static parseOrNull(d: LocalDateConfig | undefined | null): LocalDate | null {
59
+ if (!d) return null
59
60
  if (d instanceof LocalDate) return d
60
61
 
61
62
  // todo: explore more performant options
@@ -76,7 +77,7 @@ export class LocalDate {
76
77
  return new LocalDate(year, month, day)
77
78
  }
78
79
 
79
- static isValid(iso: string): boolean {
80
+ static isValid(iso: string | undefined | null): boolean {
80
81
  return this.parseOrNull(iso) !== null
81
82
  }
82
83
 
@@ -18,18 +18,6 @@ export interface LocalTimeComponents {
18
18
 
19
19
  /* eslint-disable no-dupe-class-members */
20
20
 
21
- // Design choices:
22
- // No milliseconds
23
- // No timezone support, ISO8601 is parsed as LocalDateTime, discarding Timezone information
24
- // Formats as unix timestamp, ISO8601 or "pretty string"
25
- // toString and .toJSON formats as unix timestamp
26
- // No "unixMillis", just pure unixtimestamp
27
- // .valueOf returns unix timestamp (no millis)
28
- // Prevents dayjs(undefined) being dayjs.now()
29
- // Validates on parse, throws if invalid. Doesn't allow invalid objects
30
- // No arbitrary .format('') (which is slow to parse) vs well-defined (opinionated) formats
31
- // Separate LocalTime, powered by native js Date, and LocalDate - a smaller functionality class when
32
- // you only need "whole dates", no time, no timezone worry
33
21
  /**
34
22
  * @experimental
35
23
  */
@@ -63,7 +51,8 @@ export class LocalTime {
63
51
  /**
64
52
  * Returns null if invalid
65
53
  */
66
- static parseOrNull(d: LocalTimeConfig): LocalTime | null {
54
+ static parseOrNull(d: LocalTimeConfig | undefined | null): LocalTime | null {
55
+ if (!d) return null
67
56
  if (d instanceof LocalTime) return d
68
57
 
69
58
  let date
@@ -89,7 +78,7 @@ export class LocalTime {
89
78
  return new LocalTime(date, false)
90
79
  }
91
80
 
92
- static isValid(d: LocalTimeConfig): boolean {
81
+ static isValid(d: LocalTimeConfig | undefined | null): boolean {
93
82
  return this.parseOrNull(d) !== null
94
83
  }
95
84
 
@@ -49,7 +49,7 @@ export function _debounce<T extends AnyFunction>(
49
49
  const maxing = 'maxWait' in opt
50
50
 
51
51
  const { leading = false, trailing = true } = opt
52
- const maxWait = maxing ? Math.max(+opt.maxWait! || 0, wait) : opt.maxWait
52
+ const maxWait = maxing ? Math.max(Number(opt.maxWait) || 0, wait) : opt.maxWait
53
53
 
54
54
  function invokeFunc(time: number) {
55
55
  const args = lastArgs
package/src/error/try.ts CHANGED
@@ -6,18 +6,24 @@ import { AppError } from './app.error'
6
6
  * Allows to write shorter code that avoids `try/catch`.
7
7
  * Useful e.g. in unit tests.
8
8
  *
9
- * Similar to pTuple, but for sync functions.
9
+ * Similar to pTry, but for sync functions.
10
10
  *
11
11
  * For convenience, second argument type is non-optional,
12
12
  * so you can use it without `!`. But you SHOULD always check `if (err)` first!
13
13
  *
14
+ * ERR is typed as Error, not `unknown`. While unknown would be more correct,
15
+ * according to recent TypeScript, Error gives more developer convenience.
16
+ * In our code we NEVER throw non-errors.
17
+ * Only possibility of non-error is in the 3rd-party library code, in these cases it
18
+ * can be manually cast to `unknown` for extra safety.
19
+ *
14
20
  * @example
15
21
  *
16
22
  * const [err, v] = _try(() => someFunction())
17
23
  * if (err) ...do something...
18
24
  * v // go ahead and use v
19
25
  */
20
- export function _try<ERR = unknown, RETURN = void>(
26
+ export function _try<ERR = Error, RETURN = void>(
21
27
  fn: () => RETURN,
22
28
  ): [err: ERR | null, value: RETURN] {
23
29
  try {
@@ -33,7 +39,7 @@ export function _try<ERR = unknown, RETURN = void>(
33
39
  * Also, intentionally types second return item as non-optional,
34
40
  * but you should check for `err` presense first!
35
41
  */
36
- export async function pTry<ERR = unknown, RETURN = void>(
42
+ export async function pTry<ERR = Error, RETURN = void>(
37
43
  promise: Promise<RETURN>,
38
44
  ): Promise<[err: ERR | null, value: Awaited<RETURN>]> {
39
45
  try {
@@ -50,7 +56,7 @@ export async function pTry<ERR = unknown, RETURN = void>(
50
56
  */
51
57
  export class UnexpectedPassError extends AppError {
52
58
  constructor() {
53
- super('_expectedError passed unexpectedly')
59
+ super('expected error was not thrown')
54
60
  }
55
61
  }
56
62
 
@@ -1,4 +1,4 @@
1
- import { _since, _stringifyAny, CommonLogger } from '../index'
1
+ import { _anyToError, _since, _stringifyAny, CommonLogger } from '../index'
2
2
  import { AnyFunction } from '../types'
3
3
 
4
4
  export interface TryCatchOptions {
@@ -6,7 +6,7 @@ export interface TryCatchOptions {
6
6
  * The value returned from the function will be returned from the wrapped method (!).
7
7
  * onError function may be asynchronous.
8
8
  */
9
- onError?: (err: unknown) => any
9
+ onError?: (err: Error) => any
10
10
 
11
11
  /**
12
12
  * @default false
@@ -59,7 +59,7 @@ export function _tryCatch<T extends AnyFunction>(fn: T, opt: TryCatchOptions = {
59
59
 
60
60
  if (onError) {
61
61
  try {
62
- return await onError(err) // eslint-disable-line @typescript-eslint/return-await
62
+ return await onError(_anyToError(err)) // eslint-disable-line @typescript-eslint/return-await
63
63
  } catch {}
64
64
  }
65
65
  // returns undefined, but doesn't rethrow
package/src/index.ts CHANGED
@@ -78,7 +78,6 @@ export * from './promise/pProps'
78
78
  import { pRetry, pRetryFn, PRetryOptions } from './promise/pRetry'
79
79
  export * from './promise/pState'
80
80
  import { pTimeout, pTimeoutFn, PTimeoutOptions } from './promise/pTimeout'
81
- export * from './promise/pTuple'
82
81
  export * from './string/case'
83
82
  export * from './string/json.util'
84
83
  export * from './string/string.util'
@@ -20,7 +20,7 @@ export function _safeJsonStringify(
20
20
  }
21
21
  }
22
22
 
23
- /* eslint-disable @typescript-eslint/no-unused-expressions, no-bitwise */
23
+ /* eslint-disable @typescript-eslint/no-unused-expressions, no-bitwise, no-implicit-coercion */
24
24
 
25
25
  function serializer(replacer?: Reviver, cycleReplacer?: Reviver): Reviver {
26
26
  const stack: any[] = []
@@ -1,7 +0,0 @@
1
- /**
2
- * Wraps async calls in try catch blocks
3
- * to simplify syntax.
4
- *
5
- * source: https://github.com/scopsy/await-to-js/blob/master/src/await-to-js.ts
6
- */
7
- export declare function pTuple<RETURN, ERR = Error>(promise: Promise<RETURN>): Promise<[ERR, undefined] | [null, RETURN]>;
@@ -1,13 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.pTuple = void 0;
4
- /**
5
- * Wraps async calls in try catch blocks
6
- * to simplify syntax.
7
- *
8
- * source: https://github.com/scopsy/await-to-js/blob/master/src/await-to-js.ts
9
- */
10
- async function pTuple(promise) {
11
- return promise.then(data => [null, data]).catch(err => [err, undefined]);
12
- }
13
- exports.pTuple = pTuple;
@@ -1,9 +0,0 @@
1
- /**
2
- * Wraps async calls in try catch blocks
3
- * to simplify syntax.
4
- *
5
- * source: https://github.com/scopsy/await-to-js/blob/master/src/await-to-js.ts
6
- */
7
- export async function pTuple(promise) {
8
- return promise.then(data => [null, data]).catch(err => [err, undefined]);
9
- }
@@ -1,11 +0,0 @@
1
- /**
2
- * Wraps async calls in try catch blocks
3
- * to simplify syntax.
4
- *
5
- * source: https://github.com/scopsy/await-to-js/blob/master/src/await-to-js.ts
6
- */
7
- export async function pTuple<RETURN, ERR = Error>(
8
- promise: Promise<RETURN>,
9
- ): Promise<[ERR, undefined] | [null, RETURN]> {
10
- return promise.then(data => [null, data] as [null, RETURN]).catch(err => [err as ERR, undefined])
11
- }