mdk-skills 2.1.3 → 2.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,107 @@
1
+ // {
2
+ // "version": 1,
3
+ // "profiles": [
4
+ // {
5
+ // "id": "vue3-frontend",
6
+ // "name": "前端 Vue3 开发",
7
+ // "description": "Vue 3 + 业务模式库 + 设计 + 代码审查",
8
+ // "skills": ["vue", "v3-fe-biz-patterns", "frontend-design", "frontend-code-review", "ui-ux-pro-max"],
9
+ // "always_apply": ["vue", "frontend-design", "frontend-code-review", "ui-ux-pro-max"]
10
+ // },
11
+ // {
12
+ // "id": "react-frontend",
13
+ // "name": "前端 React 开发",
14
+ // "description": "设计 + 审查 + 通用前端能力",
15
+ // "skills": ["frontend-design", "frontend-code-review", "ui-ux-pro-max"],
16
+ // "always_apply": ["frontend-design", "frontend-code-review", "ui-ux-pro-max"]
17
+ // },
18
+ // {
19
+ // "id": "backend",
20
+ // "name": "java后端开发",
21
+ // "description": "API 设计、数据库、java 后端技能",
22
+ // "skills": [],
23
+ // "always_apply": []
24
+ // },
25
+ // {
26
+ // "id": "backend",
27
+ // "name": "python后端开发",
28
+ // "description": "API 设计、数据库、python 后端技能",
29
+ // "skills": [],
30
+ // "always_apply": []
31
+ // },
32
+ // {
33
+ // "id": "backend",
34
+ // "name": "nodeJs后端开发",
35
+ // "description": "API 设计、数据库、nodeJs 后端技能",
36
+ // "skills": [],
37
+ // "always_apply": []
38
+ // },
39
+ // {
40
+ // "id": "custom",
41
+ // "name": "自定义选择",
42
+ // "description": "按需勾选每一个技能",
43
+ // "skills": null
44
+ // }
45
+ // ]
46
+ // }
47
+ {
48
+ "version": 1,
49
+ "profiles": [
50
+ {
51
+ "id": "vue3-frontend",
52
+ "name": "Vue3 前端专项",
53
+ "description": "Vue3 技术栈 | 业务架构 | 界面设计 | 代码规范评审",
54
+ "skills": [
55
+ "vue",
56
+ "v3-fe-biz-patterns",
57
+ "frontend-design",
58
+ "frontend-code-review",
59
+ "ui-ux-pro-max"
60
+ ],
61
+ "always_apply": [
62
+ "vue",
63
+ "frontend-design",
64
+ "frontend-code-review",
65
+ "ui-ux-pro-max"
66
+ ]
67
+ },
68
+ {
69
+ "id": "react-frontend",
70
+ "name": "React 前端专项",
71
+ "description": "React 技术栈 | 界面设计 | 代码评审 | 通用前端能力",
72
+ "skills": ["frontend-design", "frontend-code-review", "ui-ux-pro-max"],
73
+ "always_apply": [
74
+ "frontend-design",
75
+ "frontend-code-review",
76
+ "ui-ux-pro-max"
77
+ ]
78
+ },
79
+ {
80
+ "id": "backend-java",
81
+ "name": "Java 后端开发",
82
+ "description": "接口架构设计 | 数据库建模 | Java 后端体系能力",
83
+ "skills": [],
84
+ "always_apply": []
85
+ },
86
+ {
87
+ "id": "backend-python",
88
+ "name": "Python 后端开发",
89
+ "description": "接口架构设计 | 数据层设计 | Python 后端体系能力",
90
+ "skills": [],
91
+ "always_apply": []
92
+ },
93
+ {
94
+ "id": "backend-node",
95
+ "name": "Node.js 后端开发",
96
+ "description": "接口架构设计 | 服务端架构 | Node 后端体系能力",
97
+ "skills": [],
98
+ "always_apply": []
99
+ },
100
+ {
101
+ "id": "custom",
102
+ "name": "自定义技能组合",
103
+ "description": "自由勾选技能项,按需个性化配置",
104
+ "skills": null
105
+ }
106
+ ]
107
+ }
@@ -1,21 +1,5 @@
1
1
  {
2
2
  "skills": {
3
- "simplify": {
4
- "enabled": true,
5
- "description": "审查变更代码,确保复用性、质量和效率"
6
- },
7
- "loop": {
8
- "enabled": true,
9
- "description": "按固定间隔重复执行提示词或命令"
10
- },
11
- "claude-api": {
12
- "enabled": true,
13
- "description": "构建、调试和优化 Claude API / Anthropic SDK 应用"
14
- },
15
- "agentation": {
16
- "enabled": true,
17
- "description": "Agentation React 可视化反馈工具栏"
18
- },
19
3
  "frontend-code-review": {
20
4
  "enabled": true,
21
5
  "description": "前端代码全面审查"
@@ -36,29 +20,15 @@
36
20
  "enabled": true,
37
21
  "description": "Vue 3 组件/组合式函数开发,提供 Composition API 最佳实践"
38
22
  },
39
- "init": {
40
- "enabled": true,
41
- "description": "初始化 CLAUDE.md 项目文档"
42
- },
43
- "review": {
44
- "enabled": true,
45
- "description": "Pull Request 代码审查"
46
- },
47
- "security-review": {
48
- "enabled": true,
49
- "description": "待变更代码安全审查"
50
- },
51
- "fe-biz-patterns": {
23
+ "v3-fe-biz-patterns": {
52
24
  "enabled": true,
53
25
  "description": "前端业务模式库,loading/滚动加载/导入导出/批量操作/表单联动/大列表渲染/Service层封装/Pinia Store模式/分页数据管理等常见业务场景"
54
26
  }
55
27
  },
56
28
  "always_apply_skills": [
57
- "simplify",
58
29
  "frontend-design",
59
30
  "vue",
60
31
  "frontend-code-review",
61
- "ui-ux-pro-max",
62
- "security-review"
32
+ "ui-ux-pro-max"
63
33
  ]
64
34
  }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "v3-fe-biz-patterns",
3
+ "version": "1.0.0",
4
+ "description": "MaDeKang的Vue3相关前端业务模式库,收录MaDeKang在前端业务中沉淀的方案和最佳实践",
5
+ "tags": ["frontend", "pattern", "vue3"]
6
+ }
@@ -1,11 +1,11 @@
1
1
  ---
