Files
print-tag-system/plugin/preview/loaders.ts
T
funjia ef41d98838 feat: 新增 plugin/ 插件化形态(funjia.print-tag)+ 可选 SN 条码/二维码
把本工程的标签排版能力改造成 FunjiaUI 远端插件,放进 plugin/ 子目录,
与原独立 Web 版并存(两者功能一致,模板/版面/打印行为逐项对齐)。

- 入口从 createApp().mount() 改为 activate(ctx) + ctx.addRoute,注册 1 菜单 / 1 路由 / 2 命令
- 11 个模板的渲染收敛成 SpecTag,差异集中到 templates/registry.ts(字段/选项/默认值原样保留)
- 店铺名 / 电话从写死改为可配置,记忆在插件私有存储
- 内置二维码图片改为打包 data URL —— 远端插件没有自己的 public/
- 去掉 @headlessui/vue(换原生 select)与 Tailwind,样式类名统一 pt- 前缀避免污染宿主
- 可选接入宿主 api::sn-code:按 SN 生成真 Code 128 条码与可扫二维码;
  关闭时(默认)完全保持原静态二维码行为。领码优先贴到已排版的格子,不够才新建
- 新增 commands: print-tag:issue-sn / print-tag:render-svg(后者纯本地出图,供其它插件复用)
- code128.ts 实现真 Code 128 Set B(含校验位);二维码走 qrcode-generator(真 QR)
- 自带本地预览器(preview/mock-api.ts 补了 /api/sn-codes mock)与 deploy / verify 脚本
- verify.mjs 修掉一处误报:源码边界判据改为「解析后是否逃出工程根」,
  而不是「说明符是否以 .. 开头」(后者会把 src/components/X.vue → ../codes 误判为越界)

已发布到插件仓库:funjia.print-tag@1.0.0
2026-10-03 23:48:32 +08:00

