@anjianshi/utils 1.0.8 → 1.1.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.
package/.eslintrc.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  /* eslint-env node */
2
2
  module.exports = {
3
3
  root: true,
4
- extends: ['./node_modules/@anjianshi/presets/eslint-base.js'],
4
+ extends: ['./node_modules/@anjianshi/presets-eslint-base/index.js'],
5
5
  rules: {},
6
6
  }
@@ -1,3 +1,4 @@
1
+ import chalk from 'chalk';
1
2
  import { type Logger, type LogInfo, LogHandler } from '../logging/index.js';
2
3
  export * from '../logging/index.js';
3
4
  /**
@@ -24,14 +25,14 @@ export declare class ConsoleHandler extends LogHandler {
24
25
  };
25
26
  };
26
27
  static readonly levelColors: {
27
- 1: import("chalk").ChalkInstance;
28
- 2: import("chalk").ChalkInstance;
29
- 3: import("chalk").ChalkInstance;
30
- 4: import("chalk").ChalkInstance;
28
+ 1: chalk.Chalk;
29
+ 2: chalk.Chalk;
30
+ 3: chalk.Chalk;
31
+ 4: chalk.Chalk;
31
32
  };
32
33
  private static readonly loggerColors;
33
34
  private static readonly loggerColorMap;
34
- static getLoggerColor(logger: string): "green" | "yellow" | "blue" | "cyan" | "magenta" | "greenBright" | "yellowBright" | "blueBright" | "cyanBright" | "magentaBright";
35
+ static getLoggerColor(logger: string): "green" | "yellow" | "blue" | "magenta" | "cyan" | "greenBright" | "yellowBright" | "blueBright" | "magentaBright" | "cyanBright";
35
36
  }
36
37
  /**
37
38
  * 写入文件日志
@@ -47,7 +48,7 @@ export declare class FileHandler extends LogHandler {
47
48
  readonly options: FileHandlerOptions;
48
49
  constructor(options?: Partial<FileHandlerOptions>);
49
50
  log(info: LogInfo): void;
50
- protected formatDataItem(item: unknown): string;
51
+ protected stringifyDataItem(item: unknown): string;
51
52
  private buffer;
52
53
  private bufferSize;
53
54
  protected pushBuffer(...strings: string[]): void;
@@ -7,7 +7,6 @@ import path from 'node:path';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import chalk from 'chalk';
9
9
  import dayjs from 'dayjs';
10
- import { removeANSIColor } from '../lang/index.js';
11
10
  import { logger as defaultLogger, LogLevel, LogHandler, formatters, } from '../logging/index.js';
12
11
  export * from '../logging/index.js';
13
12
  /**
@@ -21,9 +20,9 @@ export class ConsoleHandler extends LogHandler {
21
20
  const levelName = formatters.level(info);
22
21
  const loggerColor = chalk[ConsoleHandler.getLoggerColor(logger)];
23
22
  const prefix = [
24
- chalk.white(`[${formatters.datetime(info)}]`),
23
+ chalk.white(`[${formatters.time(info)}]`),
25
24
  levelColor(`[${levelName}]`),
26
- logger ? loggerColor(`[${logger}]`) : '',
25
+ loggerColor(`[${logger}]`),
27
26
  ].join('');
28
27
  method(prefix, ...args);
29
28
  }
@@ -88,7 +87,7 @@ export class FileHandler extends LogHandler {
88
87
  const itemStrings = [];
89
88
  let totalLength = prefix.length;
90
89
  for (const item of args) {
91
- const itemString = this.formatDataItem(item);
90
+ const itemString = this.stringifyDataItem(item);
92
91
  // 截断过长的日志内容 Truncate overly long log messages
93
92
  if (totalLength + itemString.length < this.options.maxLength) {
94
93
  itemStrings.push((totalLength === prefix.length ? '' : ' ') + itemString);
@@ -101,9 +100,9 @@ export class FileHandler extends LogHandler {
101
100
  }
102
101
  this.pushBuffer(prefix, ...itemStrings, '\n');
103
102
  }
104
- formatDataItem(item) {
103
+ stringifyDataItem(item) {
105
104
  if (typeof item === 'string')
106
- return removeANSIColor(item);
105
+ return item;
107
106
  if (item instanceof Error)
108
107
  return item.stack ?? String(item);
109
108
  try {
package/init-dayjs.js CHANGED
@@ -1,8 +1,7 @@
1
- import dayjs from 'dayjs';
1
+ import { extend, locale } from 'dayjs';
2
2
  import objectSupport from 'dayjs/plugin/objectSupport.js';
3
3
  import 'dayjs/locale/zh-cn.js';
4
4
  export function initDayJs() {
5
- // dayjs 的类型标记错误,这两个方法只能通过 dayjs 对象访问,并不能直接引入
6
- dayjs.extend(objectSupport); // eslint-disable-line import/no-named-as-default-member
7
- dayjs.locale('zh-cn'); // eslint-disable-line import/no-named-as-default-member
5
+ extend(objectSupport);
6
+ locale('zh-cn');
8
7
  }
package/lang/string.d.ts CHANGED
@@ -23,8 +23,3 @@ export declare function safeParseFloat(value: string | number, fallback: number)
23
23
  * dp: how many decimal places to keep(保留几位小数)
24
24
  */
