@ happyvertical/ utils (欢快的垂直)
Hare SDK的基础公用设备:ID生成,日期解析,URL处理,字符串转换,出错分类,日志,代码提取/验证/发包,CLI参数解析,以及环境配置加载.
安装
pnpm add @happyvertical/utils
可在 @happyvertical/utils/browser (不包括Node.js特定代码,例如: node:vm 沙盒和 node:crypto 散开.
使用量
ID 生成
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
字符串和 URL 工具
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
日期公用事业
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
错误分类
全部扩展 BaseError 与 code, (中文(简体) ), context,以及 timestamp 字段,加 toJSON()数字 :
import { ValidationError, ApiError, NetworkError, TimeoutError, ParsingError, FileError, DatabaseError } from '@happyvertical/utils';
throw new ValidationError('Invalid email', { field: 'email', value: input });
代码提取和沙盒
从 markdown/ AI 回复中提取代码块, 验证, 并在孤立中执行 node:vm 语境 :
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 参数分析
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' } }
环境配置
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' }
});
日志
import { getLogger, setLogger, disableLogging } from '@happyvertical/utils';
const logger = getLogger();
logger.info('Started', { userId: 123 });
disableLogging(); // Switch to no-op logger
API 参考
身份证 —— 说 makeId(type?), (中文(简体) ), createId(), (中文(简体) ), isCuid(id)
字符串 —— 说 camelCase(str), (中文(简体) ), snakeCase(str), (中文(简体) ), keysToCamel(obj), (中文(简体) ), keysToSnake(obj), (中文(简体) ), domainToCamel(str), (中文(简体) ), makeSlug(str)
URL( URL) —— 说 urlFilename(url), (中文(简体) ), urlPath(url), (中文(简体) ), isUrl(str), (中文(简体) ), normalizeUrl(url), (中文(简体) ), generateScopeFromUrl(url), (中文(简体) ), hashPageContent(html)
日期 —— 说 dateInString(str), (中文(简体) ), prettyDate(str), (中文(简体) ), parseAmazonDateString(str), (中文(简体) ), formatDate(date, format?), (中文(简体) ), parseDate(str, format?), (中文(简体) ), isValidDate(date), (中文(简体) ), addInterval(date, duration)
多元化 —— 说 pluralizeWord(word), (中文(简体) ), singularize(word), (中文(简体) ), isPlural(word), (中文(简体) ), isSingular(word)
类型警卫 —— 说 isArray(obj), (中文(简体) ), isPlainObject(obj)
自动同步 —— 说 waitFor(fn, options?), (中文(简体) ), sleep(ms)
代码 —— 说 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?)
国 际 —— 说 parseCliArgs(argv, commands, builtInCommands?)
配置 —— 说 loadEnvConfig<T>(userOptions?, options?), (中文(简体) ), toCamelCase(str), (中文(简体) ), toScreamingSnakeCase(str), (中文(简体) ), convertType(value, type)
日志 —— 说 getLogger(), (中文(简体) ), setLogger(logger), (中文(简体) ), disableLogging(), (中文(简体) ), enableLogging()
杂项 —— 说 logTicker(tick, options?), (中文(简体) ), getTempDirectory(subfolder?)
错误分类 —— 说 BaseError, (中文(简体) ), ValidationError, (中文(简体) ), ApiError, (中文(简体) ), FileError, (中文(简体) ), NetworkError, (中文(简体) ), DatabaseError, (中文(简体) ), ParsingError, (中文(简体) ), TimeoutError
类型 —— 说 Logger, (中文(简体) ), ErrorCode, (中文(简体) ), Command, (中文(简体) ), OptionConfig, (中文(简体) ), ParsedArgs, (中文(简体) ), ConfigOptions<T>, (中文(简体) ), ValidationOptions, (中文(简体) ), ValidationResult, (中文(简体) ), SandboxOptions, (中文(简体) ), ExecuteOptions
许可证
麻省理工学院