@_linked/server-utils

中文文档
1.17.0发布于 2026/10/28MITTypeScriptES Module构建来源已验证近 30 天下载 4429

provides a set of utilities for applications with a lincd-server backend.

原始使用文档
文档目录8 节
  1. Server
  2. Failed calls
  3. Authentication hook
  4. Which provider methods a client may call
  5. Work with no user: runAsSystem
  6. LinkedEmail
  7. Setting a default provider
  8. Shared state and error brands

lincd-server-utils

provides a set of utilities for applications with a lincd-server backend.

Server

import { Server } from 'lincd-server-utils/lib/utils/Server';

Call the server from the frontend.

Failed calls

By default a call that fails with a non-2xx response logs a warning and resolves undefined.

To reject instead, pass a CallConfig with rejectOnError: true as the method:

import { Server, ServerCallError } from '@_linked/server-utils/utils/Server';

try {
  const result = await Server.call(this, { method: 'selectQuery', rejectOnError: true }, query);
} catch (err) {
  if (ServerCallError.is(err)) {
    err.status; // e.g. 500 (provider threw) or 501 (no provider for the call)
    err.message; // the server's {error} message, or the status text
  }
}

With the opt-in a successful call still resolves whatever the provider returned, including null or undefined.

On the backend, Server.call calls the local server directly and follows the same rules:

  • No provider. A call that no provider handles resolves undefined by default. With rejectOnError it rejects with status 501.
  • Provider throws. A provider method that throws always rejects. With rejectOnError the rejection is a ServerCallError with status 500, and the original error is kept as cause.

Authentication hook

An auth package keeps a session alive around server calls by registering an AuthHandler. server-utils has no knowledge of tokens: the handler changes the default headers (Server.addDefaultHeaders / Server.removeDefaultHeaders), and each request's headers are built after the hook has run.

import { Server } from '@_linked/server-utils/utils/Server';