2
- name: fe-biz-patterns
3
- description: 前端业务模式库,收录 XiaoMa 在实际业务中沉淀的前端方案和最佳实践。当用户要求实现包含以下特征的功能时使用:loading/加载/加载态、滚动加载/无限滚动/触底加载、数据导入导出、批量操作、表单联动、权限控制、大列表渲染、文件上传、实时搜索、拖拽排序、Service层封装/请求层/axios封装、Pinia Store模式/状态管理/分页数据管理、Tab 锚点/TabAnchor/带锚点滚动的 Tab 切换/吸顶 Tab 栏/浮动 Tab 栏/Tab 滑动指示器等常见前端业务场景。
2
+ name: v3-fe-biz-patterns
3
+ description: 前端Vue3业务模式库,收录 MaDeKang 在实际业务中沉淀的前端方案和最佳实践。当用户要求实现包含以下特征的功能时使用:loading/加载/加载态、滚动加载/无限滚动/触底加载、数据导入导出、批量操作、表单联动、权限控制、大列表渲染、文件上传、实时搜索、拖拽排序、Service层封装/请求层/axios封装、Pinia Store模式/状态管理/分页数据管理、Tab 锚点/TabAnchor/带锚点滚动的 Tab 切换/吸顶 Tab 栏/浮动 Tab 栏/Tab 滑动指示器等常见前端业务场景。
4
4
  ---
5
5
 
6
6
  # 前端业务模式库
7
7
 
8
- XiaoMa 实战沉淀的前端业务方案集合,覆盖日常开发中高频出现的业务场景。
8
+ MaDeKang 实战沉淀的前端业务方案集合,覆盖日常开发中高频出现的业务场景。
9
9
 
10
10
  每个方案独立成篇,按需加载,避免上下文浪费。
11
11
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mdk-skills",
3
- "version": "2.1.3",
3
+ "version": "2.1.5",
4
4
  "description": "mdk-engineer - 沉稳靠谱的前端开发助手 Claude Skills 配置包,一键注入 .claude/ 技能目录和 CLAUDE.md 人设配置",
5
5
  "author": "XiaoMa",
6
6
  "license": "MIT",
package/scripts/cli.js CHANGED
@@ -115,6 +115,159 @@ function installSelectedSkills(selectedNames) {
115
115
  return installedCount;
116
116
  }
117
117
 
