@gobing-ai/ts-utils

中文文档
0.7.1发布于 2026/10/25Apache-2.0TypeScriptES Module零依赖构建来源已验证近 30 天下载 4872

Zero-dependency TypeScript utilities for dates, cursors, errors, output, origins, roles, and API responses.

原始使用文档
文档目录10 节
  1. Overview
  2. Architecture
  3. How It Works
  4. Error types
  5. Cursor-based pagination
  6. Role-based access control
  7. Date utilities
  8. Usage
  9. Install
  10. Common patterns

@gobing-ai/ts-utils

Shared utilities — error types, date helpers, cursor-based pagination, role-based access control, API response builders, and output formatting. No platform dependencies; works in Bun, Node, and Cloudflare Workers.

Overview

ts-utils provides small, composable utilities used across ts-runtime, ts-db, ts-infra, and application code. Each module is self-contained with zero external dependencies.

ModulePurpose
errorsTyped application errors (AppError, NotFoundError, ValidationError, etc.)
datenowMs(), timestamp ↔ Date conversion
cursorBase64url-encoded cursor-based pagination
accessZitadel + generic role-based access control (hasRole, getRoles)
api-responseStandard API response envelope builders
outputHuman-readable output helpers (tables, JSON, etc.)
originRequest origin parsing
constShared constants

Architecture

classDiagram
    class AppError {
        +ErrorCode code
        +string message
    }

    class NotFoundError {
    }

    class ValidationError {
    }

    class ConflictError {
    }

    class InternalError {
        +unknown cause?
    }

    class ErrorCode {
        <<enumeration>>
        NotFound
        Validation
        Conflict
        Internal
    }

    class CursorData {
        <<interface>>
        +string id
        +number createdAt?
        +number offset?
    }

    class CursorHelpers {
        +createCursor(id, createdAt?, offset?) CursorData
        +parseCursor(data) CursorData
        +encodeCursor(cursor) string
        +decodeCursor(encoded) string
        +encodeCursorFromItem(id, createdAt?, offset?) string
        +decodeAndParseCursor(encoded) CursorData
        +buildCursorMeta(items, limit, hasMore) object
    }

    class DateHelpers {
        +nowMs() number
        +toMs(input) number | null
        +fromMs(ms) Date | null
    }

    class AccessControl {
        +hasRole(profile, role) boolean
        +getRoles(profile) string[]
    }

    AppError <|-- NotFoundError
    AppError <|-- ValidationError
    AppError <|-- ConflictError
    AppError <|-- InternalError
    AppError --> ErrorCode

How It Works

Error types

Typed error hierarchy with error codes — consumers catch by type, not by string:

throw new NotFoundError(`User ${userId} not found`);
throw new ValidationError('Email is required');
throw new InternalError('DB connection lost', originalError);

// Callers can discriminate:
if (error instanceof NotFoundError) {
    return new Response(null, { status: 404 });
}
if (isAppError(error)) {
    // error.code is typed: 'NOT_FOUND' | 'VALIDATION' | 'CONFLICT' | 'INTERNAL'
}

Cursor-based pagination

Encode a cursor from the last item in a page, return it to the client, decode on the next request:

import { encodeCursorFromItem, decodeAndParseCursor } from '@gobing-ai/ts-utils';

// Page 1: encode cursor from last item
const cursor = encodeCursorFromItem(lastItem.id, lastItem.createdAt);
// → "eyJpZCI6ImFiYyIsImNyZWF0ZWRBdCI6MTcwMDAwMDAwMH0"

// Page 2: decode cursor from query param
const parsed = decodeAndParseCursor(requestCursor);
// → { id: "abc", createdAt: 1700000000 }

// Build pagination metadata
const meta = buildCursorMeta(items, limit, hasMore);
// → { nextCursor: "eyJ...", hasMore: true, limit: 20 }

Cursor flow:

sequenceDiagram
    Client->>API: GET /items?limit=20
    API->>DB: SELECT ... LIMIT 20
    DB-->>API: 20 rows
    API->>API: encodeCursorFromItem(lastItem)
    API-->>Client: { items: [...], nextCursor: "eyJ..." }

    Client->>API: GET /items?limit=20&cursor=eyJ...
    API->>API: decodeAndParseCursor("eyJ...")
    API->>DB: SELECT ... WHERE id > "abc" LIMIT 20
    DB-->>API: 20 rows
    API-->>Client: { items: [...], nextCursor: "..." }

Role-based access control

Supports Zitadel IAM roles and generic role arrays/objects:

import { hasRole, getRoles } from '@gobing-ai/ts-utils';

// Zitadel profile
const profile = {
    'urn:zitadel:iam:org:project:roles': { admin: 'project-1', viewer: 'project-1' },
};
hasRole(profile, 'admin'); // → true
getRoles(profile); // → ['admin', 'viewer']

// Generic roles array
hasRole({ roles: ['editor', 'viewer'] }, 'editor'); // → true

// Object-based roles
hasRole({ roles: { admin: true } }, 'admin'); // → true

Date utilities

import { nowMs, toMs, fromMs } from '@gobing-ai/ts-utils';

const ts = nowMs(); // → 1700000000000

toMs(new Date('2024-01-01')); // → 1704067200000
toMs('2024-01-01'); // → 1704067200000
toMs(null); // → null

fromMs(1704067200000); // → Date('2024-01-01')
fromMs(null); // → null

Usage

Install

bun add @gobing-ai/ts-utils

Common patterns

import {
    AppError, NotFoundError, ValidationError, ConflictError, InternalError,
    nowMs, toMs, fromMs,
    encodeCursorFromItem, decodeAndParseCursor, buildCursorMeta,
    hasRole, getRoles,
} from '@gobing-ai/ts-utils';

// Errors
function getUser(id: string) {
    const user = db.find(id);
    if (!user) throw new NotFoundError(`User ${id} not found`);
    return user;
}

// Pagination
async function listUsers(limit: number, cursor?: string) {
    const parsed = cursor ? decodeAndParseCursor(cursor) : undefined;
    const users = await db.query(limit, parsed?.id);
    const hasMore = users.length === limit;
    return {
        items: users,
        ...buildCursorMeta(users, limit, hasMore),
    };
}

// Auth guard
function requireAdmin(profile: unknown) {
    if (!hasRole(profile as Record<string, unknown>, 'admin')) {
        throw new ForbiddenError('Admin access required');
    }
}

版本与发布记录

@gobing-ai/ts-utils 共发布 137 个版本,首次发布于 2026/05/30;过去 12 个月发布了 137 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.7.1latest2026/10/2522 天前
0.7.02026/10/2522 天前
0.6.42026/10/2423 天前
0.6.32026/10/2424 天前
0.6.22026/10/2324 天前
0.6.12026/10/2324 天前

关于 @gobing-ai/ts-utils 的常见问题

@gobing-ai/ts-utils 是什么?

Zero-dependency TypeScript utilities for dates, cursors, errors, output, origins, roles, and API responses.

如何安装 @gobing-ai/ts-utils?

在项目目录运行 npm install @gobing-ai/ts-utils,或使用 pnpm add / yarn add / bun add。

@gobing-ai/ts-utils 支持 TypeScript 吗?

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

@gobing-ai/ts-utils 支持 ESM 还是 CommonJS?

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

@gobing-ai/ts-utils 可以商用吗?

@gobing-ai/ts-utils 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@gobing-ai/ts-utils 的下载量有多少?

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

@gobing-ai/ts-utils 还在维护吗?

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