cloudsignal-websocket
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCloudSignal WebSocket — React MQTT Context Generator
CloudSignal WebSocket — React MQTT上下文生成器
Generate a production-grade React context provider for real-time messaging over CloudSignal's MQTT broker using WebSocket. The generated code handles the full connection lifecycle: authentication via external auth providers, reconnection, proactive token refresh, message routing, and cleanup.
生成一个生产级React上下文提供者,用于通过WebSocket连接CloudSignal的MQTT代理进行实时消息传递。生成的代码处理完整的连接生命周期:通过外部身份验证提供商进行认证、重连、主动令牌刷新、消息路由以及资源清理。
What You Generate
生成内容
-
— React context provider with:
mqtt-context.tsx- Auth-provider token exchange (Clerk, Supabase, Auth0, Firebase, or custom OIDC)
- WebSocket connection to CloudSignal MQTT broker
- Auth error circuit-breaker (max 3 retries, 10s delay)
- Proactive token refresh at 50 minutes (before 60-min TTL expiry)
- Exact topic routing with safe JSON parsing
- React StrictMode double-mount protection
- Tab visibility reconnection
- Typed subscription hooks (jobs, notifications, transactions, or custom)
-
— TypeScript declarations for
cloudsignal.d.ts(the npm package does not ship types)@cloudsignal/mqtt-client
-
— 包含以下功能的React上下文提供者:
mqtt-context.tsx- 身份验证提供商令牌交换(Clerk、Supabase、Auth0、Firebase或自定义OIDC)
- 连接到CloudSignal MQTT代理的WebSocket连接
- 认证错误熔断机制(最多3次重试,10秒延迟)
- 主动令牌刷新(在60分钟令牌过期前的第50分钟执行)
- 精确主题路由与安全JSON解析
- React StrictMode双挂载保护
- 标签页可见性触发重连
- 类型化订阅钩子(任务、通知、交易或自定义类型)
-
—
cloudsignal.d.ts的TypeScript声明文件(该npm包未自带类型文件)@cloudsignal/mqtt-client
Before You Start
开始之前
Ask the user for these inputs (use defaults if not provided):
| Input | Example | Default |
|---|---|---|
| Auth provider | Clerk, Supabase, Auth0, Firebase | Ask (required) |
| Organization ID | | Ask (required) |
| Topic namespace | | App name from package.json |
| Message types needed | notifications, jobs, transactions | All three |
| Target directory | | |
向用户询问以下输入信息(未提供时使用默认值):
| 输入项 | 示例 | 默认值 |
|---|---|---|
| 身份验证提供商 | Clerk, Supabase, Auth0, Firebase | 必须询问(必填) |
| 组织ID | | 必须询问(必填) |
| 主题命名空间 | | 来自package.json的应用名称 |
| 需要的消息类型 | notifications, jobs, transactions | 全部三种 |
| 目标目录 | | |
Generation Steps
生成步骤
Step 1: Read the Reference Implementation
步骤1:阅读参考实现
Read in this skill's directory. This is the canonical reference — a production-tested context provider extracted from a live SaaS. Use it as the base for all generated code.
references/mqtt-context.tsx阅读本skill目录下的文件。这是标准参考实现——一个从上线SaaS系统中提取的经过生产环境测试的上下文提供者。以此作为所有生成代码的基础。
references/mqtt-context.tsxStep 2: Adapt the Auth Provider Hooks
步骤2:适配身份验证提供者钩子
The reference contains two placeholder functions that MUST be replaced based on the user's auth provider:
useCurrentUser(){ id: string } | null| Provider | Implementation |
|---|---|
| Clerk | |
| Supabase | |
| Auth0 | |
| Firebase | |
useGetToken()() => Promise<string | null>| Provider | Implementation |
|---|---|
| Clerk | |
| Supabase | |
| Auth0 | |
| Firebase | |
参考实现中包含两个占位函数,必须根据用户的身份验证提供者进行替换:
useCurrentUser(){ id: string } | null| 提供者 | 实现代码 |
|---|---|
| Clerk | |
| Supabase | |
| Auth0 | |
| Firebase | |
useGetToken()() => Promise<string | null>| 提供者 | 实现代码 |
|---|---|
| Clerk | |
| Supabase | |
| Auth0 | |
| Firebase | |
Step 3: Customize Message Types
步骤3:自定义消息类型
Replace the reference message interfaces with the user's domain. Keep the structure (interface + handler type + registry pattern) but adapt field names and types.
Default message types from reference: , , , .
ProgressMessageStatusMessageTransactionMessageNotificationMessage将参考实现中的消息接口替换为用户业务域的接口。保留结构(接口+处理程序类型+注册模式),但调整字段名称和类型。
参考实现中的默认消息类型:、、、。
ProgressMessageStatusMessageTransactionMessageNotificationMessageStep 4: Set Configuration Constants
步骤4:设置配置常量
tsx
const CLOUDSIGNAL_ORG_ID = process.env.NEXT_PUBLIC_CLOUDSIGNAL_ORG_ID;
const CLOUDSIGNAL_HOST = process.env.NEXT_PUBLIC_CLOUDSIGNAL_HOST || "wss://connect.cloudsignal.app:18885/";
const TOPIC_ROOT = "{user's namespace}";tsx
const CLOUDSIGNAL_ORG_ID = process.env.NEXT_PUBLIC_CLOUDSIGNAL_ORG_ID;
const CLOUDSIGNAL_HOST = process.env.NEXT_PUBLIC_CLOUDSIGNAL_HOST || "wss://connect.cloudsignal.app:18885/";
const TOPIC_ROOT = "{user's namespace}";Step 5: Write the Type Declarations
步骤5:编写类型声明文件
Read and write it to the user's directory (or wherever their project keeps type declarations). This file is required because does not ship files.
references/cloudsignal.d.tstypes/@cloudsignal/mqtt-client.d.ts阅读并将其写入用户的目录(或项目存放类型声明的其他位置)。该文件是必需的,因为未提供文件。
references/cloudsignal.d.tstypes/@cloudsignal/mqtt-client.d.tsStep 6: Write the Context Provider
步骤6:编写上下文提供者
Combine the adapted auth hooks, customized message types, and the full provider logic from the reference into the final . Preserve ALL of these production patterns:
mqtt-context.tsx- Stable ref pattern: updated every render, used by timers
connectRef - Auth error circuit-breaker: with
authErrorCountRefMAX_AUTH_ERRORS = 3 - Proactive token refresh: at 50 minutes
scheduleTokenRefresh() - StrictMode guard: +
connectingRefprevent double connectionsmountedRef - Exact topic matching: ${prefix}/notifications`
topic === \.includes()`not - Safe JSON parsing: try/catch around in message handler
JSON.parse - Client destruction on auth error: Stops SDK's stale-token reconnect loop
- Tab visibility reconnect: event listener
visibilitychange
将适配后的身份验证钩子、自定义消息类型以及参考实现中的完整提供者逻辑组合成最终的。保留所有以下生产环境模式:
mqtt-context.tsx- 稳定引用模式:在每次渲染时更新,供定时器使用
connectRef - 认证错误熔断机制:带有的
MAX_AUTH_ERRORS = 3authErrorCountRef - 主动令牌刷新:在第50分钟执行
scheduleTokenRefresh() - StrictMode防护:+
connectingRef防止重复连接mountedRef - 精确主题匹配:使用${prefix}/notifications``而非
topic ===.includes() - 安全JSON解析:消息处理程序中包裹try/catch
JSON.parse - 认证错误时销毁客户端:停止SDK的过期令牌重连循环
- 标签页可见性重连:事件监听器
visibilitychange
Step 7: Show Usage
步骤7:展示使用示例
Provide a usage example showing:
- Provider wrapping in (nested inside the auth provider)
app/providers.tsx - A consumer component using hook
useMQTT() - Environment variable setup ()
.env.local
提供使用示例,包括:
- 在中包裹提供者(嵌套在身份验证提供者内部)
app/providers.tsx - 使用钩子的消费者组件
useMQTT() - 环境变量设置()
.env.local
Critical SDK Pitfalls
SDK关键陷阱
Read for the full list. These MUST be handled in generated code:
references/sdk-pitfalls.md- Token expiry reconnect loop: Destroy client on , don't rely on SDK reconnect
onAuthError - not
externalToken: UseidTokeninexternalTokenconnectWithToken() - No TypeScript declarations: Always generate
cloudsignal.d.ts - React StrictMode double-mount: Use +
connectingRefguardsmountedRef - Token service version: SDK v2.x expects
/v2/tokens/exchange
阅读获取完整列表。生成的代码必须处理以下问题:
references/sdk-pitfalls.md- 令牌过期重连循环:在时销毁客户端,不要依赖SDK重连
onAuthError - 使用而非
externalToken:在idToken中使用connectWithToken()externalToken - 无TypeScript声明:始终生成
cloudsignal.d.ts - React StrictMode双挂载:使用+
connectingRef防护mountedRef - 令牌服务版本:SDK v2.x期望使用
/v2/tokens/exchange
Environment Variables
环境变量
Tell the user to add these to :
.env.localbash
NEXT_PUBLIC_CLOUDSIGNAL_ORG_ID=org_xxxxxxxxxxxxx # From CloudSignal dashboard
NEXT_PUBLIC_CLOUDSIGNAL_HOST=wss://connect.cloudsignal.app:18885/ # Optional, this is default告知用户将以下内容添加到:
.env.localbash
NEXT_PUBLIC_CLOUDSIGNAL_ORG_ID=org_xxxxxxxxxxxxx # 来自CloudSignal控制台
NEXT_PUBLIC_CLOUDSIGNAL_HOST=wss://connect.cloudsignal.app:18885/ # 可选,此为默认值CloudSignal Dashboard Setup
CloudSignal控制台设置
Remind the user they need to configure their CloudSignal organization:
- Create an organization at https://dashboard.cloudsignal.app
- Configure an External Auth Provider integration (select their provider, enter JWKS URL)
- Note the ID for the environment variable
org_xxx
提醒用户需要配置他们的CloudSignal组织:
- 在https://dashboard.cloudsignal.app创建组织
- 配置外部身份验证提供商集成(选择对应的提供商,输入JWKS URL)
- 记录ID用于环境变量
org_xxx
npm Dependency
npm依赖项
The user needs to install the CloudSignal MQTT client:
bash
npm install @cloudsignal/mqtt-client用户需要安装CloudSignal MQTT客户端:
bash
npm install @cloudsignal/mqtt-client