Server.setAuthHandler({
  // before every request: e.g. refresh a token that has already expired
  async beforeRequest(url, init) {
    if (tokenExpired()) await refresh(); // refresh() calls Server.addDefaultHeaders(...)
  },
  // after a 401: resolve true to send the request again, once, with the current default headers
  async onUnauthorized(url, response) {
    return refresh();
  },
});
  • Which calls. Every call made over HTTP: Server.call, Server.customPost and Server.callCustomShapeMethod. Calls made directly against the local server on the backend do not use it. There is one handler; setting another replaces it and null removes it.
  • init is a preview. To change what is sent, change the default headers.
  • 401 only. A 403 means the caller is known and not allowed; refreshing does not help, so it is not passed to onUnauthorized.
  • At most one retry per call. The retry's response goes to the caller as is: a second 401 is not passed to onUnauthorized again. If the default headers changed while the request was in flight (another call refreshed meanwhile), a 401 is retried once without asking.
  • Concurrency. Retry state belongs to each call. Making concurrent refreshes share one round trip is the handler's job.
  • A throwing hook is logged and treated as "no change" / "do not retry"; the call goes on.
  • Response actions are not retried. A provider that answers 200 with a response action (for example @_linked/auth's ENFORCE_SIGNIN) has already run, and may have written something before deciding the caller is not signed in, so sending the request again is not safe. Response actions keep going to Server.registerActionHandler.

callCustomShapeMethod sends the default headers, except Content-Type (its body is often FormData, which needs the browser to set the boundary). Headers passed to it win. Its body is sent again on a retry, so use a body that can be (a string, FormData, a Blob), not a stream.

Which provider methods a client may call

A provider method is reachable over /call/... only when it is declared. TypeScript private and protected do not exist at runtime, so the declaration is what decides. There are three declarations, all in @_linked/server-utils/utils/callable (no server imports, safe to load on the client):

  • @callable('public' | 'signed-in') on an instance method, or declareCallable(Cls, {method: level}) in plain JS. 'user' is a deprecated alias of 'signed-in', treated exactly like it.
  • @internal() on an instance method, or declareInternal(Cls, ['method']). It also works on a class you import from another package.
  • No declaration at all.

What each one does when a client calls the method:

DeclarationOver HTTP
@callable('public')Anyone may call it, signed in or not.
@callable('signed-in')Without a session the server answers 401 before the method body runs. The body reads the user from the call context, never from its arguments.
undeclaredDepends on server.rpcExposure in @_linked/server: in warn mode (the default) it runs and is logged once; in enforce mode it is 501, as if the method did not exist.
@internal()Never dispatched over HTTP, in any mode (501), even when it is also declared callable. Backend code still calls it with Server.call.

A method that acts for a signed-in user must be declared @callable('signed-in') and read the user with requireSessionUser(). 'public' lets anyone in, and a user id in the arguments is whatever the client sent.

import { BackendProvider } from '@_linked/server-utils/utils/BackendProvider';
import { callable, internal } from '@_linked/server-utils/utils/callable';
import { requireSessionUser } from '@_linked/server-utils/utils/CallContext';

export default class NotesBackendProvider extends BackendProvider {
  @callable('public')
  getPublicNotes() {
    return loadPublicNotes();
  }

  @callable('signed-in')
  getMyNotes() {
    const user = requireSessionUser(); // the session's user account, not an argument
    return loadNotesOf(user);
  }

  @internal()
  purgeNotes(olderThan: Date) {
    // only reachable from backend code
  }
}

requireSessionUser() throws a 401 ServerCallError in an HTTP call without a session, so it is also the check for a method whose declaration someone forgets.

Some rules worth knowing:

  • Only instance methods can be declared; a static method or a misspelt name throws a TypeError.
  • A subclass that overrides a declared method without redeclaring it keeps the strictest level declared up its class chain ('signed-in' over 'public'). @internal() is inherited by overrides and wins over a callable declaration (with a warning).
  • Backend-to-backend calls (Server.call on the server) skip these checks, internal methods included.

Work with no user: runAsSystem

Every HTTP call runs in a call context that carries its request, so the user of a call follows everything it awaits or schedules. Work that is not done for that user, such as a job, a timer or a queue consumer started from inside a request, must be wrapped in runAsSystem, or it keeps running as that request's user:

import { runAsSystem } from '@_linked/server-utils/utils/CallContext';

runAsSystem(() => startNightlyReindex(), 'nightly reindex');

Inside a system context requireSessionUser() throws a plain Error (there is no user to take); code there that acts for a user gets that user passed explicitly. getCallContext() returns {kind: 'http', request, response} or {kind: 'system', reason}.

LinkedEmail

Send emails from anywhere in the backend.

Make sure to install an email client first, like lincd-zeptomail. By adding lincd-zeptomail to your project (in package.json), it will automatically be used as the default email client.

After this, you can send emails from anywhere in the backend.

LinkedEmail.sendEmail({
  ...
});

Setting a default provider

If you want to implement an email client, you can use LinkedEmail.setDefaultProvider to set the default email client. You can do this in the constructor of your backend provider. Here is an example:

import { LinkedEmail } from 'lincd-server-utils/lib/utils/LinkedEmail';
// import your email client from this package
import { MyMailClient } from './utils/MyMailClient';
import { BackendProvider } from 'lincd-server-utils/lib/utils/BackendProvider';
export class MyBackendProvider extends BackendProvider {
  constructor(s) {
    super(s);
    LinkedEmail.setDefaultProvider(new MyMailClient());
  }
}

Shared state and error brands

A module of this package can be evaluated twice in one runtime (Vite's SSR runner and Node under linked start, or two browser bundles). State that callers set — Server.setLocalServer, addDefaultHeaders, setAuthHandler, registerActionHandler, LinkedEmail.setDefaultProvider, the live-update log, request data — is kept on globalThis with sharedState from @_linked/core, so every copy sees it. ServerCallError is branded: match it with isLinkedError(err, ServerCallError) from @_linked/core (or ServerCallError.is(err)), not instanceof. New code follows the same rules; see shared state and error brands.

版本与发布记录

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

版本发布日期距今
1.17.0latest2026/10/2810 天前
1.16.22026/10/2513 天前
1.16.12026/10/2414 天前
1.16.02026/10/2415 天前
1.15.02026/10/2216 天前
1.14.12026/10/1919 天前

关于 @_linked/server-utils 的常见问题

@_linked/server-utils 是什么?

provides a set of utilities for applications with a lincd-server backend.

如何安装 @_linked/server-utils?

在项目目录运行 npm install @_linked/server-utils,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^18.2.0 || ^19.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@_linked/server-utils 支持 TypeScript 吗?

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

@_linked/server-utils 支持 ESM 还是 CommonJS?

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

@_linked/server-utils 可以商用吗?

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

@_linked/server-utils 的下载量有多少?

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

@_linked/server-utils 还在维护吗?

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