#!/usr/bin/env node /** * 插件自检 —— 在 deploy 之前把「必然会在别处报错」的问题在这里拦下。 * * ## 为什么需要它 * * 这个工程里有一批值**必须严格一致**,一旦不一致,报错点离原因很远: * * | 不一致 | 你看到的现象 | 真正的原因 | * | ---- | ---- | ---- | * | `artifact` 与仓库条目对不上 | 发布脚本说「找不到产物」 | 两处各写了一遍文件名 | * | `globalKey` 与产物全局名对不上 | 脚本加载成功、插件不出现 | 宿主无从认领 | * | `kind` 与 artifact 后缀对不上 | 宿主按 IIFE 插标签、拿到 ESM 源码 | 后缀是给人看的,得自己保证 | * | 版本号硬编码进源码 | 发了新版本却显示旧版本 | 版本该由索引在运行时注入 | * * 前三条在 `vite.config.ts` 里已经拦了一部分(构建时才炸), * 本脚本的价值是**在构建之前**、并且**跨工程**(连仓库的 `repo.config.json` 一起看)。 * * ## 用法 * * npm run verify * npm run verify -- --repo ../funjia-plugin-repository # 顺带校验仓库条目 * PLUGIN_REPO=../funjia-plugin-repository npm run verify */ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs"; import { dirname, join, relative, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); /** 与 vite.config.ts 里 selfInjectStyles() 用的哨兵注释保持一致 */ const INJECTOR_SENTINEL = "/* funjia:self-inject-styles */"; /* ------------------------------------------------------------------ 输出 */ let errors = 0; let warnings = 0; const ok = (m) => console.log(` OK ${m}`); const bad = (m) => { errors += 1; console.log(` FAIL ${m}`); }; const warn = (m) => { warnings += 1; console.log(` WARN ${m}`); }; const info = (m) => console.log(` ${m}`); const step = (m) => console.log(`\n${m}`); /* ------------------------------------------------------------------ 入参 */ function parseArgs(argv) { const out = { repo: process.env.PLUGIN_REPO || null }; for (let i = 0; i < argv.length; i += 1) { if (argv[i] === "--repo") out.repo = argv[i + 1]; } return out; } const args = parseArgs(process.argv.slice(2)); /* ------------------------------------------------------------- 组 A:清单 */ step("组 A · plugin.config.json"); const cfgFile = join(root, "plugin.config.json"); if (!existsSync(cfgFile)) { console.error(`找不到 ${cfgFile} —— 这个文件是插件元数据的唯一真源。`); process.exit(1); } let cfg; try { cfg = JSON.parse(readFileSync(cfgFile, "utf8")); } catch (e) { console.error(`plugin.config.json 不是合法 JSON:${e.message}`); process.exit(1); } // 这四项缺任何一个,构建或发布就一定失败,所以在这里就说清楚 for (const key of ["id", "name", "version", "kind", "artifact"]) { if (!cfg[key] || typeof cfg[key] !== "string") bad(`缺少必填字段 ${key}`); } if (errors === 0) ok("必填字段齐全(id / name / version / kind / artifact)"); if (cfg.kind && !["iife", "esm"].includes(cfg.kind)) { bad(`kind = ${JSON.stringify(cfg.kind)},只允许 "iife" 或 "esm"(没有 builtin)`); } else if (cfg.kind) { ok(`kind = ${cfg.kind}`); } /** * 版本号必须是「数字点分」。 * * 因为仓库按点分段比大小(`1.10.0 > 1.9.0`),写了 `v1.0` 或 `1.0.0-beta` * 之后排序就会静默错位 —— 不是报错,是「更新提示不出现」,更难查。 */ if (cfg.version && !/^\d+(\.\d+)*$/.test(cfg.version)) { bad(`version = ${JSON.stringify(cfg.version)},应为数字点分(如 1.0.0)`); } else if (cfg.version) { ok(`version = ${cfg.version}`); } /** * 命名建议(只警告,不拦):`<组织>.<模块>`。 * * 这不是洁癖:`id` 是安装/卸载/事件前缀共用的唯一键,带上组织前缀才不会 * 和别人的插件撞车。仓库里所有官方示例都遵循这个形状。 */ if (cfg.id && !/^[a-z0-9]+(?:-[a-z0-9]+)*(?:\.[a-z0-9]+(?:-[a-z0-9]+)*)+$/.test(cfg.id)) { warn(`id = ${JSON.stringify(cfg.id)} 不像 <组织>.<模块>(全小写、连字符、至少一个点)`); } else if (cfg.id) { ok(`id = ${cfg.id}(符合 <组织>.<模块>)`); } /* --------------------------------------------------- artifact / kind 一致 */ if (cfg.artifact) { const shapeOk = /^[A-Za-z0-9_.-]+\.(iife|es)\.js$/.test(cfg.artifact); if (!shapeOk) { bad(`artifact = ${JSON.stringify(cfg.artifact)},应为 ".iife.js" 或 ".es.js"`); } else { ok(`artifact = ${cfg.artifact}`); // 后缀必须与 kind 对上:宿主是「按 kind 决定装载方式」的, // 后缀写错不会立刻炸 —— 而是按错误的方式去装,现象是插件不出现。 const suffix = cfg.artifact.endsWith(".iife.js") ? "iife" : "esm"; if (cfg.kind && suffix !== cfg.kind) { bad( `artifact 后缀(${cfg.artifact})暗示 ${suffix},但 kind = ${cfg.kind} —— 两者必须一致;` + `发布后宿主会按 kind 去装,后缀只在这里被校验` ); } else if (cfg.kind) { ok(`artifact 后缀与 kind 一致(${cfg.kind})`); } } } if (cfg.style && !cfg.style.endsWith(".css")) { bad(`style = ${JSON.stringify(cfg.style)} 应以 .css 结尾`); } else if (cfg.style) { ok(`style = ${cfg.style}`); } /* ------------------------------------------------------------ globalKey */ /** * `globalKey` 会被 rollup 直接写进产物当全局变量名,所以必须是合法标识符。 * 走 `window.FunjiaPlugin.register()` 自注册通道的插件其实不依赖它, * 但 rollup 仍然需要这个名字(`lib.name`),所以不能省。 */ if (cfg.globalKey) { if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(cfg.globalKey)) { bad(`globalKey = ${JSON.stringify(cfg.globalKey)} 不是合法 JS 标识符`); } else { ok(`globalKey = ${cfg.globalKey}`); } } else if (cfg.kind === "iife") { warn("未声明 globalKey:构建会按 id 推断一个,但老生态(window.)认领通道就用不了"); } else { ok("esm 形态无需 globalKey"); } /* ------------------------------------------------------- 组 B:源码边界 */ step("组 B · 源码边界"); /** * 剥掉注释再扫描。 * * **必须做这一步**:文档注释里天然会出现反面示例,比如 * * ``` * * - ❌ `import { x } from "../../src/…"` —— 绝不能引宿主内部实现 * ``` * * 不剥注释的话,这条「说明什么叫违规」的注释本身会被判成违规, * 于是自检脚本永远报一个假错 —— 而假错比没有错更糟:真错会被一起忽略。 * * 行注释用 `[^:]\/\/` 而非裸 `\/\/`,是为了不误伤 `https://` 这类串里的双斜杠。 */ function stripComments(text) { return text.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/[^\n]*/g, "$1"); } const srcDir = join(root, "src"); const entryFile = join(srcDir, "index.ts"); if (!existsSync(entryFile)) { bad("找不到 src/index.ts —— 构建入口"); } else { const entry = readFileSync(entryFile, "utf8"); /** * 自注册是本模板推荐的认领方式:产物全局名可以与插件 id 完全不同 * (产物叫 HelloBundle,插件 id 是 acme.hello),一个脚本也能塞多个插件。 */ if (entry.includes("FunjiaPlugin.register")) { ok("src/index.ts 走自注册通道(window.FunjiaPlugin.register)"); } else if (cfg.globalKey && entry.includes("export default")) { warn("未发现 window.FunjiaPlugin.register:将依赖 window. 认领(老生态通道)"); } else { bad( "src/index.ts 既没有 window.FunjiaPlugin.register,也不确定有默认导出 —— " + "宿主可能加载成功但认领不到插件" ); } /* ---------------- 版本号硬编码 ---------------- */ // 版本由仓库索引在运行时注入(ctx.plugin.version)。硬编码的后果是 // 「发了 0.2.0,界面上还显示 0.1.0」,而且换了 id 复制工程时会连版本一起带过去。 if (cfg.version) { const offenders = []; const walk = (dir) => { for (const name of readdirSync(dir)) { const p = join(dir, name); if (statSync(p).isDirectory()) { walk(p); continue; } if (!/\.(ts|js|vue|tsx|jsx)$/.test(name)) continue; const text = stripComments(readFileSync(p, "utf8")); if (text.includes(cfg.version)) offenders.push(p.slice(root.length + 1)); } }; walk(srcDir); if (offenders.length > 0) { bad( `源码里出现了 version 字面量 ${cfg.version}(${offenders.join(", ")})—— ` + `版本应取 ctx.plugin.version,让仓库索引当唯一真源` ); } else { ok(`源码未硬编码版本 ${cfg.version}(改用 ctx.plugin.version)`); } } /* ---------------- 不许引宿主内部实现 ---------------- */ // 引了宿主源码,宿主重构一次插件就整体失效。要能力就走 ctx(天然向前兼容)。 // // ⚠️ 判据是「**解析后是否逃出工程根**」,不是「说明符是不是以 .. 开头」。 // 模板原始版把两者当成一回事(只白名单 `../sdk` / `../runtime` / `../pages`), // 于是任何把代码分到子目录的插件(`src/components/X.vue` 里 `import "../codes"`) // 都会被误报成「引了工程外部模块」—— 报错点看着吓人,其实什么毛病都没有。 // 改成真正做一次路径解析,`..` 只在真的越出 root 时才算泄漏。 const leaked = []; const scanImports = (dir) => { for (const name of readdirSync(dir)) { const p = join(dir, name); if (statSync(p).isDirectory()) { scanImports(p); continue; } if (!/\.(ts|js|vue|tsx|jsx)$/.test(name)) continue; const text = stripComments(readFileSync(p, "utf8")); for (const m of text.matchAll(/from\s+["']([^"']+)["']/g)) { const spec = m[1]; // 裸说明符(vue / qrcode-generator / funjiaui)走打包器解析,不属于本组管辖 if (!spec.startsWith(".")) continue; const resolved = resolve(dirname(p), spec); const inside = resolved === root || resolved.startsWith(root + sep); if (!inside) leaked.push(`${relative(root, p)} → ${spec}`); } } }; scanImports(srcDir); if (leaked.length > 0) { bad(`发现了指向工程外部的 import(插件不能依赖宿主实现):\n ${leaked.join("\n ")}`); } else { ok("没有引用工程外部的模块(插件保持独立交付物)"); } } /* ------------------------------------------------- 组 C:构建产物(可选) */ step("组 C · 构建产物"); const distDir = join(root, "dist"); if (!existsSync(distDir)) { info("dist/ 还不存在 —— 先 npm run build,或忽略(本组只是额外确认)"); } else { const artifactPath = cfg.artifact ? join(distDir, cfg.artifact) : null; if (artifactPath && existsSync(artifactPath)) { const kb = (statSync(artifactPath).size / 1024).toFixed(1); ok(`dist/${cfg.artifact} 存在(${kb} KB)`); } else if (artifactPath) { bad(`dist/${cfg.artifact} 不存在 —— artifact 名字与构建输出对不上`); } if (cfg.style) { if (existsSync(join(distDir, cfg.style))) { ok(`dist/${cfg.style} 存在`); } else if (existsSync(artifactPath || "")) { // 组件里没写