npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@catpanel/utils

v1.0.0

Published

Enterprise TypeScript utility library for Vue 3 + Vite + Module Federation projects

Readme

@catpanel/utils

企业级 TypeScript 工具函数库,为 Vue 3 + Vite + Module Federation 项目提供通用工具方法

Test Coverage Test Files TypeScript Vitest

📦 安装

# 使用 pnpm (推荐)
pnpm add @catpanel/utils

# 使用 npm
npm install @catpanel/utils

# 使用 yarn
yarn add @catpanel/utils

🚀 快速开始

TypeScript/ESM

// 导入所需的工具函数
import { isNil, deepClone, formatTime, checkEmail, unique, debounce } from '@catpanel/utils'

// 类型检查
if (isNil(value)) {
  console.log('值为 null 或 undefined')
}

// 深拷贝对象
const cloned = deepClone(originalObject)

// 格式化日期
const formatted = formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss')

// 验证邮箱
if (checkEmail('[email protected]')) {
  console.log('邮箱格式正确')
}

// 数组去重
const uniqueArray = unique([1, 2, 2, 3, 3])  // [1, 2, 3]

// 防抖函数
const debouncedFn = debounce(() => {
  console.log('执行操作')
}, 300)

CommonJS

const { isNil, deepClone, formatTime } = require('@catpanel/utils')

📚 功能模块

1. 类型检查 (type)

提供完整的类型守卫和类型检查工具。

import { isNil, isEmpty, isObject, isArray, isString } from '@catpanel/utils'

// 类型守卫
isNil(null)        // true
isNil(undefined)   // true
isEmpty('')        // true
isEmpty([])        // true
isObject({})       // true
isArray([1, 2])    // true
isString('hello')  // true

主要函数:

  • isNil, isNull, isUndefined - null/undefined 检查
  • isEmpty - 空值检查(支持字符串、数组、对象、Map、Set)
  • isObject, isArray, isFunction - 类型检查
  • isString, isNumber, isBoolean - 基础类型检查
  • isDate, isRegExp, isPromise - 特殊类型检查

2. 数据处理 (data)

提供对象、数组和数据的操作工具。

import { deepClone, camelCase, setSessionStorage, isMobile } from '@catpanel/utils'

// 深拷贝
const obj = deepClone({ a: { b: 1 } })

// 转换下划线为驼峰
camelCase('hello_world')  // 'helloWorld'

// Session Storage (带类型安全)
setSessionStorage('user', { name: 'Alice' })
const user = getSessionStorage<{ name: string }>('user')

// 设备检测
if (isMobile()) {
  // 移动端逻辑
}

主要函数:

  • deepClone - 深拷贝对象/数组
  • camelCase, underscoreToCamelCase - 命名转换
  • setSessionStorage, getSessionStorage, removeSessionStorage - Session Storage 操作
  • isMobile - 移动设备检测
  • setObjToUrlParams - 对象转 URL 参数
  • removeEmptyValues - 删除空白值
  • swapString - HTML 实体转换

3. 日期时间 (date)

提供日期格式化和时间处理工具。

import { formatTime, getSimplifyTime, getDuration } from '@catpanel/utils'

// 格式化时间
formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss')  // '2024-01-15 14:30:45'

// 相对时间
getSimplifyTime(Date.now() - 3600000)  // '1小时前'

// 秒转时长
getDuration(3665)  // '1小时1分5秒'

主要函数:

  • formatTime - 日期格式化
  • getSimplifyTime - 相对时间显示(刚刚、5分钟前等)
  • addDay - 日期加减
  • getTimeFrame - 获取时间范围
  • getDuration - 秒转天时分秒
  • getMonthDays - 获取月份天数
  • getFirstDayOfMonth - 获取月份第一天
  • getLastDayOfMonth - 获取月份最后一天

4. 验证函数 (check)

提供各种数据格式的验证工具。

import { checkEmail, checkPhone, checkIp, checkPort, checkDomain } from '@catpanel/utils'

// 验证邮箱
checkEmail('[email protected]')  // true

// 验证手机号
checkPhone('13812345678')  // true

// 验证 IP 地址
checkIp('192.168.1.1')  // true

// 验证端口
checkPort(8080)  // true

// 验证域名
checkDomain('example.com')  // true

主要函数:

  • checkEmail, checkPhone - 邮箱/手机号验证
  • checkIp, checkIp6 - IP 地址验证
  • checkPort - 端口验证
  • checkDomain, checkDomainPort - 域名验证
  • checkUrl, checkPanelUrl - URL 验证
  • checkVersion, compareVersion - 版本号比较

5. 表单验证规则 (rule)

Element Plus 表单验证规则(开箱即用)。