25
25
  export declare function readableSize(bytes: number, si?: boolean, dp?: number): string;
26
- /**
27
- * 移除字符串中的 ASNI Color 修饰符
28
- * https://stackoverflow.com/a/7150870/2815178
29
- */
30
- export declare function removeANSIColor(string: string): string;
package/lang/string.js CHANGED
@@ -79,12 +79,3 @@ export function readableSize(bytes, si = false, dp = 1) {
79
79
  } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1);
80
80
  return `${bytes.toFixed(dp)} ${units[u]}`;
81
81
  }
82
- /**
83
- * 移除字符串中的 ASNI Color 修饰符
84
- * https://stackoverflow.com/a/7150870/2815178
85
- */
86
- export function removeANSIColor(string) {
87
- return string.replace(
88
- // eslint-disable-next-line no-control-regex
89
- /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');
90
- }
@@ -2,4 +2,4 @@ import type { Debug } from 'debug';
2
2
  /**
3
3
  * 适配 debug package
4
4
  */
5
- export declare function adaptDebugLib(debugLib: Debug, enable?: string, logger?: import("./index.js").Logger): void;
5
+ export declare function adaptDebugLib(debugLib: Debug, enable?: string): void;
package/logging/adapt.js CHANGED
@@ -2,7 +2,7 @@ import { getLogger } from './index.js';
2
2
  /**
3
3
  * 适配 debug package
4
4
  */
5
- export function adaptDebugLib(debugLib, enable = '', logger = getLogger('3rd-library')) {
5
+ export function adaptDebugLib(debugLib, enable = '') {
6
6
  // 不在 localStorage 里记录 debugLib enable 状态,
7
7
  // 以解决 web worker 里读不到 localStorage 而无法启用 debugLib 日志的问题
8
8
  const emulate = {
@@ -30,12 +30,8 @@ export function adaptDebugLib(debugLib, enable = '', logger = getLogger('3rd-lib
30
30
  };
31
31
  Object.assign(debugLib, emulate);
32
32
  // 将 debugLib 日志转发给 logger
33
- debugLib.log = (initial, ...rest) => {
34
- // 移除开头的额外空格
35
- if (typeof initial === 'string')
36
- initial = initial.trimStart();
37
- logger.debug(initial, ...rest);
38
- };
33
+ const logger = getLogger('3rd-library');
34
+ debugLib.log = logger.debug.bind(logger);
39
35
  if (enable) {
40
36
  debugLib.enable(enable);
41
37
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anjianshi/utils",
3
- "version": "1.0.8",
3
+ "version": "1.1.0",
4
4
  "description": "Common JavaScript Utils",
5
5
  "homepage": "https://github.com/anjianshi/js-utils",
6
6
  "bugs": {
@@ -25,20 +25,19 @@
25
25
  },
26
26
  "main": "index.js",
27
27
  "dependencies": {
28
- "chalk": "^5.3.0",
29
28
  "dayjs": "^1.11.10",
30
29
  "lodash": "^4.17.21"
31
30
  },
32
31
  "devDependencies": {
33
- "@anjianshi/presets": "1.3.0",
32
+ "@anjianshi/presets-eslint-node": "^1.0.3",
33
+ "@anjianshi/presets-eslint-typescript": "^1.0.3",
34
+ "@anjianshi/presets-prettier": "^1.0.0",
35
+ "@anjianshi/presets-typescript": "^1.0.1",
34
36
  "@types/debug": "^4.1.9",
35
37
  "@types/lodash": "^4.14.199",
36
38
  "@types/node": "^20.8.6",
37
- "eslint": "^8.51.0",
38
- "prettier-not-stubborn": "^3.0.3",
39
- "typescript": "^5.2.2",
40
39
  "vconsole": "^3.15.1"
41
40
  },
42
41
  "eslintIgnore": [],
43
- "prettier": "@anjianshi/presets/prettierrc"
42
+ "prettier": "@anjianshi/presets-prettier/prettierrc"
44
43
  }
package/src/.eslintrc.cjs CHANGED
@@ -1,8 +1,5 @@
1
1
  /* eslint-env node */
2
2
  module.exports = {
3
3
  root: true,
4
- extends: [
5
- '../node_modules/@anjianshi/presets/eslint-base.js',
6
- '../node_modules/@anjianshi/presets/eslint-typescript.js',
7
- ],
4
+ extends: ['../node_modules/@anjianshi/presets-eslint-typescript/exclusive.js'],
8
5
  }
@@ -1,4 +1,4 @@
1
1
  /* eslint-env node */
2
2
  module.exports = {
3
- extends: ['../../node_modules/@anjianshi/presets/eslint-node.js'],
3
+ extends: ['../../node_modules/@anjianshi/presets-eslint-node/exclusive.js'],
4
4
  }
@@ -7,7 +7,6 @@ import path from 'node:path'
7
7
  import { fileURLToPath } from 'node:url'
8
8
  import chalk from 'chalk'
9
9
  import dayjs from 'dayjs'
10
- import { removeANSIColor } from '../lang/index.js'
11
10
  import {
12
11
  logger as defaultLogger,
13
12
  type Logger,
@@ -30,9 +29,9 @@ export class ConsoleHandler extends LogHandler {
30
29
  const levelName = formatters.level(info)
31
30
  const loggerColor = chalk[ConsoleHandler.getLoggerColor(logger)]
32
31
  const prefix = [
33
- chalk.white(`[${formatters.datetime(info)}]`),
32
+ chalk.white(`[${formatters.time(info)}]`),
34
33
  levelColor(`[${levelName}]`),
35
- logger ? loggerColor(`[${logger}]`) : '',
34
+ loggerColor(`[${logger}]`),
36
35
  ].join('')
37
36
  method(prefix, ...args)
38
37
  }
@@ -121,7 +120,7 @@ export class FileHandler extends LogHandler {
121
120
  const itemStrings: string[] = []
122
121
  let totalLength = prefix.length
123
122
  for (const item of args) {
124
- const itemString = this.formatDataItem(item)
123
+ const itemString = this.stringifyDataItem(item)
125
124
 
126
125
  // 截断过长的日志内容 Truncate overly long log messages
127
126
  if (totalLength + itemString.length < this.options.maxLength) {
@@ -138,8 +137,8 @@ export class FileHandler extends LogHandler {
138
137
  this.pushBuffer(prefix, ...itemStrings, '\n')
139
138
  }
140
139
 
141
- protected formatDataItem(item: unknown) {
142
- if (typeof item === 'string') return removeANSIColor(item)
140
+ protected stringifyDataItem(item: unknown) {
141
+ if (typeof item === 'string') return item
143
142
  if (item instanceof Error) return item.stack ?? String(item)
144
143
  try {
145
144
  const json = JSON.stringify(item) as string | undefined
package/src/init-dayjs.ts CHANGED
@@ -1,9 +1,8 @@
1
- import dayjs from 'dayjs'
1
+ import { extend, locale } from 'dayjs'
2
2
  import objectSupport from 'dayjs/plugin/objectSupport.js'
3
3
  import 'dayjs/locale/zh-cn.js'
4
4
 
5
5
  export function initDayJs() {
6
- // dayjs 的类型标记错误,这两个方法只能通过 dayjs 对象访问,并不能直接引入
7
- dayjs.extend(objectSupport) // eslint-disable-line import/no-named-as-default-member
8
- dayjs.locale('zh-cn') // eslint-disable-line import/no-named-as-default-member
6
+ extend(objectSupport)
7
+ locale('zh-cn')
9
8
  }
@@ -82,15 +82,3 @@ export function readableSize(bytes: number, si = false, dp = 1) {
82
82
  } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1)
83
83
  return `${bytes.toFixed(dp)} ${units[u]!}`
84
84
  }
85
-
86
- /**
87
- * 移除字符串中的 ASNI Color 修饰符
88
- * https://stackoverflow.com/a/7150870/2815178
89
- */
90
- export function removeANSIColor(string: string) {
91
- return string.replace(
92
- // eslint-disable-next-line no-control-regex
93
- /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
94
- '',
95
- )
96
- }
@@ -4,7 +4,7 @@ import { getLogger } from './index.js'
4
4
  /**
5
5
  * 适配 debug package
6
6
  */
7
- export function adaptDebugLib(debugLib: Debug, enable = '', logger = getLogger('3rd-library')) {
7
+ export function adaptDebugLib(debugLib: Debug, enable = '') {
8
8
  // 不在 localStorage 里记录 debugLib enable 状态,
9
9
  // 以解决 web worker 里读不到 localStorage 而无法启用 debugLib 日志的问题
10
10
  const emulate = {
@@ -31,11 +31,8 @@ export function adaptDebugLib(debugLib: Debug, enable = '', logger = getLogger('
31
31
  Object.assign(debugLib, emulate)
32
32
 
33
33
  // 将 debugLib 日志转发给 logger
34
- debugLib.log = (initial?: unknown, ...rest: unknown[]) => {
35
- // 移除开头的额外空格
36
- if (typeof initial === 'string') initial = initial.trimStart()
37
- logger.debug(initial, ...rest)
38
- }
34
+ const logger = getLogger('3rd-library')
35
+ debugLib.log = logger.debug.bind(logger)
39
36
 
40
37
  if (enable) {
41
38
  debugLib.enable(enable)
@@ -14,7 +14,7 @@ export enum LogLevel {
14
14
  }
15
15
 
16
16
  export interface LogInfo {
17
- logger: string // 生成此条日志的 logger name;有多级 logger 的情况下,这是最初的 logger 名称
17
+ logger: string // logger name;有多级 logger 的情况下,这是最初的 logger 名称
18
18
  level: LogLevel
19
19
  time: Dayjs
20
20
  args: unknown[] // log content
package/src/url.ts CHANGED
@@ -31,7 +31,7 @@ function parseQuery(url: string, options?: { array?: false, strict?: boolean }):
31
31
  function parseQuery(url: string, options: { array: true, strict?: boolean }): Record<string, string | string[]> // prettier-ignore
32
32
  function parseQuery(
33
33
  url: string,
34
- options?: { array?: boolean; strict?: boolean },
34
+ options?: { array?: boolean; strict?: boolean }
35
35
  ): Record<string, string | string[]> {
36
36
  if (!url) return {}
37
37
  const { array = false, strict = false } = options ?? {}
@@ -116,7 +116,7 @@ hash string 不带 # 号;若 url 已有 hash,会用此值代替
116
116
  export function combineUrl(
117
117
  origUrl: string,
118
118
  search?: Record<string, string | string[]>,
119
- hash?: string,
119
+ hash?: string
120
120
  ) {
121
121
  search = search ?? {}
122
122
  hash = hash ?? ''