@faiber/sdk-core

中文文档
2.8.0发布于 2026/11/14TypeScriptES Module近 30 天下载 9023

Framework-neutral transport and authentication primitives shared by every Faiber TypeScript SDK.

原始使用文档
文档目录6 节
  1. Install and configure
  2. Requests and encoding
  3. Resources and generated operations
  4. Authentication refresh and errors
  5. Sockudo realtime subscriptions
  6. Short IDs

@faiber/sdk-core

Framework-neutral transport and authentication primitives shared by every Faiber TypeScript SDK.

Install and configure

npm install @faiber/sdk-core
import { FaiberClient, MemoryTokenProvider } from "@faiber/sdk-core";

const tokens = new MemoryTokenProvider({ accessToken: session.accessToken });
const client = new FaiberClient("profile", {
  domains: { profile: import.meta.env.FAIBER_PROFILE_URL },
  authMode: "bearer",
  tokenProvider: tokens,
  axios: { timeout: 15_000, withCredentials: true },
});

FaiberClient resolves only configured service origins, rejects absolute URLs by default, adds a Bearer token supplied by TokenProvider, and preserves full Axios responses. Set authMode: "cookie" to enable credentialed requests automatically and suppress Bearer injection. auto is the backward-compatible default and uses a token when available while honoring explicit Axios cookie settings. MemoryTokenProvider and opt-in StorageTokenProvider are included; custom providers can bind server-side sessions or encrypted storage.

Requests and encoding

import { multipart, urlEncoded } from "@faiber/sdk-core";

await client.post("/api/v1/login", urlEncoded({ username, password }), {
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
});

await client.post("/api/v1/profile/avatar", multipart({ file, alt: "Avatar" }));

The client provides typed get, post, put, patch, delete, and generic request methods. Query values, request headers, timeout, adapters, interceptors, AbortSignal, multipart data, and URL-encoded forms remain available through Axios-compatible options.

Native FormData uploads automatically clear a configured JSON content type so Axios can supply the multipart boundary. Pass onUploadProgress for byte progress and signal to cancel. Await the response before treating the upload as complete; a storage failure can arrive after all bytes have been sent.

Resources and generated operations

RestResource supplies typed list/show/create/update/replace/delete helpers. Each resource declares the operations its backend actually mounts; unsupported calls throw UnsupportedOperationError locally instead of sending a request that will return 405. The update verb is configurable per service.

OpenApiClient<paths> derives path, query, header, body, and response types from openapi-typescript contracts. Service packages also expose generated named operations that preserve every mounted backend verb, path parameter, query object, request body, response envelope, transport encoding, and permission annotation.

Authentication refresh and errors

Configure refreshAuth for one shared refresh when concurrent calls receive 401. Retried calls obtain the new token; in cookie mode the callback may return null after the server rotates its HttpOnly cookie and the protected request is still retried once. Failed refreshes clear stale credentials. A refresh failure preserves the original protected-request Axios error (and attaches the refresh error as its cause when possible), so applications retain the operation's status, response body, headers, request IDs, cancellation, and timeout details.

Sockudo realtime subscriptions

subscribeRealtime connects a private Sockudo channel over the Pusher-compatible WebSocket protocol. Fetch the browser-safe configuration from the owning service and authorize through its authenticated Faiber client. Chat owns conversation channels; Messenger owns notification channels. No app secret belongs in the browser.

import { FaiberClient, subscribeRealtime } from '@faiber/sdk-core';
import { ChatApi } from '@faiber/faiber-chat';
const chat = new ChatApi(new FaiberClient('chat', {
  domains: { chat: 'https://chat.example.com' }, authMode: 'cookie',
}));
const conversationId = 'your-conversation-id';
const config = (await chat.realtimeConfig(conversationId)).data.data;
const reloadMessages = async () => {
  const response = await chat.messages(conversationId);
  console.log(response.data.data);
};
const subscription = subscribeRealtime({
  config,
  authorize: async input => (await chat.realtimeAuth(conversationId, input)).data,
  onEvent: () => { void reloadMessages(); },
  onSubscribed: () => { void reloadMessages(); },
  onError: error => console.error(error.message),
});
// On logout or component teardown:
subscription.close();

Subscription authorization is repeated on reconnect. onSubscribed runs after every successful subscription: reload persisted data to recover events missed while offline. Events are invalidation hints and their service-specific payload is intentionally unknown; service HTTP responses remain authoritative. onError reports connection/authorization failures; HTTP authorization failures retain normal Axios behavior within your callback. Close cancels the connection and ignores late authorization results. HTTPS pages require wss:; allow the exact WebSocket origin in your Content Security Policy.

RequestOptions<D> preserves Axios headers, signals, timeout, adapters and the withXSRFToken predicate. Its exported RequestOptionsContext<D> describes the encoded wire body and request metadata, excluding the predicate itself. JSON requests retain their named input type; URL-encoded login/realtime operations provide URLSearchParams to that predicate. A generic metadata predicate can be reused for typed requests without casting away body types.

Short IDs

import { shortIdFromUuid } from "@faiber/sdk-core";
const code = shortIdFromUuid("550e8400-e29b-41d4-a716-446655440000"); // GDCN7L

This synchronous, offline helper accepts canonical or compact UUIDs and throws TypeError for malformed input. It derives six uppercase characters without 0, 1, I, or O. Use the classroom UUID or the profile row's id (not user_id). The alias is not guaranteed unique; retain the UUID for operations.

版本与发布记录

@faiber/sdk-core 共发布 67 个版本,首次发布于 2026/07/18;过去 12 个月发布了 67 个版本。

版本发布日期距今
2.8.0latest2026/11/14今天
2.7.02026/11/059 天前
2.6.02026/11/049 天前
2.5.02026/11/049 天前
2.4.02026/11/0310 天前
2.3.02026/11/0211 天前

关于 @faiber/sdk-core 的常见问题

@faiber/sdk-core 是什么?

Framework-neutral transport and authentication primitives shared by every Faiber TypeScript SDK.

如何安装 @faiber/sdk-core?

在项目目录运行 npm install @faiber/sdk-core,或使用 pnpm add / yarn add / bun add。

@faiber/sdk-core 支持 TypeScript 吗?

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

@faiber/sdk-core 支持 ESM 还是 CommonJS?

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

@faiber/sdk-core 可以商用吗?

@faiber/sdk-core 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@faiber/sdk-core 的下载量有多少?

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

@faiber/sdk-core 还在维护吗?

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