118
+ // ---------- 场景选择(场景 → 一键装技能) ----------
119
+
120
+ function loadProfiles() {
121
+ const profilesPath = path.join(packageDir, ".claude", "profiles.json");
122
+ if (!fs.existsSync(profilesPath)) return null;
123
+ try {
124
+ return JSON.parse(fs.readFileSync(profilesPath, "utf-8")).profiles;
125
+ } catch {
126
+ return null;
127
+ }
128
+ }
129
+
130
+ function applyProfile(profile) {
131
+ const pkgSkills = fs.readdirSync(pkgSkillsSource);
132
+ const settings = readSettings();
133
+
134
+ // 确定要启用的技能列表
135
+ let selected;
136
+ if (profile.skills === null) {
137
+ // null 表示"自定义",不做操作,由调用方处理
138
+ return;
139
+ } else if (profile.skills.length === 0) {
140
+ selected = [];
141
+ } else {
142
+ // 只取包内实际存在的技能
143
+ selected = profile.skills.filter((s) => pkgSkills.includes(s));
144
+ }
145
+
146
+ // 装启用的、删禁用的
147
+ if (!fs.existsSync(skillsDest)) {
148
+ fs.mkdirSync(skillsDest, { recursive: true });
149
+ }
150
+ for (const name of pkgSkills) {
151
+ const src = path.join(pkgSkillsSource, name);
152
+ const dest = path.join(skillsDest, name);
153
+ if (selected.includes(name)) {
154
+ if (!fs.existsSync(dest)) {
155
+ try {
156
+ copyDirSync(src, dest);
157
+ } catch (err) {
158
+ console.error(` ❌ 安装技能 "${name}" 失败:`, err.message);
159
+ }
160
+ }
161
+ } else {
162
+ if (fs.existsSync(dest)) {
163
+ fs.rmSync(dest, { recursive: true, force: true });
164
+ }
165
+ }
166
+ }
167
+
168
+ // 更新 settings
169
+ if (!settings.skills) settings.skills = {};
170
+ for (const name of pkgSkills) {
171
+ const enabled = selected.includes(name);
172
+ if (!settings.skills[name]) settings.skills[name] = {};
173
+ settings.skills[name].enabled = enabled;
174
+ }
175
+
176
+ // 更新 always_apply_skills
177
+ if (profile.always_apply) {
178
+ settings.always_apply_skills = profile.always_apply;
179
+ }
180
+
181
+ // 记录当前活动场景
182
+ settings._active_profile = profile.id;
183
+ writeSettings(settings);
184
+
185
+ // 安装 CLAUDE.md(没有才装)
186
+ const mdSource = path.join(packageDir, "CLAUDE.md");
187
+ const mdDest = path.join(projectRoot, "CLAUDE.md");
188
+ if (fs.existsSync(mdSource) && !fs.existsSync(mdDest)) {
189
+ fs.copyFileSync(mdSource, mdDest);
190
+ console.log(" 📝 CLAUDE.md 已创建\n");
191
+ }
192
+
193
+ // 输出结果
194
+ const enabledCount = selected.length;
195
+ const disabledCount = pkgSkills.length - enabledCount;
196
+ console.log(`\n ✅ 已切换到「${profile.name}」`);
197
+ console.log(` 启用 ${enabledCount} 个技能,停用 ${disabledCount} 个\n`);
198
+ }
199
+
200
+ async function startSceneSelection() {
201
+ const { select } = await import("@inquirer/prompts");
202
+ const chalk = (await import("chalk")).default;
203
+ const profiles = loadProfiles();
204
+ const settings = readSettings();
205
+ const activeProfile = settings._active_profile;
206
+ const hasExistingInstall = fs.existsSync(claudeDest);
207
+
208
+ const choices = profiles.map((p) => {
209
+ const isActive = p.id === activeProfile;
210
+ const prefix = isActive ? chalk.green("● ") : " ";
211
+ return {
212
+ name: prefix + p.name,
213
+ value: p.id,
214
+ description: isActive
215
+ ? chalk.dim("当前场景 · ") + (p.description || "")
216
+ : p.description || "",
217
+ };
218
+ });
219
+
220
+ // 底部加个分隔
221
+ choices.push(
222
+ { name: chalk.dim("────────────────"), value: "__sep__", description: "" },
223
+ { name: " 查看技能清单", value: "__list__", description: "列出所有技能状态" },
224
+ );
225
+
226
+ const selectedId = await select({
227
+ message: hasExistingInstall
228
+ ? "选择开发场景(切换将自动调整技能)"
229
+ : "选择你的开发场景",
230
+ instructions: `(↑↓ 导航, Enter 确认)`,
231
+ choices,
232
+ pageSize: 10,
233
+ loop: false,
234
+ });
235
+
236
+ if (selectedId === "__sep__") {
237
+ return startSceneSelection();
238
+ }
239
+
240
+ if (selectedId === "__list__") {
241
+ await cmdList();
242
+ // 看完列表再回到场景选择
243
+ console.log("");
244
+ return startSceneSelection();
245
+ }
246
+
247
+ const profile = profiles.find((p) => p.id === selectedId);
248
+
249
+ if (profile.skills === null) {
250
+ // "自定义选择" → 跳到 checkbox
251
+ await startInteractiveMenu();
252
+ return;
253
+ }
254
+
255
+ if (profile.id === activeProfile) {
256
+ // 选的已经是当前场景,问要不要微调
257
+ const { confirm } = await import("@inquirer/prompts");
258
+ const tweak = await confirm({
259
+ message: "已是当前场景,是否进入自定义模式微调技能?",
260
+ default: false,
261
+ });
262
+ if (tweak) {
263
+ await startInteractiveMenu();
264
+ }
265
+ return;
266
+ }
267
+
268
+ applyProfile(profile);
269
+ }
270
+
118
271
  // ---------- 命令:list ----------
