# @grantjs/client 中文文档

规范地址：https://npmcn.com/package/%40grantjs/client/

版本：1\.29\.0
npm 元数据更新时间：2026-11-10T14:40:16.841Z
中文译文更新时间：2026-11-17T07:05:19.948Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40grantjs/client
原文对照：https://npmcn.com/package/%40grantjs/client/?lang=original
项目主页：https://github.com/grant-js/grant#readme
源码仓库：https://github.com/grant-js/grant

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：128 kB，27 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：react ^18 \|\| ^19，@tanstack/react-query ^5
- 首次发布：2026-03-11T21:06:33.481Z
- 最新版本发布：2026-11-10T14:40:16.073Z
- 近 30 天下载量：5370（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：71（近 12 个月 71 个）

## 中文简介

Grant 授权的浏览器 SDK - 基于权限的 UI 渲染的反应钩和组件

## 安装

```sh
npm install @grantjs/client
```

也可以使用：`pnpm add @grantjs/client`、`yarn add @grantjs/client`、`bun add @grantjs/client`

## README

# @ granjs/ 客户端

Grant授权平台的浏览器SDK. 提供轻量级客户端,用于使用React hooks和组件进行许可检查,用于有条件的UI渲染.

**联合国** [客户端 SDK](https://github.com/grant-js/grant/blob/main/docs/integration/client-sdk.md) 在官方的文档.

## 特征

-   **基于 REST 的 API** - 本地用途 `fetch`,不需要图形QL客户端
-   **自动刷新令牌** - 处理401个错误,并更新和重试
-   **内建缓存** - 配置基于 TTL 的缓存以尽量减少API 调用
-   **多租户支助** - 会话符号动态范围切换
-   **反应整合** - 用于申报许可检查的钩和组件
-   **类型脚本** - 全面类型的安全,类型来自 `@grantjs/schema`

## 安装

```bash
npm install @grantjs/client
# or
pnpm add @grantjs/client
# or
yarn add @grantjs/client
```

## 快速启动

### 1\. 创建客户

```typescript
import { GrantClient } from '@grantjs/client';

const grant = new GrantClient({
  apiUrl: 'https://api.your-app.com',

  getAccessToken: () => localStorage.getItem('accessToken'),

  // Cookie-based refresh: your callback calls POST /api/auth/refresh with credentials: 'include',
  // then updates app token storage. Refresh token is in HttpOnly cookie; response body has only accessToken.
  onRefreshWithCredentials: async () => {
    const res = await fetch('https://api.your-app.com/api/auth/refresh', {
      method: 'POST',
      credentials: 'include',
    });
    if (!res.ok) return false;
    const { data } = await res.json();
    if (data?.accessToken) {
      localStorage.setItem('accessToken', data.accessToken);
      return true;
    }
    return false;
  },

  onTokenRefresh: (tokens) => {
    localStorage.setItem('accessToken', tokens.accessToken);
    // tokens.refreshToken may be undefined when using cookie-based refresh
  },

  onUnauthorized: () => {
    window.location.href = '/login';
  },
});

// Check permission
const canEdit = await grant.can('Document', 'Update');
```

### 2\. 反应设置

包装您的应用程序 `GrantProvider` 与您的认证库合并 :

```tsx
'use client';

import { useMemo } from 'react';
import { GrantProvider, type GrantClientConfig } from '@grantjs/client/react';
import { useAuthStore } from '@/stores/auth.store';

export function AppProviders({ children }: { children: React.ReactNode }) {
  const config = useMemo<GrantClientConfig>(
    () => ({
      apiUrl: process.env.NEXT_PUBLIC_API_URL!,

      getAccessToken: () => useAuthStore.getState().accessToken,

      // Cookie-based refresh: POST /api/auth/refresh with credentials: 'include', then update store
      onRefreshWithCredentials: async () => {
        const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/auth/refresh`, {
          method: 'POST',
          credentials: 'include',
        });
        if (!res.ok) return false;
        const { data } = await res.json();
        if (data?.accessToken) {
          useAuthStore.getState().setAccessToken(data.accessToken);
          return true;
        }
        return false;
      },

      onTokenRefresh: (tokens) => {
        useAuthStore.getState().setAccessToken(tokens.accessToken);
      },

      onUnauthorized: () => {
        useAuthStore.getState().logout();
        if (typeof window !== 'undefined') {
          window.location.href = '/auth/login';
        }
      },

      cache: {
        ttl: 5 * 60 * 1000, // 5 minutes
        prefix: 'grant',
      },
    }),
    []
  );

  return <GrantProvider config={config}>{children}</GrantProvider>;
}
```

### 3\. 有范围的使用

对于多租户的应用程序,通过特定上下文检查权限的范围:

```tsx
'use client';