import { emailVerify, phoneVerify, pawVerify } from '@catpanel/utils'

// 在 Vue 3 组件中使用
const rules = {
  email: emailVerify(),
  phone: phoneVerify(),
  password: pawVerify({
    complex: { length: 8, small: true, big: true, number: true },
    message: {
      value: '请输入密码',
      length: '密码长度至少8位',
      small: '密码必须包含小写字母',
      big: '密码必须包含大写字母',
      number: '密码必须包含数字',
    }
  })
}

主要函数:

  • defaultVerify - 默认必填规则
  • userVerify - 用户名验证
  • pawVerify - 密码验证(支持复杂度配置)
  • emailVerify, phoneVerify - 邮箱/手机验证
  • ipVerify, urlVerify - IP/URL 验证
  • domainVerify, portVerify - 域名/端口验证

6. 常用工具 (common)

提供日常开发常用的工具函数。

import { getByteUnit, getStyleUnit, clearBlankSpace } from '@catpanel/utils'

// 字节单位转换
getByteUnit(1536)  // '1.50 KB'

// 样式单位处理
getStyleUnit(10, 'px')  // '10px'

// 清理空格
clearBlankSpace('hello world')  // 'helloworld'

主要函数:

  • getByteUnit - 字节单位转换
  • getStyleUnit - 样式单位处理
  • clearBlankSpace - 清理空格
  • isSame - 对象/数组比较
  • getQueryString - 获取URL参数
  • getExtension - 获取文件扩展名
  • getRandomStr - 生成随机字符串

7. 数组工具 (array)

提供丰富的数组操作函数。

import { unique, groupBy, chunk, shuffle, sortBy, flatten, arraySum } from '@catpanel/utils'

// 数组去重
unique([1, 2, 2, 3])  // [1, 2, 3]

// 按字段分组
groupBy([{type: 'a'}, {type: 'b'}], 'type')  // { a: [...], b: [...] }

// 分块
chunk([1, 2, 3, 4, 5], 2)  // [[1, 2], [3, 4], [5]]

// 打乱
shuffle([1, 2, 3])  // [3, 1, 2] (随机)

// 排序
sortBy([{a: 2}, {a: 1}], 'a')  // [{a: 1}, {a: 2}]

// 扁平化
flatten([1, [2, [3]]])  // [1, 2, [3]]

// 求和
arraySum([1, 2, 3, 4, 5])  // 15

主要函数:

  • unique, uniqueBy - 去重
  • groupBy - 分组
  • chunk - 分块
  • shuffle - 打乱
  • sortBy - 排序
  • flatten - 扁平化
  • difference, intersection, union - 集合操作
  • sample - 随机采样
  • arraySum, arrayAvg, arrayMax, arrayMin - 统计
  • paginate - 分页
  • range - 创建范围
  • move, swap - 移动/交换元素

8. 浏览器工具 (browser)

提供浏览器环境检测和操作工具。

import { getOS, getBrowser, copyToClipboard, isMobile } from '@catpanel/utils'

// 获取操作系统
getOS()  // 'Windows' | 'Mac' | 'Linux' | 'iOS' | 'Android'

// 获取浏览器类型
getBrowser()  // 'Chrome' | 'Firefox' | 'Safari' | 'Edge' | 'IE'

// 复制到剪贴板
await copyToClipboard('text to copy')

// 移动端检测
isMobile()  // boolean

主要函数:

  • getOS - 操作系统检测
  • getBrowser - 浏览器检测
  • getDevice - 设备类型检测
  • getBrowserLanguage - 获取浏览器语言
  • isOnline - 网络状态检测
  • isMobile, isIE, isChrome, isFirefox, isSafari - 浏览器判断
  • isWeChat, isQQ - 第三方浏览器判断
  • getUrlParams - URL参数解析
  • copyToClipboard - 剪贴板操作

9. 函数工具 (function)

提供函数式编程工具。

import { debounce, throttle, memoize, retry, compose, pipe } from '@catpanel/utils'

// 防抖
const debouncedFn = debounce(() => console.log('Hello'), 300)

// 节流
const throttledFn = throttle(() => console.log('Hello'), 300)

// 记忆化
const memoizedFn = memoize((n: number) => n * 2)

// 重试
await retry(() => fetchData(), { times: 3, delay: 1000 })

// 函数组合(从右到左)
const composed = compose(
  (x: number) => x * 2,
  (x: number) => x + 1
)
composed(3)  // 8

// 管道(从左到右)
const piped = pipe(
  (x: number) => x + 1,
  (x: number) => x * 2
)
piped(3)  // 8