196 lines
7.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 「插件从哪来」的两种模式。
*
* | 模式 | 插件来源 | 回答的问题 | 快慢 |
* | ---- | -------- | ---------- | ---- |
* | `source` | `src/index.ts` 的静态 import | 我写的东西长什么样、逻辑对不对 | 改完即见(Vite 热更新) |
* | `artifact` | `dist/` 里的真实产物 | **交给宿主的那几个字节**能不能跑 | 要先 `npm run build` |
*
* 之所以两个都要,是因为它们会分别失败在不同的地方:
*
* - 源码模式跑得通、产物模式跑不通 → 问题在**构建配置**(`external` 没生效、
* 产物名不对、`output.globals` 映射错了、样式没抽出来);
* - 两个都跑通、宿主里不跑 → 问题在**仓库与装载链路**(路径、`checksum`、
* import map、`activation` 与 `contributes` 不匹配)。
*
* 这条分界线能省掉大量「到底哪一步坏了我」的排查时间,所以别只用一个模式。
*/
import type { PluginModule } from "../src/sdk";
import { pendingRegistrations } from "./contract";
/** `plugin.config.json` 的形状(只声明预览用得上的字段) */
export interface PluginConfig {
id: string;
name: string;
version: string;
kind: "iife" | "esm";
artifact: string;
style?: string;
globalKey?: string;
activation?: string;
[key: string]: any;
}
export interface LoadedPlugin {
module: PluginModule;
/** 装载过程中的说明,会写进预览的日志台 —— 让「怎么装载的」可见 */
notes: string[];
}
export interface PreviewLoader {
mode: "source" | "artifact";
/** 顶栏徽标上的短标签 */
label: string;
/** 一句话说明这个模式在验什么 */
hint: string;
/**
* 点「重新装载」时是不是该刷新页面。
*
* 源码模式:模块已经求值过(自注册被消费、模块内状态也变了),重新装载
* 最可靠的方式是刷新页面 —— 预览页启动很快,刷新几乎无感。
* 产物模式:重新拉一次产物即可,不必刷新。
*/
reloadPageOnRerun: boolean;
getModule(): Promise<LoadedPlugin>;
}
/* ------------------------------------------------------------ 工具 */
/**
* 用 `<script>` 加载产物 —— 与宿主装载 IIFE 插件的方式完全一致。
*
* `async = false` 是有意的:让脚本按插入顺序执行。这里只有一个脚本,
* 但不写会让「加载完成」与「执行完成」之间多一个不确定的间隙。
*/
function loadScript(src: string): Promise<void> {
return new Promise((resolve, reject) => {
const el = document.createElement("script");
el.src = src;
el.async = false;
el.onload = () => resolve();
el.onerror = () =>
reject(
new Error(
`产物加载失败:${src}\n` +
"多半是还没构建 —— 跑一次 npm run build(或直接用 npm run preview,它会先构建)。"
)
);
document.head.appendChild(el);
});
}
/**
* 注入样式表,模拟宿主按 `manifest.style` 注入插件样式。
*
* 失败**不阻断**装载:样式拿不到插件逻辑照样能跑,真实宿主也是尽力注入。
* (但控制台里会留一条 404,能看出 `style` 字段写了却没产出对应文件。)
*/
function injectStyle(href: string): Promise<void> {
return new Promise((resolve) => {
const el = document.createElement("link");
el.rel = "stylesheet";
el.href = href;
el.onload = () => resolve();
el.onerror = () => resolve();
document.head.appendChild(el);
});
}
/** 从自注册队列里认领指定 id 的插件(真实宿主的认领动作,在此复刻) */
function claimById(id: string): PluginModule | null {
const i = pendingRegistrations.findIndex((r) => r?.manifest?.id === id);
if (i < 0) return null;
return pendingRegistrations.splice(i, 1)[0].module as PluginModule;
}
/* ------------------------------------------------------- 源码模式 */
/**
* 源码模式。
*
* 模块由调用方**静态 import** 并传进来 —— 这一点是必需的:只有静态依赖,
* Vite 的 HMR 依赖图里才有它,改 `pages/*.vue` 才能热更新;而且静态 import
* 的求值顺序受 import 声明控制,契约(`./contract`)能排在它前面先执行。
*/
export function createSourceLoader(module: PluginModule): PreviewLoader {
return {
mode: "source",
label: "源码",
hint: "直接跑 src/ 下的源码:改页面组件由 Vite 热更新,不走构建、不碰仓库",
reloadPageOnRerun: true,
async getModule() {
return {
module,
notes: ["模块来自 src/index.ts 的静态 import(契约已先于它求值,所以自注册不会落空)"],
};
},
};
}
/* ------------------------------------------------------- 产物模式 */
/**
* 产物模式:把 `dist/` 里的东西当远端插件装一遍。
*
* 每一步都刻意贴着宿主的真实动作:
*
* 1. 按 `manifest.style` 注入 CSS(宿主的做法);
* 2. `iife` → `<script src>`;`esm` → `import()`,裸说明符由 import map 解析;
* 3. 认领:先看自注册队列(`window.FunjiaPlugin.register`),再退回
* `window[globalKey]` —— 与宿主的两条认领通道一致。
*/
export function createArtifactLoader(config: PluginConfig): PreviewLoader {
return {
mode: "artifact",
label: "产物",
hint: "加载 dist/ 里的真实产物,走宿主装载时的同一套路径规则(能验 external 是否真的生效)",
reloadPageOnRerun: false,
async getModule() {
const notes: string[] = [];
// 每次装载都换一个查询串,避免浏览器把上一次的产物缓存住 ——
// 「重新装载还是旧行为」是最容易浪费时间的假象之一
const bust = `?t=${Date.now()}`;
if (config.style) {
await injectStyle(`/artifact/${config.style}`);
notes.push(`已按 manifest.style 注入 ${config.style}`);
}
if (config.kind === "esm") {
const mod = await import(/* @vite-ignore */ `/artifact/${config.artifact}${bust}`);
notes.push(
"以 ESM 形态 import():产物里的裸说明符 vue 由 index.html 的 import map 解析到预览页同一份 Vue"
);
const module = (mod as any).default ?? mod;
if (!module) throw new Error("ESM 产物没有默认导出,宿主会拿不到插件对象");
return { module, notes };
}
await loadScript(`/artifact/${config.artifact}${bust}`);
const claimed = claimById(config.id);
if (claimed) {
notes.push("产物自注册成功(window.FunjiaPlugin.register),按 id 认领");
return { module: claimed, notes };
}
const byGlobal = config.globalKey ? (window as any)[config.globalKey] : undefined;
if (byGlobal) {
notes.push(`走老生态通道 window.${config.globalKey} 认领`);
return { module: byGlobal, notes };
}
// 这条报错要尽量说清「是哪一环断了」——它对应宿主里那个
// 「脚本已执行,但自注册队列与全局变量都没拿到插件」的经典现场
throw new Error(
`产物已执行,但两条认领通道都没拿到插件:\n` +
` · 自注册队列里没有 id 为 "${config.id}" 的注册(检查 src/index.ts 里的 PLUGIN_ID)\n` +
` · window.${config.globalKey} 也是空的(检查 plugin.config.json 的 globalKey,` +
`以及产物是不是被打成了 namespace:window.X = { default: … })`
);
},
};
}