import { useGrant } from '@grantjs/client/react';
import { Tenant } from '@grantjs/schema';

interface OrganizationActionsProps {
  organization: { id: string; name: string };
}

export function OrganizationActions({ organization }: OrganizationActionsProps) {
  // Scope permissions to this specific organization
  const scope = { tenant: Tenant.Organization, id: organization.id };

  // Check permissions - these call POST /api/auth/is-authorized
  const canUpdate = useGrant('Organization', 'Update', { scope });
  const canDelete = useGrant('Organization', 'Delete', { scope });

  // Hide component entirely if user has no permissions
  if (!canUpdate && !canDelete) {
    return null;
  }

  return (
    <div>
      {canUpdate && <button>Edit</button>}
      {canDelete && <button>Delete</button>}
    </div>
  );
}
```

### 4\. 使用组件

```tsx
import { GrantGate } from '@grantjs/client/react';
import { Tenant } from '@grantjs/schema';

function Dashboard({ projectId }: { projectId: string }) {
  const scope = { tenant: Tenant.Organization, id: projectId };

  return (
    <div>
      {/* Hide if no permission */}
      <GrantGate resource="Analytics" action="Read" scope={scope}>
        <AnalyticsWidget />
      </GrantGate>

      {/* Show fallback if denied */}
      <GrantGate
        resource="Settings"
        action="Update"
        scope={scope}
        fallback={<p>Contact admin for access</p>}
      >
        <SettingsPanel />
      </GrantGate>

      {/* With loading state */}
      <GrantGate resource="Report" action="Create" scope={scope} loading={<Spinner />}>
        <ExportButton />
      </GrantGate>
    </div>
  );
}
```

## API 参考

### 赠与客户端

```typescript
const grant = new GrantClient(config: GrantClientConfig);
```

#### 配置

```typescript
interface GrantClientConfig {
  apiUrl: string;

  getAccessToken?: () => string | null | Promise<string | null>;
  /** Called after cookie-based refresh; use to update app token storage. `tokens.refreshToken` may be undefined. */
  onTokenRefresh?: (tokens: AuthTokens) => void | Promise<void>;
  onUnauthorized?: () => void;
  /** Cookie-based refresh on 401: call POST /api/auth/refresh with credentials: 'include', update token, return true on success. */
  onRefreshWithCredentials?: () => Promise<boolean>;

  fetch?: typeof fetch;
  credentials?: RequestCredentials; // default: 'include'
  cache?: { ttl?: number; prefix?: string };
}
```

#### 方法

```typescript
// Permission checks
grant.can(resource, action, options?): Promise<boolean>
grant.hasPermission(resource, action, options?): Promise<boolean>  // Alias
grant.isAuthorized(resource, action, options?): Promise<AuthorizationResult>

// Cache management
grant.clearCache(): void
grant.clearScopeCache(scope?): void
```

### 反应钩

#### `useGrant(resource, action, options?)`

默认返回布尔或对象 `isGranted` 财务报告和审定财务报表 `isLoading` 何时 `returnLoading: true`。 。 。 .

**默认( 布尔 ) :**

```tsx
import { useGrant } from '@grantjs/client/react';
import { Tenant } from '@grantjs/schema';

const canEdit = useGrant('Document', 'Update', {
  scope: { tenant: Tenant.Organization, id: orgId },
});

return <div>{canEdit && <EditButton />}</div>;
```

**装入状态 :**

```tsx
const { isGranted, isLoading } = useGrant('Document', 'Update', {
  scope: { tenant: Tenant.Organization, id: orgId },
  returnLoading: true,
});

if (isLoading) return <Spinner />;
if (!isGranted) return null;

return <EditButton />;
```

#### 钩子选项

```typescript
interface UseGrantOptions {
  scope?: Scope; // Multi-tenant scope override
  enabled?: boolean; // Skip check if false (default: true)
  useCache?: boolean; // Use cached result (default: true)
  returnLoading?: boolean; // Return object with isGranted and isLoading (default: false)
}

interface UseGrantResult {
  isGranted: boolean; // Whether the user is granted permission
  isLoading: boolean; // Whether the permission check is loading
}
```

### 反应组件

#### `<GrantGate>`

```tsx
<GrantGate
  resource="Resource"
  action="Action"
  scope={{ tenant: Tenant.Organization, id: '...' }} // Optional
  fallback={<FallbackComponent />} // Optional
  loading={<LoadingSpinner />} // Optional
>
  <ProtectedContent />
</GrantGate>
```

## 多十年范围覆盖

Grant平台支持有动态范围切换的多租户授权:

-   **会话符号**: 可按请求时间覆盖范围(用户在组织之间切换)
-   **API 密钥符号**: 使用其嵌入范围( 无法覆盖)

```tsx
import { useGrant } from '@grantjs/client/react';
import { Tenant } from '@grantjs/schema';

