@layerzerolabs/lz-utilities 3.0.67 → 3.0.68

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/dist/index.d.ts CHANGED
@@ -1,12 +1,39 @@
1
- import * as winston from 'winston';
2
- import { Logger } from 'winston';
3
- export { Logger } from 'winston';
1
+ import { pino } from 'pino';
4
2
  import { KeyPair } from '@ton/crypto';
5
3
  import { WalletContractV4 } from '@ton/ton';
6
4
  import { ChainType, EndpointVersion, Network, Chain, EndpointId } from '@layerzerolabs/lz-definitions';
7
5
  import { ethers } from 'ethers';
8
6
  import { Options } from 'memoizee';
9
7
 
8
+ type Logger = pino.Logger;
9
+ /**
10
+ * Creates a replacer function for handling circular references in JSON.stringify.
11
+ * details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value
12
+ *
13
+ * @returns {(key: string, value: unknown) => unknown} The replacer function.
14
+ */
15
+ declare function getCircularReplacer(): (key: string, value: unknown) => unknown;
16
+ /**
17
+ * Initializes the logger with the specified log level.
18
+ *
19
+ * @param {string} level - The log level.
20
+ */
21
+ declare function initLogger(level: string): void;
22
+ /**
23
+ * Creates a new logger with the specified log level.
24
+ *
25
+ * @param {string} level - The log level.
26
+ * @returns {Logger} The created logger.
27
+ */
28
+ declare function createLogger(level: string): pino.Logger;
29
+ /**
30
+ * Gets the current logger instance.
31
+ *
32
+ * @returns {Logger} The current logger instance.
33
+ * @throws {Error} If the logger is not initialized.
34
+ */
35
+ declare function getLogger(): Logger;
36
+
10
37
  /**
11
38
  * Interface representing an account mnemonic.
12
39
  */
@@ -104,34 +131,6 @@ declare function getTonWalletFromMnemonic(mnemonic: string, path?: string, workc
104
131
  keyPair: KeyPair;
105
132
  }>;
106
133
 
107
- /**
108
- * Creates a replacer function for handling circular references in JSON.stringify.
109
- * details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value
110
- *
111
- * @returns {(key: string, value: unknown) => unknown} The replacer function.
112
- */
113
- declare function getCircularReplacer(): (key: string, value: unknown) => unknown;
114
- /**
115
- * Initializes the logger with the specified log level.
116
- *
117
- * @param {string} level - The log level.
118
- */
119
- declare function initLogger(level: string): void;
120
- /**
121
- * Creates a new logger with the specified log level.
122
- *
123
- * @param {string} level - The log level.
124
- * @returns {Logger} The created logger.
125
- */
126
- declare function createLogger(level: string): Logger;
127
- /**
128
- * Gets the current logger instance.
129
- *
130
- * @returns {Logger} The current logger instance.
131
- * @throws {Error} If the logger is not initialized.
132
- */
133
- declare function getLogger(): Logger;
134
-
135
134
  /**
136
135
  * Interface representing a contract deployment.
137
136
  */
@@ -333,6 +332,8 @@ type Bytes = Uint8Array;
333
332
  * @throws {Error} If the condition is false.
334
333
  */
335
334
  declare function assert(condition: boolean, message?: string): asserts condition;
335
+ type Constructor<T> = new (...args: any[]) => T;
336
+ type TypeGuard<M> = (v: unknown) => v is M;
336
337
  /**
337
338
  * Asserts that a value is of a certain type, using a type guard function.
338
339
  * assertType can be used to assert that a value is of a certain type, and without naming a new variable explicitly.
@@ -342,7 +343,7 @@ declare function assert(condition: boolean, message?: string): asserts condition
342
343
  * @param {string} [message] - The error message to throw if the value is not of the expected type.
343
344
  * @throws {Error} If the value is not of the expected type.
344
345
  */
