@critical-path/server

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

Web Fetch API compatible server router and adapters for Next.js App Router, SvelteKit, and Express

原始使用文档
文档目录8 节
  1. 📦 Installation
  2. 🚀 Next.js App Router Integration
  3. 🧡 SvelteKit Integration
  4. 🔐 Authentication, CORS & Mount Path
  5. ✅ Request Validation & OpenAPI
  6. ⚠️ Error Responses
  7. Reporting & Exposing Unexpected Errors
  8. 📄 License

@critical-path/server

Web Fetch API compatible server router & framework adapters 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/server bridges standard Web Fetch API Request and Response objects to @critical-path/core, offering turnkey adapters for Next.js App Router and SvelteKit.


📦 Installation

npm install @critical-path/core @critical-path/server
# or
pnpm add @critical-path/core @critical-path/server

🚀 Next.js App Router Integration

File: app/api/critical-path/[...path]/route.ts

import { createNextHandler } from '@critical-path/server';
import { SQLiteStore } from '@critical-path/core';

export const { GET, POST, PUT, PATCH, DELETE, OPTIONS } = createNextHandler({
  store: new SQLiteStore({ filename: 'critical-path.db' })
});

// Equivalent: the handler is also callable, so `export { handler as GET, ... }` works too.

🧡 SvelteKit Integration

File: src/routes/api/critical-path/[...path]/+server.ts

import { createSvelteKitHandler } from '@critical-path/server';

const handler = createSvelteKitHandler();

export const GET = handler.GET;
export const POST = handler.POST;
export const PUT = handler.PUT;
export const PATCH = handler.PATCH;
export const DELETE = handler.DELETE;
export const OPTIONS = handler.OPTIONS;

🔐 Authentication, CORS & Mount Path

Router options are the second argument to createNextHandler, createSvelteKitHandler, createUniversalHandler and new CriticalPathRouter(config, options):

OptionDefaultDescription
getContext(request)noneResolve the caller ({ userId, userName?, actorType?, tenantId?, roles? }). tenantId and roles feed the engine's tenant isolation and authorize policy. Every mutation is attributed to that user, or to anonymous (ANONYMOUS_ACTOR) when no user is resolved. Request bodies never carry identity. For SvelteKit it receives the RequestEvent, so event.locals is available.
requireAuthfalseReturn 401 unless getContext yields a userId. OPTIONS preflight is always allowed.
maxBodyBytes10 MiBLargest accepted request body; larger bodies get 413 (enforced while streaming, not just via Content-Length).
basePathstrip up to first /critical-pathExact mount path, e.g. /api/pm. Requests outside it return 404.
corsfalse (no CORS headers){ origins: string[] | '*', credentials?, allowHeaders?, maxAge? }, or false for no CORS headers. credentials cannot be combined with '*'.
onError, exposeErrorssee belowUnexpected error reporting.
export const { GET, POST, PUT, PATCH, DELETE, OPTIONS } = createNextHandler(
  { store },
  {
    getContext: async () => {
      const session = await auth();
      return session?.user ? { userId: session.user.id } : null;
    },
    requireAuth: true,
    cors: { origins: ['https://app.example.com'], credentials: true } // omit for same-origin apps
  }
);

For other Fetch runtimes (Workers, Deno, Bun, Hono), use createUniversalHandler(config, options), which returns (request) => Promise<Response>.


✅ Request Validation & OpenAPI

Every request body is parsed with the zod schemas from @critical-path/core/schemas before it reaches the engine:

  • Wrong types or missing required fields return 400 with issues: [{ path, message }].
  • Bodies are strict: server-assigned fields (id, createdAt, updatedAt, task key, the owning projectId on updates), identity fields (actorId, authorId, userId, uploaderId) and unknown keys are rejected with 400, so a PATCH cannot move a task to another project or rewrite timestamps.
  • Authors of comments, reactions, attachments and time entries are the resolved caller, or anonymous. Remove a reaction with DELETE /comments/:id/reactions?emoji=👍.

Webhooks are managed at GET/POST /webhooks and GET/PATCH/DELETE /webhooks/:id (workspace.manage under a role policy). POST returns the signing secret once.

GET /openapi.json serves an OpenAPI 3.1 document whose request bodies are generated from the same schemas (behind the same auth as other routes). It includes plugin routes, described by their openapi metadata (or hidden: true to omit one). To publish it statically:

import { buildOpenApiDocument } from '@critical-path/server';

const doc = buildOpenApiDocument({ serverUrl: 'https://app.example.com/api/critical-path', pluginRoutes: engine.plugins.getRoutes() });

⚠️ Error Responses

StatusWhen
400Malformed JSON, invalid body (with issues), ValidationError, workflow transition or custom field validation failures
401requireAuth is set and no user was resolved
403The engine's authorize policy denies the action (ForbiddenError)
404Unknown route (paths must match exactly; extra segments never fall through to a parent route), NotFoundError, or DELETE of a resource that does not exist (successful deletes return { "success": true })
405Known path, wrong method (with an Allow header)
409CircularDependencyError (body includes cyclePath)
413Request body larger than maxBodyBytes
415Non-empty body not sent as application/json (blocks cross-site form posts)
500Unexpected errors. The body is always { "error": "Internal Server Error" }; the real error is logged with console.error.

OPTIONS preflight requests return 204 with CORS headers.

Reporting & Exposing Unexpected Errors

Both adapters (and new CriticalPathRouter(config, options)) accept router options as a second argument:

export const { GET, POST, PUT, PATCH, DELETE, OPTIONS } = createNextHandler(
  { store },
  {
    // Called only for unexpected (500) errors. Return a Response to replace the default.
    onError: (error, request) => {
      Sentry.captureException(error, { extra: { url: request.url } });
    },
    // Include real error messages in 500 responses.
    // Defaults to true only when NODE_ENV === 'development'.
    exposeErrors: false
  }
);

Without onError, unexpected errors are logged with console.error. Expected errors (400, 404, 409) always include their message and never reach onError.


📄 License

MIT © Critical Path

版本与发布记录

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

版本发布日期距今
0.37.1latest2026/11/055 天前
0.37.02026/11/037 天前
0.36.02026/11/038 天前
0.35.02026/10/2813 天前
0.34.12026/10/2813 天前
0.34.02026/10/2813 天前

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

@critical-path/server 是什么?

Web Fetch API compatible server router and adapters for Next.js App Router, SvelteKit, and Express

如何安装 @critical-path/server?

在项目目录运行 npm install @critical-path/server,或使用 pnpm add / yarn add / bun add。

@critical-path/server 支持 TypeScript 吗?

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

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

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

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

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

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

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

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

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

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

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