# Wx Cloudfunctions

> Use this skill when creating, modifying, reviewing, or packaging WeChat cloud functions (微信云函数) in a uni-app project: 新增云函数, 修改云函数, 添加 action, 云函数分层/目录结构, zod 校验, 云函数单测, 本地调试 JSON, 云函数打包/构建 (vite-plugin-uni-cloudfunctions), 数据模型 ER 图确认与 CloudBase 同步. Triggers on work under cloudfunctions/ or wx-server-sdk code.

- Skill: `jsonlee12138/wx-cloudfunctions` (Agent Skill, multi-file: 7 files)
- Install (CLI): `npx skillmds@latest add jsonlee12138/wx-cloudfunctions`
- Raw SKILL.md: https://api.skillmd.com/api/skills/jsonlee12138/wx-cloudfunctions/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: DevOps & Infra
- Author: jsonlee12138 (https://skillmd.com/u/jsonlee12138)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/jsonlee12138/wx-cloudfunctions

---


# WX Cloud Functions

## Contract

Use this skill to develop TypeScript WeChat cloud functions following the project's layered module conventions, and to package them with `vite-plugin-uni-cloudfunctions`.

Do not use this skill for:
- 运营数据写入（新增提示词/分类/图片）— redirect to `content-ops`.
- CloudBase 环境管理、安全规则、云存储 — redirect to `cloudbase` skill.
- 微信开发者工具的预览/自动化操作 — redirect to `wechatide-skill`.

Stop and ask when: 新集合的数据模型 ER 图未经用户确认就要求云端同步；或某个 action 预期高并发/长耗时，需要用户决定是否拆独立云函数。

## Input Contract

Required:
- 业务需求：函数名（module 名）、action 列表、每个 action 的输入/输出
- 涉及的 CloudBase 集合与字段

Optional (read when needed):
- [references/conventions.md](references/conventions.md) — 完整 13 条规范 + CloudBase 系统字段清单（新建函数或做 review 时必读）
- [references/mcp-setup.md](references/mcp-setup.md) — cloudbase MCP 不可用时的配置模板（Claude Code / Cursor / Codex，占位符版）
- [assets/function-scaffold.md](assets/function-scaffold.md) — 新建云函数时复制的文件骨架模板
- [assets/tsconfig.json](assets/tsconfig.json) / [assets/tsconfig.app.json](assets/tsconfig.app.json) / [assets/tsconfig.cloudfunctions.json](assets/tsconfig.cloudfunctions.json) — project references 三件套模板（项目缺少时复制到项目根目录）

## Output Contract

Return:
- 变更的文件路径清单
- 类型检查与单测结果（命令 + pass/fail）
- 构建产物验证结果（`dist/**/cloudfunctions/<fn>/index.js` 是否生成）
- 若新增/变更数据模型：mermaid ER 图（含字段类型与关联）与用户确认记录

### 新增云函数（一个函数 = 一个业务 module）

1. 读 [references/conventions.md](references/conventions.md)，确认分层与命名规则。
2. 若涉及新集合：先用 mermaid `erDiagram` 画数据模型（注明字段类型、关联关系），给用户确认；字段不得与 CloudBase 系统字段重名（清单见 references）。确认后才可经 cloudbase MCP 同步云端。
   - 若会话中没有可用的 cloudbase MCP 工具：按 [references/mcp-setup.md](references/mcp-setup.md) 把对应客户端的 MCP 配置写入项目（Claude Code → `.mcp.json`，Cursor → `.cursor/mcp.json`，Codex → `.codex/config.toml`），环境变量只写占位符，然后提示用户手动填入真实 `CLOUDBASE_ENV_ID` / `CLOUDBASE_API_KEY` 并重载 MCP；配置好之前跳过云端同步步骤。
3. 按 [assets/function-scaffold.md](assets/function-scaffold.md) 创建目录骨架：
   - `cloudfunctions/<fn>/`：`index.ts`、`package.json`、`handlers.ts`、`services.ts`、`repository.ts`（CloudBase 数据访问 + DTO 转换）、`model.ts`（zod v4 schema）、`model.d.ts`（纯 TS 类型）、`__tests__/`、`debug/`
   - 跨函数复用件放 `cloudfunctions/_shared/lib/`：`runtime.ts`（SDK 初始化+入口装配封装）、`errors.ts`、`sort.ts`、通用校验件
   - 项目根目录若缺 project references 配置，从 assets 复制三份 tsconfig 模板（`tsconfig.json` / `tsconfig.app.json` / `tsconfig.cloudfunctions.json`）；app 侧必须 `exclude` 掉 `cloudfunctions/`
4. 实现顺序：`model.ts` schema → `services.ts` 接口+默认实现 → `handlers.ts` action 分发 → `repository.ts` 真实实现 → `index.ts` 经 `_shared/lib/runtime.ts` 装配导出 `main`。
5. payload 校验默认 `.strict()`，非法输入抛 `BAD_REQUEST`；对接三方 API 等场景可放宽，但要在代码注释说明原因。
6. 每个 action 在 `debug/` 下补一个 event JSON 样例，供微信开发者工具本地调试直接粘贴。
7. `__tests__/` 注入 mock services 做纯逻辑单测，不依赖真实 CloudBase。

### 修改既有云函数

1. 先读目标函数全部分层文件，再动手；新增 action 时同步更新 action 枚举、model schema、debug 样例、单测。
2. 不做顺带重构；函数间禁止互相 import，禁止 import `cloudfunctions/` 之外的本地文件（插件会强制校验）。

### 打包与发布（vite-plugin-uni-cloudfunctions）

打包统一使用 npm 包 `vite-plugin-uni-cloudfunctions`（Vite 插件，peer 依赖 Vite `^5.2.8`）：

```ts
// vite.config.ts
import { uniCloudFunctions } from 'vite-plugin-uni-cloudfunctions';

export default defineConfig({
  plugins: [uniCloudFunctions({ external: ['wx-server-sdk'] })],
});
```

- 开发期：`UNI_PLATFORM=mp-weixin` 下 dev server watcher 增量编译 → `dist/dev/mp-weixin/cloudfunctions/`
- 生产期：常规小程序构建即可，插件在 `writeBundle` 编译发布 → `dist/build/mp-weixin/cloudfunctions/`
- 每个函数输出自包含单文件 `index.js` + 自己的 `package.json`；`external` 只允许 bare package name（默认 `['wx-server-sdk']`），external 的依赖必须写进函数级 `package.json` dependencies
- 禁止手写部署/拷贝脚本；不要绕过插件直接往 dist 写产物

## Validation

```bash
# 云函数独立类型检查
pnpm exec tsc -p tsconfig.cloudfunctions.json --noEmit

# 单测
pnpm vitest run cloudfunctions

# 构建产物验证
pnpm build:mp-weixin
test -f dist/build/mp-weixin/cloudfunctions/<fn>/index.js && echo OK
```

全部通过才算完成；报告中附命令与结果。数据模型变更需附用户已确认 ER 图的记录。

## Common Mistakes

- 手动给写操作传 `_openid` —— SDK 自动管理，手动传会直接报错。
- 自定义字段撞 CloudBase 系统字段（`createdAt`/`updatedAt`/`owner` 等，全表见 references）。
- 在 `_shared` 里放函数私有的 action 枚举/payload schema —— 函数专属 schema 留在函数内 `model.ts`，`_shared` 只放真正通用件。
- 云函数持有跨请求内存状态 —— 必须无状态、幂等；限流/去重走审计集合。
- 新增 action 忘了同步 debug JSON 样例和单测。

