@gajae-code/utils

中文文档
0.21.0发布于 2026/11/16MITTypeScriptES Module构建来源已验证近 30 天下载 8374

Pi 包共用水电费

中文使用文档
文档目录12 节
  1. 锁定器
  2. 路径( E) dirs (中文(简体) )
  3. 环境 env (中文(简体) )
  4. 格式化( format (中文(简体) )
  5. 同步和流
  6. 进程
  7. 文件
  8. 错误
  9. 其他模块
  10. 命名空间
  11. 发展
  12. 许可证

@gajae-code/ utils (英语)

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

下面所有东西都从包根导出(@gajae-code/utils) (中文(简体) ). 一些模块作为命名空间导出;参见 命名空间。 。 。 .

锁定器

导出为 logger 名称空间。 默认它会把 JSON 线条写入一个旋转文件, gjc.<YYYY-MM-DD>.log 日志目录中 (getLogsDir(),参见 路径· ; GJC_LOG_DIR 推翻它). 它没有写出任何 stdout 或 stderr, 因为控制台输出会腐蚀 TUI.

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(中文(简体) )

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_HOMEXDG 基准目录(见下文)

<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(中文(简体) )

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(中文(简体) )

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"

同步和流

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 也可以在根上导出.

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);

文件

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

错误

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 分类其他文件系统错误.

其他模块

模块主要出口
colorhexToRgb, (中文(简体) ), rgbToHex, (中文(简体) ), hsvToRgb, (中文(简体) ), adjustHsv
crash-fingerprint, (中文(简体) ), crash-journal, (中文(简体) ), crash-redactioncomputeCrashFingerprint, (中文(简体) ), appendCrashEvent, (中文(简体) ), redactCrashSecrets
fetch-retryfetchWithRetry
frontmatterparseFrontmatter (回报) { frontmatter, body }, (中文(简体) ), FrontmatterError
mermaid-asciirenderMermaidAscii
sanitize-textsanitizeText, (中文(简体) ), sanitizeDisplayLine
snowflakeSnowflake (各种身份帮助)
tab-spacinggetDefaultTabWidth (3个默认), setDefaultTabWidth
type-guardsisRecord, (中文(简体) ), asRecord, (中文(简体) ), toError
which$which

命名空间

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

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

发展

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

许可证

麻省理工学院

版本与发布记录

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

版本发布日期距今
0.21.0latest2026/11/16今天
0.20.1-nightly.20261108030927.43711868338.gb4127889c4a8nightly2026/11/15今天
0.20.1-nightly.20261108030927.43590872198.gb4127889c4a82026/11/141 天前
0.20.1-nightly.20261108030927.43424588966.gb4127889c4a82026/11/132 天前
0.20.1-nightly.20261108030927.43222623203.gb4127889c4a82026/11/123 天前
0.20.1-nightly.20261108030927.43016219422.gb4127889c4a82026/11/114 天前

关于 @gajae-code/utils 的常见问题

@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 和提交记录判断。