SKILL.md
readonly只读
name
extension-core-infrastructure
description
核心基础设施,提供后端连接配置、存储客户端和React应用入口点。
version
1.1.0
核心基础设施
Caffeine AI 的核心基础设施扩展。
概述
该组件为所有项目提供基础架构:后端连接配置、Internet Identity 认证钩子和 actor 管理工具。
要求
"@caffeineai/core-infrastructure": "^1.1.0"
"@caffeineai/object-storage": "^1.1.0"
"@icp-sdk/auth": "^7.1.0"
"@icp-sdk/core": "^5.3.0"
@caffeineai/object-storage 是 core-infrastructure 的对等依赖。每个项目必须将其作为直接的 npm 依赖安装(构建模板已包含这两个包)。
集成
核心基础设施会自动包含在每个项目中。无需手动集成步骤。
前端
core-infrastructure 前端包(@caffeineai/core-infrastructure)会自动包含在每个项目中。
应用入口点
使用 InternetIdentityProvider 和 QueryClientProvider 包裹应用:
import { InternetIdentityProvider } from "@caffeineai/core-infrastructure";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import ReactDOM from "react-dom/client";
import App from "./App";
const queryClient = new QueryClient();
ReactDOM.createRoot(document.getElementById("root")!).render(
<QueryClientProvider client={queryClient}>
<InternetIdentityProvider>
<App />
</InternetIdentityProvider>
</QueryClientProvider>,
);
useInternetIdentity() — 认证钩子
提供 Internet Identity 的身份状态、登录和登出功能。
返回值
| 字段 | 类型 | 描述 |
|---|---|---|
identity |
Identity | undefined |
用户身份(登录或会话恢复后可用) |
login |
() => void |
打开 II 弹窗。即发即忘 — 不要 await。 |
clear |
() => void |
登出并清除存储的身份。即发即忘。 |
isAuthenticated |
boolean |
用户拥有有效身份时为 true。用于 UI 门控。 |
isInitializing |
boolean |
AuthClient 从 IndexedDB 加载时为 true |
isLoggingIn |
boolean |
II 弹窗打开时为 true |
isLoginSuccess |
boolean |
仅在交互式登录后为 true(页面刷新恢复后不触发) |
isLoginError |
boolean |
登录或初始化失败时为 true |
loginError |
Error | undefined |
当 isLoginError 为 true 时的错误对象 |
认证状态生命周期
| 场景 | loginStatus |
isAuthenticated |
|---|---|---|
| 页面加载,无存储会话 | "idle" |
false |
| 恢复存储的会话 | "initializing" |
false → true |
| 刷新后恢复存储的会话 | "idle" |
true |
| 交互式登录进行中 | "logging-in" |
false |
| 交互式登录刚完成 | "success" |
true |
| 登录弹窗失败/取消 | "loginError" |
false |
重要: isLoginSuccess 仅在通过弹窗进行交互式登录后为 true — 页面刷新恢复存储身份时不会触发。始终使用 isAuthenticated 进行条件渲染。
用法
基于 isAuthenticated 门控认证 UI:
const { isAuthenticated } = useInternetIdentity();
{isAuthenticated ? <AuthenticatedApp /> : <LoginScreen />}
在初始化或登录中时禁用登录按钮:
const { login, isInitializing, isLoggingIn } = useInternetIdentity();
<button onClick={() => login()} disabled={isInitializing || isLoggingIn}>
登录
</button>
login() 和 clear() 是即发即忘的 — 钩子的状态字段(isLoggingIn、isInitializing)跟踪异步生命周期。不要将它们包裹在本地 useState / isPending 逻辑中。
useActor() — 后端 Actor 钩子
创建并管理一个类型化的后端 actor 实例。当用户身份发生变化(登录/登出)时自动重新创建 actor。
import { useActor } from "@caffeineai/core-infrastructure";
import { createActor } from "declarations/backend";
function MyComponent() {
const { actor, isFetching } = useActor(createActor);
// actor 在加载时为 null,之后为类型化的后端 actor
if (!actor || isFetching) return <Loading />;
// 直接调用后端方法
const data = await actor.myBackendMethod();
}
返回值
| 字段 | 类型 | 描述 |
|---|---|---|
actor |
T | null |
类型化的后端 actor,加载时为 null |
isFetching |
boolean |
actor 正在创建时为 true |
当身份发生变化(登录、登出或会话恢复)时,actor 会自动使用新身份重新创建,所有依赖的查询将被失效并重新获取。






