@happyvertical/utils

中文文档
0.113.1发布于 2026/11/17MITTypeScriptES Module近 30 天下载 5.7万

Foundation utilities for ID generation, date parsing, URL handling, string conversion, error handling, and logging

原始使用文档
文档目录12 节
  1. Installation
  2. Usage
  3. ID Generation
  4. String & URL Utilities
  5. Date Utilities
  6. Error Classes
  7. Code Extraction & Sandbox
  8. CLI Argument Parsing
  9. Environment Config
  10. Logging
  11. API Reference
  12. License

@happyvertical/utils

Foundation utilities for the HAVE SDK: ID generation, date parsing, URL handling, string conversion, error classes, logging, code extraction/validation/sandboxing, CLI argument parsing, and environment config loading.

Installation

pnpm add @happyvertical/utils

A browser-safe entry point is available at @happyvertical/utils/browser (excludes Node.js-specific code like node:vm sandbox and node:crypto hashing).

Usage

ID Generation

import { makeId, createId, isCuid } from '@happyvertical/utils';

const id = makeId();         // CUID2 (default)
const uuid = makeId('uuid'); // UUID via crypto.randomUUID()
const cuid = createId();     // CUID2 directly
isCuid(id);                  // true

String & URL Utilities

import { camelCase, snakeCase, keysToCamel, keysToSnake, makeSlug, urlFilename, isUrl } from '@happyvertical/utils';

camelCase('hello-world');      // "helloWorld"
snakeCase('helloWorld');       // "hello_world"
keysToCamel({ user_name: 'j' }); // { userName: 'j' } (recursive)
makeSlug('My Title & Co.');   // "my-title-38-co"
urlFilename('https://example.com/path/file.pdf'); // "file.pdf"
isUrl('https://example.com'); // true

Date Utilities

import { dateInString, formatDate, parseDate, parseAmazonDateString, addInterval } from '@happyvertical/utils';

dateInString('Report_January_15_2023.pdf'); // Date(2023, 0, 15)
formatDate(new Date(), 'yyyy-MM-dd');       // "2023-01-15"
parseDate('2023-01-15');                    // Date object (ISO)
parseDate('01/15/2023', 'MM/dd/yyyy');      // Date object (custom format)
parseAmazonDateString('20220223T215409Z');   // Date object
addInterval(new Date(), { days: 7 });       // Date 7 days from now

Error Classes

All extend BaseError with code, context, and timestamp fields, plus toJSON():

import { ValidationError, ApiError, NetworkError, TimeoutError, ParsingError, FileError, DatabaseError } from '@happyvertical/utils';

throw new ValidationError('Invalid email', { field: 'email', value: input });

Code Extraction & Sandbox

Extract code blocks from markdown/AI responses, validate, and execute in isolated node:vm contexts:

import { extractCodeBlock, extractJSON, validateCode, executeInSandbox } from '@happyvertical/utils';

const code = extractCodeBlock(markdownText, 'javascript');
const data = extractJSON<{ name: string }>(aiResponse);

const result = validateCode(code, { maxLength: 10000 });
if (result.valid) {
  const output = executeInSandbox(code, { globals: { data }, timeout: 5000 });
}

CLI Argument Parsing

import { parseCliArgs } from '@happyvertical/utils';

const parsed = parseCliArgs(process.argv, [
  { name: 'build', description: 'Build project', options: { output: { type: 'string', description: 'Output dir' } } }
]);
// { command: 'build', args: [], options: { output: './dist' } }

Environment Config

import { loadEnvConfig } from '@happyvertical/utils';

// Loads HAVE_AI_* env vars, merged with user options (user options take precedence)
const config = loadEnvConfig({ provider: 'openai' }, {
  packageName: 'ai',
  schema: { provider: 'string', model: 'string', timeout: 'number' }
});

Logging

import { getLogger, setLogger, disableLogging } from '@happyvertical/utils';

const logger = getLogger();
logger.info('Started', { userId: 123 });
disableLogging(); // Switch to no-op logger

API Reference

IDs — makeId(type?), createId(), isCuid(id)

Strings — camelCase(str), snakeCase(str), keysToCamel(obj), keysToSnake(obj), domainToCamel(str), makeSlug(str)

URLs — urlFilename(url), urlPath(url), isUrl(str), normalizeUrl(url), generateScopeFromUrl(url), hashPageContent(html)

Dates — dateInString(str), prettyDate(str), parseAmazonDateString(str), formatDate(date, format?), parseDate(str, format?), isValidDate(date), addInterval(date, duration)

Pluralization — pluralizeWord(word), singularize(word), isPlural(word), isSingular(word)

Type Guards — isArray(obj), isPlainObject(obj)

Async — waitFor(fn, options?), sleep(ms)

Code — extractCodeBlock(text, lang?), extractAllCodeBlocks(text, lang?), extractJSON<T>(text), extractFunctionDefinition(code, name), validateCode(code, options?), isSafeCode(code), createSandbox(options?), executeCode(code, sandbox, options?), executeCodeAsync(code, sandbox, options?), executeInSandbox(code, options?), executeInSandboxAsync(code, options?)

CLI — parseCliArgs(argv, commands, builtInCommands?)

Config — loadEnvConfig<T>(userOptions?, options?), toCamelCase(str), toScreamingSnakeCase(str), convertType(value, type)

Logging — getLogger(), setLogger(logger), disableLogging(), enableLogging()

Misc — logTicker(tick, options?), getTempDirectory(subfolder?)

Error Classes — BaseError, ValidationError, ApiError, FileError, NetworkError, DatabaseError, ParsingError, TimeoutError

Types — Logger, ErrorCode, Command, OptionConfig, ParsedArgs, ConfigOptions<T>, ValidationOptions, ValidationResult, SandboxOptions, ExecuteOptions

License

MIT

版本与发布记录

@happyvertical/utils 共发布 131 个版本,首次发布于 2026/06/23;过去 12 个月发布了 131 个版本。

版本发布日期距今
0.113.1latest2026/11/17今天
0.113.02026/11/152 天前
0.112.32026/11/134 天前
0.112.22026/11/125 天前
0.112.02026/11/125 天前
0.112.12026/11/125 天前

关于 @happyvertical/utils 的常见问题

@happyvertical/utils 是什么?

Foundation utilities for ID generation, date parsing, URL handling, string conversion, error handling, and logging

如何安装 @happyvertical/utils?

在项目目录运行 npm install @happyvertical/utils,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 have-utils-context,可以用 npx have-utils-context 直接运行。

@happyvertical/utils 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@happyvertical/utils 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@happyvertical/utils 可以商用吗?

@happyvertical/utils 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@happyvertical/utils 的下载量有多少?

根据 npm 官方下载统计,@happyvertical/utils 在 2026/10/17 – 2026/11/15 这 30 天内被下载 56,776 次,日均约 1,893 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@happyvertical/utils 还在维护吗?

最新版本 0.113.1 发布于 2026/11/17(今天);至今共发布 131 个版本,其中过去 12 个月发布了 131 个;首次发布于 2026/06/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。