# @gajae-code/utils 中文文档

规范地址：https://npmcn.com/package/%40gajae-code/utils/

版本：0\.21\.0
npm 元数据更新时间：2026-11-16T05:06:39.826Z
中文译文更新时间：2026-11-16T05:07:27.838Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40gajae-code/utils
原文对照：https://npmcn.com/package/%40gajae-code/utils/?lang=original
项目主页：https://gajae-code.com/
源码仓库：https://github.com/Yeachan-Heo/gajae-code

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：489 kB，92 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：4 个
- 首次发布：2026-05-27T18:45:24.068Z
- 最新版本发布：2026-11-16T05:06:39.506Z
- 近 30 天下载量：8374（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：159（近 12 个月 159 个）

## 中文简介

Pi 包共用水电费

## 安装

```sh
npm install @gajae-code/utils
```

也可以使用：`pnpm add @gajae-code/utils`、`yarn add @gajae-code/utils`、`bun add @gajae-code/utils`

## README

# @gajae-code/ utils (英语)

共享gajae-code包的功能:日志、配置和数据路径、环境访问、格式化、流、流程管理、文件助手和崩溃报告.

下面所有东西都从包根导出(`@gajae-code/utils`) (中文(简体) ). 一些模块作为命名空间导出;参见 [命名空间](https://npmcn.com/package/%40gajae-code/utils/#readme-namespaces)。 。 。 .

## 锁定器

导出为 `logger` 名称空间。 默认它会把 JSON 线条写入一个旋转文件, `gjc.<YYYY-MM-DD>.log` 日志目录中 (`getLogsDir()`,参见 [路径](https://npmcn.com/package/%40gajae-code/utils/#readme-paths-dirs)· ; `GJC_LOG_DIR` 推翻它). 它没有写出任何 stdout 或 stderr, 因为控制台输出会腐蚀 TUI.

```typescript
import { logger } from "@gajae-code/utils";

logger.info("Server started", { port: 3847 });
logger.warn("Retrying", { attempt: 3 });
logger.error("Connection failed", { error: "ECONNRESET" });
logger.debug("Request details", { url: "https://example.com" });

// Long-running headless services can log to the console instead of the file.
logger.setTransports({ console: true, file: false });
```

-   级别 : `error`, (中文(简体) ), `warn`, (中文(简体) ), `info`, (中文(简体) ), `debug`每个记录包括: `timestamp`, (中文(简体) ), `level`, (中文(简体) ), `pid`, (中文(简体) ), `message`,以及上下文字段.
-   旋转:每日文件,以10 MB,gzipped再旋转,最多保存了5个.
-   在伐木机完成加载前所写的记录被缓冲,可达一万.
-   `logger.time(op, fn)`, (中文(简体) ), `logger.startTiming()`, (中文(简体) ), `logger.endTiming()`,以及 `logger.printTimings()` 创纪录的筑巢时间跨度.

## 路径( E)`dirs`(中文(简体) )

```typescript
import {
  APP_NAME,
  CONFIG_DIR_NAME,
  getAgentDir,
  getConfigRootDir,
  getEffectiveLogsDir,
  getLogsDir,
  getProjectDir,
  getSessionsDir,
} from "@gajae-code/utils";

APP_NAME; // "gjc"
CONFIG_DIR_NAME; // ".gjc"

getConfigRootDir(); // config root, ~/.gjc by default
getAgentDir(); // agent directory under the config root
getSessionsDir(); // ~/.gjc/agent/sessions by default
getLogsDir(); // ~/.gjc/logs by default
getEffectiveLogsDir(); // where the logger actually writes (honors a trusted GJC_LOG_DIR)
getProjectDir(); // the current project directory (process.cwd() unless setProjectDir() changed it)
```

模块有较多的代理状态路径获取器( E)`getPluginsDir`, (中文(简体) ), `getMemoriesDir`, (中文(简体) ), `getCrashLogPath`, (中文(简体) ), `getMCPConfigPath`页:1 他们都进来了 `src/dirs.ts`。 。 。 .

环境变量读取于 `dirs`数字 :

| 变量 | 目的 |
| --- | --- |
| `GJC_CONFIG_DIR` | 配置目录名称( legacy) `PI_CONFIG_DIR`(中文(简体) ) |
| `GJC_CODING_AGENT_DIR` | 代理目录覆盖( 遗留) `PI_CODING_AGENT_DIR`(中文(简体) ) |
| `GJC_LOG_DIR` | 日志目录覆盖 |
| `XDG_DATA_HOME`, (中文(简体) ), `XDG_STATE_HOME`, (中文(简体) ), `XDG_CACHE_HOME` | XDG 基准目录(见下文) |

`<config>` 以下为 `~/.gjc`,或 `~/<GJC_CONFIG_DIR>` 当变量设定时。 XDG 路由只在设定变量时适用于 Linux 和 macOS **财务报告和审定财务报表** `$XDG_*_HOME/gjc` 已经存在( e)`gjc config init-xdg` 创建),并且只针对默认代理目录:

| 设置 | `getLogsDir()` | `getSessionsDir()` |
| --- | --- | --- |
| 默认代理目录, XDG 未使用 | `<config>/logs` | `<config>/agent/sessions` |
| 默认代理目录, XDG 在使用中 | `$XDG_STATE_HOME/gjc/logs` | `$XDG_DATA_HOME/gjc/sessions` |
| 自定义 `GJC_CODING_AGENT_DIR` (XDG 被忽略) | `<config>/logs` | `$GJC_CODING_AGENT_DIR/sessions` |

这些路径变量( E)`GJC_CONFIG_DIR`, (中文(简体) ), `GJC_CODING_AGENT_DIR`,以及 `XDG_*_HOME`) 只有在它们来自过程环境时才算出,比如你的外壳. 当前目录的 `.env` 无法设置它们 : Bun 加载到环境中, 但值等于 `.env` 条目被忽略。 如果 `.env` 条目用途 `$` 或 backtick 扩展,即使 shell 设置了不同的值,变量也会被忽略. 在这两种情况下,都适用默认路径.

## 环境`env`(中文(简体) )

```typescript
import { $env, $flag, $pickenv, parseEnvFile } from "@gajae-code/utils";

const home = $env.HOME;
const apiKey = $pickenv("ANTHROPIC_API_KEY", "OPENAI_API_KEY"); // first non-empty value
const verbose = $flag("GJC_VERBOSE"); // boolean flag, false when unset
const fromFile = parseEnvFile(".env"); // reads and parses the file at this path
```

## 格式化(`format`(中文(简体) )

```typescript
import {
  formatAge,
  formatBytes,
  formatCount,
  formatDuration,
  formatNumber,
  formatPercent,
  pluralize,
  truncate,
} from "@gajae-code/utils";

formatDuration(1500); // "1.5s"
formatDuration(123456789); // "1d10h"
formatNumber(12345); // "12K"
formatNumber(1234567); // "1.2M"
formatBytes(1024 * 1024); // "1.0MB"
formatPercent(0.1234); // "12.3%"
truncate("Hello World", 8); // "Hello W…"
formatCount("request", 42); // "42 requests"
formatAge(3661); // "1h ago" (argument in seconds)
pluralize("item", 5); // "items"
```

## 同步和流

```typescript
import { createAbortableStream, readJsonl, readLines, withTimeout } from "@gajae-code/utils";

// Rejects with the message if the promise does not settle within 5 s.
const response = await withTimeout(fetch("https://example.com"), 5000, "request timed out");

// readLines yields each line as bytes; readJsonl yields parsed values.
const body = createAbortableStream(response.body!, AbortSignal.timeout(10_000));
for await (const line of readLines(body)) {
  console.log(new TextDecoder().decode(line));
}
```

`readJsonl`, (中文(简体) ), `readSseJson`, (中文(简体) ), `readSseEvents`,以及 `parseJsonlLenient` 覆盖 JSONL 和服务器发送事件流 .

## 进程

进程助手通过 `ptree` 财务报告和审定财务报表 `procmgr` 名称空间。 错误类别 `AbortError`, (中文(简体) ), `ChildProcess`, (中文(简体) ), `Exception`,以及 `NonZeroExitError` 也可以在根上导出.

```typescript
import { procmgr, ptree } from "@gajae-code/utils";

const result = await ptree.exec(["git", "status", "--short"]);
if (result.ok) console.log(result.stdout);

const child = ptree.spawn(["bun", "--version"]);
procmgr.isPidRunning(child.pid);
```

## 文件

```typescript
import { globPaths, peekFile, TempDir, tryParseJson } from "@gajae-code/utils";

// Glob relative to cwd (defaults to getProjectDir()), with exclusions.
const sources = await globPaths("src/**/*.ts", { cwd: process.cwd(), exclude: ["**/*.test.ts"] });

// Read only the first bytes of a file.
const header = await peekFile("package.json", 64, bytes => new TextDecoder().decode(bytes));

// A temporary directory that is removed when the scope exits.
await using tmp = await TempDir.create("my-tool-");
console.log(tmp.path());

const parsed = tryParseJson<{ name: string }>("{\"name\":\"gjc\"}"); // null on invalid JSON
```

## 错误

```typescript
import { isDesignedError, isEnoent, markDesignedError, safeErrorDescription, toError } from "@gajae-code/utils";

try {
  await Bun.file("missing.txt").text();
} catch (error) {
  if (isEnoent(error)) console.log("not found");
  console.log(safeErrorDescription(error)); // a string for any thrown value
}

const expected = markDesignedError(new Error("user cancelled"));
isDesignedError(expected); // true
toError("plain string"); // wraps non-Error values in an Error
```

`isEacces`, (中文(简体) ), `isEisdir`, (中文(简体) ), `isEnotdir`, (中文(简体) ), `isEexist`, (中文(简体) ), `isEnotempty`,以及 `hasFsCode` 分类其他文件系统错误.

## 其他模块

| 模块 | 主要出口 |
| --- | --- |
| `color` | `hexToRgb`, (中文(简体) ), `rgbToHex`, (中文(简体) ), `hsvToRgb`, (中文(简体) ), `adjustHsv` |
| `crash-fingerprint`, (中文(简体) ), `crash-journal`, (中文(简体) ), `crash-redaction` | `computeCrashFingerprint`, (中文(简体) ), `appendCrashEvent`, (中文(简体) ), `redactCrashSecrets` |
| `fetch-retry` | `fetchWithRetry` |
| `frontmatter` | `parseFrontmatter` (回报) `{ frontmatter, body }`, (中文(简体) ), `FrontmatterError` |
| `mermaid-ascii` | `renderMermaidAscii` |
| `sanitize-text` | `sanitizeText`, (中文(简体) ), `sanitizeDisplayLine` |
| `snowflake` | `Snowflake` (各种身份帮助) |
| `tab-spacing` | `getDefaultTabWidth` (3个默认), `setDefaultTabWidth` |
| `type-guards` | `isRecord`, (中文(简体) ), `asRecord`, (中文(简体) ), `toError` |
| `which` | `$which` |

## 命名空间

这些模块被导出为命名空间而不是平面名称 :

| 命名空间 | 目录 |
| --- | --- |
| `logger` | 伐木和时间跨度 |
| `postmortem` | 崩溃记录 |
| `procmgr` | 进程活度和退出帮助 |
| `prompt` | 快速帮助者 |
| `ptree` | `spawn`, (中文(简体) ), `exec`,以及儿童流程课程 |

## 发展

```bash
cd packages/utils
bun run check   # Biome + tsc
bun test
```

## 许可证

麻省理工学院

## 常见问题

### @gajae-code/utils 是什么？

Pi 包共用水电费

### 如何安装 @gajae-code/utils？

在项目目录运行 npm install @gajae-code/utils，或使用 pnpm add / yarn add / bun add。

### @gajae-code/utils 支持 TypeScript 吗？

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

### @gajae-code/utils 支持 ESM 还是 CommonJS？

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

### @gajae-code/utils 可以商用吗？

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

### @gajae-code/utils 的下载量有多少？

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

### @gajae-code/utils 还在维护吗？

最新版本 0\.21\.0 发布于 2026/11/16（今天）；至今共发布 159 个版本，其中过去 12 个月发布了 159 个；首次发布于 2026/05/28。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

