@binblink/wasmnest-plugin-sdk-mobile 0.0.0-stage → 0.0.1

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.
Files changed (114) hide show
  1. package/README.md +363 -2
  2. package/README_en.md +353 -0
  3. package/bin/build.js +269 -0
  4. package/bin/cli.js +96 -0
  5. package/bin/lib.js +349 -0
  6. package/bin/manifest-gen.js +324 -0
  7. package/bin/package.js +150 -0
  8. package/bin/scaffold.js +285 -0
  9. package/dev-shell/README.md +151 -0
  10. package/dev-shell/index.html +27 -0
  11. package/dev-shell/package.json +27 -0
  12. package/dev-shell/pnpm-workspace.yaml +9 -0
  13. package/dev-shell/postcss.config.js +6 -0
  14. package/dev-shell/src/App.vue +90 -0
  15. package/dev-shell/src/apps/mock-terminal/MockTerminalSlotCard.vue +51 -0
  16. package/dev-shell/src/apps/mock-terminal/MockTerminalView.vue +168 -0
  17. package/dev-shell/src/apps/mock-terminal/index.ts +50 -0
  18. package/dev-shell/src/components/DevToolbar.vue +100 -0
  19. package/dev-shell/src/components/DialogHost.vue +119 -0
  20. package/dev-shell/src/components/LogPanel.vue +80 -0
  21. package/dev-shell/src/i18n.ts +22 -0
  22. package/dev-shell/src/loader.ts +239 -0
  23. package/dev-shell/src/locale.ts +29 -0
  24. package/dev-shell/src/locales/en-shell.ts +328 -0
  25. package/dev-shell/src/locales/index.ts +70 -0
  26. package/dev-shell/src/locales/shell.ts +328 -0
  27. package/dev-shell/src/main.ts +58 -0
  28. package/dev-shell/src/mock/dialog-service.ts +58 -0
  29. package/dev-shell/src/mock/file-transfer.ts +390 -0
  30. package/dev-shell/src/mock/mobile-api.ts +369 -0
  31. package/dev-shell/src/mock/preset-tasks.ts +186 -0
  32. package/dev-shell/src/mock/session.ts +121 -0
  33. package/dev-shell/src/mock-context.ts +351 -0
  34. package/dev-shell/src/registry.ts +151 -0
  35. package/dev-shell/src/shared-runtime.ts +44 -0
  36. package/dev-shell/src/shell/ShellView.vue +52 -0
  37. package/dev-shell/src/shell/adapters/devAppSource.ts +155 -0
  38. package/dev-shell/src/shell/components/PluginContextHost.vue +40 -0
  39. package/dev-shell/src/shell/components/ShellAppCell.vue +75 -0
  40. package/dev-shell/src/shell/components/ShellAppIcon.vue +111 -0
  41. package/dev-shell/src/shell/components/ShellAppSurface.vue +46 -0
  42. package/dev-shell/src/shell/components/ShellBrandTile.vue +27 -0
  43. package/dev-shell/src/shell/components/ShellCapsuleMenu.vue +123 -0
  44. package/dev-shell/src/shell/components/ShellChip.vue +49 -0
  45. package/dev-shell/src/shell/components/ShellGroupCard.vue +17 -0
  46. package/dev-shell/src/shell/components/ShellHost.vue +75 -0
  47. package/dev-shell/src/shell/components/ShellNotificationShade.vue +496 -0
  48. package/dev-shell/src/shell/components/ShellPermissionPrompt.vue +127 -0
  49. package/dev-shell/src/shell/components/ShellPlaceholderSurface.vue +33 -0
  50. package/dev-shell/src/shell/components/ShellSection.vue +27 -0
  51. package/dev-shell/src/shell/components/ShellSheet.vue +74 -0
  52. package/dev-shell/src/shell/components/ShellStatusbar.vue +84 -0
  53. package/dev-shell/src/shell/components/screens/PluginRoutePage.vue +98 -0
  54. package/dev-shell/src/shell/components/screens/ShellAppDetailScreen.vue +378 -0
  55. package/dev-shell/src/shell/components/screens/ShellAppRunScreen.vue +90 -0
  56. package/dev-shell/src/shell/components/screens/ShellAppsScreen.vue +195 -0
  57. package/dev-shell/src/shell/components/screens/ShellHomeScreen.vue +316 -0
  58. package/dev-shell/src/shell/components/screens/ShellPermissionsScreen.vue +376 -0
  59. package/dev-shell/src/shell/components/screens/ShellSettingsScreen.vue +240 -0
  60. package/dev-shell/src/shell/components/screens/ShellSwitcherScreen.vue +559 -0
  61. package/dev-shell/src/shell/components/ui/ConfirmDialog.vue +137 -0
  62. package/dev-shell/src/shell/components/ui/Toggle.vue +53 -0
  63. package/dev-shell/src/shell/composables/useShellApps.ts +415 -0
  64. package/dev-shell/src/shell/composables/useShellNavigation.ts +197 -0
  65. package/dev-shell/src/shell/composables/useShellNotifications.ts +115 -0
  66. package/dev-shell/src/shell/composables/useShellOpen.ts +35 -0
  67. package/dev-shell/src/shell/composables/useShellOverlays.ts +101 -0
  68. package/dev-shell/src/shell/composables/useShellPreferences.ts +143 -0
  69. package/dev-shell/src/shell/composables/useShellRecent.ts +84 -0
  70. package/dev-shell/src/shell/composables/useToast.ts +33 -0
  71. package/dev-shell/src/shell/index.ts +88 -0
  72. package/dev-shell/src/shell/logger.ts +45 -0
  73. package/dev-shell/src/shell/permissions.ts +145 -0
  74. package/dev-shell/src/shell/registry.ts +220 -0
  75. package/dev-shell/src/shell/styles/shell.css +841 -0
  76. package/dev-shell/src/shell/types.ts +137 -0
  77. package/dev-shell/src/shell/utils.ts +54 -0
  78. package/dev-shell/src/styles/main.css +153 -0
  79. package/dev-shell/src/styles/mobile.css +884 -0
  80. package/dev-shell/src/styles/wallpaper.css +130 -0
  81. package/dev-shell/src/theme.ts +71 -0
  82. package/dev-shell/src/vite-env.d.ts +20 -0
  83. package/dev-shell/tailwind.config.js +101 -0
  84. package/dev-shell/tsconfig.json +16 -0
  85. package/dev-shell/vite.config.ts +130 -0
  86. package/dist/index.d.ts +84 -0
  87. package/dist/index.js +161 -0
  88. package/dist/types.d.ts +637 -0
  89. package/dist/types.js +0 -0
  90. package/dist/vite-plugin.d.ts +16 -0
  91. package/dist/vite-plugin.js +95 -0
  92. package/package.json +80 -3
  93. package/src/constants.ts +6 -0
  94. package/src/global-dialog.ts +168 -0
  95. package/src/index.ts +87 -0
  96. package/src/runtime.ts +44 -0
  97. package/src/types.ts +715 -0
  98. package/src/ui/PluginGlobalDialog.vue +388 -0
  99. package/src/ui/Select.d.ts +37 -0
  100. package/src/ui/Select.vue +307 -0
  101. package/src/ui/plugin-global-dialog.d.ts +11 -0
  102. package/src/ui/useSwipeTabs.d.ts +20 -0
  103. package/src/ui/useSwipeTabs.ts +53 -0
  104. package/src/vite-plugin.ts +132 -0
  105. package/template/.gitignore +4 -0
  106. package/template/README.md +46 -0
  107. package/template/package.json +23 -0
  108. package/template/plugin.json +13 -0
  109. package/template/rust/Cargo.toml +19 -0
  110. package/template/rust/src/lib.rs +33 -0
  111. package/template/src/env.d.ts +24 -0
  112. package/template/src/index.ts +37 -0
  113. package/template/tsconfig.json +17 -0
  114. package/template/vite.config.ts +21 -0