主要函数:

  • debounce, throttle - 防抖/节流
  • sleep, delay - 延迟执行
  • once - 只执行一次
  • memoize - 记忆化
  • retry - 重试
  • timeout - 超时控制
  • compose, pipe - 函数组合
  • curry - 柯里化
  • settleAll - Promise.allSettled封装
  • limitConcurrency - 并发控制
  • poll - 轮询

10. 数学工具 (math)

提供数学计算和格式化工具。

import { randomInt, clamp, formatNumber, formatCurrency, formatBytes } from '@catpanel/utils'

// 随机整数
randomInt(1, 10)  // 1-10之间的随机整数

// 限制范围
clamp(5, 0, 10)  // 5
clamp(15, 0, 10)  // 10

// 数字格式化
formatNumber(1234567)  // '1,234,567'

// 货币格式化
formatCurrency(1234.5)  // '¥1,234.50'

// 文件大小格式化
formatBytes(1536)  // '1.50 KB'

主要函数:

  • randomInt, randomFloat - 随机数生成
  • clamp - 限制范围
  • formatNumber, formatPercent, formatCurrency - 格式化
  • formatBytes - 文件大小格式化
  • safeMath, add, sub, mul, div - 安全数学运算
  • sum, average, max, min - 统计
  • round, ceil, floor - 四舍五入
  • lerp, mapRange - 插值/映射
  • degToRad, radToDeg - 角度转换
  • isEven, isOdd, isPositive, isNegative - 判断

11. 字符串工具 (string)

提供字符串处理和格式化工具。

import { truncate, maskString, kebabCase, camelCase, snakeCase } from '@catpanel/utils'

// 截断
truncate('Hello World', 8)  // 'Hello...'

// 脱敏
maskString('13812345678', 3, 4)  // '138****5678'

// 大小写转换
kebabCase('helloWorld')  // 'hello-world'
camelCase('hello-world')  // 'helloWorld'
snakeCase('helloWorld')  // 'hello_world'

// 首字母大写
capitalize('hello')  // 'Hello'

// 生成唯一ID
uid('prefix')  // 'prefix_1732461234567-abc123'

主要函数:

  • truncate - 截断
  • maskString, maskPhone, maskEmail - 脱敏
  • kebabCase, camelCase, snakeCase - 命名转换
  • capitalize, lowercase - 大小写转换
  • hash - 哈希
  • uid - 唯一ID
  • compile - 模板编译
  • reverse - 反转
  • countOccurrences - 统计出现次数
  • removeSpaces, removeSpecialChars - 移除字符
  • isJSON - JSON检测
  • toBase64, fromBase64 - Base64编解码
  • encodeURL, decodeURL - URL编解码
  • highlightKeyword - 高亮关键词
  • stringToColor - 字符串转颜色

12. 随机数工具 (random)

提供随机数和密码生成工具。

import { getRandomChart, getRandomPwd, getComplexRandomString } from '@catpanel/utils'

// 生成随机字符串
getRandomChart(10, 'default')  // 10位随机字符

// 生成密码
getRandomPwd(16)  // 16位随机密码

// 生成复杂随机字符串
getComplexRandomString(12)  // 包含大小写字母和数字

// 根据配置生成密码
generatePasswordByConfig({
  validatePasswordLength: 16,
  validatePasswordMixedCaseCount: 2,
  validatePasswordNumberCount: 2,
  validatePasswordSpecialCharCount: 2
})

主要函数:

  • getRandomChart - 生成随机字符串(支持多种类型)
  • getRandomPrefix - 生成带前缀的随机字符串
  • getRandomPwd - 生成密码
  • getRandom - 生成随机hex字符串
  • getComplexRandomString - 生成复杂随机字符串
  • generatePasswordByConfig - 根据配置生成密码

13. 其他工具 (other)

提供文件类型判断和其他工具。

import { determineFileType, getExtIcon, getFileExt } from '@catpanel/utils'

// 判断文件类型
determineFileType('jpg')  // 'images'
determineFileType('jpg', 'images')  // true

// 获取文件图标
getExtIcon('image.jpg', 'file')  // 'jpg'

// 获取文件扩展名
getFileExt('archive.tar.gz')  // 'gz'

主要函数:

  • determineFileType - 文件类型判断
  • getExtIcon - 获取文件图标
  • getFileExt - 获取文件扩展名
  • setColumnCustom - 设置缓存表格列

14. DOM工具 (dom)

提供DOM操作工具。

import { getBody, setCenterInBody, inputFocus, setFullScreen } from '@catpanel/utils'

// 获取body元素
const body = getBody()

// 居中元素
setCenterInBody(element)

// 聚焦元素
inputFocus(element, 'fieldName')

// 全屏
setFullScreen()
exitFullscreen()