345
- declare function assertType<T, M>(value: T, fn: (v: unknown) => v is M, message?: string): asserts value is T & M;
346
+ declare function assertType<T, M>(value: T, typeOrGuard: TypeGuard<M> | Constructor<M>, message?: string): asserts value is T & M;
346
347
  /**
347
348
  * Asserts that a value is defined (not undefined or null).
348
349
  *
@@ -681,7 +682,38 @@ declare function loadJSorTS(fileName: string, relativeToPath: string): Promise<a
681
682
 
682
683
  declare function Memoizee<F extends (...args: any[]) => any>(options?: Options<F>): MethodDecorator;
683
684
 
684
- declare const logger: winston.Logger;
685
+ /**
686
+ * Extracts the element type from an array type, or returns the type itself if not an array
687
+ * @template T The input type to extract from
688
+ * @example
689
+ * type A = ElementOf<number[]> // number
690
+ * type B = ElementOf<string> // string
691
+ */
692
+ type ElementOf<T> = T extends (infer U)[] ? U : T;
693
+ /**
694
+ * Takes multiple inputs and returns their cartesian product as an array of tuples.
695
+ * Each input can be either a single value or an array of values.
696
+ * @template T Array of input types
697
+ * @param inputs Rest parameter of inputs, where each input can be a single value or array
698
+ * @returns Array of tuples containing all possible combinations of input elements
699
+ * @example
700
+ * cartesianProduct(1, ['a', 'b'], [true])
701
+ * // Returns: [[1, 'a', true], [1, 'b', true]]
702
+ *
703
+ * cartesianProduct(['x', 'y'], [1, 2])
704
+ * // Returns: [['x', 1], ['x', 2], ['y', 1], ['y', 2]]
705
+ *
706
+ * cartesianProduct()
707
+ * // Returns: []
708
+ *
709
+ * cartesianProduct([], [])
710
+ * // Returns: []
711
+ */
712
+ declare function cartesianProduct<T extends readonly unknown[]>(...inputs: T): {
713
+ [K in keyof T]: ElementOf<T[K]>;
714
+ }[];
715
+
716
+ declare const logger: Logger;
685
717
  /**
686
718
  * Sleeps for the specified timeout.
687
719
  *
@@ -728,4 +760,4 @@ declare function extractUrlInfo(url: string): {
728
760
  port: string;
729
761
  };
730
762
 
731
- export { type AccountMnemonic, type AtLeast, type Bytes, type DeepPartial, type DeepRequired, type Deployment, type Factory, type Hash, type Hex, Memoizee, type NestedKeys, type NonPromise, type PadReturnType, type RequireAtLeastOne, type RequiredOnly, SizeExceedsPaddingSizeError, type SizeExceedsPaddingSizeErrorType, arrayify, asEnum, asType, assert, assertDefined, assertType, assumeType, bytesToHex, createLogger, deploymentToEvmContract, dirname, enableTS, ensure0x, extractUrlInfo, findContract, findDeployment, findUp, first, firstFactory, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getEvmAccountFromMnemonic, getInitiaAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, getTonAccountFromMnemonic, getTonWalletFromMnemonic, hasRequiredProperties, hexToBytes, hexlify, initLogger, isHash, isHex, isHexString, isHttpServiceReachable, loadJSorTS, logger, padify, parallel, pkgroot, safeMap, sequence, sleep, trim0x, tryFindDeployment };
763
+ export { type AccountMnemonic, type AtLeast, type Bytes, type DeepPartial, type DeepRequired, type Deployment, type Factory, type Hash, type Hex, type Logger, Memoizee, type NestedKeys, type NonPromise, type PadReturnType, type RequireAtLeastOne, type RequiredOnly, SizeExceedsPaddingSizeError, type SizeExceedsPaddingSizeErrorType, arrayify, asEnum, asType, assert, assertDefined, assertType, assumeType, bytesToHex, cartesianProduct, createLogger, deploymentToEvmContract, dirname, enableTS, ensure0x, extractUrlInfo, findContract, findDeployment, findUp, first, firstFactory, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getEvmAccountFromMnemonic, getInitiaAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, getTonAccountFromMnemonic, getTonWalletFromMnemonic, hasRequiredProperties, hexToBytes, hexlify, initLogger, isHash, isHex, isHexString, isHttpServiceReachable, loadJSorTS, logger, padify, parallel, pkgroot, safeMap, sequence, sleep, trim0x, tryFindDeployment };
package/dist/index.mjs CHANGED
@@ -10,9 +10,9 @@ import * as bip39 from 'bip39';
10
10
  import * as ed25519HdKey from 'ed25519-hd-key';
11
11
  import { ethers } from 'ethers';
12
12
  import { ChainType, networkToChain, isNetworkEndpointIdSupported, networkToEndpointId } from '@layerzerolabs/lz-definitions';
13
- import * as winston from 'winston';
14
- import { format } from 'winston';
15
- export { Logger } from 'winston';
13
+ import dayjs from 'dayjs';
14
+ import pc from 'picocolors';
15
+ import { pino } from 'pino';
16
16
  import module2 from 'module';
17
17
  import * as fs from 'fs';
18
18
  import memoizee from 'memoizee';
@@ -63,7 +63,7 @@ function padBytes(bytes, { dir, size = 32 } = {}) {
63
63
 
64
64
  // src/types.ts
65
65
  function isHex(value) {
66
- return /^(0x)?[0-9A-F]+/i.test(value);
66
+ return /^(0x)?[0-9A-F]+$/i.test(value);
67
67
  }
68
68
  function isHash(value) {
69
69
  return /^(0x)?[0-9A-F]+/i.test(value);
@@ -295,52 +295,82 @@ function extractCallerInfo(line) {
295
295
  }
296
296
  return "<unknown>";
297
297
  }
298
- var logFormat = format.printf(
299
- (info) => {
300
- if (info.level.toUpperCase() !== "ERROR" && info.level.toUpperCase() !== "WARN") {
301
- return `${info.timestamp} ${info.level.toUpperCase()}: ${info.message}`;
302
- }
303
- const stack = getStackTrace() ?? "";
304
- const stackLines = stack.split("\n");
305
- const index = stackLines.findIndex((line) => {
306
- return line.match(/create-logger.js/);
307
- }) + 1;
308
- let fileInfo = "<unknown>";
309
- if (stackLines.length > index) {
310
- const line = stackLines[index];
311
- fileInfo = extractCallerInfo(line);
312
- }
313
- const formats = [];
314
- if (fileInfo !== "<unknown>") {
315
- formats.push(fileInfo);
316
- }
317
- const { pretty, format: format2 } = info.metadata ?? {};
318
- const spaces = pretty === true ? 2 : void 0;
319
- const value = typeof info.message === "string" ? info.message : JSON.stringify(info.message, getCircularReplacer(), spaces);
320
- const message = format2 !== void 0 ? format2.replace(/%s/g, value) : value;
321
- return [...formats, message].map((x) => `${info.timestamp} ${info.level.toUpperCase()}: ${x}`).join("\n");
322
- }
323
- );
324
- var loggerFormat = format.combine(
325
- format.timestamp({ format: "YY-MM-DD HH:mm:ss" }),
326
- format.splat(),
327
- format.metadata({ fillExcept: ["level", "timestamp", "message"] }),
328
- logFormat,
329
- format.colorize({
330
- all: true
331
- })
332
- );
298
+ function getCaller(pattern) {
299
+ const stack = getStackTrace() ?? "";
300
+ const stackLines = stack.split("\n");
301
+ const index = stackLines.findIndex((line) => {
302
+ return line.match(pattern);
303
+ }) + 1;
304
+ let fileInfo = "<unknown>";
305
+ if (stackLines.length > index) {
306
+ const line = stackLines[index];
307
+ fileInfo = extractCallerInfo(line);
308
+ }
309
+ return fileInfo;
310
+ }
333
311
  function initLogger(level) {
334
312
  if (!logger) {
335
- logger = createLogger2(level);
313
+ logger = createLogger(level);
336
314
  }
337
315
  }
338
- function createLogger2(level) {
339
- const logger3 = winston.createLogger({
340
- level,
341
- format: loggerFormat,
342
- transports: [new winston.transports.Console()]
343
- });
316
+ var levelColors = {
317
+ TRACE: pc.reset,
318
+ DEBUG: pc.reset,
319
+ INFO: pc.green,
320
+ WARN: pc.yellow,
321
+ ERROR: pc.red,
322
+ FATAL: pc.red
323
+ };
324
+ var customStream = {
325
+ write: (msg) => {
326
+ try {
327
+ const customLogger = (output) => {
328
+ if (typeof process !== "undefined") {
329
+ process.stdout.write(output + "\n");
330
+ } else {
331
+ console.log(output);
332
+ }
333
+ };
334
+ const logObj = JSON.parse(msg);
335
+ const { level, msg: message, time } = logObj;
336
+ const newMsgs = message.split("#caller#");
337
+ const formattedTime = dayjs(time).format("YYYY-MM-DD HH:mm:ss");
338
+ const colorFn = levelColors[level] || pc.reset;
339
+ newMsgs.forEach((newMsg) => {
340
+ customLogger(colorFn(`[${formattedTime}] [${level}] ${newMsg}`));
341
+ });
342
+ } catch (error) {
343
+ console.error("Failed to process log:", msg);
344
+ }
345
+ }
346
+ };
347
+ function createLogger(level) {
348
+ const logger3 = pino(
349
+ {
350
+ level,
351
+ base: void 0,
352
+ // customLevels: customLevels.levels,
353
+ // timestamp: () => `,"time":"${formatTime(Date.now())}"`,
354
+ formatters: {
355
+ level(levelLabel, levelNumber) {
356
+ return { level: levelLabel.toUpperCase(), levelNumber };
357
+ }
358
+ },
359
+ hooks: {
360
+ logMethod(inputArgs, method, level2) {
361
+ const [msg, ...args] = inputArgs;
362
+ let newMsg = msg;
363
+ let caller = "";
364
+ if (level2 >= 50) {
365
+ caller = getCaller(/lib\/tools.js/);
366
+ newMsg = `${caller}#caller#${msg} `;
367
+ }
368
+ method.apply(this, [newMsg, ...args, caller]);
369
+ }
370
+ }
371
+ },
372
+ customStream
373
+ );
344
374
  return logger3;
345
375
  }
346
376
  function getLogger() {
@@ -413,7 +443,7 @@ function getStackTrace2(stackTraceLimit = Infinity) {
413
443
  Error.stackTraceLimit = oldLimit;
414
444
  return retval;
415
445
  }
416
- function getCaller() {
446
+ function getCaller2() {
417
447
  const lines = (getStackTrace2(10) ?? "").split("\n");
418
448
  if (lines.length > 1 + 1 + 1 + 1) {
419
449
  const line = lines[4];
@@ -426,7 +456,7 @@ function getCaller() {
426
456
  }
427
457
  function pkgroot(packageName, relativeToPath) {
428
458
  if (relativeToPath === void 0) {
429
- relativeToPath = getCaller();
459
+ relativeToPath = getCaller2();
430
460
  if (relativeToPath === void 0) {
431
461
  relativeToPath = __filename;
432
462
  }
@@ -442,9 +472,21 @@ function assert(condition, message) {
442
472
  throw new Error(`Assertion Error: ${message ?? "condition is false"}`);
443
473
  }
444
474
  }
445
- function assertType(value, fn, message) {
446
- if (!fn(value)) {
447
- throw new Error(`Expected value to be ${message ?? "of correct type"}`);
475
+ function assertType(value, typeOrGuard, message) {
476
+ if (typeof typeOrGuard === "function") {
477
+ if (typeOrGuard === String || typeOrGuard === Number || typeOrGuard === Boolean) {
478
+ if (typeof value !== typeOrGuard.name.toLowerCase()) {
479
+ throw new Error(`Expected value to be ${message ?? "of correct type"}`);
480
+ }
481
+ } else if ("prototype" in typeOrGuard && typeOrGuard.prototype !== void 0) {
482
+ if (!(value instanceof typeOrGuard)) {
483
+ throw new Error(`Expected value to be ${message ?? "of correct type"}`);
484
+ }
485
+ } else {
486
+ if (!typeOrGuard(value)) {
487
+ throw new Error(`Expected value to be ${message ?? "of correct type"}`);
488
+ }
489
+ }
448
490
  }
449
491
  }
450
492
  function assertDefined(value, message) {
@@ -558,7 +600,7 @@ async function loadJSorTS(fileName, relativeToPath) {
558
600
  const modulePath = require2.resolve(fileName);
559
601
  if (fileName.endsWith(".ts")) {
560
602
  enableTS(relativeToPath);
561
- return import(modulePath);
603
+ return require2(modulePath);
562
604
  } else if (fileName.endsWith(".mjs")) {
563
605
  return import(modulePath);
564
606
  } else if (fileName.endsWith(".cjs")) {
@@ -605,6 +647,18 @@ function Memoizee(options) {
605
647
  };
606
648
  }
607
649
 
650
+ // src/combinatorial.ts
651
+ function cartesianProduct(...inputs) {
652
+ if (inputs.length === 0) {
653
+ return [];
654
+ }
655
+ const normalizedArrays = inputs.map((input) => Array.isArray(input) ? input : [input]);
656
+ return normalizedArrays.reduce(
657
+ (combinations, currentArray) => combinations.flatMap((combination) => currentArray.map((element) => [...combination, element])),
658
+ [[]]
659
+ );
660
+ }
661
+
608
662
  // src/index.ts
609
663
  var logger2 = getLogger();
610
664
  async function sleep(timeout) {
@@ -658,6 +712,6 @@ function extractUrlInfo(url) {
658
712
  };
659
713
  }
660
714
 
661
- export { Memoizee, SizeExceedsPaddingSizeError, arrayify, asEnum, asType, assert, assertDefined, assertType, assumeType, bytesToHex, createLogger2 as createLogger, deploymentToEvmContract, dirname, enableTS, ensure0x, extractUrlInfo, findContract, findDeployment, findUp, first, firstFactory, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getEvmAccountFromMnemonic, getInitiaAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, getTonAccountFromMnemonic, getTonWalletFromMnemonic, hasRequiredProperties, hexToBytes, hexlify, initLogger, isHash, isHex, isHexString, isHttpServiceReachable, loadJSorTS, logger2 as logger, padify, parallel, pkgroot, safeMap, sequence, sleep, trim0x, tryFindDeployment };
715
+ export { Memoizee, SizeExceedsPaddingSizeError, arrayify, asEnum, asType, assert, assertDefined, assertType, assumeType, bytesToHex, cartesianProduct, createLogger, deploymentToEvmContract, dirname, enableTS, ensure0x, extractUrlInfo, findContract, findDeployment, findUp, first, firstFactory, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getEvmAccountFromMnemonic, getInitiaAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, getTonAccountFromMnemonic, getTonWalletFromMnemonic, hasRequiredProperties, hexToBytes, hexlify, initLogger, isHash, isHex, isHexString, isHttpServiceReachable, loadJSorTS, logger2 as logger, padify, parallel, pkgroot, safeMap, sequence, sleep, trim0x, tryFindDeployment };
662
716
  //# sourceMappingURL=index.mjs.map
663
717
  //# sourceMappingURL=index.mjs.map