@@ -0,0 +1,324 @@
1
+ /**
2
+ * manifest-gen — plugin.json contributes/permissions 自动填充
3
+ *
4
+ * 单一事实来源是插件源码:前端 register* 调用推导 UI 扩展点,
5
+ * 前端 context API 使用 + Rust host 调用推导权限,
6
+ * Rust invoke_command 匹配臂推导 commands。
7
+ * (terminal handlers 推导线已随票 15 阶段 B 删除——terminal-hooks 退役,
8
+ * `terminal:input` 权限位同步退役;`.terminal` 宽推导规则一并移除,
9
+ * 否则终端 UI 域源码里的 `.terminal` 子串会把退役权限自动加回 manifest)
10
+ *
11
+ * 合并策略(保守,避免误删导致运行时拒绝):
12
+ * - permissions:派生结果与手工声明取并集
13
+ * - contributes.routes/settings/commands:
14
+ * 扫描到注册调用时以扫描结果为准(按 id 从旧条目继承无法静态求值的字段,
15
+ * 如 i18n.t() 动态 title);未扫描到时保留原值
16
+ * - contributes.views/navTab/terminal.toolbarItems:票 2026-10-10 批次 C2 起不再派生
17
+ * (对应扩展点整面退役);存量字段按「退役残留」处理,由 manifest 清理落掉
18
+ * - configuration/lifecycle/icon 等手工字段永不覆盖
19
+ */
20
+
21
+ import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
22
+ import { join } from 'node:path'
23
+
24
+ // ==================== 权限映射表 ====================
25
+
26
+ /** 前端 context API 使用 → 权限(正则按合并后的前端源码匹配) */
27
+ const FRONTEND_PERMISSION_RULES = [
28
+ { re: /\.(storage)\b/, perm: 'storage' },
29
+ // `session:read` 只从真实会话 API 用法推导(`context.session.list/get/onStatusChange`)。
30
+ // 裸 `\.session\b` 会把 i18n key(如 `monitor.footer.session`) / 普通字段名误判成
31
+ // 权限使用 → 构建期静默给 manifest 加一条未用到的权限。
32
+ { re: /\.session\s*\.\s*(list|get|onStatusChange)\b/, perm: 'session:read' },
33
+ ]
34
+
35
+ /** Rust host API 调用 → 权限(与 SDK permission 常量一一对应) */
36
+ const RUST_PERMISSION_RULES = [
37
+ { re: /\b(storage_get|storage_set|storage_delete|db_execute|db_query)\b/, perm: 'storage' },
38
+ { re: /\b(session_list|session_get)\b/, perm: 'session:read' },
39
+ { re: /\bhttp_fetch\b/, perm: 'network:http' },
40
+ { re: /\b(fs_read|fs_copy)\b/, perm: 'fs:read' },
41
+ { re: /\bfs_write\b/, perm: 'fs:write' },
42
+ ]
43
+
44
+ /**
45
+ * UI 注册调用 → 权限
46
+ *
47
+ * 票 2026-10-10 批次 C2:`registerToolboxPage` / `registerNavTab` /
48
+ * `registerTerminalToolbarItem` / `registerTerminalView` 四个旧嵌入扩展点已随宿主壳
49
+ * 改纯 surface 形态整面退役,对应权限位(ui:toolbox / ui:navtab / ui:input)同时失效。
50
+ * 本生成器不再为它们产出 `contributes` 与权限位——继续产出等于让 manifest 声明
51
+ * 退役权限,装载期会被 fail-visible 闸门直接拒绝(见 SDK permission::RETIRED_PERMISSIONS)。
52
+ */
53
+ const REGISTER_PERMISSIONS = {
54
+ registerSettingsSection: 'ui:settings',
55
+ registerRoute: 'ui:route',
56
+ }
57
+
58
+ /**
59
+ * 已退役权限位(票 2026-10-10 批次 C2)
60
+ *
61
+ * 与 SDK `permission::RETIRED_PERMISSIONS` 逐字一致;生成期剔除,宿主装载期拒载,
62
+ * 两道闸门都认这张表(见 SDK permission.rs 的同名常量与装载期校验)。
63
+ */
64
+ const RETIRED_PERMISSIONS = ['ui:toolbox', 'ui:navtab', 'ui:input']
65
+
66
+ // ==================== 文件收集 ====================
67
+
68
+ const FRONTEND_EXTS = new Set(['.ts', '.tsx', '.vue', '.js'])
69
+
70
+ /** 递归收集指定扩展名的文件 */
71
+ function collectFiles(dir, exts, out = []) {
72
+ if (!existsSync(dir)) return out
73
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
74
+ if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name.startsWith('.')) continue
75
+ const full = join(dir, entry.name)
76
+ if (entry.isDirectory()) {
77
+ collectFiles(full, exts, out)
78
+ } else if (entry.isFile() && exts.some((e) => entry.name.endsWith(e))) {
79
+ out.push(full)
80
+ }
81
+ }
82
+ return out
83
+ }
84
+
85
+ // ==================== 对象字面量解析 ====================
86
+
87
+ /** 从源码指定下标起提取配对的 {...} 对象字面量文本 */
88
+ function extractObjectLiteral(source, fromIndex) {
89
+ const start = source.indexOf('{', fromIndex)
90
+ if (start === -1) return null
91
+ let depth = 0
92
+ let inStr = null
93
+ for (let i = start; i < source.length; i++) {
94
+ const ch = source[i]
95
+ if (inStr) {
96
+ if (ch === '\\') i++
97
+ else if (ch === inStr) inStr = null
98
+ continue
99
+ }
100
+ if (ch === "'" || ch === '"' || ch === '`') inStr = ch
101
+ else if (ch === '{') depth++
102
+ else if (ch === '}') {
103
+ depth--
104
+ if (depth === 0) return source.slice(start, i + 1)
105
+ }
106
+ }
107
+ return null
108
+ }
109
+
110
+ /** 按顶层逗号切分对象字面量内部(忽略嵌套与字符串内的逗号) */
111
+ function splitTopLevel(body) {
112
+ const parts = []
113
+ let depth = 0
114
+ let inStr = null
115
+ let cur = ''
116
+ for (let i = 0; i < body.length; i++) {
117
+ const ch = body[i]
118
+ if (inStr) {
119
+ cur += ch
120
+ if (ch === '\\') cur += body[++i] ?? ''
121
+ else if (ch === inStr) inStr = null
122
+ continue
123
+ }
124
+ if (ch === "'" || ch === '"' || ch === '`') { inStr = ch; cur += ch; continue }
125
+ if (ch === '{' || ch === '[' || ch === '(') depth++
126
+ else if (ch === '}' || ch === ']' || ch === ')') depth--
127
+ if (ch === ',' && depth === 0) {
128
+ parts.push(cur)
129
+ cur = ''
130
+ } else {
131
+ cur += ch
132
+ }
133
+ }
134
+ if (cur.trim()) parts.push(cur)
135
+ return parts
136
+ }
137
+
138
+ /** 分类字面量值:字符串/数字/布尔/标识符,动态表达式返回 null */
139
+ function classifyValue(raw) {
140
+ const text = raw.trim().replace(/,$/, '').trim()
141
+ const strMatch = text.match(/^(['"])((?:\\.|(?!\1).)*)\1$/s)
142
+ if (strMatch) return strMatch[2]
143
+ if (/^-?\d+(\.\d+)?$/.test(text)) return Number(text)
144
+ if (text === 'true') return true
145
+ if (text === 'false') return false
146
+ if (/^[A-Za-z_$][\w$]*$/.test(text)) return { __ident: text }
147
+ return null
148
+ }
149
+
150
+ /** 解析简单对象字面量为键值映射(嵌套对象/动态值 → null) */
151
+ function parseObjectLiteral(literal) {
152
+ const body = literal.slice(literal.indexOf('{') + 1, literal.lastIndexOf('}'))
153
+ const result = {}
154
+ for (const part of splitTopLevel(body)) {
155
+ const m = part.match(/^\s*(?:['"](\w+)['"]|(\w+))\s*:\s*([\s\S]+)$/)
156
+ if (!m) continue
157
+ const key = m[1] || m[2]
158
+ result[key] = classifyValue(m[3])
159
+ }
160
+ return result
161
+ }
162
+
163
+ /** 提取源码中所有 `.callName({...})` 注册调用的对象参数 */
164
+ function findRegisterCalls(source, callName) {
165
+ const results = []
166
+ const re = new RegExp(`\\.${callName}\\s*\\(`, 'g')
167
+ let m
168
+ while ((m = re.exec(source)) !== null) {
169
+ const literal = extractObjectLiteral(source, m.index + m[0].length - 1)
170
+ if (literal) results.push(parseObjectLiteral(literal))
171
+ }
172
+ return results
173
+ }
174
+
175
+ // ==================== 字段合并 ====================
176
+
177
+ /** 旧条目按 id 建索引 */
178
+ function indexById(entries) {
179
+ const map = new Map()
180
+ for (const e of entries || []) {
181
+ if (e && e.id) map.set(e.id, e)
182
+ }
183
+ return map
184
+ }
185
+
186
+ /** 合并扫描条目与旧条目:扫描值优先,null(动态表达式)回退旧值,再回退默认值 */
187
+ function mergeEntry(scanned, old, defaults = {}) {
188
+ const merged = { ...defaults }
189
+ if (old) Object.assign(merged, old)
190
+ for (const [key, value] of Object.entries(scanned)) {
191
+ if (value === null || value === undefined) continue
192
+ if (value && typeof value === 'object' && value.__ident) {
193
+ merged[key] = value.__ident
194
+ continue
195
+ }
196
+ merged[key] = value
197
+ }
198
+ return merged
199
+ }
200
+
201
+ // ==================== Rust 扫描 ====================
202
+
203
+ /** 提取 invoke_command 匹配臂中的 command id 列表 */
204
+ function extractRustCommands(rustSource) {
205
+ const fnIndex = rustSource.search(/\bfn\s+invoke_command\b/)
206
+ if (fnIndex === -1) return []
207
+ const body = extractObjectLiteral(rustSource, fnIndex)
208
+ if (!body) return []
209
+ const ids = []
210
+ const re = /"([\w][\w.-]*)"\s*=>/g
211
+ let m
212
+ while ((m = re.exec(body)) !== null) ids.push(m[1])
213
+ return [...new Set(ids)]
214
+ }
215
+
216
+ // ==================== 主入口 ====================
217
+
218
+ /**
219
+ * 扫描插件源码并自动填充 plugin.json 的 contributes/permissions
220
+ * @param {string} cwd 插件工程根目录
221
+ * @param {{ check?: boolean }} options check 模式只报告不写入
222
+ * @returns {{ changed: boolean, report: string[] }}
223
+ */
224
+ export function generateManifest(cwd, { check = false } = {}) {
225
+ const manifestPath = join(cwd, 'plugin.json')
226
+ if (!existsSync(manifestPath)) {
227
+ throw new Error(`plugin.json 不存在: ${manifestPath}`)
228
+ }
229
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'))
230
+ const report = []
231
+ const permissions = new Set(manifest.permissions || [])
232
+ const contributes = { ...(manifest.contributes || {}) }
233
+
234
+ // ---------- 前端扫描 ----------
235
+ const frontendSource = collectFiles(join(cwd, 'src'), [...FRONTEND_EXTS])
236
+ .map((f) => readFileSync(f, 'utf-8'))
237
+ .join('\n')
238
+
239
+ const settingsSections = findRegisterCalls(frontendSource, 'registerSettingsSection')
240
+
241
+ if (settingsSections.length > 0) {
242
+ const old = contributes.settings && contributes.settings.id ? contributes.settings : null
243
+ contributes.settings = mergeEntry(
244
+ settingsSections[0],
245
+ old && old.id === settingsSections[0].id ? old : null
246
+ )
247
+ permissions.add(REGISTER_PERMISSIONS.registerSettingsSection)
248
+ report.push(`contributes.settings ← ${contributes.settings.id}`)
249
+ }
250
+ const routes = findRegisterCalls(frontendSource, 'registerRoute')
251
+ if (routes.length > 0) {
252
+ const old = indexById(contributes.routes)
253
+ contributes.routes = routes.map((s) => mergeEntry(s, old.get(s.id)))
254
+ permissions.add(REGISTER_PERMISSIONS.registerRoute)
255
+ report.push(`contributes.routes ← ${contributes.routes.map((v) => v.id).join(', ')}`)
256
+ }
257
+
258
+ for (const rule of FRONTEND_PERMISSION_RULES) {
259
+ if (rule.re.test(frontendSource)) {
260
+ if (!permissions.has(rule.perm)) report.push(`permissions + ${rule.perm}(前端 API 使用)`)
261
+ permissions.add(rule.perm)
262
+ }
263
+ }
264
+
265
+ // ---------- Rust 扫描 ----------
266
+ const rustSource = collectFiles(join(cwd, 'rust/src'), ['.rs'])
267
+ .map((f) => readFileSync(f, 'utf-8'))
268
+ .join('\n')
269
+
270
+ if (rustSource) {
271
+ for (const rule of RUST_PERMISSION_RULES) {
272
+ if (rule.re.test(rustSource)) {
273
+ if (!permissions.has(rule.perm)) report.push(`permissions + ${rule.perm}(Rust host 调用)`)
274
+ permissions.add(rule.perm)
275
+ }
276
+ }
277
+
278
+ const commandIds = extractRustCommands(rustSource)
279
+ if (commandIds.length > 0) {
280
+ const old = indexById(contributes.commands)
281
+ contributes.commands = commandIds.map((id) =>
282
+ mergeEntry({ id }, old.get(id), { id, title: id })
283
+ )
284
+ report.push(`contributes.commands ← ${commandIds.length} 个`)
285
+ }
286
+ }
287
+
288
+ // ---------- 退役面清理(票 2026-10-10 批次 C2) ----------
289
+ //
290
+ // 上面不再派生 contributes.views / navTab / terminal.toolbarItems,但存量 manifest
291
+ // 里还留着它们;按上面的「未扫描到则保留」策略会被原样保留——那等于每次重新生成
292
+ // 都把退役面原样带回,且 permissions 里的退役位会让宿主装载期直接拒载。
293
+ // 这里显式剔除:退役是不可逆的,生成器必须幂等地把它落干净。
294
+ for (const key of ['views', 'navTab']) {
295
+ if (contributes[key] !== undefined) {
296
+ delete contributes[key]
297
+ report.push(`contributes.${key} - 退役面(票 2026-10-10 C2)已剔除`)
298
+ }
299
+ }
300
+ if (contributes.terminal?.toolbarItems) {
301
+ delete contributes.terminal.toolbarItems
302
+ report.push('contributes.terminal.toolbarItems - 退役面(票 2026-10-10 C2)已剔除')
303
+ if (Object.keys(contributes.terminal).length === 0) delete contributes.terminal
304
+ }
305
+ for (const perm of RETIRED_PERMISSIONS) {
306
+ if (permissions.delete(perm)) {
307
+ report.push(`permissions - ${perm}(票 2026-10-10 C2 退役位)已剔除`)
308
+ }
309
+ }
310
+
311
+ // ---------- 生成结果 ----------
312
+ const generated = {
313
+ ...manifest,
314
+ permissions: [...permissions].sort(),
315
+ contributes,
316
+ }
317
+ const changed = JSON.stringify(generated, null, 2) !== JSON.stringify(manifest, null, 2)
318
+
319
+ if (changed && !check) {
320
+ writeFileSync(manifestPath, JSON.stringify(generated, null, 2) + '\n', 'utf-8')
321
+ }
322
+
323
+ return { changed, report }
324
+ }
package/bin/package.js ADDED
@@ -0,0 +1,150 @@
1
+ /**
2
+ * wasmnest-plugin 打包与自检命令:package / doctor(自 cli.js 拆出)
3
+ */
4
+ import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
5
+ import { createHash } from "node:crypto"
6
+ import { join, resolve } from "node:path"
7
+ import { spawnSync } from "node:child_process"
8
+ import { generateManifest } from "./manifest-gen.js"
9
+ import { SDK_ROOT, DEV_SHELL_VITE, resolveWasmPath, resolveDevShellDir, buildZip, readJson, toPosix } from "./lib.js"
10
+
11
+ // ==================== 命令:package ====================
12
+
13
+ function cmdPackage(flags) {
14
+ const cwd = process.cwd()
15
+ const manifestPath = join(cwd, 'plugin.json')
16
+ if (!existsSync(manifestPath)) {
17
+ console.error(`[wasmnest-plugin] 当前目录不是插件工程(缺少 plugin.json): ${cwd}`)
18
+ process.exit(1)
19
+ }
20
+ const manifest = readJson(manifestPath, 'plugin.json')
21
+ const { id, main, rustLibrary, pluginType } = manifest
22
+ const hasWasm = pluginType === 'wasm' && rustLibrary
23
+
24
+ // 打包前自动填充,保证 zip 内 plugin.json 与源码一致
25
+ try {
26
+ const { changed, report } = generateManifest(cwd)
27
+ if (changed) {
28
+ for (const line of report) console.log(`[wasmnest-plugin] ${line}`)
29
+ console.log('[wasmnest-plugin] plugin.json 已自动填充')
30
+ }
31
+ } catch (e) {
32
+ console.error(`[wasmnest-plugin] manifest 自动填充失败: ${e.message}`)
33
+ process.exit(1)
34
+ }
35
+
36
+ const distDir = join(cwd, 'dist')
37
+ const distMain = join(distDir, main || 'index.js')
38
+ const wasmPath = hasWasm ? resolveWasmPath(cwd, rustLibrary) : null
39
+
40
+ if (!existsSync(distMain)) {
41
+ console.error(`[wasmnest-plugin] dist/${main || 'index.js'} 缺失 — 先运行 pnpm run build`)
42
+ process.exit(1)
43
+ }
44
+ if (hasWasm && !existsSync(wasmPath)) {
45
+ console.error(`[wasmnest-plugin] ${rustLibrary}.wasm 缺失 — 先运行 pnpm run build`)
46
+ process.exit(1)
47
+ }
48
+
49
+ // --hash:计算 WASM SHA256 写入 plugin.json(安装时宿主按 wasmHash 校验完整性)
50
+ if (hasWasm && flags.hash) {
51
+ const hash = `sha256-${createHash('sha256').update(readFileSync(wasmPath)).digest('hex')}`
52
+ const current = readJson(manifestPath, 'plugin.json')
53
+ if (current.wasmHash !== hash) {
54
+ current.wasmHash = hash
55
+ writeFileSync(manifestPath, JSON.stringify(current, null, 2) + '\n', 'utf-8')
56
+ console.log(`[wasmnest-plugin] 已写入 wasmHash: ${hash.slice(0, 20)}…`)
57
+ }
58
+ }
59
+
60
+ // 打包条目:plugin.json + dist 全部产物 + wasm,全部位于 zip 根目录
61
+ const entries = [{ name: 'plugin.json', data: readFileSync(manifestPath) }]
62
+ for (const f of readdirSync(distDir)) {
63
+ const full = join(distDir, f)
64
+ if (statSync(full).isFile()) entries.push({ name: f, data: readFileSync(full) })
65
+ }
66
+ if (hasWasm) entries.push({ name: `${rustLibrary}.wasm`, data: readFileSync(wasmPath) })
67
+
68
+ const outFile = flags.o ? resolve(cwd, flags.o) : join(distDir, `${id}.zip`)
69
+ writeFileSync(outFile, buildZip(entries))
70
+
71
+ console.log(`\n[wasmnest-plugin] 已打包 ${entries.length} 个文件 -> ${outFile}`)
72
+ }
73
+
74
+
75
+ // ==================== 命令:doctor(环境自检) ====================
76
+
77
+ function cmdDoctor() {
78
+ const checks = []
79
+ const add = (name, ok, detail) => checks.push({ name, ok, detail })
80
+
81
+ // Node 版本
82
+ const nodeMajor = Number(process.versions.node.split('.')[0])
83
+ add('Node.js >= 20', nodeMajor >= 20, process.version)
84
+
85
+ // Rust + wasm32 target
86
+ let rustOk = false
87
+ let rustDetail = '未安装'
88
+ try {
89
+ const r = spawnSync('cargo', ['--version'], { stdio: 'pipe' })
90
+ if (r.status === 0) {
91
+ rustOk = true
92
+ rustDetail = r.stdout.toString().trim()
93
+ }
94
+ } catch {
95
+ // 未安装
96
+ }
97
+ add('Rust (cargo)', rustOk, rustDetail)
98
+ if (rustOk) {
99
+ const t = spawnSync('rustup', ['target', 'list', '--installed'], { stdio: 'pipe' })
100
+ const hasWasm = t.status === 0 && t.stdout.toString().includes('wasm32-unknown-unknown')
101
+ add(
102
+ 'wasm32-unknown-unknown target',
103
+ hasWasm,
104
+ hasWasm ? '已安装' : '缺失 — 运行 rustup target add wasm32-unknown-unknown',
105
+ )
106
+ } else {
107
+ add('wasm32-unknown-unknown target', false, '需先安装 Rust')
108
+ }
109
+
110
+ // 当前目录是否为插件工程
111
+ const manifestPath = join(process.cwd(), 'plugin.json')
112
+ if (existsSync(manifestPath)) {
113
+ try {
114
+ const m = readJson(manifestPath, 'plugin.json')
115
+ add('当前目录是插件工程', true, `${m.id} (${m.pluginType})`)
116
+ } catch {
117
+ add('当前目录是插件工程', false, 'plugin.json 解析失败')
118
+ }
119
+ } else {
120
+ add('当前目录是插件工程', false, '缺少 plugin.json — 在插件目录内运行本命令时检查才有意义')
121
+ }
122
+
123
+ // dev-shell 依赖(dev 命令就绪性)
124
+ const devShellVite = join(resolveDevShellDir(process.cwd()), DEV_SHELL_VITE)
125
+ add(
126
+ 'dev-shell 依赖(dev 命令)',
127
+ existsSync(devShellVite),
128
+ existsSync(devShellVite) ? '已安装' : '首次运行 dev 命令时自动安装',
129
+ )
130
+
131
+ // SDK dist(file: 依赖的插件需要)
132
+ const sdkDist = join(SDK_ROOT, 'dist/index.js')
133
+ add(
134
+ 'SDK 构建产物(file: 依赖)',
135
+ existsSync(sdkDist),
136
+ existsSync(sdkDist) ? '已构建' : '缺失 — 运行 pnpm run build(SDK 目录内)',
137
+ )
138
+
139
+ let failed = 0
140
+ for (const c of checks) {
141
+ const icon = c.ok ? '✓' : '✗'
142
+ if (!c.ok) failed++
143
+ console.log(` ${icon} ${c.name} — ${c.detail}`)
144
+ }
145
+ console.log(`\n[wasmnest-plugin] doctor 完成: ${checks.length - failed}/${checks.length} 通过`)
146
+ if (failed) process.exit(1)
147
+ }
148
+
149
+
150
+ export { cmdPackage, cmdDoctor }