119
272
 
120
273
  async function cmdList() {
@@ -156,7 +309,7 @@ async function cmdList() {
156
309
  }
157
310
 
158
311
  console.log(
159
- `\n ${chalk.cyan("💡")} ${chalk.dim("运行 npx mdk-skills 进入交互选择模式")}\n`,
312
+ `\n ${chalk.cyan("💡")} ${chalk.dim("运行 npx mdk-skills 进入场景选择")}\n`,
160
313
  );
161
314
  }
162
315
 
@@ -229,17 +382,24 @@ async function main() {
229
382
  const args = process.argv.slice(3);
230
383
 
231
384
  if (!command) {
232
- await startInteractiveMenu();
385
+ const profiles = loadProfiles();
386
+ if (profiles) {
387
+ await startSceneSelection();
388
+ } else {
389
+ // 没有 profiles.json 时回退到原来的 checkbox
390
+ await startInteractiveMenu();
391
+ }
233
392
  } else if (command === "--help" || command === "-h") {
234
393
  console.log(`
235
394
  mdk-skills CLI
236
395
 
237
396
  用法:
238
- npx mdk-skills 交互式选择并安装技能
397
+ npx mdk-skills 场景选择 → 一键安装对应技能
239
398
  npx mdk-skills list 查看已安装的技能
240
399
  npx mdk-skills --help 显示帮助
241
400
 
242
- 首次运行会自动创建 .claude/ 目录,勾选要安装的技能即可
401
+ 首次运行选择场景后自动配置技能和 CLAUDE.md
402
+ 再次运行可切换场景或进入自定义模式微调
243
403
 
244
404
  示例:
245
405
  npx mdk-skills
@@ -1,4 +0,0 @@
1
- [2026-05-09 20:45:26] [INFO] Install started (upgrade)
2
- [2026-05-09 20:45:38] [INFO] Install started (upgrade)
3
- [2026-05-09 20:46:37] [INFO] Install started (upgrade)
4
- [2026-05-09 20:47:06] [INFO] Install started (upgrade)
@@ -1,7 +0,0 @@
1
- {
2
- "permissions": {
3
- "allow": [
4
- "mcp__chrome-devtools__evaluate_script"
5
- ]
6
- }
7
- }
@@ -1,6 +0,0 @@
1
- {
2
- "name": "agentation",
3
- "version": "1.0.0",
4
- "description": "Agentation React 可视化反馈工具栏",
5
- "tags": ["react", "ui", "debug"]
6
- }
@@ -1,107 +0,0 @@
1
- ---
2
- name: agentation
3
- description: Add Agentation visual feedback toolbar to any React project
4
- ---
5
-
6
- # Agentation Setup
7
-
8
- Set up the Agentation annotation toolbar in this project.
9
-
10
- ## Requirements
11
-
12
- - React 18+
13
- - Zero dependencies beyond React
14
-
15
- ## Steps
16
-
17
- 1. **Check if already installed**
18
- - Look for `agentation` in package.json dependencies
19
- - If not found, run `npm install agentation` (or pnpm/yarn based on lockfile)
20
-
21
- 2. **Check if already configured**
22
- - Search for `<Agentation` or `import { Agentation }` in src/ or app/
23
- - If found, report that Agentation is already set up and exit
24
-
25
- 3. **Detect project type**
26
- - **Next.js App Router**: has `app/layout.tsx` or `app/layout.js`
27
- - **Next.js Pages Router**: has `pages/_app.tsx` or `pages/_app.js`
28
- - **Vite + React**: has `vite.config.ts/js` and `src/main.tsx/jsx`
29
- - **Create React App**: has `src/index.tsx/jsx` or `src/App.tsx/jsx`
30
- - **Other React projects**: look for main entry file
31
-
32
- 4. **Add the component**
33
-
34
- **For Next.js App Router**, add to `app/layout.tsx`:
35
- ```tsx
36
- import { Agentation } from "agentation";
37
-
38
- export default function RootLayout({ children }) {
39
- return (
40
- <html>
41
- <body>
42
- {children}
43
- {process.env.NODE_ENV === "development" && <Agentation />}
44
- </body>
45
- </html>
46
- );
47
- }
48
- ```
49
-
50
- **For Next.js Pages Router**, add to `pages/_app.tsx`:
51
- ```tsx
52
- import { Agentation } from "agentation";
53
-
54
- export default function App({ Component, pageProps }) {
55
- return (
56
- <>
57
- <Component {...pageProps} />
58
- {process.env.NODE_ENV === "development" && <Agentation />}
59
- </>
60
- );
61
- }
62
- ```
63
-
64
- **For Vite + React**, add to `src/main.tsx`:
65
- ```tsx
66
- import { Agentation } from "agentation";
67
-
68
- ReactDOM.createRoot(document.getElementById('root')!).render(
69
- <React.StrictMode>
70
- <App />
71
- {import.meta.env.DEV && <Agentation />}
72
- </React.StrictMode>
73
- );
74
- ```
75
-
76
- **For Create React App**, add to `src/index.tsx`:
77
- ```tsx
78
- import { Agentation } from "agentation";
79
-
80
- const root = ReactDOM.createRoot(document.getElementById('root'));
81
- root.render(
82
- <React.StrictMode>
83
- <App />
84
- {process.env.NODE_ENV === "development" && <Agentation />}
85
- </React.StrictMode>
86
- );
87
- ```
88
-
89
- **For other React projects**, add to the root component or main entry file:
90
- ```tsx
91
- import { Agentation } from "agentation";
92
-
93
- // Add at the end of your root component
94
- {process.env.NODE_ENV === "development" && <Agentation />}
95
- ```
96
-
97
- 5. **Confirm setup**
98
- - Tell the user to run their dev server and look for the Agentation toolbar (floating button in bottom-right corner)
99
- - The toolbar should appear in the bottom-right corner of the page
100
-
101
- ## Notes
102
-
103
- - The environment check ensures Agentation only loads in development
104
- - For Vite projects, use `import.meta.env.DEV` instead of `process.env.NODE_ENV`
105
- - For Next.js, use `process.env.NODE_ENV === "development"`
106
- - No additional configuration needed — it works out of the box
107
- - Compatible with any React 18+ project
@@ -1,6 +0,0 @@
1
- {
2
- "name": "fe-biz-patterns",
3
- "version": "1.0.0",
4
- "description": "小马自己的前端业务模式库,收录小马在前端业务中沉淀的方案和最佳实践",
5
- "tags": ["frontend", "pattern", "vue", "react"]
6
- }
@@ -1,6 +0,0 @@
1
- {
2
- "name": "moai-framework-electron",
3
- "version": "1.0.0",
4
- "description": "Electron 桌面应用开发,含主进程/渲染进程/IPC/自动更新/打包",
5
- "tags": ["electron", "desktop", "node"]
6
- }
@@ -1,328 +0,0 @@
1
- ---
2
- name: moai-framework-electron
3
- description: >
4
- Electron 33+ desktop app development specialist covering Main/Renderer
5
- process architecture, IPC communication, auto-update, and packaging with
6
- Electron Forge. Use when building cross-platform desktop applications.
7
- license: Apache-2.0
8
- compatibility: Designed for Claude Code
9
- allowed-tools: Read, Grep, Glob, mcp__context7__resolve-library-id, mcp__context7__get-library-docs
10
- user-invocable: false
11
- metadata:
12
- version: "2.0.0"
13
- category: "framework"
14
- status: "active"
15
- updated: "2026-01-10"
16
- modularized: "false"
17
- tags: "electron, desktop, cross-platform, nodejs, chromium, ipc, auto-update, electron-builder, electron-forge"
18
- context7-libraries: "/electron/electron, /electron/forge, /electron-userland/electron-builder"
19
- related-skills: "moai-lang-typescript, moai-domain-frontend, moai-lang-javascript"
20
- ---
21
-
22
- # Electron 33+ Desktop Development
23
-
24
- ## Quick Reference
25
-
26
- Electron 33+ Desktop App Development Specialist enables building cross-platform desktop applications with web technologies.
27
-
28
- Auto-Triggers: Electron projects detected via electron.vite.config.ts or electron-builder.yml files, desktop app development requests, IPC communication pattern implementation
29
-
30
- ### Core Capabilities
31
-
32
- Electron 33 Platform:
33
-
34
- - Chromium 130 rendering engine for modern web features
35
- - Node.js 20.18 runtime for native system access
36
- - Native ESM support in main process
37
- - WebGPU API support for GPU-accelerated graphics
38
-
39
- Process Architecture:
40
-
41
- - Main process runs as single instance per application with full Node.js access
42
- - Renderer processes display web content in sandboxed environments
43
- - Preload scripts bridge main and renderer with controlled API exposure
44
- - Utility processes handle background tasks without blocking UI
45
-
46
- IPC Communication:
47
-
48
- - Type-safe invoke/handle patterns for request-response communication
49
- - contextBridge API for secure renderer access to main process functionality
50
- - Event-based messaging for push notifications from main to renderer
51
-
52
- Auto-Update Support:
53
-
54
- - electron-updater integration with GitHub and S3 publishing
55
- - Differential updates for smaller download sizes
56
- - Update notification and installation management
57
-
58
- Packaging Options:
59
-
60
- - Electron Forge for integrated build tooling and plugin ecosystem
61
- - electron-builder for flexible multi-platform distribution
62
-
63
- Security Features:
64
-
65
- - contextIsolation for preventing prototype pollution
66
- - Sandbox enforcement for renderer process isolation
67
- - Content Security Policy configuration
68
- - Input validation patterns for IPC handlers
69
-
70
- ### Project Initialization
71
-
72
- Creating a new Electron application requires running the create-electron-app command with the vite-typescript template. Install electron-builder as a development dependency for packaging. Add electron-updater as a runtime dependency for auto-update functionality.
73
-
74
- For detailed commands and configuration, see reference.md Quick Commands section.
75
-
76
- ---
77
-
78
- ## Implementation Guide
79
-
80
- ### Project Structure
81
-
82
- Recommended Directory Layout:
83
-
84
- The source directory should contain four main subdirectories:
85
-
86
- Main Directory: Contains the main process entry point, IPC handler definitions organized by domain, business logic services, and window management modules
87
-
88
- Preload Directory: Contains the preload script entry point and exposed API definitions that bridge main and renderer
89
-
90
- Renderer Directory: Contains the web application built with React, Vue, or Svelte, including the HTML entry point and Vite configuration
91
-
92
- Shared Directory: Contains TypeScript types and constants shared between main and renderer processes
93
-
94
- The project root should include the electron.vite.config.ts for build configuration, electron-builder.yml for packaging options, and resources directory for app icons and assets.
95
-
96
- ### Main Process Setup
97
-
98
- Application Lifecycle Management:
99
-
100
- The main process initialization follows a specific sequence. First, enable sandbox globally using app.enableSandbox() to ensure all renderer processes run in isolated environments. Then request single instance lock to prevent multiple app instances from running simultaneously.
101
-
102
- Window creation should occur after the app ready event fires. Configure BrowserWindow with security-focused webPreferences including contextIsolation enabled, nodeIntegration disabled, sandbox enabled, and webSecurity enabled. Set the preload script path to expose safe APIs to the renderer.
103
-
104
- Handle platform-specific behaviors: on macOS, re-create windows when the dock icon is clicked if no windows exist. On other platforms, quit the application when all windows close.
105
-
106
- For implementation examples, see examples.md Main Process Entry Point section.
107
-
108
- ### Type-Safe IPC Communication
109
-
110
- IPC Type Definition Pattern:
111
-
112
- Define an interface that maps channel names to their payload types. Group channels by domain such as file operations, window operations, and storage operations. This enables type checking for both main process handlers and renderer invocations.
113
-
114
- Main Process Handler Registration:
115
-
116
- Register IPC handlers in a dedicated module that imports from the shared types. Each handler should validate input using a schema validation library such as Zod before processing. Use ipcMain.handle for request-response patterns and return structured results.
117
-
118
- Preload Script Implementation:
119
-
120
- Create an API object that wraps ipcRenderer.invoke calls for each channel. Use contextBridge.exposeInMainWorld to make this API available in the renderer as window.electronAPI. Include cleanup functions for event listeners to prevent memory leaks.
121
-
122
- For complete IPC implementation patterns, see examples.md Type-Safe IPC Implementation section.
123
-
124
- ### Security Best Practices
125
-
126
- Mandatory Security Settings:
127
-
128
- Every BrowserWindow must have webPreferences configured with four critical settings. contextIsolation must always be enabled to prevent renderer code from accessing Electron internals. nodeIntegration must always be disabled in renderer processes. sandbox must always be enabled for process-level isolation. webSecurity must never be disabled to maintain same-origin policy enforcement.
129
-
130
- Content Security Policy:
131
-
132
- Configure session-level CSP headers using webRequest.onHeadersReceived. Restrict default-src to self, script-src to self without unsafe-inline, and connect-src to allowed API domains. This prevents XSS attacks and unauthorized resource loading.
133
-
134
- Input Validation:
135
-
136
- Every IPC handler must validate inputs before processing. Prevent path traversal attacks by rejecting paths containing parent directory references. Validate file names against reserved characters. Use allowlists for permitted directories when implementing file access.
137
-
138
- For security implementation details, see reference.md Security Best Practices section.
139
-
140
- ### Auto-Update Implementation
141
-
142
- Update Service Architecture:
143
-
144
- Create an UpdateService class that manages the electron-updater lifecycle. Initialize with the main window reference to enable UI notifications. Configure autoDownload as false to give users control over bandwidth usage.
145
-
146
- Event Handling:
147
-
148
- Handle update-available events by notifying the renderer and prompting the user for download confirmation. Track download-progress events to display progress indicators. Handle update-downloaded events by prompting for restart.
149
-
150
- User Notification Pattern:
151
-
152
- Use system dialogs to prompt users when updates are available and when downloads complete. Send events to the renderer for in-app notification display. Support both immediate and deferred installation.
153
-
154
- For complete update service implementation, see examples.md Auto-Update Integration section.
155
-
156
- ### App Packaging
157
-
158
- Electron Builder Configuration:
159
-
160
- Configure the appId with reverse-domain notation for platform registration. Specify productName for display in system UI. Set up platform-specific targets for macOS, Windows, and Linux.
161
-
162
- macOS Configuration:
163
-
164
- Set category for App Store classification. Enable hardenedRuntime and configure entitlements for notarization. Configure universal builds targeting both x64 and arm64 architectures.
165
-
166
- Windows Configuration:
167
-
168
- Specify icon path for executable and installer. Configure NSIS installer options including installation directory selection. Set up code signing with appropriate hash algorithms.
169
-
170
- Linux Configuration:
171
-
172
- Configure category for desktop environment integration. Set up multiple targets including AppImage for universal distribution and deb/rpm for package manager installation.
173
-
174
- For complete configuration examples, see reference.md Configuration section.
175
-
176
- ---
177
-
178
- ## Advanced Patterns
179
-
180
- For comprehensive documentation on advanced topics, see reference.md and examples.md:
181
-
182
- Window State Persistence:
183
-
184
- - Saving and restoring window position and size across sessions
185
- - Handling multiple displays and display changes
186
- - Managing maximized and fullscreen states
187
-
188
- Multi-Window Management:
189
-
190
- - Creating secondary windows with proper parent-child relationships
191
- - Sharing state between multiple windows
192
- - Coordinating window lifecycle events
193
-
194
- System Tray and Native Menus:
195
-
196
- - Creating and updating system tray icons with context menus
197
- - Building application menus with keyboard shortcuts
198
- - Platform-specific menu patterns for macOS and Windows
199
-
200
- Utility Processes:
201
-
202
- - Spawning utility processes for CPU-intensive background tasks
203
- - Communicating with utility processes via MessageChannel
204
- - Managing utility process lifecycle and error handling
205
-
206
- Native Module Integration:
207
-
208
- - Rebuilding native modules for Electron Node.js version
209
- - Using better-sqlite3 for local database storage
210
- - Integrating keytar for secure credential storage
211
-
212
- Protocol Handlers and Deep Linking:
213
-
214
- - Registering custom URL protocols for app launching
215
- - Handling deep links on different platforms
216
- - OAuth callback handling via custom protocols
217
-
218
- Performance Optimization:
219
-
220
- - Lazy loading windows and heavy modules
221
- - Optimizing startup time with deferred initialization
222
- - Memory management for long-running applications
223
-
224
- ---
225
-
226
- ## Works Well With
227
-
228
- - moai-lang-typescript - TypeScript patterns for type-safe Electron development
229
- - moai-domain-frontend - React, Vue, or Svelte renderer development
230
- - moai-lang-javascript - Node.js patterns for main process
231
- - moai-domain-backend - Backend API integration
232
- - moai-workflow-testing - Testing strategies for desktop apps
233
-
234
- ---
235
-
236
- ## Troubleshooting
237
-
238
- Common Issues and Solutions:
239
-
240
- White Screen on Launch:
241
-
242
- Verify the preload script path is correctly configured relative to the built output directory. Check that loadFile or loadURL paths point to existing files. Enable devTools to inspect console errors. Review CSP settings that may block script execution.
243
-
244
- IPC Not Working:
245
-
246
- Confirm channel names match exactly between main handlers and renderer invocations. Ensure handlers are registered before windows load content. Verify contextBridge usage follows the correct pattern with exposeInMainWorld.
247
-
248
- Native Modules Fail:
249
-
250
- Run electron-rebuild after npm install to recompile native modules. Match the Node.js version embedded in Electron. Add a postinstall script to automate rebuilding.
251
-
252
- Auto-Update Not Working:
253
-
254
- Verify the application is code-signed as updates require signing. Check publish configuration in electron-builder.yml. Enable electron-updater logging to diagnose connection issues. Review firewall settings that may block update checks.
255
-
256
- Debug Commands:
257
-
258
- Rebuild native modules with npx electron-rebuild. Check Electron version with npx electron --version. Enable verbose update logging with DEBUG=electron-updater environment variable.
259
-
260
- ---
261
-
262
- ## Resources
263
-
264
- For complete code examples and configuration templates, see:
265
-
266
- - reference.md - Detailed API documentation, version matrix, Context7 library mappings
267
- - examples.md - Production-ready code examples for all patterns
268
-
269
- For latest documentation, use Context7 to query:
270
-
271
- - /electron/electron for core Electron APIs
272
- - /electron/forge for Electron Forge tooling
273
- - /electron-userland/electron-builder for packaging configuration
274
-
275
- ---
276
-
277
- Version: 2.0.0
278
- Last Updated: 2026-01-10
279
- Changes: Restructured to comply with CLAUDE.md Documentation Standards - removed all code examples, converted to narrative text format
280
-
281
- <!-- moai:evolvable-start id="rationalizations" -->
282
- ## Common Rationalizations
283
-
284
- | Rationalization | Reality |
285
- |---|---|
286
- | "I can use Node.js APIs directly in the renderer process" | Renderer process runs untrusted content. Direct Node.js access is a remote code execution vector. Use IPC through the preload bridge. |
287
- | "contextIsolation is unnecessary since I trust my own code" | Context isolation prevents prototype pollution from web content reaching Node.js. It is not about trusting your code, it is about isolating contexts. |
288
- | "Auto-update can be configured after release" | Shipping without auto-update means users stay on vulnerable versions. Configure it before the first release. |
289
- | "I will package the app later, development builds are enough for testing" | Development builds have different file paths, permissions, and code signing. Only production-packaged builds reveal real distribution issues. |
290
- | "IPC is slow, I will share state through global variables" | IPC overhead is microseconds. Global variables bypass process isolation, which exists for security. |
291
-
292
- <!-- moai:evolvable-end -->
293
-
294
- <!-- moai:evolvable-start id="red-flags" -->
295
- ## Red Flags
296
-
297
- - nodeIntegration set to true in BrowserWindow options
298
- - contextIsolation set to false without documented security justification
299
- - Renderer process imports directly from electron or node modules (bypass preload)
300
- - No auto-update mechanism configured
301
- - IPC handler does not validate or sanitize arguments from renderer
302
-
303
- <!-- moai:evolvable-end -->
304
-
305
- <!-- moai:evolvable-start id="verification" -->
306
- ## Verification
307
-
308
- - [ ] nodeIntegration is false and contextIsolation is true in all BrowserWindows
309
- - [ ] All renderer-to-main communication uses contextBridge and IPC
310
- - [ ] IPC handlers validate input arguments before processing
311
- - [ ] Auto-update configured and tested (show update configuration)
312
- - [ ] Application packages successfully with Electron Forge (show build output)
313
- - [ ] No direct require('electron') in renderer process code
314
-
315
- <!-- moai:evolvable-end -->
316
-
317
- ## Telemetry Window
318
-
319
- **Status**: UNCLEAR (60-day window)
320
- **R4 audit verdict**: KEEP (monitor)
321
- **SPEC**: SPEC-V3R2-WF-001 §6.2 (REQ-WF001-013)
322
- **Window start**: 2026-04-25 (Wave 1.5 commit date)
323
- **Window end**: 2026-06-24 (60 days)
324
- **Re-audit trigger**: SessionStart hook activation count for this skill
325
- **Decision criteria**:
326
- - If activation count >= 5 during window → retain permanently
327
- - If activation count = 0 during window → schedule RETIRE in v3.1
328
- - If 0 < count < 5 → retain with "low-use" tag