web-extend-plugin-vue2 0.1.4 → 0.2.0

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.
package/dist/index.mjs ADDED
@@ -0,0 +1,1291 @@
1
+ import { coerce, satisfies } from 'semver';
2
+ import Vue from 'vue';
3
+
4
+ /**
5
+ * 宿主可覆盖的默认运行时配置(路径、白名单、超时等)。
6
+ * 使用方式:`resolveRuntimeOptions({ ...defaultWebExtendPluginRuntime, manifestListPath: '/api/my-plugins' })`
7
+ * 或只传需要改动的字段:`resolveRuntimeOptions({ manifestListPath: '/api/my-plugins' })`。
8
+ *
9
+ * @module default-runtime-config
10
+ */
11
+
12
+ /**
13
+ * @typedef {typeof defaultWebExtendPluginRuntime} WebExtendPluginDefaultRuntime
14
+ */
15
+
16
+ const defaultWebExtendPluginRuntime = {
17
+ /** 清单 HTTP 服务前缀(与后端 context-path 对齐),不含尾部 `/` */
18
+ manifestBase: '/fp-api',
19
+
20
+ /**
21
+ * 拉取插件清单的 **路径段**(以 `/` 开头),拼在 `manifestBase` 之后。
22
+ * 完整 URL:`{manifestBase}{manifestListPath}` → 默认 `/fp-api/api/frontend-plugins`
23
+ */
24
+ manifestListPath: '/api/frontend-plugins',
25
+
26
+ /** 清单 `fetch` 的 `credentials`,需 Cookie 会话时用 `include` */
27
+ manifestFetchCredentials: 'include',
28
+
29
+ /** 插件 dev 服务存活探测路径(拼在 `webPluginDevOrigin` 后) */
30
+ devPingPath: '/__web_plugin_dev_ping',
31
+
32
+ /** 插件 dev 热更新 SSE 路径(拼在插件 dev 的 origin 后) */
33
+ devReloadSsePath: '/__web_plugin_reload_stream',
34
+
35
+ /** 隐式 dev 映射里,每个 id 对应的入口路径(相对插件 dev origin) */
36
+ webPluginDevEntryPath: '/src/plugin-entry.js',
37
+
38
+ /** `fetch(devPingUrl)` 超时毫秒数 */
39
+ devPingTimeoutMs: 500,
40
+
41
+ /**
42
+ * **隐式 dev 映射**(可选):开发模式下若 `webPluginDevOrigin` 上 ping 成功,运行时会为若干插件 id 自动生成
43
+ * `{ id → origin + webPluginDevEntryPath }`,从而用 dev 服务入口替代清单里的 dist,便于热更新联调。
44
+ *
45
+ * 插件 id 来源优先级:`webPluginDevIds`(或 `VITE_WEB_PLUGIN_DEV_IDS`)→ 本字段。**默认 `[]`**,
46
+ * 避免把仓库示例 id 写进通用宿主;联调时在 `.env` 里设 `VITE_WEB_PLUGIN_DEV_IDS=com.xxx,com.yyy`,
47
+ * 或 `resolveRuntimeOptions({ defaultImplicitDevPluginIds: ['com.xxx'] })` 即可。
48
+ */
49
+ defaultImplicitDevPluginIds: [],
50
+
51
+ /**
52
+ * 允许通过 `<script>` / 动态 `import()` 加载的插件脚本所在主机名(小写),防误配公网 URL。
53
+ */
54
+ allowedScriptHosts: ['localhost', '127.0.0.1', '::1'],
55
+
56
+ /**
57
+ * `hostApi.getBridge().request(path)` 允许的 path 前缀;须以 `/` 开头。
58
+ * 需与后端实际 API 前缀一致。
59
+ */
60
+ bridgeAllowedPathPrefixes: ['/api/']
61
+ };
62
+
63
+ /**
64
+ * 不依赖 `import.meta`,兼容 Webpack 4/5、Vue CLI、Vite、Rspack 等宿主。
65
+ * - Webpack / Vue CLI:依赖构建时注入的 `process.env`(如 `VUE_APP_*`、`DefinePlugin` 注入的 `VITE_*`)。
66
+ * - Vite:在入口调用 `setWebExtendPluginEnv(import.meta.env)`,或 `installWebExtendPluginVue2(..., { env: import.meta.env })`。
67
+ * - 也可在入口前设置 `globalThis.__WEP_ENV__ = import.meta.env`(与 setWebExtendPluginEnv 二选一即可)。
68
+ *
69
+ * @module bundled-env
70
+ */
71
+
72
+ /** @type {Record<string, unknown> | null} */
73
+ let _explicitEnv = null;
74
+
75
+ /**
76
+ * 显式注入与 `import.meta.env` 同形态的对象(推荐 Vite 宿主在入口调用一次)。
77
+ * @param {Record<string, unknown> | null | undefined} env
78
+ */
79
+ function setWebExtendPluginEnv(env) {
80
+ _explicitEnv = env && typeof env === 'object' ? env : null;
81
+ }
82
+
83
+ /**
84
+ * @returns {Record<string, unknown> | null}
85
+ */
86
+ function getInjectedEnvObject() {
87
+ if (_explicitEnv) {
88
+ return _explicitEnv
89
+ }
90
+ try {
91
+ const g = typeof globalThis !== 'undefined' ? globalThis : undefined;
92
+ if (g && g.__WEP_ENV__ && typeof g.__WEP_ENV__ === 'object') {
93
+ return g.__WEP_ENV__
94
+ }
95
+ } catch (_) {}
96
+ return null
97
+ }
98
+
99
+ /**
100
+ * 从注入环境读取字符串配置键(`VITE_*` / `PLUGIN_*` 等)。
101
+ * @param {string} key
102
+ * @returns {string|undefined}
103
+ */
104
+ function readInjectedEnvKey(key) {
105
+ const o = getInjectedEnvObject();
106
+ if (!o || !(key in o)) {
107
+ return undefined
108
+ }
109
+ const v = o[key];
110
+ if (v === undefined || v === '') {
111
+ return undefined
112
+ }
113
+ return String(v)
114
+ }
115
+
116
+ /**
117
+ * @returns {boolean}
118
+ */
119
+ function readInjectedEnvDev() {
120
+ const o = getInjectedEnvObject();
121
+ return !!(o && o.DEV === true)
122
+ }
123
+
124
+ /**
125
+ * 与 `plugin-web-starter`(WebPluginsResponse)返回的 `hostPluginApiVersion` 保持一致,用于契约校验。
126
+ * @type {string}
127
+ */
128
+ const HOST_PLUGIN_API_VERSION = '1.0.0';
129
+
130
+ /**
131
+ * 宿主侧插件引导:拉取清单、dev 映射、加载入口脚本、调用 activator。
132
+ * 路径与白名单等默认值见 `defaultWebExtendPluginRuntime`,可通过 `resolveRuntimeOptions` / 环境变量覆盖。
133
+ *
134
+ * **Webpack 宿主**:用 `DefinePlugin` 注入 `process.env.VITE_*` 或 **`PLUGIN_*`**(等价键),或 `resolveRuntimeOptions` 显式传参。
135
+ * **Vite 宿主**:入口调用 `setWebExtendPluginEnv(import.meta.env)`,或 `installWebExtendPluginVue2(..., { env: import.meta.env })`。
136
+ *
137
+ * @module PluginRuntime
138
+ */
139
+
140
+ const DEF = defaultWebExtendPluginRuntime;
141
+
142
+ /**
143
+ * @typedef {object} WebExtendPluginRuntimeOptions
144
+ * @property {string} [manifestBase] 清单服务 URL 前缀
145
+ * @property {string} [manifestListPath] 清单接口路径(以 `/` 开头),拼在 manifestBase 后
146
+ * @property {RequestCredentials} [manifestFetchCredentials] 清单 fetch 的 credentials
147
+ * @property {boolean} [isDev] 开发模式
148
+ * @property {string} [webPluginDevOrigin] 插件 dev origin
149
+ * @property {string} [webPluginDevIds] 逗号分隔 id,隐式 dev 映射
150
+ * @property {string} [webPluginDevMapJson] 显式 dev 映射 JSON
151
+ * @property {string} [webPluginDevEntryPath] 隐式 dev 入口路径(相对插件 dev origin)
152
+ * @property {string} [devPingPath] dev 存活探测路径
153
+ * @property {string} [devReloadSsePath] dev 热更新 SSE 路径
154
+ * @property {number} [devPingTimeoutMs] 探测超时
155
+ * @property {string[]} [defaultImplicitDevPluginIds] 无 `webPluginDevIds`/env 时用于隐式 dev 的 id;包内默认 `[]`
156
+ * @property {string[]} [allowedScriptHosts] 允许加载脚本的主机名
157
+ * @property {string[]} [bridgeAllowedPathPrefixes] bridge.request 白名单前缀
158
+ * @property {boolean} [bootstrapSummary] bootstrap 结束是否打印摘要
159
+ */
160
+
161
+ /**
162
+ * 从 Webpack `DefinePlugin` 等注入的 `process.env` 读取。
163
+ * @param {string} key
164
+ * @returns {string|undefined}
165
+ */
166
+ function readProcessEnv(key) {
167
+ try {
168
+ if (typeof process !== 'undefined' && process.env && key in process.env) {
169
+ const v = process.env[key];
170
+ if (v !== undefined && v !== '') {
171
+ return String(v)
172
+ }
173
+ }
174
+ } catch (_) {}
175
+ return undefined
176
+ }
177
+
178
+ /**
179
+ * `VITE_*` 的并列命名:同值可读 `PLUGIN_*`(`VITE_WEB_PLUGIN_X` → `PLUGIN_WEB_PLUGIN_X`)。
180
+ * Vite 需在 `defineConfig({ envPrefix: ['VITE_', 'PLUGIN_'] })` 中暴露 `PLUGIN_`;Webpack 用 DefinePlugin 注入即可。
181
+ * @param {string} viteStyleKey 以 `VITE_` 开头的键名
182
+ * @returns {string|null}
183
+ */
184
+ function viteKeyToPluginAlternate(viteStyleKey) {
185
+ if (typeof viteStyleKey !== 'string' || !viteStyleKey.startsWith('VITE_')) {
186
+ return null
187
+ }
188
+ return `PLUGIN_${viteStyleKey.slice(5)}`
189
+ }
190
+
191
+ /**
192
+ * 先读注入环境(`setWebExtendPluginEnv` / `__WEP_ENV__`)中的 `VITE_*` 与并列 `PLUGIN_*`,再读 `process.env`,最后 `fallback`。
193
+ * @param {string} key 仍以 `VITE_*` 为逻辑名(与文档一致)
194
+ * @param {string} [fallback='']
195
+ */
196
+ function resolveBundledEnv(key, fallback = '') {
197
+ const alt = viteKeyToPluginAlternate(key);
198
+ const fromInjected =
199
+ readInjectedEnvKey(key) ?? (alt ? readInjectedEnvKey(alt) : undefined);
200
+ const fromProcess =
201
+ readProcessEnv(key) ?? (alt ? readProcessEnv(alt) : undefined);
202
+ return fromInjected ?? fromProcess ?? fallback
203
+ }
204
+
205
+ /**
206
+ * @returns {boolean}
207
+ */
208
+ function resolveBundledIsDev() {
209
+ try {
210
+ if (readInjectedEnvDev()) {
211
+ return true
212
+ }
213
+ } catch (_) {}
214
+ try {
215
+ if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'development') {
216
+ return true
217
+ }
218
+ } catch (_) {}
219
+ return false
220
+ }
221
+
222
+ /**
223
+ * @param {string} p
224
+ */
225
+ function ensureLeadingPath(p) {
226
+ const t = String(p || '').trim();
227
+ if (!t) {
228
+ return '/'
229
+ }
230
+ return t.startsWith('/') ? t : `/${t}`
231
+ }
232
+
233
+ /**
234
+ * 解析 `include` | `omit` | `same-origin`,非法时回退默认值。
235
+ * @param {string|undefined} userVal
236
+ * @param {string} envKey
237
+ * @param {RequestCredentials} fallback
238
+ */
239
+ function resolveManifestCredentials(userVal, envKey, fallback) {
240
+ if (userVal !== undefined && userVal !== '') {
241
+ const s = String(userVal);
242
+ if (s === 'include' || s === 'omit' || s === 'same-origin') {
243
+ return s
244
+ }
245
+ }
246
+ const e = resolveBundledEnv(envKey, '');
247
+ if (e === 'include' || e === 'omit' || e === 'same-origin') {
248
+ return e
249
+ }
250
+ return fallback
251
+ }
252
+
253
+ /**
254
+ * @param {number|undefined} userVal
255
+ * @param {string} envKey
256
+ * @param {number} fallback
257
+ */
258
+ function resolvePositiveInt(userVal, envKey, fallback) {
259
+ if (typeof userVal === 'number' && Number.isFinite(userVal) && userVal > 0) {
260
+ return Math.floor(userVal)
261
+ }
262
+ const raw = resolveBundledEnv(envKey, '');
263
+ const n = raw ? parseInt(raw, 10) : NaN;
264
+ if (Number.isFinite(n) && n > 0) {
265
+ return n
266
+ }
267
+ return fallback
268
+ }
269
+
270
+ /**
271
+ * 合并用户、环境变量与 `defaultWebExtendPluginRuntime`,得到完整运行时选项(宿主可只传需要覆盖的字段)。
272
+ * @param {WebExtendPluginRuntimeOptions} [user]
273
+ * @returns {object}
274
+ */
275
+ function resolveRuntimeOptions(user = {}) {
276
+ const manifestBaseRaw =
277
+ user.manifestBase !== undefined && user.manifestBase !== ''
278
+ ? String(user.manifestBase)
279
+ : resolveBundledEnv('VITE_FRONTEND_PLUGIN_BASE', DEF.manifestBase) || DEF.manifestBase;
280
+
281
+ const manifestListPath = ensureLeadingPath(
282
+ user.manifestListPath !== undefined && user.manifestListPath !== ''
283
+ ? user.manifestListPath
284
+ : resolveBundledEnv('VITE_WEB_PLUGIN_MANIFEST_PATH', DEF.manifestListPath)
285
+ );
286
+
287
+ const defaultImplicitDevPluginIds =
288
+ Array.isArray(user.defaultImplicitDevPluginIds)
289
+ ? user.defaultImplicitDevPluginIds.map(String).filter(Boolean)
290
+ : (() => {
291
+ const e = resolveBundledEnv('VITE_WEB_PLUGIN_IMPLICIT_DEV_IDS', '');
292
+ if (e) {
293
+ return e
294
+ .split(',')
295
+ .map((s) => s.trim())
296
+ .filter(Boolean)
297
+ }
298
+ return [...DEF.defaultImplicitDevPluginIds]
299
+ })();
300
+
301
+ const allowedScriptHosts =
302
+ Array.isArray(user.allowedScriptHosts) && user.allowedScriptHosts.length > 0
303
+ ? user.allowedScriptHosts.map((h) => normalizeHost(String(h))).filter(Boolean)
304
+ : (() => {
305
+ const e = resolveBundledEnv('VITE_WEB_PLUGIN_ALLOWED_SCRIPT_HOSTS', '');
306
+ if (e) {
307
+ return e
308
+ .split(',')
309
+ .map((s) => normalizeHost(s.trim()))
310
+ .filter(Boolean)
311
+ }
312
+ return [...DEF.allowedScriptHosts]
313
+ })();
314
+
315
+ const bridgeAllowedPathPrefixes =
316
+ Array.isArray(user.bridgeAllowedPathPrefixes) && user.bridgeAllowedPathPrefixes.length > 0
317
+ ? user.bridgeAllowedPathPrefixes.map((p) => ensureLeadingPath(p)).filter(Boolean)
318
+ : (() => {
319
+ const e = resolveBundledEnv('VITE_WEB_PLUGIN_BRIDGE_PREFIXES', '');
320
+ if (e) {
321
+ return e
322
+ .split(',')
323
+ .map((s) => ensureLeadingPath(s.trim()))
324
+ .filter(Boolean)
325
+ }
326
+ return [...DEF.bridgeAllowedPathPrefixes]
327
+ })();
328
+
329
+ return {
330
+ manifestBase: manifestBaseRaw.replace(/\/$/, '') || DEF.manifestBase.replace(/\/$/, ''),
331
+ manifestListPath,
332
+ manifestFetchCredentials: resolveManifestCredentials(
333
+ user.manifestFetchCredentials,
334
+ 'VITE_WEB_PLUGIN_MANIFEST_CREDENTIALS',
335
+ DEF.manifestFetchCredentials
336
+ ),
337
+ isDev: user.isDev !== undefined ? user.isDev : resolveBundledIsDev(),
338
+ webPluginDevOrigin:
339
+ user.webPluginDevOrigin !== undefined ? user.webPluginDevOrigin : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_ORIGIN', ''),
340
+ webPluginDevIds:
341
+ user.webPluginDevIds !== undefined ? user.webPluginDevIds : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_IDS', ''),
342
+ webPluginDevMapJson:
343
+ user.webPluginDevMapJson !== undefined
344
+ ? user.webPluginDevMapJson
345
+ : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_MAP', ''),
346
+ webPluginDevEntryPath: ensureLeadingPath(
347
+ user.webPluginDevEntryPath !== undefined && user.webPluginDevEntryPath !== ''
348
+ ? user.webPluginDevEntryPath
349
+ : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_ENTRY', DEF.webPluginDevEntryPath)
350
+ ),
351
+ devPingPath: ensureLeadingPath(
352
+ user.devPingPath !== undefined && user.devPingPath !== ''
353
+ ? user.devPingPath
354
+ : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_PING_PATH', DEF.devPingPath)
355
+ ),
356
+ devReloadSsePath: ensureLeadingPath(
357
+ user.devReloadSsePath !== undefined && user.devReloadSsePath !== ''
358
+ ? user.devReloadSsePath
359
+ : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_SSE_PATH', DEF.devReloadSsePath)
360
+ ),
361
+ devPingTimeoutMs: resolvePositiveInt(user.devPingTimeoutMs, 'VITE_WEB_PLUGIN_DEV_PING_TIMEOUT_MS', DEF.devPingTimeoutMs),
362
+ defaultImplicitDevPluginIds,
363
+ allowedScriptHosts,
364
+ bridgeAllowedPathPrefixes,
365
+ bootstrapSummary: user.bootstrapSummary
366
+ }
367
+ }
368
+
369
+ /**
370
+ * @param {ReturnType<typeof resolveRuntimeOptions>} opts
371
+ */
372
+ function shouldShowBootstrapSummary(opts) {
373
+ if (opts.bootstrapSummary === true) {
374
+ return true
375
+ }
376
+ if (opts.bootstrapSummary === false) {
377
+ return false
378
+ }
379
+ const env = resolveBundledEnv('VITE_PLUGINS_BOOTSTRAP_SUMMARY', '');
380
+ if (env === '0' || env === 'false') {
381
+ return false
382
+ }
383
+ if (env === '1' || env === 'true') {
384
+ return true
385
+ }
386
+ return resolveBundledIsDev()
387
+ }
388
+
389
+ /**
390
+ * @param {string} hostname
391
+ */
392
+ function normalizeHost(hostname) {
393
+ if (!hostname) {
394
+ return ''
395
+ }
396
+ const h = hostname.toLowerCase();
397
+ if (h.startsWith('[') && h.endsWith(']')) {
398
+ return h.slice(1, -1)
399
+ }
400
+ return h
401
+ }
402
+
403
+ /**
404
+ * @param {string[]} hostnames
405
+ * @returns {Set<string>}
406
+ */
407
+ function buildAllowedScriptHostsSet(hostnames) {
408
+ const s = new Set();
409
+ for (const h of hostnames) {
410
+ const n = normalizeHost(h);
411
+ if (n) {
412
+ s.add(n);
413
+ }
414
+ }
415
+ return s
416
+ }
417
+
418
+ /**
419
+ * @param {string} url
420
+ * @param {Set<string>} hostSet
421
+ */
422
+ function isScriptHostAllowed(url, hostSet) {
423
+ if (typeof window === 'undefined') {
424
+ return false
425
+ }
426
+ try {
427
+ const u = new URL(url, window.location.origin);
428
+ const h = normalizeHost(u.hostname);
429
+ return hostSet.has(h)
430
+ } catch {
431
+ return false
432
+ }
433
+ }
434
+
435
+ /**
436
+ * @param {ReturnType<typeof resolveRuntimeOptions>} opts
437
+ */
438
+ function parseWebPluginDevMapExplicit(opts) {
439
+ if (!opts.isDev) {
440
+ return null
441
+ }
442
+ const raw = opts.webPluginDevMapJson;
443
+ if (raw === undefined || raw === null || String(raw).trim() === '') {
444
+ return null
445
+ }
446
+ try {
447
+ const map = JSON.parse(String(raw));
448
+ return map && typeof map === 'object' ? map : null
449
+ } catch {
450
+ console.warn('[plugins] webPluginDevMapJson / VITE_WEB_PLUGIN_DEV_MAP is not valid JSON');
451
+ return null
452
+ }
453
+ }
454
+
455
+ /**
456
+ * @param {ReturnType<typeof resolveRuntimeOptions>} opts
457
+ * @param {Set<string>} hostSet
458
+ */
459
+ async function buildImplicitWebPluginDevMap(opts, hostSet) {
460
+ if (!opts.isDev) {
461
+ return {}
462
+ }
463
+ const origin =
464
+ opts.webPluginDevOrigin === undefined || opts.webPluginDevOrigin === null
465
+ ? ''
466
+ : String(opts.webPluginDevOrigin).trim();
467
+ if (!origin) {
468
+ return {}
469
+ }
470
+ if (!isScriptHostAllowed(`${origin}/`, hostSet)) {
471
+ return {}
472
+ }
473
+
474
+ const idsRaw = opts.webPluginDevIds;
475
+ const ids =
476
+ idsRaw !== undefined && idsRaw !== null && String(idsRaw).trim() !== ''
477
+ ? String(idsRaw)
478
+ .split(',')
479
+ .map((s) => s.trim())
480
+ .filter(Boolean)
481
+ : [...opts.defaultImplicitDevPluginIds];
482
+
483
+ if (ids.length === 0) {
484
+ return {}
485
+ }
486
+
487
+ const base = origin.replace(/\/$/, '');
488
+ const pingUrl = `${base}${opts.devPingPath}`;
489
+ try {
490
+ const ctrl = new AbortController();
491
+ const timer = setTimeout(() => ctrl.abort(), opts.devPingTimeoutMs);
492
+ const r = await fetch(pingUrl, {
493
+ mode: 'cors',
494
+ cache: 'no-store',
495
+ signal: ctrl.signal
496
+ });
497
+ clearTimeout(timer);
498
+ if (!r.ok) {
499
+ return {}
500
+ }
501
+ const body = (await r.text()).trim();
502
+ if (body !== 'ok') {
503
+ return {}
504
+ }
505
+ } catch {
506
+ return {}
507
+ }
508
+
509
+ const pathPart = opts.webPluginDevEntryPath;
510
+ const map = {};
511
+ for (const id of ids) {
512
+ map[id] = `${base}${pathPart}`;
513
+ }
514
+ if (ids.length) {
515
+ console.info(
516
+ '[plugins] 已检测到插件 dev 服务(',
517
+ base,
518
+ '),下列 id 将加载隐式 dev 入口(',
519
+ pathPart,
520
+ ')而非清单 dist:',
521
+ ids.join(', ')
522
+ );
523
+ }
524
+ return map
525
+ }
526
+
527
+ /**
528
+ * @param {Record<string, string>} implicit
529
+ * @param {Record<string, string>|null} explicit
530
+ */
531
+ function mergeDevMaps(implicit, explicit) {
532
+ const i = implicit && typeof implicit === 'object' ? implicit : {};
533
+ const e = explicit && typeof explicit === 'object' ? explicit : {};
534
+ return { ...i, ...e }
535
+ }
536
+
537
+ /** @type {Map<string, EventSource>} */
538
+ const pluginDevEventSources = new Map();
539
+
540
+ let pluginDevBeforeUnloadRegistered = false;
541
+
542
+ function closeAllPluginDevEventSources() {
543
+ for (const es of pluginDevEventSources.values()) {
544
+ try {
545
+ es.close();
546
+ } catch (_) {}
547
+ }
548
+ pluginDevEventSources.clear();
549
+ }
550
+
551
+ function ensurePluginDevBeforeUnload() {
552
+ if (pluginDevBeforeUnloadRegistered || typeof window === 'undefined') {
553
+ return
554
+ }
555
+ pluginDevBeforeUnloadRegistered = true;
556
+ window.addEventListener('beforeunload', closeAllPluginDevEventSources);
557
+ }
558
+
559
+ /**
560
+ * @param {string} origin
561
+ * @param {Set<string>} hostSet
562
+ */
563
+ function isDevOriginAllowedForSse(origin, hostSet) {
564
+ try {
565
+ const u = new URL(origin);
566
+ return hostSet.has(normalizeHost(u.hostname))
567
+ } catch {
568
+ return false
569
+ }
570
+ }
571
+
572
+ /**
573
+ * @param {string} origin
574
+ * @param {boolean} isDev
575
+ * @param {Set<string>} hostSet
576
+ * @param {string} ssePath
577
+ */
578
+ function startPluginDevReloadSse(origin, isDev, hostSet, ssePath) {
579
+ if (!isDev || pluginDevEventSources.has(origin)) {
580
+ return
581
+ }
582
+ if (!isDevOriginAllowedForSse(origin, hostSet)) {
583
+ return
584
+ }
585
+ ensurePluginDevBeforeUnload();
586
+ const base = origin.replace(/\/$/, '');
587
+ const url = `${base}${ssePath}`;
588
+ try {
589
+ const es = new EventSource(url);
590
+ pluginDevEventSources.set(origin, es);
591
+ es.addEventListener('reload', () => {
592
+ window.location.reload();
593
+ });
594
+ es.onopen = () => {
595
+ console.info('[plugins] plugin dev reload SSE:', url);
596
+ };
597
+ } catch (e) {
598
+ console.warn('[plugins] EventSource failed', url, e);
599
+ }
600
+ }
601
+
602
+ /**
603
+ * @param {Record<string, string>|null|undefined} devMap
604
+ * @param {boolean} isDev
605
+ * @param {Set<string>} hostSet
606
+ * @param {string} ssePath
607
+ */
608
+ function startPluginDevSseForMap(devMap, isDev, hostSet, ssePath) {
609
+ if (!isDev || !devMap || typeof window === 'undefined') {
610
+ return
611
+ }
612
+ const origins = new Set();
613
+ for (const entry of Object.values(devMap)) {
614
+ if (typeof entry !== 'string') {
615
+ continue
616
+ }
617
+ const t = entry.trim();
618
+ if (!t) {
619
+ continue
620
+ }
621
+ try {
622
+ origins.add(new URL(t, window.location.href).origin);
623
+ } catch {
624
+ /* skip */
625
+ }
626
+ }
627
+ for (const o of origins) {
628
+ startPluginDevReloadSse(o, isDev, hostSet, ssePath);
629
+ }
630
+ }
631
+
632
+ const loadScriptMemo = new Map();
633
+
634
+ function loadScript(src) {
635
+ if (typeof document === 'undefined') {
636
+ return Promise.reject(new Error('loadScript: no document'))
637
+ }
638
+ if (loadScriptMemo.has(src)) {
639
+ return loadScriptMemo.get(src)
640
+ }
641
+ const p = new Promise((resolve, reject) => {
642
+ const scripts = document.getElementsByTagName('script');
643
+ for (let i = 0; i < scripts.length; i++) {
644
+ const el = scripts[i];
645
+ if (el.src === src) {
646
+ if (el.getAttribute('data-wep-loaded') === 'true') {
647
+ resolve();
648
+ return
649
+ }
650
+ el.addEventListener(
651
+ 'load',
652
+ () => {
653
+ el.setAttribute('data-wep-loaded', 'true');
654
+ resolve();
655
+ },
656
+ { once: true }
657
+ );
658
+ el.addEventListener('error', () => reject(new Error('loadScript failed: ' + src)), { once: true });
659
+ return
660
+ }
661
+ }
662
+ const s = document.createElement('script');
663
+ s.async = true;
664
+ s.src = src;
665
+ s.onload = () => {
666
+ s.setAttribute('data-wep-loaded', 'true');
667
+ resolve();
668
+ };
669
+ s.onerror = () => reject(new Error('loadScript failed: ' + src));
670
+ document.head.appendChild(s);
671
+ });
672
+ loadScriptMemo.set(src, p);
673
+ p.catch(() => loadScriptMemo.delete(src));
674
+ return p
675
+ }
676
+
677
+ /**
678
+ * @param {{ id: string }} p
679
+ * @param {string} [entryUrl]
680
+ * @param {Record<string, string>|null|undefined} devMap
681
+ * @param {Set<string>} hostSet
682
+ */
683
+ async function loadPluginEntry(p, entryUrl, devMap, hostSet) {
684
+ const devEntry = devMap && typeof devMap[p.id] === 'string' ? devMap[p.id].trim() : '';
685
+ if (devEntry) {
686
+ if (!isScriptHostAllowed(devEntry, hostSet)) {
687
+ console.warn('[plugins] dev entry URL not allowed', p.id, devEntry);
688
+ return
689
+ }
690
+ try {
691
+ await import(
692
+ /* webpackIgnore: true */
693
+ /* @vite-ignore */
694
+ devEntry
695
+ );
696
+ } catch (e) {
697
+ console.warn('[plugins] dev module import failed, try manifest entryUrl', p.id, e);
698
+ if (entryUrl && isScriptHostAllowed(entryUrl, hostSet)) {
699
+ await loadScript(entryUrl);
700
+ }
701
+ return
702
+ }
703
+ return
704
+ }
705
+ if (!entryUrl || !isScriptHostAllowed(entryUrl, hostSet)) {
706
+ console.warn('[plugins] skip (entryUrl not allowed)', p.id, entryUrl);
707
+ return
708
+ }
709
+ await loadScript(entryUrl);
710
+ }
711
+
712
+ /**
713
+ * @param {import('vue-router').default} router
714
+ * @param {(pluginId: string, router: import('vue-router').default, hostKit?: { bridgeAllowedPathPrefixes: string[] }) => object} createHostApiFactory
715
+ * 始终传入三个参数;单参工厂 `(id) => createHostApi(id, router)` 仍可用,后两个实参被忽略。
716
+ * @param {WebExtendPluginRuntimeOptions} [runtimeOptions]
717
+ */
718
+ async function bootstrapPlugins(router, createHostApiFactory, runtimeOptions) {
719
+ if (typeof window === 'undefined') {
720
+ console.warn('[plugins] bootstrapPlugins skipped: requires browser (window)');
721
+ return
722
+ }
723
+ const opts = resolveRuntimeOptions(runtimeOptions || {});
724
+ const base = String(opts.manifestBase).replace(/\/$/, '');
725
+ const manifestUrl = `${base}${opts.manifestListPath}`;
726
+ const hostSet = buildAllowedScriptHostsSet(opts.allowedScriptHosts);
727
+ const explicit = parseWebPluginDevMapExplicit(opts);
728
+
729
+ const [manifestResult, implicit] = await Promise.all([
730
+ (async () => {
731
+ try {
732
+ const res = await fetch(manifestUrl, { credentials: opts.manifestFetchCredentials });
733
+ if (!res.ok) {
734
+ return { ok: false, status: res.status, data: null }
735
+ }
736
+ const data = await res.json();
737
+ return { ok: true, data }
738
+ } catch (e) {
739
+ return { ok: false, error: e, data: null }
740
+ }
741
+ })(),
742
+ buildImplicitWebPluginDevMap(opts, hostSet)
743
+ ]);
744
+
745
+ const devMap = mergeDevMaps(implicit, explicit);
746
+ startPluginDevSseForMap(devMap, opts.isDev, hostSet, opts.devReloadSsePath);
747
+
748
+ const hostKit = { bridgeAllowedPathPrefixes: opts.bridgeAllowedPathPrefixes };
749
+
750
+ if (!manifestResult.ok) {
751
+ if (manifestResult.error) {
752
+ console.warn('[plugins] fetch manifest failed', manifestResult.error);
753
+ } else {
754
+ console.warn('[plugins] manifest HTTP', manifestResult.status, manifestUrl);
755
+ }
756
+ if (shouldShowBootstrapSummary(opts)) {
757
+ console.info('[plugins] bootstrap_summary', { ok: false, reason: 'manifest_fetch' });
758
+ }
759
+ return
760
+ }
761
+ /** @type {{ hostPluginApiVersion?: string, plugins?: object[] }} */
762
+ const data = manifestResult.data;
763
+ if (!data) {
764
+ if (shouldShowBootstrapSummary(opts)) {
765
+ console.info('[plugins] bootstrap_summary', { ok: false, reason: 'manifest_empty_body' });
766
+ }
767
+ return
768
+ }
769
+
770
+ const apiVer = data.hostPluginApiVersion;
771
+ if (apiVer) {
772
+ const coerced = coerce(apiVer);
773
+ const maj = coerced ? coerced.major : 0;
774
+ const range = `^${maj}.0.0`;
775
+ if (!satisfies(HOST_PLUGIN_API_VERSION, range, { includePrerelease: true })) {
776
+ console.warn(
777
+ '[plugins] host API version mismatch: host implements',
778
+ HOST_PLUGIN_API_VERSION,
779
+ 'server declares',
780
+ apiVer
781
+ );
782
+ }
783
+ }
784
+
785
+ window.__PLUGIN_ACTIVATORS__ = window.__PLUGIN_ACTIVATORS__ || {};
786
+
787
+ const plugins = data.plugins || [];
788
+ if (plugins.length === 0) {
789
+ console.info(
790
+ '[plugins] 清单为空。请检查:① 后端清单服务(plugin-web-starter)是否已接入;② web-plugin.web-plugins-dir 是否指向含各插件子目录及 manifest.json 的路径;③ 浏览器直接访问',
791
+ manifestUrl,
792
+ '是否返回 plugins 条目。'
793
+ );
794
+ }
795
+
796
+ const summary = {
797
+ manifestCount: plugins.length,
798
+ activated: 0,
799
+ skipEngines: 0,
800
+ skipLoad: 0,
801
+ skipNoActivator: 0,
802
+ activateFail: 0
803
+ };
804
+
805
+ for (const p of plugins) {
806
+ const range = p.engines && p.engines.host;
807
+ if (range && !satisfies(HOST_PLUGIN_API_VERSION, range, { includePrerelease: true })) {
808
+ console.warn('[plugins] skip (engines.host)', p.id, range);
809
+ summary.skipEngines++;
810
+ continue
811
+ }
812
+ const entryUrl = p.entryUrl;
813
+ try {
814
+ await loadPluginEntry(p, entryUrl, devMap, hostSet);
815
+ } catch (e) {
816
+ console.warn('[plugins] script load failed', p.id, e);
817
+ summary.skipLoad++;
818
+ continue
819
+ }
820
+ const activator = window.__PLUGIN_ACTIVATORS__[p.id];
821
+ if (typeof activator !== 'function') {
822
+ console.warn('[plugins] no activator for', p.id);
823
+ summary.skipNoActivator++;
824
+ continue
825
+ }
826
+ const hostApi = createHostApiFactory(p.id, router, hostKit);
827
+ try {
828
+ activator(hostApi);
829
+ summary.activated++;
830
+ } catch (e) {
831
+ console.error('[plugins] activate failed', p.id, e);
832
+ summary.activateFail++;
833
+ }
834
+ }
835
+
836
+ if (shouldShowBootstrapSummary(opts)) {
837
+ console.info('[plugins] bootstrap_summary', { ok: true, ...summary });
838
+ }
839
+ }
840
+
841
+ /**
842
+ * 插件通过宿主访问后端的受控通道:仅允许配置的前缀路径,默认 `/api/`;强制默认 `same-origin` 携带 Cookie。
843
+ * 前缀列表由 `createRequestBridge({ allowedPathPrefixes })` 传入,与 `defaultWebExtendPluginRuntime.bridgeAllowedPathPrefixes` 对齐。
844
+ *
845
+ * @module bridge
846
+ */
847
+
848
+ /**
849
+ * @param {string} p
850
+ */
851
+ function ensureLeadingSlash(p) {
852
+ const t = String(p || '').trim();
853
+ if (!t) {
854
+ return '/'
855
+ }
856
+ return t.startsWith('/') ? t : `/${t}`
857
+ }
858
+
859
+ /**
860
+ * @param {{ allowedPathPrefixes?: string[] }} [config]
861
+ */
862
+ function createRequestBridge(config = {}) {
863
+ const raw =
864
+ Array.isArray(config.allowedPathPrefixes) && config.allowedPathPrefixes.length > 0
865
+ ? config.allowedPathPrefixes
866
+ : defaultWebExtendPluginRuntime.bridgeAllowedPathPrefixes;
867
+ const allowedPathPrefixes = raw.map((p) => ensureLeadingSlash(p));
868
+
869
+ return {
870
+ /**
871
+ * 发起受控 `fetch`。
872
+ * @param {string} path 必须以 `/` 开头,且匹配某一 `allowedPathPrefixes` 前缀
873
+ * @param {RequestInit} [init] 会与默认 `{ credentials: 'same-origin' }` 合并(后者可被覆盖)
874
+ */
875
+ async request(path, init = {}) {
876
+ if (typeof path !== 'string' || !path.startsWith('/')) {
877
+ throw new Error('[bridge] path must be a string starting with /')
878
+ }
879
+ const allowed = allowedPathPrefixes.some((p) => path.startsWith(p));
880
+ if (!allowed) {
881
+ throw new Error('[bridge] path not allowed: ' + path)
882
+ }
883
+ return fetch(path, {
884
+ credentials: 'same-origin',
885
+ ...init
886
+ })
887
+ }
888
+ }
889
+ }
890
+
891
+ /**
892
+ * 宿主全局响应式注册表:菜单与扩展点槽位,供布局与 `ExtensionPoint` 订阅。
893
+ *
894
+ * @module registries
895
+ */
896
+
897
+ /**
898
+ * @type {{
899
+ * menus: object[],
900
+ * slots: Record<string, Array<{ pluginId: string, component: import('vue').Component, priority: number, key: string }>>
901
+ * }}
902
+ */
903
+ const registries = Vue.observable({
904
+ menus: [],
905
+ /** 扩展点 id → 已注册组件列表(内容区 / 工具栏等共用模型) */
906
+ slots: {},
907
+ /**
908
+ * 每次变更 slots 时递增,供 ExtensionPoint 计算属性显式依赖。
909
+ * Vue 2 对「先访问不存在的 slots[key]、后 Vue.set 补 key」的依赖收集不可靠,会导致扩展点不刷新。
910
+ */
911
+ slotRevision: 0
912
+ });
913
+
914
+ /**
915
+ * 按 `pluginId` 收集 `onTeardown` 回调,供 `disposeWebPlugin` 统一执行。
916
+ *
917
+ * @module teardown-registry
918
+ */
919
+
920
+ /** @type {Map<string, Function[]>} */
921
+ const byPlugin = new Map();
922
+
923
+ /**
924
+ * 登记插件卸载时要执行的同步回调(建议只做解绑、清定时器等轻量逻辑)。
925
+ * @param {string} pluginId
926
+ * @param {() => void} fn
927
+ */
928
+ function registerPluginTeardown(pluginId, fn) {
929
+ if (typeof fn !== 'function') {
930
+ return
931
+ }
932
+ let arr = byPlugin.get(pluginId);
933
+ if (!arr) {
934
+ arr = [];
935
+ byPlugin.set(pluginId, arr);
936
+ }
937
+ arr.push(fn);
938
+ }
939
+
940
+ /**
941
+ * 执行并清空该插件已登记的全部 teardown;调用后 Map 中不再保留该 id。
942
+ * @param {string} pluginId
943
+ */
944
+ function runPluginTeardowns(pluginId) {
945
+ const arr = byPlugin.get(pluginId);
946
+ if (!arr) {
947
+ return
948
+ }
949
+ byPlugin.delete(pluginId);
950
+ for (const fn of arr) {
951
+ try {
952
+ fn();
953
+ } catch (e) {
954
+ console.warn('[plugins] teardown failed', pluginId, e);
955
+ }
956
+ }
957
+ }
958
+
959
+ /**
960
+ * 构造供插件 activator 调用的宿主 API(路由、菜单、扩展点、资源注入等)。
961
+ * 与打包工具无关;Webpack 宿主需已配置 `vue-loader` 以编译本包内的 `.vue` 依赖。
962
+ *
963
+ * @module createHostApi
964
+ */
965
+
966
+ /** 扩展点列表项 key 递增,避免用 Date.now() 导致列表重排时误卸载组件 */
967
+ let slotItemKeySeq = 0;
968
+ /** 无 name 的动态路由合成名递增,避免多次 registerRoutes 重名 */
969
+ let routeSynthSeq = 0;
970
+
971
+ /**
972
+ * @typedef {object} RegisterSlotEntry
973
+ * @property {import('vue').Component} component
974
+ * @property {number} [priority]
975
+ */
976
+
977
+ /**
978
+ * @typedef {object} HostApi
979
+ * @property {string} hostPluginApiVersion 宿主实现的协议版本
980
+ * @property {(routes: import('vue-router').RouteConfig[]) => void} registerRoutes 注册路由;无 `name` 时自动生成稳定合成名;优先 `router.addRoute`
981
+ * @property {(items: object[]) => void} registerMenuItems 注册菜单并按 `order` 排序
982
+ * @property {(pointId: string, components: RegisterSlotEntry[]) => void} registerSlotComponents 向扩展点挂载组件
983
+ * @property {(urls?: string[]) => void} registerStylesheetUrls 注入 `link[rel=stylesheet]`,带 `data-plugin-asset`
984
+ * @property {(urls?: string[]) => void} registerScriptUrls 顺序注入外链脚本
985
+ * @property {() => void} registerSanitizedHtmlSnippet MVP 未实现,调用即抛错
986
+ * @property {() => ReturnType<typeof createRequestBridge>} getBridge 受控 `fetch` 代理
987
+ * @property {(pluginId: string, fn: () => void) => void} onTeardown 注册卸载回调;由 `disposeWebPlugin(pluginId)` 触发
988
+ */
989
+
990
+ /**
991
+ * @typedef {object} HostKitOptions
992
+ * @property {string[]} [bridgeAllowedPathPrefixes] 覆盖 `getBridge().request` 允许的 URL 前缀;默认见 `defaultWebExtendPluginRuntime.bridgeAllowedPathPrefixes`
993
+ */
994
+
995
+ /**
996
+ * 创建单个插件在宿主侧的 API 句柄,传入插件 `activator(hostApi)`。
997
+ *
998
+ * `bootstrapPlugins` 始终以 `(pluginId, router, hostKitOptions)` 调用工厂;请使用 `(id, r, kit) => createHostApi(id, r, kit)` 传入 `bridgeAllowedPathPrefixes`。
999
+ * 单参工厂 `(id) => createHostApi(id, router)` 仍可用(忽略后两个实参),此时 bridge 仅用包内默认前缀。
1000
+ *
1001
+ * @param {string} pluginId 与 manifest.id 一致
1002
+ * @param {import('vue-router').default} router 宿主 Vue Router 实例(vue-router@3)
1003
+ * @param {HostKitOptions} [hostKitOptions]
1004
+ * @returns {HostApi}
1005
+ */
1006
+ function createHostApi(pluginId, router, hostKitOptions = {}) {
1007
+ const bridgePrefixes =
1008
+ Array.isArray(hostKitOptions.bridgeAllowedPathPrefixes) &&
1009
+ hostKitOptions.bridgeAllowedPathPrefixes.length > 0
1010
+ ? hostKitOptions.bridgeAllowedPathPrefixes
1011
+ : defaultWebExtendPluginRuntime.bridgeAllowedPathPrefixes;
1012
+ const bridge = createRequestBridge({ allowedPathPrefixes: bridgePrefixes });
1013
+
1014
+ /**
1015
+ * 注入样式表;`disposeWebPlugin` 会按 `data-plugin-asset` 移除对应节点。
1016
+ * @param {string} href
1017
+ */
1018
+ function injectStylesheet(href) {
1019
+ const link = document.createElement('link');
1020
+ link.rel = 'stylesheet';
1021
+ link.href = href;
1022
+ link.setAttribute('data-plugin-asset', pluginId);
1023
+ document.head.appendChild(link);
1024
+ }
1025
+
1026
+ /**
1027
+ * 注入外链脚本(用于插件额外资源,非清单主入口)。
1028
+ * @param {string} src
1029
+ * @returns {Promise<void>}
1030
+ */
1031
+ function injectScript(src) {
1032
+ return new Promise((resolve, reject) => {
1033
+ const s = document.createElement('script');
1034
+ s.async = true;
1035
+ s.src = src;
1036
+ s.setAttribute('data-plugin-asset', pluginId);
1037
+ s.onload = () => resolve();
1038
+ s.onerror = () => reject(new Error('script failed: ' + src));
1039
+ document.head.appendChild(s);
1040
+ })
1041
+ }
1042
+
1043
+ return {
1044
+ hostPluginApiVersion: HOST_PLUGIN_API_VERSION,
1045
+
1046
+ /**
1047
+ * 动态注册路由。Vue Router 3.5+ 推荐 `addRoute`;若不存在则回退已弃用的 `addRoutes`。
1048
+ * @param {import('vue-router').RouteConfig[]} routes
1049
+ */
1050
+ registerRoutes(routes) {
1051
+ const wrapped = routes.map((r) => ({
1052
+ ...r,
1053
+ name: r.name || `__wep_${pluginId}_${routeSynthSeq++}`,
1054
+ meta: { ...(r.meta || {}), pluginId }
1055
+ }));
1056
+ if (typeof router.addRoute === 'function') {
1057
+ for (const r of wrapped) {
1058
+ router.addRoute(r);
1059
+ }
1060
+ } else {
1061
+ router.addRoutes(wrapped);
1062
+ }
1063
+ },
1064
+
1065
+ /**
1066
+ * 写入全局菜单注册表(响应式);按 `order` 升序排列。
1067
+ * @param {object[]} items
1068
+ */
1069
+ registerMenuItems(items) {
1070
+ for (const item of items) {
1071
+ registries.menus.push({ ...item, pluginId });
1072
+ }
1073
+ registries.menus.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
1074
+ },
1075
+
1076
+ /**
1077
+ * 向指定扩展点 id 注册 Vue 组件;`ExtensionPoint` 按 `priority` 降序渲染。
1078
+ * @param {string} pointId
1079
+ * @param {RegisterSlotEntry[]} components
1080
+ */
1081
+ registerSlotComponents(pointId, components) {
1082
+ if (!pointId) {
1083
+ return
1084
+ }
1085
+ if (!registries.slots[pointId]) {
1086
+ Vue.set(registries.slots, pointId, []);
1087
+ }
1088
+ const list = registries.slots[pointId];
1089
+ for (const c of components) {
1090
+ list.push({
1091
+ pluginId,
1092
+ component: c.component,
1093
+ priority: c.priority ?? 0,
1094
+ key: `${pluginId}-${pointId}-${++slotItemKeySeq}`
1095
+ });
1096
+ }
1097
+ list.sort((a, b) => b.priority - a.priority);
1098
+ registries.slotRevision++;
1099
+ },
1100
+
1101
+ /**
1102
+ * @param {string[]|undefined} urls
1103
+ */
1104
+ registerStylesheetUrls(urls) {
1105
+ for (const u of urls || []) {
1106
+ if (typeof u === 'string' && u) {
1107
+ injectStylesheet(u);
1108
+ }
1109
+ }
1110
+ },
1111
+
1112
+ /**
1113
+ * 串行加载多个脚本,失败仅告警不中断宿主。
1114
+ * @param {string[]|undefined} urls
1115
+ */
1116
+ registerScriptUrls(urls) {
1117
+ const chain = (urls || []).filter((u) => typeof u === 'string' && u).reduce(
1118
+ (p, u) => p.then(() => injectScript(u)),
1119
+ Promise.resolve()
1120
+ );
1121
+ chain.catch((e) => console.warn('[plugins] registerScriptUrls', pluginId, e));
1122
+ },
1123
+
1124
+ registerSanitizedHtmlSnippet() {
1125
+ throw new Error('registerSanitizedHtmlSnippet is not enabled in MVP')
1126
+ },
1127
+
1128
+ getBridge: () => bridge,
1129
+
1130
+ /**
1131
+ * 插件卸载前清理逻辑;第一个参数为预留与协议对齐,实际以创建 API 时的 `pluginId` 为准。
1132
+ * @param {string} _pluginId 预留,与 manifest.id 一致时可传入
1133
+ * @param {() => void} fn
1134
+ */
1135
+ onTeardown(_pluginId, fn) {
1136
+ if (typeof fn === 'function') {
1137
+ registerPluginTeardown(pluginId, fn);
1138
+ }
1139
+ }
1140
+ }
1141
+ }
1142
+
1143
+ /**
1144
+ * 单插件卸载:与 `bootstrapPlugins` / `createHostApi` 对称,清理注册表与 DOM 副作用。
1145
+ *
1146
+ * @module dispose-plugin
1147
+ */
1148
+
1149
+ /**
1150
+ * 卸载指定 id 的插件:依次执行 teardown、移除菜单与扩展点条目、删除 activator、移除带 `data-plugin-asset` 的节点。
1151
+ *
1152
+ * **路由**:Vue Router 3 无公开 `removeRoute`,此处不改动 matcher;动态路由需整页刷新或自行维护路由表。
1153
+ *
1154
+ * @param {string} pluginId 与 manifest.id 一致
1155
+ */
1156
+ function disposeWebPlugin(pluginId) {
1157
+ if (!pluginId || typeof pluginId !== 'string') {
1158
+ return
1159
+ }
1160
+
1161
+ runPluginTeardowns(pluginId);
1162
+
1163
+ for (let i = registries.menus.length - 1; i >= 0; i--) {
1164
+ if (registries.menus[i].pluginId === pluginId) {
1165
+ registries.menus.splice(i, 1);
1166
+ }
1167
+ }
1168
+
1169
+ const slots = registries.slots;
1170
+ for (const pointId of Object.keys(slots)) {
1171
+ const list = slots[pointId];
1172
+ if (!Array.isArray(list)) {
1173
+ continue
1174
+ }
1175
+ const next = list.filter((x) => x.pluginId !== pluginId);
1176
+ if (next.length === 0) {
1177
+ Vue.delete(slots, pointId);
1178
+ } else if (next.length !== list.length) {
1179
+ Vue.set(slots, pointId, next);
1180
+ }
1181
+ }
1182
+ registries.slotRevision++;
1183
+
1184
+ if (typeof window !== 'undefined' && window.__PLUGIN_ACTIVATORS__) {
1185
+ delete window.__PLUGIN_ACTIVATORS__[pluginId];
1186
+ }
1187
+
1188
+ if (typeof document !== 'undefined') {
1189
+ document.querySelectorAll('[data-plugin-asset]').forEach((el) => {
1190
+ if (el.getAttribute('data-plugin-asset') === pluginId) {
1191
+ el.remove();
1192
+ }
1193
+ });
1194
+ }
1195
+ }
1196
+
1197
+ /**
1198
+ * 在宿主布局中声明扩展点;插件通过 `hostApi.registerSlotComponents(pointId, ...)` 注入组件。
1199
+ * 使用纯 render 函数,便于 Rollup 发布 dist,宿主无需再转译 .vue。
1200
+ */
1201
+
1202
+ const SlotErrorBoundary = {
1203
+ name: 'SlotErrorBoundary',
1204
+ props: { label: String },
1205
+ data() {
1206
+ return { error: null }
1207
+ },
1208
+ errorCaptured(err) {
1209
+ this.error = err && err.message ? err.message : String(err);
1210
+ console.error('[ExtensionPoint] render error in', this.label, err);
1211
+ return false
1212
+ },
1213
+ render(h) {
1214
+ if (this.error) {
1215
+ return h(
1216
+ 'div',
1217
+ { class: 'plugin-point-error', style: { color: '#c00', fontSize: '12px' } },
1218
+ `[插件 ${this.label}] 渲染失败`
1219
+ )
1220
+ }
1221
+ const d = this.$slots.default;
1222
+ return d && d[0] ? d[0] : h('span')
1223
+ }
1224
+ };
1225
+
1226
+ var ExtensionPoint = {
1227
+ name: 'ExtensionPoint',
1228
+ components: { SlotErrorBoundary },
1229
+ props: {
1230
+ pointId: { type: String, required: true },
1231
+ slotProps: { type: Object, default: () => ({}) }
1232
+ },
1233
+ computed: {
1234
+ items() {
1235
+ void registries.slotRevision;
1236
+ return registries.slots[this.pointId] || []
1237
+ },
1238
+ forwardProps() {
1239
+ return this.slotProps || {}
1240
+ }
1241
+ },
1242
+ render(h) {
1243
+ return h(
1244
+ 'div',
1245
+ {
1246
+ class: 'extension-point',
1247
+ style: { minHeight: '8px' },
1248
+ attrs: { 'data-point-id': this.pointId }
1249
+ },
1250
+ this.items.map((item) =>
1251
+ h(
1252
+ SlotErrorBoundary,
1253
+ {
1254
+ key: item.key,
1255
+ props: { label: item.pluginId }
1256
+ },
1257
+ [h(item.component, { props: this.forwardProps })]
1258
+ )
1259
+ )
1260
+ )
1261
+ }
1262
+ };
1263
+
1264
+ /**
1265
+ * 一键接入:注册 `ExtensionPoint` 并执行 `bootstrapPlugins`。
1266
+ * @module install
1267
+ */
1268
+
1269
+ /**
1270
+ * 注册全局组件 `ExtensionPoint` 并异步引导插件清单。
1271
+ *
1272
+ * @param {*} Vue
1273
+ * @param {*} router vue-router 实例
1274
+ * @param {Record<string, unknown>} [options] 传给 `resolveRuntimeOptions` 的字段;可含 `env`(Vite 传入 `import.meta.env`)以读取 `VITE_*`。
1275
+ * @returns {Promise<void>}
1276
+ */
1277
+ function installWebExtendPluginVue2(Vue, router, options) {
1278
+ const opts = options || {};
1279
+ const { env: injectedEnv, ...runtimeUser } = opts;
1280
+ if (injectedEnv && typeof injectedEnv === 'object') {
1281
+ setWebExtendPluginEnv(injectedEnv);
1282
+ }
1283
+ if (Vue && ExtensionPoint) {
1284
+ Vue.component('ExtensionPoint', ExtensionPoint);
1285
+ }
1286
+ const runtime = resolveRuntimeOptions(runtimeUser);
1287
+ return bootstrapPlugins(router, (id, r, kit) => createHostApi(id, r, kit), runtime)
1288
+ }
1289
+
1290
+ export { ExtensionPoint, HOST_PLUGIN_API_VERSION, bootstrapPlugins, createHostApi, createRequestBridge, defaultWebExtendPluginRuntime, disposeWebPlugin, installWebExtendPluginVue2, registries, resolveRuntimeOptions, setWebExtendPluginEnv };
1291
+ //# sourceMappingURL=index.mjs.map