主要函数:

  • getBody - 获取body元素
  • setCenterInBody - 居中元素
  • inputFocus, ruleInputFocus - 聚焦
  • setFullScreen, exitFullscreen - 全屏控制
  • clearAssignStyle - 清除样式
  • getElementsByClassName - 按类名获取元素
  • scrollBottom - 滚动到底部
  • getChildElementByClassName - 获取子元素
  • loadFiles - 动态加载文件

15. 错误处理 (error)

提供错误处理和抛出工具。

import { throwConfigError, throwFileTypeError, throwValidationError } from '@catpanel/utils'

// 抛出配置错误
throwConfigError('Invalid config', { key: 'value' })

// 抛出文件类型错误
throwFileTypeError('Invalid file type', { ext: 'xyz' })

// 抛出验证错误
throwValidationError('Validation failed', { field: 'email' })

主要函数:

  • throwConfigError - 配置错误
  • throwFileTypeError - 文件类型错误
  • throwValidationError - 验证错误

16. Worker管理器 (worker-manager)

提供Web Worker管理功能。

import { ProWorkerManager } from '@catpanel/utils'

// 创建Worker管理器
const manager = new ProWorkerManager(workerScript, {
  concurrency: 4
})

// 执行任务
const result = await manager.exec(payload, {
  priority: 'HIGH',
  timeout: 5000,
  signal: abortSignal
})

// 终止所有worker
manager.terminate()

主要功能:

  • 优先级任务调度
  • 并发控制
  • 超时处理
  • 任务取消
  • 进度回调
  • Worker崩溃自动恢复

🧪 测试

本项目拥有 450+ 测试用例,覆盖 16 个功能模块,确保代码质量和稳定性。

# 运行所有测试
pnpm test

# 查看测试覆盖率
pnpm test:coverage

# 监听模式(开发时使用)
pnpm test:watch

# UI 模式
pnpm test:ui

测试文件列表

  • test/array.test.ts - 32 tests
  • test/browser.test.ts - 44 tests
  • test/check.test.ts - 47 tests
  • test/common.test.ts - 11 tests
  • test/data.test.ts - 50 tests
  • test/date.test.ts - 40 tests
  • test/dom.test.ts - 29 tests
  • test/error.test.ts - 28 tests
  • test/function.test.ts - 29 tests
  • test/math.test.ts - 57 tests
  • test/other.test.ts - 21 tests
  • test/random.test.ts - 34 tests
  • test/rule.test.ts - 54 tests
  • test/string.test.ts - 57 tests
  • test/type.test.ts - 30 tests

🏗️ 构建与开发

# 开发模式(监听文件变化)
pnpm dev

# 构建
pnpm build

# 类型检查
pnpm type-check

# 代码检查
pnpm lint
pnpm lint:fix

📊 模块概览

| 模块 | 函数数量 | 测试覆盖 | 说明 | |------|---------|---------|------| | type | 30+ | 30 tests | 类型检查和类型守卫 | | check | 40+ | 47 tests | 数据验证 | | rule | 13 | 54 tests | 表单验证规则 | | data | 17 | 50 tests | 数据处理 | | date | 15 | 40 tests | 日期时间处理 | | common | 10 | 11 tests | 常用工具 | | error | 3 | 28 tests | 错误处理 | | array | 45 | 32 tests | 数组操作 | | browser | 13 | 44 tests | 浏览器检测 | | function | 14 | 29 tests | 函数式编程 | | math | 35 | 57 tests | 数学计算 | | string | 25 | 57 tests | 字符串处理 | | random | 6 | 34 tests | 随机数生成 | | other | 4 | 21 tests | 其他工具 | | dom | 10 | 29 tests | DOM操作 | | worker-manager | 1 class | - | Web Worker管理 |

🔧 TypeScript 支持

本库完全使用 TypeScript 编写,提供完整的类型定义。

// 所有函数都有完整的类型标注
import { isEmpty } from '@catpanel/utils'

const value: string | null = null

if (isEmpty(value)) {
  // TypeScript 知道这里 value 是 string | null
  // 但 isEmpty 返回 boolean,不会进行类型收窄
}

// 使用类型守卫进行类型收窄
import { isString } from '@catpanel/utils'

if (isString(value)) {
  // TypeScript 知道这里 value 是 string
  console.log(value.length)
}

🤝 贡献指南

欢迎贡献代码!请遵循以下步骤:

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 开启 Pull Request

开发规范

  • 遵循 ESLint 规则
  • 添加单元测试(新功能覆盖率需 > 80%)
  • 更新相关文档
  • 确保 TypeScript 类型正确

📄 License

MIT

🙏 致谢

感谢所有为这个项目做出贡献的开发者!


Note: 本库是 panel-docker 项目的一部分,专为 Vue 3 + Vite + Module Federation 微前端架构设计。