// User is viewing Organization A
const scopeA = { tenant: Tenant.Organization, id: 'org-a-id' };
const canEditA = useGrant('Project', 'Update', { scope: scopeA });

// User switches to Organization B
const scopeB = { tenant: Tenant.Organization, id: 'org-b-id' };
const canEditB = useGrant('Project', 'Update', { scope: scopeB });
```

现有租户类型(来自 `@grantjs/schema`:

```typescript
enum Tenant {
  System = 'system',
  Account = 'account',
  Organization = 'organization',
  AccountProject = 'accountProject',
  OrganizationProject = 'organizationProject',
  ProjectUser = 'projectUser',
  // ... and more
}
```

## 缓存

客户端缓存默认结果( 5分 TTL) 。 你可以这样:

```typescript
// Configure TTL
const grant = new GrantClient({
  apiUrl: '...',
  cache: { ttl: 10 * 60 * 1000 }, // 10 minutes
});

// Bypass cache for a specific check
const fresh = await grant.can('Resource', 'Action', { useCache: false });

// Clear all cache
grant.clearCache();

// Clear cache for a specific scope
grant.clearScopeCache({ tenant: Tenant.Organization, id: orgId });
```

## 认证流程

1.  **访问令牌** 发送通过 `Authorization: Bearer <token>` (当 `getAccessToken` 页:1.
2.  **饼干** 默认情况下包含在内(`credentials: 'include'`) (中文(简体) ).
3.  打开 **401 (中文(简体) )**,客户端使用 **仅基于饼干的刷新** (没有基于身体的安全刷新):
    -   若为 `onRefreshWithCredentials` 已经设定,它叫做。 你该回电了 `POST /api/auth/refresh` 与 `credentials: 'include'`,读取新的 `accessToken` 从响应机构,更新您的存储,然后返回 `true` 在成功方面.
    -   成功时,客户端重试原始请求;您也可以使用 `onTokenRefresh` 以同步符号状态.
    -   失败或失败时 `onRefreshWithCredentials` 未设定, `onUnauthorized()` 称为(例如重定向到登录).
    -   刷新符号生活在 HttpOnly cookie; API 只返回 `accessToken` 在更新的反应机构.

## 发展说明

### 反应严格模式

在开发中, 启用了 React Print 模式( 默认在 Next.js 13+), 您将看到 **2个API电话** 每个权限检查。 这是预期的行为:

1.  组件挂载 —— 效果运行 —— API呼叫 # 1
2.  严格模式卸载组件
3.  组件重载 → 效果运行 → API呼叫 # 2

这只在发展过程中发生。 生产建设一呼而起.

### 稳定范围

钩子自动处理范围对象参考变化. 你不需要记住瞄准器:

```tsx
// This is fine - hooks compare by value, not reference
const scope = { tenant: Tenant.Organization, id: organization.id };
const canEdit = useGrant('Resource', 'Action', { scope });
```

## 类型脚本

包括全部类型的定义。 从包中导入类型或从中再出口 `@grantjs/schema`数字 :

```typescript
import type {
  GrantClientConfig,
  AuthorizationResult,
  Permission,
  Resource,
  Scope,
  Tenant,
} from '@grantjs/client';

// Or import Tenant enum directly from schema
import { Tenant } from '@grantjs/schema';
```

## 捐款

欢迎捐款! 请看 [主要仓库](https://github.com/grant-js/grant) 捐款准则.

## 支助

-   **文档**: 见 [主要赠款文件](https://github.com/grant-js/grant)
-   **问题**: 报告错误或请求特性 [GitHub 问题](https://github.com/grant-js/grant/issues)
-   **产品账户帮助( A)**数字 : [支持@ granjs.org](mailto:support@grantjs.org)
-   **安全脆弱性**: 跟着 [警卫](https://github.com/grant-js/grant/blob/main/SECURITY.md) (达到) **[工程学@ granjs.org](mailto:engineering@grantjs.org)**(中文(简体) )

## 许可证

麻省理工学院

## 常见问题

### @grantjs/client 是什么？

Grant 授权的浏览器 SDK - 基于权限的 UI 渲染的反应钩和组件

### 如何安装 @grantjs/client？

在项目目录运行 npm install @grantjs/client，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react（^18 \|\| ^19）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @grantjs/client 支持 TypeScript 吗？

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

### @grantjs/client 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @grantjs/client 可以商用吗？

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

### @grantjs/client 的下载量有多少？

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

### @grantjs/client 还在维护吗？

最新版本 1\.29\.0 发布于 2026/11/10（6 天前）；至今共发布 71 个版本，其中过去 12 个月发布了 71 个；首次发布于 2026/03/12。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

