@critical-path/client

中文文档
0.29.2发布于 2026/11/05MITTypeScriptES Module构建来源已验证近 30 天下载 4491

Type-safe JavaScript/TypeScript client SDK for consuming Critical Path API endpoints

原始使用文档
文档目录6 节
  1. 📦 Installation
  2. 💡 Usage Example
  3. ⚙️ Configuration
  4. Cancellation and per-call headers
  5. Errors
  6. 📄 License

@critical-path/client

Type-safe JavaScript/TypeScript HTTP Client SDK for Critical Path.

Upgrading? Upgrade every @critical-path/* package together. Coding agents: follow UPGRADING.md; breaking changes are marked BREAKING in this package's CHANGELOG.md.

@critical-path/client provides a lightweight, end-to-end type-safe SDK for interacting with Critical Path REST API endpoints from any web or Node.js application.


📦 Installation

npm install @critical-path/client
# or
pnpm add @critical-path/client

💡 Usage Example

import { CriticalPathClient } from '@critical-path/client';

const client = new CriticalPathClient({
  baseUrl: '/api/critical-path'
});

// Fetch projects
const projects = await client.getProjects();

// Fetch tasks for a project
const tasks = await client.getTasks('proj_1'); // every task, following pagination

// One page at a time, with filters
const { items, nextCursor } = await client.queryTasks({ projectId: 'proj_1', status: ['todo', 'in_progress'], limit: 50 });

// Create a new task
const newTask = await client.createTask({
  projectId: 'proj_1',
  title: 'Design UI Wireframes',
  priority: 'high',
  status: 'todo'
});

// Identity comes from your auth headers (resolved by the server's getContext), never from
// request bodies. Without auth, writes are attributed to "anonymous".

// Update task status
await client.updateTask(newTask.id, { status: 'in_progress' });

// Add threaded comment
const comment = await client.addComment({
  taskId: newTask.id,
  content: 'Initial implementation ready for review'
}); // authored by the caller the server resolves from your auth headers

// Add emoji reaction
await client.addCommentReaction(comment.id, { emoji: '🚀' });

// Remove emoji reaction
await client.removeCommentReaction(comment.id, { emoji: '🚀' });

// Upload file directly or register storage attachment
const attachment = await client.uploadAttachmentFile({
  filename: 'architecture.png',
  data: fileBuffer,
  mimeType: 'image/png',
  taskId: newTask.id,
  commentId: comment.id
}); // binary data is base64-encoded automatically

// Calculate Critical Path Method (CPM) schedule & bottlenecks
const cpmAnalysis = await client.calculateCriticalPath('proj_1'); // or { calendars: 'assignee', levelResources: true }
const portfolio = await client.calculatePortfolioCriticalPath({ projectIds: ['proj_1', 'proj_2'], calendars: 'assignee', levelResources: true });
// Options on both: effort: 'remaining'; on portfolio: includeHiddenWork, projectOrder
console.log('Total project duration:', cpmAnalysis.totalDurationHours);
console.log('Bottleneck tasks:', cpmAnalysis.criticalTaskIds);

// Ladder of Abstraction (macro, standard, concrete rungs)
const ladder = await client.getTimelineLadder('proj_1', { level: 'all' });
console.log('Macro phase progress:', ladder.macro?.overallProgressPercentage);
console.log('Standard Gantt items:', ladder.standard?.tasks.length);
console.log('Concrete deliverables & daily effort:', ladder.concrete);

// Single task ladder drilldown
const taskLadder = await client.getTaskLadder(newTask.id);

⚙️ Configuration

const client = new CriticalPathClient({
  baseUrl: '/api/critical-path',
  // Static headers, or a function called before every request (e.g. to refresh tokens)
  headers: async () => ({ Authorization: `Bearer ${await auth.getAccessToken()}` }),
  timeoutMs: 15_000,                       // abort slow requests (default: none)
  retry: { retries: 2, baseDelayMs: 250 }, // GET only: network errors, 429, 502-504 (default: off)
  fetch: customFetch                       // optional fetch implementation
});

Cancellation and per-call headers

with() returns a scoped client that applies options to every call it makes:

const controller = new AbortController();
const tasks = await client.with({ signal: controller.signal }).getTasks(projectId);
// later, e.g. when a component unmounts:
controller.abort();

await client.with({ headers: { 'X-Request-Id': id }, timeoutMs: 5_000 }).getProject(projectId);

Errors

Non-2xx responses throw CriticalPathError:

import { CriticalPathError } from '@critical-path/client';

try {
  await client.addDependency(taskId, { dependsOnTaskId });
} catch (err) {
  if (err instanceof CriticalPathError) {
    err.status;          // e.g. 409
    err.issues;          // field-level problems for 400 validation errors
    err.body?.cyclePath; // the rest of the server's error body
  }
}

Delete methods resolve to false instead of throwing when the resource does not exist. Network failures, timeouts (TimeoutError) and cancellations (AbortError) are thrown as-is.

Every server route has a client method; routes.test.ts fails if a route is added without one.


📄 License

MIT © Critical Path

版本与发布记录

@critical-path/client 共发布 86 个版本,首次发布于 2026/08/24;过去 12 个月发布了 86 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.29.2latest2026/11/055 天前
0.29.12026/11/037 天前
0.29.02026/11/038 天前
0.28.02026/10/2813 天前
0.27.22026/10/2813 天前
0.27.12026/10/2813 天前

关于 @critical-path/client 的常见问题

@critical-path/client 是什么?

Type-safe JavaScript/TypeScript client SDK for consuming Critical Path API endpoints

如何安装 @critical-path/client?

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

@critical-path/client 支持 TypeScript 吗?

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

@critical-path/client 支持 ESM 还是 CommonJS?

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

@critical-path/client 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@critical-path/client 可以商用吗?

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

@critical-path/client 的下载量有多少?

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

@critical-path/client 还在维护吗?

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