web-extend-plugin-vue2 0.2.3 → 0.2.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.
package/dist/index.mjs CHANGED
@@ -1,378 +1,491 @@
1
1
  import Vue from 'vue';
2
2
 
3
- /**
4
- * `resolveRuntimeOptions` 的默认值来源;宿主可只覆盖部分字段。
5
- */
6
- const defaultWebExtendPluginRuntime = {
7
- manifestBase: '/fp-api',
8
- manifestListPath: '/api/frontend-plugins',
9
- manifestFetchCredentials: 'include',
10
- devPingPath: '/__web_plugin_dev_ping',
11
- devReloadSsePath: '/__web_plugin_reload_stream',
12
- webPluginDevEntryPath: '/src/plugin-entry.js',
13
- devPingTimeoutMs: 500,
14
- defaultImplicitDevPluginIds: [],
15
- allowedScriptHosts: ['localhost', '127.0.0.1', '::1'],
16
- bridgeAllowedPathPrefixes: ['/api/']
3
+ /**
4
+ * 对外配置单一入口:`resolveRuntimeOptions` / 文档 / 其它模块的默认值与环境键名均由此引用。
5
+ * 宿主通过 `resolveRuntimeOptions(partial)` 覆盖的对象形状见 `defaultWebExtendPluginRuntime`。
6
+ */
7
+ /** 与 `package.json` 的 peer 下限一致;`npm run test:peer-min` / CI matrix 须与此保持同步 */
8
+ const peerMinimumVersions = {
9
+ vue: '2.6.14',
10
+ vueRouter: '3.5.4'
11
+ };
12
+ // ---------------------------------------------------------------------------
13
+ // 协议与品牌(发布契约;与清单 `hostPluginApiVersion` 对齐 semver 主版本,一般不随宿主覆盖)
14
+ // ---------------------------------------------------------------------------
15
+ const HOST_PLUGIN_API_VERSION = '1.0.0';
16
+ /** 控制台日志与首次引导横幅使用的短名称 */
17
+ const RUNTIME_CONSOLE_LABEL = 'web-extend-plugin-vue2';
18
+ // ---------------------------------------------------------------------------
19
+ // 与 `build-env` / `resolveBundledEnv` 配套的键名(单一事实来源,便于检索与文档)
20
+ // ---------------------------------------------------------------------------
21
+ const webExtendPluginEnvKeys = {
22
+ manifestBase: 'VITE_FRONTEND_PLUGIN_BASE',
23
+ manifestListPath: 'VITE_WEB_PLUGIN_MANIFEST_PATH',
24
+ implicitDevIds: 'VITE_WEB_PLUGIN_IMPLICIT_DEV_IDS',
25
+ allowedScriptHosts: 'VITE_WEB_PLUGIN_ALLOWED_SCRIPT_HOSTS',
26
+ bridgePrefixes: 'VITE_WEB_PLUGIN_BRIDGE_PREFIXES',
27
+ devFallbackManifestUrl: 'VITE_WEB_PLUGIN_DEV_FALLBACK_MANIFEST_URL',
28
+ manifestMode: 'VITE_WEB_PLUGIN_MANIFEST_MODE',
29
+ staticManifestUrl: 'VITE_WEB_PLUGIN_STATIC_MANIFEST_URL',
30
+ mountPath: 'VITE_WEB_PLUGIN_MOUNT_PATH',
31
+ devEntry: 'VITE_WEB_PLUGIN_DEV_ENTRY',
32
+ devPing: 'VITE_WEB_PLUGIN_DEV_PING_PATH',
33
+ devSse: 'VITE_WEB_PLUGIN_DEV_SSE_PATH',
34
+ devPingTimeout: 'VITE_WEB_PLUGIN_DEV_PING_TIMEOUT_MS',
35
+ manifestCredentials: 'VITE_WEB_PLUGIN_MANIFEST_CREDENTIALS',
36
+ devManifestFallback: 'VITE_WEB_PLUGIN_DEV_MANIFEST_FALLBACK',
37
+ webPluginDevOrigin: 'VITE_WEB_PLUGIN_DEV_ORIGIN',
38
+ webPluginDevIds: 'VITE_WEB_PLUGIN_DEV_IDS',
39
+ webPluginDevMap: 'VITE_WEB_PLUGIN_DEV_MAP',
40
+ pluginsBootstrapSummary: 'VITE_PLUGINS_BOOTSTRAP_SUMMARY',
41
+ /** 清单路径备选:部分宿主单独使用 */
42
+ manifestPathAlt: 'VUE_APP_WEB_PLUGIN_MANIFEST_PATH'
43
+ };
44
+ // ---------------------------------------------------------------------------
45
+ // `manifestMode` 未配置且环境未指定时的默认值
46
+ // ---------------------------------------------------------------------------
47
+ const defaultManifestMode = 'api';
48
+ // ---------------------------------------------------------------------------
49
+ // `manifest-fetch-composer` 中间件默认(中间件 options 可逐项覆盖)
50
+ // ---------------------------------------------------------------------------
51
+ const defaultManifestFetchCache = {
52
+ storageKeyPrefix: 'wep.manifestFetch.v1',
53
+ maxEntries: 50
54
+ };
55
+ // ---------------------------------------------------------------------------
56
+ // 路由合成名前缀(`createHostApi` 为无 name 的路由生成 `__wep_${pluginId}_${seq}`)
57
+ // ---------------------------------------------------------------------------
58
+ const routeSynthNamePrefix = '__wep_';
59
+ // ---------------------------------------------------------------------------
60
+ // 宿主可通过 `resolveRuntimeOptions` 覆盖的运行时默认值(与 README / index.d.ts 描述一致)
61
+ // ---------------------------------------------------------------------------
62
+ const defaultWebExtendPluginRuntime = {
63
+ manifestBase: '/fp-api',
64
+ manifestListPath: '/api/frontend-plugins',
65
+ manifestFetchCredentials: 'include',
66
+ devPingPath: '/__web_plugin_dev_ping',
67
+ devReloadSsePath: '/__web_plugin_reload_stream',
68
+ webPluginDevEntryPath: '/src/plugin-entry.js',
69
+ devPingTimeoutMs: 500,
70
+ defaultImplicitDevPluginIds: [],
71
+ allowedScriptHosts: ['localhost', '127.0.0.1', '::1'],
72
+ bridgeAllowedPathPrefixes: ['/api/'],
73
+ /** 与 `hostLayoutComponent` 同时使用时默认父路由 name */
74
+ pluginRoutesParentName: '__wepPluginHost',
75
+ /** 插件壳路径(与菜单、ensurePluginHostRoute 一致) */
76
+ pluginMountPath: '/plugin',
77
+ /** `manifestMode=api` 且开发环境下,API 失败或 plugins 为空时尝试的静态 JSON(可放于 `public/web-plugins/`) */
78
+ devFallbackStaticManifestUrl: '/web-plugins/plugins.manifest.json'
17
79
  };
18
80
 
19
81
  /**
20
82
  * 与具体打包器解耦的运行时环境读取:优先显式注入,其次 `globalThis.__WEP_ENV__`,再读 `process.env`。
21
83
  * Vite 宿主建议在入口调用 `setWebExtendPluginEnv(import.meta.env)`。
22
84
  */
23
-
24
- /** @type {Record<string, unknown> | null} */
25
85
  let _injected = null;
26
-
27
86
  /**
28
87
  * 注入与 `import.meta.env` 同形态的对象(键如 `VITE_*`、`DEV`)。
29
- * @param {Record<string, unknown> | null | undefined} env
30
88
  */
31
89
  function setWebExtendPluginEnv(env) {
32
- _injected = env && typeof env === 'object' ? env : null;
90
+ _injected = env && typeof env === 'object' ? env : null;
33
91
  }
34
-
35
- /**
36
- * @returns {Record<string, unknown> | null}
37
- */
38
92
  function getEnvObject() {
39
- if (_injected) {
40
- return _injected
41
- }
42
- try {
43
- const g = typeof globalThis !== 'undefined' ? globalThis : undefined;
44
- if (g && g.__WEP_ENV__ && typeof g.__WEP_ENV__ === 'object') {
45
- return g.__WEP_ENV__
93
+ if (_injected) {
94
+ return _injected;
95
+ }
96
+ try {
97
+ const g = typeof globalThis !== 'undefined' ? globalThis : undefined;
98
+ const raw = g;
99
+ if (raw && raw.__WEP_ENV__ && typeof raw.__WEP_ENV__ === 'object') {
100
+ return raw.__WEP_ENV__;
101
+ }
102
+ }
103
+ catch {
104
+ /* ignore */
46
105
  }
47
- } catch (_) {
48
- /* ignore */
49
- }
50
- return null
106
+ return null;
51
107
  }
52
-
53
108
  /**
54
109
  * 读取注入环境中的字符串配置(`VITE_*` / `PLUGIN_*` 等价键由调用方传入)。
55
- * @param {string} key
56
- * @returns {string|undefined}
57
110
  */
58
111
  function readInjectedEnvKey(key) {
59
- const o = getEnvObject();
60
- if (!o || !(key in o)) {
61
- return undefined
62
- }
63
- const v = o[key];
64
- if (v === undefined || v === '') {
65
- return undefined
66
- }
67
- return String(v)
112
+ const o = getEnvObject();
113
+ if (!o || !(key in o)) {
114
+ return undefined;
115
+ }
116
+ const v = o[key];
117
+ if (v === undefined || v === '') {
118
+ return undefined;
119
+ }
120
+ return String(v);
68
121
  }
69
-
70
- /** @returns {boolean} */
71
122
  function readInjectedEnvDev() {
72
- const o = getEnvObject();
73
- return !!(o && o.DEV === true)
123
+ const o = getEnvObject();
124
+ return !!(o && o.DEV === true);
74
125
  }
75
126
 
76
127
  /**
77
128
  * 从注入环境与 `process.env` 解析 `VITE_*` / `PLUGIN_*` 键。
78
129
  */
79
-
80
- /**
81
- * @param {string} key
82
- * @returns {string|undefined}
83
- */
84
130
  function readProcessEnv(key) {
85
- try {
86
- if (typeof process !== 'undefined' && process.env && key in process.env) {
87
- const v = process.env[key];
88
- if (v !== undefined && v !== '') {
89
- return String(v)
90
- }
131
+ try {
132
+ if (typeof process !== 'undefined' && process.env && key in process.env) {
133
+ const v = process.env[key];
134
+ if (v !== undefined && v !== '') {
135
+ return String(v);
136
+ }
137
+ }
91
138
  }
92
- } catch (_) {
93
- /* ignore */
94
- }
95
- return undefined
139
+ catch {
140
+ /* ignore */
141
+ }
142
+ return undefined;
96
143
  }
97
-
98
- /**
99
- * @param {string} viteStyleKey
100
- * @returns {string|null}
101
- */
102
144
  function viteKeyToPluginAlternate(viteStyleKey) {
103
- if (typeof viteStyleKey !== 'string' || !viteStyleKey.startsWith('VITE_')) {
104
- return null
105
- }
106
- return `PLUGIN_${viteStyleKey.slice(5)}`
145
+ if (typeof viteStyleKey !== 'string' || !viteStyleKey.startsWith('VITE_')) {
146
+ return null;
147
+ }
148
+ return `PLUGIN_${viteStyleKey.slice(5)}`;
107
149
  }
108
-
109
- /**
110
- * @param {string} key
111
- * @param {string} [fallback='']
112
- */
113
150
  function resolveBundledEnv(key, fallback = '') {
114
- const alt = viteKeyToPluginAlternate(key);
115
- const inj = readInjectedEnvKey(key);
116
- const fromInjected =
117
- inj === undefined || inj === null ? (alt ? readInjectedEnvKey(alt) : undefined) : inj;
118
- const proc = readProcessEnv(key);
119
- const fromProcess =
120
- proc === undefined || proc === null ? (alt ? readProcessEnv(alt) : undefined) : proc;
121
- const first = fromInjected === undefined || fromInjected === null ? fromProcess : fromInjected;
122
- return first === undefined || first === null ? fallback : first
151
+ const alt = viteKeyToPluginAlternate(key);
152
+ const inj = readInjectedEnvKey(key);
153
+ const fromInjected = inj === undefined || inj === null ? (alt ? readInjectedEnvKey(alt) : undefined) : inj;
154
+ const proc = readProcessEnv(key);
155
+ const fromProcess = proc === undefined || proc === null ? (alt ? readProcessEnv(alt) : undefined) : proc;
156
+ const first = fromInjected === undefined || fromInjected === null ? fromProcess : fromInjected;
157
+ return first === undefined || first === null ? fallback : first;
123
158
  }
124
-
125
- /** @returns {boolean} */
126
159
  function resolveBundledIsDev() {
127
- try {
128
- if (readInjectedEnvDev()) {
129
- return true
160
+ try {
161
+ if (readInjectedEnvDev()) {
162
+ return true;
163
+ }
130
164
  }
131
- } catch (_) {
132
- /* ignore */
133
- }
134
- try {
135
- if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'development') {
136
- return true
165
+ catch {
166
+ /* ignore */
137
167
  }
138
- } catch (_) {
139
- /* ignore */
140
- }
141
- return false
168
+ try {
169
+ if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'development') {
170
+ return true;
171
+ }
172
+ }
173
+ catch {
174
+ /* ignore */
175
+ }
176
+ return false;
142
177
  }
143
178
 
144
179
  /**
145
- * 路径与脚本主机名校验工具。
146
- * @module runtime/path-host-utils
180
+ * 清单模式与静态清单 URL 配置解析(显式 options + VITE_* / PLUGIN_* 环境)。
147
181
  */
182
+ const EK$1 = webExtendPluginEnvKeys;
183
+ function resolveManifestModeFromInputs(userMode) {
184
+ if (userMode !== undefined && userMode !== null && String(userMode).trim() !== '') {
185
+ const s = String(userMode).trim().toLowerCase();
186
+ if (s === 'static' || s === 'api') {
187
+ return s;
188
+ }
189
+ }
190
+ const e = resolveBundledEnv(EK$1.manifestMode, '');
191
+ if (e) {
192
+ const s = String(e).trim().toLowerCase();
193
+ if (s === 'static' || s === 'api') {
194
+ return s;
195
+ }
196
+ }
197
+ return defaultManifestMode;
198
+ }
199
+ function resolveStaticManifestUrlFromInputs(userUrl) {
200
+ if (userUrl !== undefined && userUrl !== null) {
201
+ const s = String(userUrl).trim();
202
+ if (s !== '') {
203
+ return s;
204
+ }
205
+ }
206
+ return String(resolveBundledEnv(EK$1.staticManifestUrl, '') || '').trim();
207
+ }
148
208
 
149
209
  /**
150
- * @param {string} p
210
+ * 路径与脚本主机名校验工具。
151
211
  */
152
212
  function ensureLeadingPath(p) {
153
- const t = String(p || '').trim();
154
- if (!t) {
155
- return '/'
156
- }
157
- return t.startsWith('/') ? t : `/${t}`
213
+ const t = String(p || '').trim();
214
+ if (!t) {
215
+ return '/';
216
+ }
217
+ return t.startsWith('/') ? t : `/${t}`;
158
218
  }
159
-
160
- /**
161
- * @param {string} hostname
162
- */
163
219
  function normalizeHost(hostname) {
164
- if (!hostname) {
165
- return ''
166
- }
167
- const h = hostname.toLowerCase();
168
- if (h.startsWith('[') && h.endsWith(']')) {
169
- return h.slice(1, -1)
170
- }
171
- return h
220
+ if (!hostname) {
221
+ return '';
222
+ }
223
+ const h = hostname.toLowerCase();
224
+ if (h.startsWith('[') && h.endsWith(']')) {
225
+ return h.slice(1, -1);
226
+ }
227
+ return h;
172
228
  }
173
-
174
- /**
175
- * @param {string[]} hostnames
176
- * @returns {Set<string>}
177
- */
178
229
  function buildAllowedScriptHostsSet(hostnames) {
179
- const s = new Set();
180
- for (const h of hostnames) {
181
- const n = normalizeHost(h);
182
- if (n) {
183
- s.add(n);
230
+ const s = new Set();
231
+ for (const h of hostnames) {
232
+ const n = normalizeHost(h);
233
+ if (n) {
234
+ s.add(n);
235
+ }
184
236
  }
185
- }
186
- return s
237
+ return s;
187
238
  }
188
-
189
- /**
190
- * @param {string} url
191
- * @param {Set<string>} hostSet
192
- */
193
239
  function isScriptHostAllowed(url, hostSet) {
194
- if (typeof window === 'undefined') {
195
- return false
196
- }
197
- try {
198
- const u = new URL(url, window.location.origin);
199
- const h = normalizeHost(u.hostname);
200
- return hostSet.has(h)
201
- } catch {
202
- return false
203
- }
240
+ if (typeof window === 'undefined') {
241
+ return false;
242
+ }
243
+ try {
244
+ const u = new URL(url, window.location.origin);
245
+ const h = normalizeHost(u.hostname);
246
+ return hostSet.has(h);
247
+ }
248
+ catch {
249
+ return false;
250
+ }
204
251
  }
205
252
 
206
253
  /**
207
254
  * 合并用户、环境与默认配置得到运行时选项。
208
- * @module runtime/resolve-runtime-options
209
255
  */
210
-
211
-
212
256
  const DEF = defaultWebExtendPluginRuntime;
213
-
214
- /**
215
- * @param {string|undefined} userVal
216
- * @param {string} envKey
217
- * @param {RequestCredentials} fallback
218
- */
257
+ const EK = webExtendPluginEnvKeys;
219
258
  function resolveManifestCredentials(userVal, envKey, fallback) {
220
- if (userVal !== undefined && userVal !== '') {
221
- const s = String(userVal);
222
- if (s === 'include' || s === 'omit' || s === 'same-origin') {
223
- return s
259
+ if (userVal !== undefined) {
260
+ const s = String(userVal);
261
+ if (s === 'include' || s === 'omit' || s === 'same-origin') {
262
+ return s;
263
+ }
264
+ }
265
+ const e = resolveBundledEnv(envKey, '');
266
+ if (e === 'include' || e === 'omit' || e === 'same-origin') {
267
+ return e;
224
268
  }
225
- }
226
- const e = resolveBundledEnv(envKey, '');
227
- if (e === 'include' || e === 'omit' || e === 'same-origin') {
228
- return e
229
- }
230
- return fallback
269
+ return fallback;
231
270
  }
232
-
233
- /**
234
- * @param {number|undefined} userVal
235
- * @param {string} envKey
236
- * @param {number} fallback
237
- */
238
271
  function resolvePositiveInt(userVal, envKey, fallback) {
239
- if (typeof userVal === 'number' && Number.isFinite(userVal) && userVal > 0) {
240
- return Math.floor(userVal)
241
- }
242
- const raw = resolveBundledEnv(envKey, '');
243
- const n = raw ? parseInt(raw, 10) : NaN;
244
- if (Number.isFinite(n) && n > 0) {
245
- return n
246
- }
247
- return fallback
272
+ if (typeof userVal === 'number' && Number.isFinite(userVal) && userVal > 0) {
273
+ return Math.floor(userVal);
274
+ }
275
+ const raw = resolveBundledEnv(envKey, '');
276
+ const n = raw ? parseInt(raw, 10) : NaN;
277
+ if (Number.isFinite(n) && n > 0) {
278
+ return n;
279
+ }
280
+ return fallback;
248
281
  }
249
-
250
- /**
251
- * 合并用户、环境变量与 `defaultWebExtendPluginRuntime`,得到完整运行时选项(宿主可只传需要覆盖的字段)。
252
- * @param {WebExtendPluginRuntimeOptions} [user]
253
- * @returns {object}
254
- */
282
+ /** 合并用户、环境变量与 `defaultWebExtendPluginRuntime`,得到完整运行时选项(宿主可只传需要覆盖的字段)。 */
283
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
255
284
  function resolveRuntimeOptions$1(user = {}) {
256
- const manifestBaseRaw =
257
- user.manifestBase !== undefined && user.manifestBase !== ''
258
- ? String(user.manifestBase)
259
- : resolveBundledEnv('VITE_FRONTEND_PLUGIN_BASE', DEF.manifestBase) || DEF.manifestBase;
260
-
261
- const manifestListPath = ensureLeadingPath(
262
- user.manifestListPath !== undefined && user.manifestListPath !== ''
263
- ? user.manifestListPath
264
- : resolveBundledEnv('VITE_WEB_PLUGIN_MANIFEST_PATH', DEF.manifestListPath)
265
- );
266
-
267
- const defaultImplicitDevPluginIds = Array.isArray(user.defaultImplicitDevPluginIds)
268
- ? user.defaultImplicitDevPluginIds.map(String).filter(Boolean)
269
- : (() => {
270
- const e = resolveBundledEnv('VITE_WEB_PLUGIN_IMPLICIT_DEV_IDS', '');
271
- if (e) {
272
- return e
273
- .split(',')
274
- .map((s) => s.trim())
275
- .filter(Boolean)
276
- }
277
- return [...DEF.defaultImplicitDevPluginIds]
278
- })();
279
-
280
- const allowedScriptHosts =
281
- Array.isArray(user.allowedScriptHosts) && user.allowedScriptHosts.length > 0
282
- ? user.allowedScriptHosts.map((h) => normalizeHost(String(h))).filter(Boolean)
283
- : (() => {
284
- const e = resolveBundledEnv('VITE_WEB_PLUGIN_ALLOWED_SCRIPT_HOSTS', '');
285
- if (e) {
286
- return e
287
- .split(',')
288
- .map((s) => normalizeHost(s.trim()))
289
- .filter(Boolean)
290
- }
291
- return [...DEF.allowedScriptHosts]
285
+ const manifestBaseRaw = user.manifestBase !== undefined && user.manifestBase !== ''
286
+ ? String(user.manifestBase)
287
+ : resolveBundledEnv(EK.manifestBase, DEF.manifestBase) || DEF.manifestBase;
288
+ const manifestListPath = ensureLeadingPath(user.manifestListPath !== undefined && user.manifestListPath !== ''
289
+ ? user.manifestListPath
290
+ : resolveBundledEnv(EK.manifestListPath, DEF.manifestListPath));
291
+ const defaultImplicitDevPluginIds = Array.isArray(user.defaultImplicitDevPluginIds)
292
+ ? user.defaultImplicitDevPluginIds.map(String).filter(Boolean)
293
+ : (() => {
294
+ const e = resolveBundledEnv(EK.implicitDevIds, '');
295
+ if (e) {
296
+ return e
297
+ .split(',')
298
+ .map((s) => s.trim())
299
+ .filter(Boolean);
300
+ }
301
+ return [...DEF.defaultImplicitDevPluginIds];
292
302
  })();
293
-
294
- const bridgeAllowedPathPrefixes =
295
- Array.isArray(user.bridgeAllowedPathPrefixes) && user.bridgeAllowedPathPrefixes.length > 0
296
- ? user.bridgeAllowedPathPrefixes.map((p) => ensureLeadingPath(p)).filter(Boolean)
297
- : (() => {
298
- const e = resolveBundledEnv('VITE_WEB_PLUGIN_BRIDGE_PREFIXES', '');
299
- if (e) {
300
- return e
301
- .split(',')
302
- .map((s) => ensureLeadingPath(s.trim()))
303
- .filter(Boolean)
304
- }
305
- return [...DEF.bridgeAllowedPathPrefixes]
303
+ const allowedScriptHosts = Array.isArray(user.allowedScriptHosts) && user.allowedScriptHosts.length > 0
304
+ ? user.allowedScriptHosts.map((h) => normalizeHost(String(h))).filter(Boolean)
305
+ : (() => {
306
+ const e = resolveBundledEnv(EK.allowedScriptHosts, '');
307
+ if (e) {
308
+ return e
309
+ .split(',')
310
+ .map((s) => normalizeHost(s.trim()))
311
+ .filter(Boolean);
312
+ }
313
+ return [...DEF.allowedScriptHosts];
306
314
  })();
307
-
308
- return {
309
- manifestBase: manifestBaseRaw.replace(/\/$/, '') || DEF.manifestBase.replace(/\/$/, ''),
310
- manifestListPath,
311
- manifestFetchCredentials: resolveManifestCredentials(
312
- user.manifestFetchCredentials,
313
- 'VITE_WEB_PLUGIN_MANIFEST_CREDENTIALS',
314
- DEF.manifestFetchCredentials
315
- ),
316
- isDev: user.isDev !== undefined ? user.isDev : resolveBundledIsDev(),
317
- webPluginDevOrigin:
318
- user.webPluginDevOrigin !== undefined ? user.webPluginDevOrigin : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_ORIGIN', ''),
319
- webPluginDevIds:
320
- user.webPluginDevIds !== undefined ? user.webPluginDevIds : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_IDS', ''),
321
- webPluginDevMapJson:
322
- user.webPluginDevMapJson !== undefined
323
- ? user.webPluginDevMapJson
324
- : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_MAP', ''),
325
- webPluginDevEntryPath: ensureLeadingPath(
326
- user.webPluginDevEntryPath !== undefined && user.webPluginDevEntryPath !== ''
327
- ? user.webPluginDevEntryPath
328
- : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_ENTRY', DEF.webPluginDevEntryPath)
329
- ),
330
- devPingPath: ensureLeadingPath(
331
- user.devPingPath !== undefined && user.devPingPath !== ''
332
- ? user.devPingPath
333
- : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_PING_PATH', DEF.devPingPath)
334
- ),
335
- devReloadSsePath: ensureLeadingPath(
336
- user.devReloadSsePath !== undefined && user.devReloadSsePath !== ''
337
- ? user.devReloadSsePath
338
- : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_SSE_PATH', DEF.devReloadSsePath)
339
- ),
340
- devPingTimeoutMs: resolvePositiveInt(user.devPingTimeoutMs, 'VITE_WEB_PLUGIN_DEV_PING_TIMEOUT_MS', DEF.devPingTimeoutMs),
341
- defaultImplicitDevPluginIds,
342
- allowedScriptHosts,
343
- bridgeAllowedPathPrefixes,
344
- bootstrapSummary: user.bootstrapSummary,
345
- pluginRoutesParentName:
346
- user.pluginRoutesParentName !== undefined && String(user.pluginRoutesParentName).trim() !== ''
347
- ? String(user.pluginRoutesParentName).trim()
348
- : '',
349
- ...(typeof user.fetchManifest === 'function' ? { fetchManifest: user.fetchManifest } : {}),
350
- ...(typeof user.transformRoutes === 'function' ? { transformRoutes: user.transformRoutes } : {}),
351
- ...(typeof user.interceptRegisterRoutes === 'function'
352
- ? { interceptRegisterRoutes: user.interceptRegisterRoutes }
353
- : {}),
354
- ...(typeof user.adaptRouteDeclarations === 'function'
355
- ? { adaptRouteDeclarations: user.adaptRouteDeclarations }
356
- : {})
357
- }
315
+ const bridgeAllowedPathPrefixes = Array.isArray(user.bridgeAllowedPathPrefixes) && user.bridgeAllowedPathPrefixes.length > 0
316
+ ? user.bridgeAllowedPathPrefixes.map((p) => ensureLeadingPath(p)).filter(Boolean)
317
+ : (() => {
318
+ const e = resolveBundledEnv(EK.bridgePrefixes, '');
319
+ if (e) {
320
+ return e
321
+ .split(',')
322
+ .map((s) => ensureLeadingPath(s.trim()))
323
+ .filter(Boolean);
324
+ }
325
+ return [...DEF.bridgeAllowedPathPrefixes];
326
+ })();
327
+ const manifestMode = resolveManifestModeFromInputs(user.manifestMode);
328
+ const staticManifestUrl = resolveStaticManifestUrlFromInputs(user.staticManifestUrl);
329
+ const isDevResolved = user.isDev !== undefined ? user.isDev : resolveBundledIsDev();
330
+ const devFallbackStaticManifestUrl = (() => {
331
+ if (user.devFallbackStaticManifestUrl !== undefined && String(user.devFallbackStaticManifestUrl).trim() !== '') {
332
+ return String(user.devFallbackStaticManifestUrl).trim();
333
+ }
334
+ const e = resolveBundledEnv(EK.devFallbackManifestUrl, '');
335
+ if (e) {
336
+ return e.trim();
337
+ }
338
+ return String(DEF.devFallbackStaticManifestUrl).trim();
339
+ })();
340
+ const hostLayoutComponent = user.hostLayoutComponent;
341
+ const pluginRoutesParentName = (() => {
342
+ if (user.pluginRoutesParentName !== undefined) {
343
+ return String(user.pluginRoutesParentName).trim();
344
+ }
345
+ if (hostLayoutComponent != null) {
346
+ return String(DEF.pluginRoutesParentName).trim();
347
+ }
348
+ return '';
349
+ })();
350
+ const pluginMountRaw = user.pluginMountPath !== undefined && String(user.pluginMountPath).trim() !== ''
351
+ ? String(user.pluginMountPath).trim()
352
+ : String(resolveBundledEnv(EK.mountPath, '') || DEF.pluginMountPath).trim();
353
+ const pluginMountPath = ensureLeadingPath(pluginMountRaw || DEF.pluginMountPath);
354
+ const pluginHostRouteMeta = user.pluginHostRouteMeta !== undefined && user.pluginHostRouteMeta !== null
355
+ ? user.pluginHostRouteMeta
356
+ : undefined;
357
+ const ensurePluginHostRoute = user.ensurePluginHostRoute !== false;
358
+ const devManifestFallback = (() => {
359
+ if (manifestMode === 'static') {
360
+ return false;
361
+ }
362
+ if (user.devManifestFallback === false) {
363
+ return false;
364
+ }
365
+ if (user.devManifestFallback === true) {
366
+ return true;
367
+ }
368
+ const envFlag = resolveBundledEnv(EK.devManifestFallback, '');
369
+ if (envFlag === '0' || envFlag === 'false') {
370
+ return false;
371
+ }
372
+ if (envFlag === '1' || envFlag === 'true') {
373
+ return true;
374
+ }
375
+ return !!isDevResolved;
376
+ })();
377
+ return {
378
+ manifestBase: manifestBaseRaw.replace(/\/$/, '') || DEF.manifestBase.replace(/\/$/, ''),
379
+ manifestListPath,
380
+ manifestMode,
381
+ staticManifestUrl,
382
+ devManifestFallback,
383
+ devFallbackStaticManifestUrl,
384
+ manifestFetchCredentials: resolveManifestCredentials(user.manifestFetchCredentials, EK.manifestCredentials, DEF.manifestFetchCredentials),
385
+ isDev: isDevResolved,
386
+ webPluginDevOrigin: user.webPluginDevOrigin !== undefined
387
+ ? user.webPluginDevOrigin
388
+ : resolveBundledEnv(EK.webPluginDevOrigin, ''),
389
+ webPluginDevIds: user.webPluginDevIds !== undefined ? user.webPluginDevIds : resolveBundledEnv(EK.webPluginDevIds, ''),
390
+ webPluginDevMapJson: user.webPluginDevMapJson !== undefined
391
+ ? user.webPluginDevMapJson
392
+ : resolveBundledEnv(EK.webPluginDevMap, ''),
393
+ webPluginDevEntryPath: ensureLeadingPath(user.webPluginDevEntryPath !== undefined && user.webPluginDevEntryPath !== ''
394
+ ? user.webPluginDevEntryPath
395
+ : resolveBundledEnv(EK.devEntry, DEF.webPluginDevEntryPath)),
396
+ devPingPath: ensureLeadingPath(user.devPingPath !== undefined && user.devPingPath !== ''
397
+ ? user.devPingPath
398
+ : resolveBundledEnv(EK.devPing, DEF.devPingPath)),
399
+ devReloadSsePath: ensureLeadingPath(user.devReloadSsePath !== undefined && user.devReloadSsePath !== ''
400
+ ? user.devReloadSsePath
401
+ : resolveBundledEnv(EK.devSse, DEF.devReloadSsePath)),
402
+ devPingTimeoutMs: resolvePositiveInt(user.devPingTimeoutMs, EK.devPingTimeout, DEF.devPingTimeoutMs),
403
+ defaultImplicitDevPluginIds,
404
+ allowedScriptHosts,
405
+ bridgeAllowedPathPrefixes,
406
+ bootstrapSummary: user.bootstrapSummary,
407
+ hostLayoutComponent,
408
+ pluginMountPath,
409
+ pluginHostRouteMeta,
410
+ ensurePluginHostRoute,
411
+ pluginRoutesParentName,
412
+ ...(typeof user.fetchManifest === 'function' ? { fetchManifest: user.fetchManifest } : {}),
413
+ ...(typeof user.transformRoutes === 'function' ? { transformRoutes: user.transformRoutes } : {}),
414
+ ...(typeof user.interceptRegisterRoutes === 'function'
415
+ ? { interceptRegisterRoutes: user.interceptRegisterRoutes }
416
+ : {}),
417
+ ...(typeof user.adaptRouteDeclarations === 'function'
418
+ ? { adaptRouteDeclarations: user.adaptRouteDeclarations }
419
+ : {}),
420
+ ...(typeof user.applyPluginMenuItems === 'function'
421
+ ? { applyPluginMenuItems: user.applyPluginMenuItems }
422
+ : {}),
423
+ ...(typeof user.revokePluginMenuItems === 'function'
424
+ ? { revokePluginMenuItems: user.revokePluginMenuItems }
425
+ : {}),
426
+ ...(user.hostContext !== undefined &&
427
+ user.hostContext !== null &&
428
+ typeof user.hostContext === 'object' &&
429
+ !Array.isArray(user.hostContext)
430
+ ? { hostContext: user.hostContext }
431
+ : {}),
432
+ ...(typeof user.onBeforePluginActivate === 'function'
433
+ ? { onBeforePluginActivate: user.onBeforePluginActivate }
434
+ : {}),
435
+ ...(typeof user.onAfterPluginActivate === 'function'
436
+ ? { onAfterPluginActivate: user.onAfterPluginActivate }
437
+ : {}),
438
+ ...(typeof user.onPluginActivateError === 'function'
439
+ ? { onPluginActivateError: user.onPluginActivateError }
440
+ : {})
441
+ };
358
442
  }
359
443
 
360
444
  /**
361
- * 未配置 `fetchManifest` 时使用的清单 `fetch` 实现。
362
- * @param {{ manifestUrl: string, credentials: RequestCredentials }} ctx
445
+ * 将裸 `{ plugins }` `{ code, data: { plugins } }` 式响应解包为清单对象。
363
446
  */
447
+ function unwrapNestedManifestBody(body) {
448
+ if (!body || typeof body !== 'object') {
449
+ return null;
450
+ }
451
+ const o = body;
452
+ if (Array.isArray(o.plugins)) {
453
+ return o;
454
+ }
455
+ const d = o.data;
456
+ if (d && typeof d === 'object') {
457
+ const inner = d;
458
+ if (Array.isArray(inner.plugins)) {
459
+ return inner;
460
+ }
461
+ if ('plugins' in inner) {
462
+ return inner;
463
+ }
464
+ }
465
+ return d !== undefined && d !== null && typeof d === 'object' ? d : o;
466
+ }
467
+
364
468
  async function defaultFetchWebPluginManifest$1(ctx) {
365
- const { manifestUrl, credentials } = ctx;
366
- try {
367
- const res = await fetch(manifestUrl, { credentials });
368
- if (!res.ok) {
369
- return { ok: false, status: res.status, data: null }
469
+ const { manifestUrl, credentials } = ctx;
470
+ try {
471
+ const res = await fetch(manifestUrl, { credentials });
472
+ if (!res.ok) {
473
+ return { ok: false, status: res.status, data: null };
474
+ }
475
+ const body = await res.json();
476
+ const data = unwrapNestedManifestBody(body);
477
+ if (!data || typeof data !== 'object') {
478
+ return {
479
+ ok: false,
480
+ error: new Error('[wep] invalid manifest response body'),
481
+ data: null
482
+ };
483
+ }
484
+ return { ok: true, data };
485
+ }
486
+ catch (e) {
487
+ return { ok: false, error: e, data: null };
370
488
  }
371
- const data = await res.json();
372
- return { ok: true, data }
373
- } catch (e) {
374
- return { ok: false, error: e, data: null }
375
- }
376
489
  }
377
490
 
378
491
  function getDefaultExportFromCjs (x) {
@@ -3100,1337 +3213,1349 @@ function requireSemver () {
3100
3213
  var semverExports = requireSemver();
3101
3214
  var semver = /*@__PURE__*/getDefaultExportFromCjs(semverExports);
3102
3215
 
3103
- /** 与清单服务 `hostPluginApiVersion` 对齐,用于 `semver` 校验。 */
3104
- const HOST_PLUGIN_API_VERSION = '1.0.0';
3105
-
3106
- /** 控制台日志与横幅使用的短名称。 */
3107
- const RUNTIME_CONSOLE_LABEL = 'web-extend-plugin-vue2';
3108
-
3109
3216
  /**
3110
- * 开发模式插件 URL 映射(显式 JSON + 隐式 dev 探测)。
3111
- * @module runtime/dev-map
3217
+ * `disposeWebPlugin` 使用的菜单撤销钩子:在 `bootstrapPlugins` 中用 `resolveRuntimeOptions` 结果注册。
3112
3218
  */
3219
+ let revokePluginMenuItems;
3220
+ function setRevokePluginMenuItems(fn) {
3221
+ revokePluginMenuItems = fn;
3222
+ }
3223
+ function revokePluginMenusIfConfigured(pluginId) {
3224
+ if (typeof revokePluginMenuItems === 'function') {
3225
+ try {
3226
+ revokePluginMenuItems(pluginId);
3227
+ }
3228
+ catch (e) {
3229
+ console.warn('[wep] revokePluginMenuItems failed', pluginId, e);
3230
+ }
3231
+ }
3232
+ }
3113
3233
 
3114
3234
  /**
3115
- * @param {{ isDev: boolean, webPluginDevMapJson?: string|null }} opts
3235
+ * 开发模式插件 URL 映射(显式 JSON + 隐式 dev 探测)。
3116
3236
  */
3117
3237
  function parseWebPluginDevMapExplicit(opts) {
3118
- if (!opts.isDev) {
3119
- return null
3120
- }
3121
- const raw = opts.webPluginDevMapJson;
3122
- if (raw === undefined || raw === null || String(raw).trim() === '') {
3123
- return null
3124
- }
3125
- try {
3126
- const map = JSON.parse(String(raw));
3127
- return map && typeof map === 'object' ? map : null
3128
- } catch {
3129
- console.warn('[wep] invalid webPluginDevMapJson / VITE_WEB_PLUGIN_DEV_MAP');
3130
- return null
3131
- }
3238
+ if (!opts.isDev) {
3239
+ return null;
3240
+ }
3241
+ const raw = opts.webPluginDevMapJson;
3242
+ if (raw === undefined || raw === null || String(raw).trim() === '') {
3243
+ return null;
3244
+ }
3245
+ try {
3246
+ const map = JSON.parse(String(raw));
3247
+ return map && typeof map === 'object' ? map : null;
3248
+ }
3249
+ catch {
3250
+ console.warn('[wep] invalid webPluginDevMapJson / VITE_WEB_PLUGIN_DEV_MAP');
3251
+ return null;
3252
+ }
3132
3253
  }
3133
-
3134
- /**
3135
- * @param {Record<string, string>} implicit
3136
- * @param {Record<string, string>|null} explicit
3137
- */
3138
3254
  function mergeDevMaps(implicit, explicit) {
3139
- const i = implicit && typeof implicit === 'object' ? implicit : {};
3140
- const e = explicit && typeof explicit === 'object' ? explicit : {};
3141
- return { ...i, ...e }
3255
+ const i = implicit && typeof implicit === 'object' ? implicit : {};
3256
+ const e = explicit && typeof explicit === 'object' ? explicit : {};
3257
+ return { ...i, ...e };
3142
3258
  }
3143
-
3144
- /**
3145
- * @param {object} opts
3146
- * @param {boolean} opts.isDev
3147
- * @param {string|undefined|null} opts.webPluginDevOrigin
3148
- * @param {string|undefined|null} opts.webPluginDevIds
3149
- * @param {string[]} opts.defaultImplicitDevPluginIds
3150
- * @param {string} opts.devPingPath
3151
- * @param {number} opts.devPingTimeoutMs
3152
- * @param {string} opts.webPluginDevEntryPath
3153
- * @param {Set<string>} hostSet
3154
- */
3155
3259
  async function buildImplicitWebPluginDevMap(opts, hostSet) {
3156
- if (!opts.isDev) {
3157
- return {}
3158
- }
3159
- const origin =
3160
- opts.webPluginDevOrigin === undefined || opts.webPluginDevOrigin === null
3161
- ? ''
3162
- : String(opts.webPluginDevOrigin).trim();
3163
- if (!origin) {
3164
- return {}
3165
- }
3166
- if (!isScriptHostAllowed(`${origin}/`, hostSet)) {
3167
- return {}
3168
- }
3169
-
3170
- const idsRaw = opts.webPluginDevIds;
3171
- const ids =
3172
- idsRaw !== undefined && idsRaw !== null && String(idsRaw).trim() !== ''
3173
- ? String(idsRaw)
3174
- .split(',')
3175
- .map((s) => s.trim())
3176
- .filter(Boolean)
3177
- : [...opts.defaultImplicitDevPluginIds];
3178
-
3179
- if (ids.length === 0) {
3180
- return {}
3181
- }
3182
-
3183
- const base = origin.replace(/\/$/, '');
3184
- const pingUrl = `${base}${opts.devPingPath}`;
3185
- try {
3186
- const ctrl = new AbortController();
3187
- const timer = setTimeout(() => ctrl.abort(), opts.devPingTimeoutMs);
3188
- const r = await fetch(pingUrl, {
3189
- mode: 'cors',
3190
- cache: 'no-store',
3191
- signal: ctrl.signal
3192
- });
3193
- clearTimeout(timer);
3194
- if (!r.ok) {
3195
- return {}
3260
+ if (!opts.isDev) {
3261
+ return {};
3262
+ }
3263
+ const origin = opts.webPluginDevOrigin === undefined || opts.webPluginDevOrigin === null
3264
+ ? ''
3265
+ : String(opts.webPluginDevOrigin).trim();
3266
+ if (!origin) {
3267
+ return {};
3196
3268
  }
3197
- const body = (await r.text()).trim();
3198
- if (body !== 'ok') {
3199
- return {}
3269
+ if (!isScriptHostAllowed(`${origin}/`, hostSet)) {
3270
+ return {};
3200
3271
  }
3201
- } catch {
3202
- return {}
3203
- }
3204
-
3205
- const pathPart = opts.webPluginDevEntryPath;
3206
- const map = {};
3207
- for (const id of ids) {
3208
- map[id] = `${base}${pathPart}`;
3209
- }
3210
- if (ids.length) {
3211
- console.info('[wep] plugin dev server', base, '→ implicit entries', pathPart, ids.join(', '));
3212
- }
3213
- return map
3272
+ const idsRaw = opts.webPluginDevIds;
3273
+ const ids = idsRaw !== undefined && idsRaw !== null && String(idsRaw).trim() !== ''
3274
+ ? String(idsRaw)
3275
+ .split(',')
3276
+ .map((s) => s.trim())
3277
+ .filter(Boolean)
3278
+ : [...opts.defaultImplicitDevPluginIds];
3279
+ if (ids.length === 0) {
3280
+ return {};
3281
+ }
3282
+ const base = origin.replace(/\/$/, '');
3283
+ const pingUrl = `${base}${opts.devPingPath}`;
3284
+ try {
3285
+ const ctrl = new AbortController();
3286
+ const timer = setTimeout(() => ctrl.abort(), opts.devPingTimeoutMs);
3287
+ const r = await fetch(pingUrl, {
3288
+ mode: 'cors',
3289
+ cache: 'no-store',
3290
+ signal: ctrl.signal
3291
+ });
3292
+ clearTimeout(timer);
3293
+ if (!r.ok) {
3294
+ return {};
3295
+ }
3296
+ const body = (await r.text()).trim();
3297
+ if (body !== 'ok') {
3298
+ return {};
3299
+ }
3300
+ }
3301
+ catch {
3302
+ return {};
3303
+ }
3304
+ const pathPart = opts.webPluginDevEntryPath;
3305
+ const map = {};
3306
+ for (const id of ids) {
3307
+ map[id] = `${base}${pathPart}`;
3308
+ }
3309
+ if (ids.length) {
3310
+ console.info('[wep] plugin dev server', base, '→ implicit entries', pathPart, ids.join(', '));
3311
+ }
3312
+ return map;
3214
3313
  }
3215
3314
 
3216
3315
  /**
3217
3316
  * 开发模式下插件热更新 SSE(按 dev 映射中的 origin 连接)。
3218
- * @module runtime/dev-reload-sse
3219
3317
  */
3220
-
3221
- /** @type {Map<string, EventSource>} */
3222
3318
  const pluginDevEventSources = new Map();
3223
-
3224
3319
  let pluginDevBeforeUnloadRegistered = false;
3225
-
3226
3320
  function closeAllPluginDevEventSources() {
3227
- for (const es of pluginDevEventSources.values()) {
3228
- try {
3229
- es.close();
3230
- } catch (_) {}
3231
- }
3232
- pluginDevEventSources.clear();
3321
+ for (const es of pluginDevEventSources.values()) {
3322
+ try {
3323
+ es.close();
3324
+ }
3325
+ catch {
3326
+ /* ignore */
3327
+ }
3328
+ }
3329
+ pluginDevEventSources.clear();
3233
3330
  }
3234
-
3235
3331
  function ensurePluginDevBeforeUnload() {
3236
- if (pluginDevBeforeUnloadRegistered || typeof window === 'undefined') {
3237
- return
3238
- }
3239
- pluginDevBeforeUnloadRegistered = true;
3240
- window.addEventListener('beforeunload', closeAllPluginDevEventSources);
3332
+ if (pluginDevBeforeUnloadRegistered || typeof window === 'undefined') {
3333
+ return;
3334
+ }
3335
+ pluginDevBeforeUnloadRegistered = true;
3336
+ window.addEventListener('beforeunload', closeAllPluginDevEventSources);
3241
3337
  }
3242
-
3243
- /**
3244
- * @param {string} origin
3245
- * @param {Set<string>} hostSet
3246
- */
3247
3338
  function isDevOriginAllowedForSse(origin, hostSet) {
3248
- try {
3249
- const u = new URL(origin);
3250
- return hostSet.has(normalizeHost(u.hostname))
3251
- } catch {
3252
- return false
3253
- }
3339
+ try {
3340
+ const u = new URL(origin);
3341
+ return hostSet.has(normalizeHost(u.hostname));
3342
+ }
3343
+ catch {
3344
+ return false;
3345
+ }
3254
3346
  }
3255
-
3256
- /**
3257
- * @param {string} origin
3258
- * @param {boolean} isDev
3259
- * @param {Set<string>} hostSet
3260
- * @param {string} ssePath
3261
- */
3262
3347
  function startPluginDevReloadSse(origin, isDev, hostSet, ssePath) {
3263
- if (!isDev || pluginDevEventSources.has(origin)) {
3264
- return
3265
- }
3266
- if (!isDevOriginAllowedForSse(origin, hostSet)) {
3267
- return
3268
- }
3269
- ensurePluginDevBeforeUnload();
3270
- const base = origin.replace(/\/$/, '');
3271
- const url = `${base}${ssePath}`;
3272
- try {
3273
- const es = new EventSource(url);
3274
- pluginDevEventSources.set(origin, es);
3275
- es.addEventListener('reload', () => {
3276
- window.location.reload();
3277
- });
3278
- es.onopen = () => {
3279
- console.info('[wep] dev reload SSE', url);
3280
- };
3281
- } catch (e) {
3282
- console.warn('[wep] EventSource failed', url, e);
3283
- }
3348
+ if (!isDev || pluginDevEventSources.has(origin)) {
3349
+ return;
3350
+ }
3351
+ if (!isDevOriginAllowedForSse(origin, hostSet)) {
3352
+ return;
3353
+ }
3354
+ ensurePluginDevBeforeUnload();
3355
+ const base = origin.replace(/\/$/, '');
3356
+ const url = `${base}${ssePath}`;
3357
+ try {
3358
+ const es = new EventSource(url);
3359
+ pluginDevEventSources.set(origin, es);
3360
+ es.addEventListener('reload', () => {
3361
+ window.location.reload();
3362
+ });
3363
+ es.onopen = () => {
3364
+ console.info('[wep] dev reload SSE', url);
3365
+ };
3366
+ }
3367
+ catch (e) {
3368
+ console.warn('[wep] EventSource failed', url, e);
3369
+ }
3284
3370
  }
3285
-
3286
- /**
3287
- * @param {Record<string, string>|null|undefined} devMap
3288
- * @param {boolean} isDev
3289
- * @param {Set<string>} hostSet
3290
- * @param {string} ssePath
3291
- */
3292
3371
  function startPluginDevSseForMap(devMap, isDev, hostSet, ssePath) {
3293
- if (!isDev || !devMap || typeof window === 'undefined') {
3294
- return
3295
- }
3296
- const origins = new Set();
3297
- for (const entry of Object.values(devMap)) {
3298
- if (typeof entry !== 'string') {
3299
- continue
3372
+ if (!isDev || !devMap || typeof window === 'undefined') {
3373
+ return;
3300
3374
  }
3301
- const t = entry.trim();
3302
- if (!t) {
3303
- continue
3375
+ const origins = new Set();
3376
+ for (const entry of Object.values(devMap)) {
3377
+ if (typeof entry !== 'string') {
3378
+ continue;
3379
+ }
3380
+ const t = entry.trim();
3381
+ if (!t) {
3382
+ continue;
3383
+ }
3384
+ try {
3385
+ origins.add(new URL(t, window.location.href).origin);
3386
+ }
3387
+ catch {
3388
+ /* skip */
3389
+ }
3304
3390
  }
3305
- try {
3306
- origins.add(new URL(t, window.location.href).origin);
3307
- } catch {
3308
- /* skip */
3391
+ for (const o of origins) {
3392
+ startPluginDevReloadSse(o, isDev, hostSet, ssePath);
3309
3393
  }
3310
- }
3311
- for (const o of origins) {
3312
- startPluginDevReloadSse(o, isDev, hostSet, ssePath);
3313
- }
3314
3394
  }
3315
3395
 
3316
3396
  /**
3317
3397
  * 动态加载脚本(去重与并发合并)。
3318
- * @module runtime/load-script
3319
3398
  */
3320
-
3321
3399
  const loadScriptMemo = new Map();
3322
-
3323
- /**
3324
- * @param {string} src
3325
- * @returns {Promise<void>}
3326
- */
3327
3400
  function loadScript(src) {
3328
- if (typeof document === 'undefined') {
3329
- return Promise.reject(new Error('loadScript: no document'))
3330
- }
3331
- if (loadScriptMemo.has(src)) {
3332
- return loadScriptMemo.get(src)
3333
- }
3334
- const p = new Promise((resolve, reject) => {
3335
- const scripts = document.getElementsByTagName('script');
3336
- for (let i = 0; i < scripts.length; i++) {
3337
- const el = scripts[i];
3338
- if (el.src === src) {
3339
- if (el.getAttribute('data-wep-loaded') === 'true') {
3340
- resolve();
3341
- return
3401
+ if (typeof document === 'undefined') {
3402
+ return Promise.reject(new Error('loadScript: no document'));
3403
+ }
3404
+ if (loadScriptMemo.has(src)) {
3405
+ return loadScriptMemo.get(src);
3406
+ }
3407
+ const p = new Promise((resolve, reject) => {
3408
+ const scripts = document.getElementsByTagName('script');
3409
+ for (let i = 0; i < scripts.length; i++) {
3410
+ const el = scripts[i];
3411
+ if (el.src === src) {
3412
+ if (el.getAttribute('data-wep-loaded') === 'true') {
3413
+ resolve();
3414
+ return;
3415
+ }
3416
+ el.addEventListener('load', () => {
3417
+ el.setAttribute('data-wep-loaded', 'true');
3418
+ resolve();
3419
+ }, { once: true });
3420
+ el.addEventListener('error', () => reject(new Error('loadScript failed: ' + src)), { once: true });
3421
+ return;
3422
+ }
3342
3423
  }
3343
- el.addEventListener(
3344
- 'load',
3345
- () => {
3346
- el.setAttribute('data-wep-loaded', 'true');
3424
+ const s = document.createElement('script');
3425
+ s.async = true;
3426
+ s.src = src;
3427
+ s.onload = () => {
3428
+ s.setAttribute('data-wep-loaded', 'true');
3347
3429
  resolve();
3348
- },
3349
- { once: true }
3350
- );
3351
- el.addEventListener('error', () => reject(new Error('loadScript failed: ' + src)), { once: true });
3352
- return
3353
- }
3354
- }
3355
- const s = document.createElement('script');
3356
- s.async = true;
3357
- s.src = src;
3358
- s.onload = () => {
3359
- s.setAttribute('data-wep-loaded', 'true');
3360
- resolve();
3361
- };
3362
- s.onerror = () => reject(new Error('loadScript failed: ' + src));
3363
- document.head.appendChild(s);
3364
- });
3365
- loadScriptMemo.set(src, p);
3366
- p.catch(() => loadScriptMemo.delete(src));
3367
- return p
3430
+ };
3431
+ s.onerror = () => reject(new Error('loadScript failed: ' + src));
3432
+ document.head.appendChild(s);
3433
+ });
3434
+ loadScriptMemo.set(src, p);
3435
+ p.catch(() => loadScriptMemo.delete(src));
3436
+ return p;
3368
3437
  }
3369
3438
 
3370
3439
  let _printed = false;
3371
-
3372
3440
  /** 在首次引导插件时打印一行运行时标识(非大块 ASCII art)。 */
3373
3441
  function printRuntimeBannerOnce() {
3374
- if (_printed) {
3375
- return
3376
- }
3377
- _printed = true;
3378
- if (typeof console !== 'undefined' && typeof console.info === 'function') {
3379
- console.info(`[wep] ${RUNTIME_CONSOLE_LABEL} · host API ${HOST_PLUGIN_API_VERSION}`);
3380
- }
3442
+ if (_printed) {
3443
+ return;
3444
+ }
3445
+ _printed = true;
3446
+ if (typeof console !== 'undefined' && typeof console.info === 'function') {
3447
+ console.info(`[wep] ${RUNTIME_CONSOLE_LABEL} · host API ${HOST_PLUGIN_API_VERSION}`);
3448
+ }
3381
3449
  }
3382
3450
 
3383
3451
  /**
3384
- * 拉取插件清单、加载入口脚本并调用各插件 `activator`。
3452
+ * 浏览器 fetch 静态 JSON 清单(与 defaultFetchWebPluginManifest 相同解包规则)。
3385
3453
  */
3454
+ async function fetchStaticManifestViaHttp(ctx) {
3455
+ const { manifestUrl, credentials } = ctx;
3456
+ try {
3457
+ const creds = credentials === 'omit' ? 'omit' : 'same-origin';
3458
+ const res = await fetch(manifestUrl, {
3459
+ method: 'GET',
3460
+ credentials: creds,
3461
+ cache: 'no-store'
3462
+ });
3463
+ if (!res.ok) {
3464
+ return {
3465
+ ok: false,
3466
+ status: res.status,
3467
+ error: new Error('[wep] static manifest HTTP ' + res.status),
3468
+ data: null
3469
+ };
3470
+ }
3471
+ const body = await res.json();
3472
+ const data = unwrapNestedManifestBody(body);
3473
+ if (!data || typeof data !== 'object') {
3474
+ return {
3475
+ ok: false,
3476
+ error: new Error('[wep] invalid static manifest JSON'),
3477
+ data: null
3478
+ };
3479
+ }
3480
+ return { ok: true, data };
3481
+ }
3482
+ catch (e) {
3483
+ return { ok: false, error: e, data: null };
3484
+ }
3485
+ }
3386
3486
 
3387
3487
  /**
3388
- * @param {import('./resolve-runtime-options.js').WebExtendPluginRuntimeOptions|object} opts
3488
+ * 开箱:在未手工配置时,注册 `/plugin` + 宿主 Layout 的命名父路由,供 `router.addRoute(parentName, child)` 挂载插件页。
3389
3489
  */
3390
- function shouldShowBootstrapSummary(opts) {
3391
- if (opts.bootstrapSummary === true) {
3392
- return true
3393
- }
3394
- if (opts.bootstrapSummary === false) {
3395
- return false
3396
- }
3397
- const env = resolveBundledEnv('VITE_PLUGINS_BOOTSTRAP_SUMMARY', '');
3398
- if (env === '0' || env === 'false') {
3399
- return false
3400
- }
3401
- if (env === '1' || env === 'true') {
3402
- return true
3403
- }
3404
- return resolveBundledIsDev()
3490
+ function routeNameExists(router, name) {
3491
+ if (!name) {
3492
+ return false;
3493
+ }
3494
+ if (typeof router.getRoutes === 'function') {
3495
+ return router.getRoutes().some((r) => r.name === name);
3496
+ }
3497
+ return walkRouteNames(router.options && router.options.routes, name);
3498
+ }
3499
+ function walkRouteNames(routes, name) {
3500
+ if (!Array.isArray(routes)) {
3501
+ return false;
3502
+ }
3503
+ for (const r of routes) {
3504
+ if (r && typeof r === 'object' && r.name === name) {
3505
+ return true;
3506
+ }
3507
+ const ch = r && typeof r === 'object' ? r.children : null;
3508
+ if (walkRouteNames(ch, name)) {
3509
+ return true;
3510
+ }
3511
+ }
3512
+ return false;
3513
+ }
3514
+ function ensurePluginHostRoute$1(router, opts) {
3515
+ if (opts.ensurePluginHostRoute === false) {
3516
+ return;
3517
+ }
3518
+ if (!router || typeof router.addRoute !== 'function') {
3519
+ return;
3520
+ }
3521
+ const parentName = String(opts.pluginRoutesParentName || '').trim();
3522
+ if (!parentName) {
3523
+ return;
3524
+ }
3525
+ if (routeNameExists(router, parentName)) {
3526
+ return;
3527
+ }
3528
+ const Layout = opts.hostLayoutComponent;
3529
+ if (!Layout) {
3530
+ console.warn('[wep] 缺少 hostLayoutComponent,未自动注册插件壳路由;请传入宿主 Layout,或在路由表中自行配置与 pluginRoutesParentName 一致的父路由');
3531
+ return;
3532
+ }
3533
+ const mountDefault = defaultWebExtendPluginRuntime.pluginMountPath;
3534
+ let pathRaw = String(opts.pluginMountPath || mountDefault).trim().replace(/\/$/, '') || mountDefault;
3535
+ if (!pathRaw.startsWith('/')) {
3536
+ pathRaw = `/${pathRaw}`;
3537
+ }
3538
+ const meta = opts.pluginHostRouteMeta && typeof opts.pluginHostRouteMeta === 'object'
3539
+ ? { ...opts.pluginHostRouteMeta }
3540
+ : { requiresConfig: true, hidden: true };
3541
+ router.addRoute({
3542
+ path: pathRaw,
3543
+ name: parentName,
3544
+ component: Layout,
3545
+ redirect: 'noredirect',
3546
+ meta,
3547
+ children: []
3548
+ });
3405
3549
  }
3406
3550
 
3407
3551
  /**
3408
- * @param {{ id: string }} p
3409
- * @param {string} [entryUrl]
3410
- * @param {Record<string, string>|null|undefined} devMap
3411
- * @param {Set<string>} hostSet
3552
+ * 宿主通过 `resolveRuntimeOptions({ hostContext })` 注入的只读上下文,
3553
+ * 经浅拷贝 + 浅冻结后挂到 `hostApi.hostContext`,供插件访问 store/i18n 等而不污染 HostApi 顶层命名。
3412
3554
  */
3413
- async function loadPluginEntry(p, entryUrl, devMap, hostSet) {
3414
- const devEntry = devMap && typeof devMap[p.id] === 'string' ? devMap[p.id].trim() : '';
3415
- if (devEntry) {
3416
- if (!isScriptHostAllowed(devEntry, hostSet)) {
3417
- console.warn('[wep] dev entry URL not allowed', p.id, devEntry);
3418
- return
3555
+ function freezeShallowHostContext(input) {
3556
+ if (input == null || typeof input !== 'object' || Array.isArray(input)) {
3557
+ return Object.freeze({});
3558
+ }
3559
+ return Object.freeze({ ...input });
3560
+ }
3561
+
3562
+ /**
3563
+ * 将静态清单配置路径解析为用于 fetch 的绝对 URL(浏览器)。
3564
+ */
3565
+ function resolveStaticManifestUrlForFetch(url, origin) {
3566
+ const u = String(url || '').trim();
3567
+ if (!u) {
3568
+ return '';
3569
+ }
3570
+ if (/^https?:\/\//i.test(u)) {
3571
+ return u;
3572
+ }
3573
+ const o = String(origin || '').trim();
3574
+ if (!o) {
3575
+ return u.startsWith('/') ? u : `/${u}`;
3419
3576
  }
3420
3577
  try {
3421
- await import(
3422
- /* webpackIgnore: true */
3423
- /* @vite-ignore */
3424
- devEntry
3425
- );
3426
- } catch (e) {
3427
- console.warn('[wep] dev import failed, trying manifest entryUrl', p.id, e);
3428
- if (entryUrl && isScriptHostAllowed(entryUrl, hostSet)) {
3429
- await loadScript(entryUrl);
3430
- }
3431
- return
3578
+ const pathPart = u.startsWith('/') ? u : `/${u}`;
3579
+ return new URL(pathPart, o).href;
3580
+ }
3581
+ catch {
3582
+ return u;
3432
3583
  }
3433
- return
3434
- }
3435
- if (!entryUrl || !isScriptHostAllowed(entryUrl, hostSet)) {
3436
- console.warn('[wep] skip (entryUrl not allowed)', p.id, entryUrl);
3437
- return
3438
- }
3439
- await loadScript(entryUrl);
3440
3584
  }
3441
3585
 
3442
3586
  /**
3443
- * @param {import('vue-router').default} router
3444
- * @param {(pluginId: string, router: import('vue-router').default, hostKit?: object) => object} createHostApiFactory
3445
- * @param {import('./resolve-runtime-options.js').WebExtendPluginRuntimeOptions} [runtimeOptions]
3587
+ * 拉取插件清单、加载入口脚本并调用各插件 `activator`。
3446
3588
  */
3447
- async function bootstrapPlugins$1(router, createHostApiFactory, runtimeOptions) {
3448
- if (typeof window === 'undefined') {
3449
- console.warn('[wep] bootstrapPlugins skipped (no window)');
3450
- return
3451
- }
3452
- printRuntimeBannerOnce();
3453
- const opts = resolveRuntimeOptions$1(runtimeOptions || {});
3454
- const base = String(opts.manifestBase).replace(/\/$/, '');
3455
- const manifestUrl = `${base}${opts.manifestListPath}`;
3456
- const hostSet = buildAllowedScriptHostsSet(opts.allowedScriptHosts);
3457
- const explicit = parseWebPluginDevMapExplicit(opts);
3458
-
3459
- const manifestCtx = {
3460
- manifestUrl,
3461
- credentials: opts.manifestFetchCredentials
3462
- };
3463
- const [manifestResult, implicit] = await Promise.all([
3464
- (async () => {
3465
- try {
3466
- if (typeof opts.fetchManifest === 'function') {
3467
- return await opts.fetchManifest(manifestCtx)
3589
+ function shouldShowBootstrapSummary(opts) {
3590
+ if (opts.bootstrapSummary === true) {
3591
+ return true;
3592
+ }
3593
+ if (opts.bootstrapSummary === false) {
3594
+ return false;
3595
+ }
3596
+ const env = resolveBundledEnv(webExtendPluginEnvKeys.pluginsBootstrapSummary, '');
3597
+ if (env === '0' || env === 'false') {
3598
+ return false;
3599
+ }
3600
+ if (env === '1' || env === 'true') {
3601
+ return true;
3602
+ }
3603
+ return resolveBundledIsDev();
3604
+ }
3605
+ async function loadPluginEntry(p, entryUrl, devMap, hostSet) {
3606
+ const devEntry = devMap && typeof devMap[p.id] === 'string' ? devMap[p.id].trim() : '';
3607
+ if (devEntry) {
3608
+ if (!isScriptHostAllowed(devEntry, hostSet)) {
3609
+ console.warn('[wep] dev entry URL not allowed', p.id, devEntry);
3610
+ return;
3468
3611
  }
3469
- return await defaultFetchWebPluginManifest$1(manifestCtx)
3470
- } catch (e) {
3471
- return { ok: false, error: e, data: null }
3472
- }
3473
- })(),
3474
- buildImplicitWebPluginDevMap(opts, hostSet)
3475
- ]);
3476
-
3477
- const devMap = mergeDevMaps(implicit, explicit);
3478
- startPluginDevSseForMap(devMap, opts.isDev, hostSet, opts.devReloadSsePath);
3479
-
3480
- const hostKit = {
3481
- bridgeAllowedPathPrefixes: opts.bridgeAllowedPathPrefixes,
3482
- ...(opts.pluginRoutesParentName
3483
- ? { pluginRoutesParentName: opts.pluginRoutesParentName }
3484
- : {}),
3485
- ...(typeof opts.transformRoutes === 'function' ? { transformRoutes: opts.transformRoutes } : {}),
3486
- ...(typeof opts.interceptRegisterRoutes === 'function'
3487
- ? { interceptRegisterRoutes: opts.interceptRegisterRoutes }
3488
- : {}),
3489
- ...(typeof opts.adaptRouteDeclarations === 'function'
3490
- ? { adaptRouteDeclarations: opts.adaptRouteDeclarations }
3491
- : {})
3492
- };
3493
-
3494
- if (!manifestResult.ok) {
3495
- if (manifestResult.error) {
3496
- console.warn('[wep] fetch manifest failed', manifestResult.error);
3497
- } else {
3498
- console.warn('[wep] manifest HTTP', manifestResult.status, manifestUrl);
3612
+ try {
3613
+ await import(
3614
+ /* webpackIgnore: true */
3615
+ /* @vite-ignore */
3616
+ devEntry);
3617
+ }
3618
+ catch (e) {
3619
+ console.warn('[wep] dev import failed, trying manifest entryUrl', p.id, e);
3620
+ if (entryUrl && isScriptHostAllowed(entryUrl, hostSet)) {
3621
+ await loadScript(entryUrl);
3622
+ }
3623
+ return;
3624
+ }
3625
+ return;
3499
3626
  }
3500
- if (shouldShowBootstrapSummary(opts)) {
3501
- console.info('[wep] bootstrap_summary', { ok: false, reason: 'manifest_fetch' });
3627
+ if (!entryUrl || !isScriptHostAllowed(entryUrl, hostSet)) {
3628
+ console.warn('[wep] skip (entryUrl not allowed)', p.id, entryUrl);
3629
+ return;
3502
3630
  }
3503
- return
3504
- }
3505
- /** @type {{ hostPluginApiVersion?: string, plugins?: object[] }} */
3506
- const data = manifestResult.data;
3507
- if (!data) {
3508
- if (shouldShowBootstrapSummary(opts)) {
3509
- console.info('[wep] bootstrap_summary', { ok: false, reason: 'manifest_empty_body' });
3631
+ await loadScript(entryUrl);
3632
+ }
3633
+ async function bootstrapPlugins$1(
3634
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3635
+ router,
3636
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3637
+ createHostApiFactory, runtimeOptions) {
3638
+ if (typeof window === 'undefined') {
3639
+ console.warn('[wep] bootstrapPlugins skipped (no window)');
3640
+ return;
3510
3641
  }
3511
- return
3512
- }
3513
-
3514
- const apiVer = data.hostPluginApiVersion;
3515
- if (apiVer) {
3516
- const coerced = semver.coerce(apiVer);
3517
- const maj = coerced ? coerced.major : 0;
3518
- const range = `^${maj}.0.0`;
3519
- if (!semver.satisfies(HOST_PLUGIN_API_VERSION, range, { includePrerelease: true })) {
3520
- console.warn('[wep] host API version mismatch', {
3521
- host: HOST_PLUGIN_API_VERSION,
3522
- manifest: apiVer
3523
- });
3642
+ printRuntimeBannerOnce();
3643
+ const opts = resolveRuntimeOptions$1(runtimeOptions || {});
3644
+ setRevokePluginMenuItems(typeof opts.revokePluginMenuItems === 'function' ? opts.revokePluginMenuItems : undefined);
3645
+ ensurePluginHostRoute$1(router, opts);
3646
+ const base = String(opts.manifestBase).replace(/\/$/, '');
3647
+ const isStatic = opts.manifestMode === 'static';
3648
+ let manifestUrl;
3649
+ if (isStatic) {
3650
+ const raw = String(opts.staticManifestUrl || '').trim();
3651
+ if (!raw) {
3652
+ console.warn('[wep] manifestMode=static requires non-empty staticManifestUrl (or env VITE_WEB_PLUGIN_STATIC_MANIFEST_URL)');
3653
+ if (shouldShowBootstrapSummary(opts)) {
3654
+ console.info('[wep] bootstrap_summary', { ok: false, reason: 'static_manifest_url_missing' });
3655
+ }
3656
+ return;
3657
+ }
3658
+ manifestUrl = resolveStaticManifestUrlForFetch(raw, window.location.origin);
3524
3659
  }
3525
- }
3526
-
3527
- window.__PLUGIN_ACTIVATORS__ = window.__PLUGIN_ACTIVATORS__ || {};
3528
-
3529
- const plugins = data.plugins || [];
3530
- if (plugins.length === 0) {
3531
- console.info('[wep] empty plugin manifest — check backend and URL', manifestUrl);
3532
- }
3533
-
3534
- const summary = {
3535
- manifestCount: plugins.length,
3536
- activated: 0,
3537
- skipEngines: 0,
3538
- skipLoad: 0,
3539
- skipNoActivator: 0,
3540
- activateFail: 0
3541
- };
3542
-
3543
- for (const p of plugins) {
3544
- const range = p.engines && p.engines.host;
3545
- if (range && !semver.satisfies(HOST_PLUGIN_API_VERSION, range, { includePrerelease: true })) {
3546
- console.warn('[wep] skip plugin (engines.host)', p.id, range);
3547
- summary.skipEngines++;
3548
- continue
3660
+ else {
3661
+ manifestUrl = `${base}${opts.manifestListPath}`;
3549
3662
  }
3550
- const entryUrl = p.entryUrl;
3551
- try {
3552
- await loadPluginEntry(p, entryUrl, devMap, hostSet);
3553
- } catch (e) {
3554
- console.warn('[wep] script load failed', p.id, e);
3555
- summary.skipLoad++;
3556
- continue
3663
+ const hostSet = buildAllowedScriptHostsSet(opts.allowedScriptHosts);
3664
+ const explicit = parseWebPluginDevMapExplicit(opts);
3665
+ const manifestCtx = {
3666
+ manifestUrl,
3667
+ credentials: opts.manifestFetchCredentials
3668
+ };
3669
+ const [primaryResult, implicit] = await Promise.all([
3670
+ (async () => {
3671
+ try {
3672
+ if (typeof opts.fetchManifest === 'function') {
3673
+ return await opts.fetchManifest(manifestCtx);
3674
+ }
3675
+ return await defaultFetchWebPluginManifest$1(manifestCtx);
3676
+ }
3677
+ catch (e) {
3678
+ return { ok: false, error: e, data: null };
3679
+ }
3680
+ })(),
3681
+ buildImplicitWebPluginDevMap(opts, hostSet)
3682
+ ]);
3683
+ let manifestResult = primaryResult;
3684
+ let manifestUrlUsed = manifestUrl;
3685
+ if (!isStatic && opts.devManifestFallback && opts.isDev) {
3686
+ const dataObj = primaryResult.ok && primaryResult.data && typeof primaryResult.data === 'object'
3687
+ ? primaryResult.data
3688
+ : null;
3689
+ const plen = dataObj && Array.isArray(dataObj.plugins) ? dataObj.plugins.length : 0;
3690
+ const needFallback = !primaryResult.ok || plen === 0;
3691
+ const fallbackRaw = String(opts.devFallbackStaticManifestUrl || '').trim();
3692
+ if (needFallback && fallbackRaw) {
3693
+ const fallbackUrl = resolveStaticManifestUrlForFetch(fallbackRaw, window.location.origin);
3694
+ const fallbackCtx = {
3695
+ manifestUrl: fallbackUrl,
3696
+ credentials: opts.manifestFetchCredentials
3697
+ };
3698
+ const fr = await fetchStaticManifestViaHttp(fallbackCtx);
3699
+ const fdata = fr.ok && fr.data && typeof fr.data === 'object' ? fr.data : null;
3700
+ const flen = fdata && Array.isArray(fdata.plugins) ? fdata.plugins.length : 0;
3701
+ if (fr.ok && flen > 0) {
3702
+ manifestResult = fr;
3703
+ manifestUrlUsed = fallbackUrl;
3704
+ console.info('[wep] dev manifest fallback', { url: fallbackUrl, plugins: flen });
3705
+ }
3706
+ }
3557
3707
  }
3558
- const activator = window.__PLUGIN_ACTIVATORS__[p.id];
3559
- if (typeof activator !== 'function') {
3560
- console.warn('[wep] no activator for', p.id);
3561
- summary.skipNoActivator++;
3562
- continue
3708
+ const devMap = mergeDevMaps(implicit, explicit);
3709
+ startPluginDevSseForMap(devMap, opts.isDev, hostSet, opts.devReloadSsePath);
3710
+ const frozenHostContext = freezeShallowHostContext(opts.hostContext !== undefined ? opts.hostContext : undefined);
3711
+ const hostKit = {
3712
+ hostContext: frozenHostContext,
3713
+ bridgeAllowedPathPrefixes: opts.bridgeAllowedPathPrefixes,
3714
+ ...(opts.pluginRoutesParentName ? { pluginRoutesParentName: opts.pluginRoutesParentName } : {}),
3715
+ ...(typeof opts.transformRoutes === 'function' ? { transformRoutes: opts.transformRoutes } : {}),
3716
+ ...(typeof opts.interceptRegisterRoutes === 'function'
3717
+ ? { interceptRegisterRoutes: opts.interceptRegisterRoutes }
3718
+ : {}),
3719
+ ...(typeof opts.adaptRouteDeclarations === 'function'
3720
+ ? { adaptRouteDeclarations: opts.adaptRouteDeclarations }
3721
+ : {}),
3722
+ ...(typeof opts.applyPluginMenuItems === 'function'
3723
+ ? { applyPluginMenuItems: opts.applyPluginMenuItems }
3724
+ : {}),
3725
+ ...(typeof opts.revokePluginMenuItems === 'function'
3726
+ ? { revokePluginMenuItems: opts.revokePluginMenuItems }
3727
+ : {})
3728
+ };
3729
+ if (!manifestResult.ok) {
3730
+ if (manifestResult.error) {
3731
+ console.warn('[wep] fetch manifest failed', manifestResult.error);
3732
+ }
3733
+ else {
3734
+ const label = isStatic ? 'static manifest' : 'manifest HTTP';
3735
+ console.warn(`[wep] ${label}`, manifestResult.status, manifestUrlUsed);
3736
+ }
3737
+ if (shouldShowBootstrapSummary(opts)) {
3738
+ console.info('[wep] bootstrap_summary', { ok: false, reason: 'manifest_fetch' });
3739
+ }
3740
+ return;
3563
3741
  }
3564
- const hostApi = createHostApiFactory(p.id, router, hostKit);
3565
- try {
3566
- const pluginRecord = Object.freeze({ ...p });
3567
- activator(hostApi, { pluginRecord });
3568
- summary.activated++;
3569
- } catch (e) {
3570
- console.error('[wep] activate failed', p.id, e);
3571
- summary.activateFail++;
3742
+ const data = manifestResult.data;
3743
+ if (!data) {
3744
+ if (shouldShowBootstrapSummary(opts)) {
3745
+ console.info('[wep] bootstrap_summary', { ok: false, reason: 'manifest_empty_body' });
3746
+ }
3747
+ return;
3748
+ }
3749
+ const apiVer = data.hostPluginApiVersion;
3750
+ if (apiVer) {
3751
+ const coerced = semver.coerce(apiVer);
3752
+ const maj = coerced ? coerced.major : 0;
3753
+ const range = `^${maj}.0.0`;
3754
+ if (!semver.satisfies(HOST_PLUGIN_API_VERSION, range, { includePrerelease: true })) {
3755
+ console.warn('[wep] host API version mismatch', {
3756
+ host: HOST_PLUGIN_API_VERSION,
3757
+ manifest: apiVer
3758
+ });
3759
+ }
3760
+ }
3761
+ window.__PLUGIN_ACTIVATORS__ = window.__PLUGIN_ACTIVATORS__ || {};
3762
+ const plugins = data.plugins || [];
3763
+ if (plugins.length === 0) {
3764
+ const hint = isStatic ? 'check static JSON file and plugins[]' : 'check backend and URL';
3765
+ console.info('[wep] empty plugin manifest — ' + hint, manifestUrlUsed);
3766
+ }
3767
+ const summary = {
3768
+ manifestCount: plugins.length,
3769
+ activated: 0,
3770
+ skipEngines: 0,
3771
+ skipLoad: 0,
3772
+ skipNoActivator: 0,
3773
+ activateFail: 0
3774
+ };
3775
+ for (const p of plugins) {
3776
+ const range = p.engines && p.engines.host;
3777
+ if (range && !semver.satisfies(HOST_PLUGIN_API_VERSION, range, { includePrerelease: true })) {
3778
+ console.warn('[wep] skip plugin (engines.host)', p.id, range);
3779
+ summary.skipEngines++;
3780
+ continue;
3781
+ }
3782
+ const entryUrl = p.entryUrl;
3783
+ try {
3784
+ await loadPluginEntry(p, entryUrl, devMap, hostSet);
3785
+ }
3786
+ catch (e) {
3787
+ console.warn('[wep] script load failed', p.id, e);
3788
+ summary.skipLoad++;
3789
+ continue;
3790
+ }
3791
+ const activator = window.__PLUGIN_ACTIVATORS__[p.id];
3792
+ if (typeof activator !== 'function') {
3793
+ console.warn('[wep] no activator for', p.id);
3794
+ summary.skipNoActivator++;
3795
+ continue;
3796
+ }
3797
+ const pluginRecord = Object.freeze({ ...p });
3798
+ try {
3799
+ if (typeof opts.onBeforePluginActivate === 'function') {
3800
+ await Promise.resolve(opts.onBeforePluginActivate({
3801
+ pluginId: p.id,
3802
+ router,
3803
+ pluginRecord
3804
+ }));
3805
+ }
3806
+ }
3807
+ catch (e) {
3808
+ console.warn('[wep] activate skipped (onBeforePluginActivate)', p.id, e);
3809
+ summary.activateFail++;
3810
+ continue;
3811
+ }
3812
+ const hostApi = createHostApiFactory(p.id, router, hostKit);
3813
+ try {
3814
+ await Promise.resolve(activator(hostApi, { pluginRecord }));
3815
+ summary.activated++;
3816
+ if (typeof opts.onAfterPluginActivate === 'function') {
3817
+ await Promise.resolve(opts.onAfterPluginActivate({
3818
+ pluginId: p.id,
3819
+ router,
3820
+ pluginRecord,
3821
+ hostApi
3822
+ }));
3823
+ }
3824
+ }
3825
+ catch (e) {
3826
+ console.error('[wep] activate failed', p.id, e);
3827
+ summary.activateFail++;
3828
+ if (typeof opts.onPluginActivateError === 'function') {
3829
+ try {
3830
+ await Promise.resolve(opts.onPluginActivateError({
3831
+ pluginId: p.id,
3832
+ error: e,
3833
+ pluginRecord,
3834
+ hostApi
3835
+ }));
3836
+ }
3837
+ catch (hookErr) {
3838
+ console.warn('[wep] onPluginActivateError hook failed', p.id, hookErr);
3839
+ }
3840
+ }
3841
+ }
3842
+ }
3843
+ if (shouldShowBootstrapSummary(opts)) {
3844
+ console.info('[wep] bootstrap_summary', { ok: true, ...summary });
3572
3845
  }
3573
- }
3574
-
3575
- if (shouldShowBootstrapSummary(opts)) {
3576
- console.info('[wep] bootstrap_summary', { ok: true, ...summary });
3577
- }
3578
3846
  }
3579
3847
 
3580
3848
  /**
3581
- * 运行时引导相关 API 的聚合导出(实现位于 `./runtime/`)。
3849
+ * 运行时引导相关 API 的聚合导出。
3582
3850
  */
3583
3851
 
3584
3852
  var pluginRuntime = /*#__PURE__*/Object.freeze({
3585
- __proto__: null,
3586
- bootstrapPlugins: bootstrapPlugins$1,
3587
- defaultFetchWebPluginManifest: defaultFetchWebPluginManifest$1,
3588
- resolveRuntimeOptions: resolveRuntimeOptions$1
3853
+ __proto__: null,
3854
+ bootstrapPlugins: bootstrapPlugins$1,
3855
+ defaultFetchWebPluginManifest: defaultFetchWebPluginManifest$1,
3856
+ ensurePluginHostRoute: ensurePluginHostRoute$1,
3857
+ resolveRuntimeOptions: resolveRuntimeOptions$1
3589
3858
  });
3590
3859
 
3591
3860
  /**
3592
3861
  * 清单拉取函数的组合工具:缓存、埋点等以**中间件**形式扩展,不侵入 `bootstrapPlugins` 核心逻辑,
3593
3862
  * 可组合的 `fetchManifest` 包装;入参/出参与 `resolveRuntimeOptions({ fetchManifest })` 一致。
3594
- *
3595
- * @module runtime/manifest-fetch-composer
3596
- */
3597
-
3598
- /**
3599
- * @typedef {object} FetchWebPluginManifestContext
3600
- * @property {string} manifestUrl
3601
- * @property {RequestCredentials} credentials
3602
- */
3603
-
3604
- /**
3605
- * @typedef {object} FetchWebPluginManifestResult
3606
- * @property {boolean} ok
3607
- * @property {number} [status]
3608
- * @property {{ hostPluginApiVersion?: string, plugins?: object[] }|null} [data]
3609
- * @property {unknown} [error]
3610
- */
3611
-
3612
- /**
3613
- * @callback FetchWebPluginManifestFn
3614
- * @param {FetchWebPluginManifestContext} ctx
3615
- * @returns {Promise<FetchWebPluginManifestResult>}
3616
- */
3617
-
3618
- /**
3619
- * 将内层 `fetchManifest` 包装为带缓存的版本。等价于
3620
- * `composeManifestFetch(inner, manifestFetchCacheMiddleware(options))`。
3621
- *
3622
- * @param {FetchWebPluginManifestFn} inner 内层实现(如预设生成的 `fetchManifest` 或 `defaultFetchWebPluginManifest`)
3623
- * @param {ManifestFetchCacheOptions} [options]
3624
- * @returns {FetchWebPluginManifestFn}
3625
3863
  */
3626
3864
  function wrapManifestFetchWithCache$1(inner, options = {}) {
3627
- return composeManifestFetch$1(inner, manifestFetchCacheMiddleware$1(options))
3865
+ return composeManifestFetch$1(inner, manifestFetchCacheMiddleware$1(options));
3628
3866
  }
3629
-
3630
- /**
3631
- * @typedef {object} ManifestFetchCacheOptions
3632
- * @property {number} [ttlMs] 缓存时长(毫秒)。`<= 0` 或未传时**不缓存**(直接透传 `inner`)。
3633
- * @property {'memory'|'session'|'local'} [storage='memory'] `session`/`local` 依赖 `JSON.stringify`,仅适合可序列化的 `data`。
3634
- * @property {string} [storageKeyPrefix='wep.manifestFetch.v1'] Web Storage 键前缀(仅 storage 非 memory 时生效)。
3635
- * @property {(ctx: FetchWebPluginManifestContext) => string} [cacheKey] 默认 `manifestUrl + '\0' + credentials`。
3636
- * @property {(result: FetchWebPluginManifestResult) => boolean} [shouldCache] 默认:`ok === true` 且 `data` 非空。
3637
- * @property {number} [maxEntries=50] 仅 `memory`:超过条数时淘汰最久未读条目。
3638
- * @property {() => number} [now] 测试注入时间戳。
3639
- */
3640
-
3641
- /**
3642
- * 清单拉取**中间件工厂**:`next` 为内层 `fetchManifest`。
3643
- *
3644
- * @param {ManifestFetchCacheOptions} options
3645
- * @returns {(next: FetchWebPluginManifestFn) => FetchWebPluginManifestFn}
3646
- */
3647
3867
  function manifestFetchCacheMiddleware$1(options = {}) {
3648
- const ttlMs = typeof options.ttlMs === 'number' && Number.isFinite(options.ttlMs) ? options.ttlMs : 0;
3649
- if (ttlMs <= 0) {
3650
- return (next) => next
3651
- }
3652
-
3653
- const storage = options.storage || 'memory';
3654
- const prefix = options.storageKeyPrefix || 'wep.manifestFetch.v1';
3655
- const maxEntries = typeof options.maxEntries === 'number' && options.maxEntries > 0 ? options.maxEntries : 50;
3656
- const getNow = typeof options.now === 'function' ? options.now : () => Date.now();
3657
- const cacheKeyFn =
3658
- typeof options.cacheKey === 'function'
3659
- ? options.cacheKey
3660
- : (ctx) => `${String(ctx.manifestUrl)}\0${String(ctx.credentials)}`;
3661
-
3662
- const shouldCache =
3663
- typeof options.shouldCache === 'function'
3664
- ? options.shouldCache
3665
- : (r) => !!(r && r.ok === true && r.data != null);
3666
-
3667
- /** @type {Map<string, { expiresAt: number, result: FetchWebPluginManifestResult, lastRead: number }>} */
3668
- const memory = new Map();
3669
-
3670
- function cloneResult(r) {
3671
- try {
3672
- if (typeof structuredClone === 'function') {
3673
- return structuredClone(r)
3674
- }
3675
- } catch (_) {}
3676
- try {
3677
- return JSON.parse(JSON.stringify(r))
3678
- } catch (_) {
3679
- return { ...r, data: r.data }
3868
+ const ttlMs = typeof options.ttlMs === 'number' && Number.isFinite(options.ttlMs) ? options.ttlMs : 0;
3869
+ if (ttlMs <= 0) {
3870
+ return (next) => next;
3680
3871
  }
3681
- }
3682
-
3683
- function touchMemory(key) {
3684
- const e = memory.get(key);
3685
- if (e) {
3686
- e.lastRead = getNow();
3687
- }
3688
- }
3689
-
3690
- function pruneMemory() {
3691
- if (memory.size <= maxEntries) {
3692
- return
3693
- }
3694
- const entries = [...memory.entries()].sort((a, b) => a[1].lastRead - b[1].lastRead);
3695
- const drop = memory.size - maxEntries;
3696
- for (let i = 0; i < drop; i++) {
3697
- memory.delete(entries[i][0]);
3872
+ const storage = options.storage || 'memory';
3873
+ const prefix = options.storageKeyPrefix || defaultManifestFetchCache.storageKeyPrefix;
3874
+ const maxEntries = typeof options.maxEntries === 'number' && options.maxEntries > 0
3875
+ ? options.maxEntries
3876
+ : defaultManifestFetchCache.maxEntries;
3877
+ const getNow = typeof options.now === 'function' ? options.now : () => Date.now();
3878
+ const cacheKeyFn = typeof options.cacheKey === 'function'
3879
+ ? options.cacheKey
3880
+ : (ctx) => `${String(ctx.manifestUrl)}\0${String(ctx.credentials)}`;
3881
+ const shouldCache = typeof options.shouldCache === 'function'
3882
+ ? options.shouldCache
3883
+ : (r) => !!(r && r.ok === true && r.data != null);
3884
+ const memory = new Map();
3885
+ function cloneResult(r) {
3886
+ try {
3887
+ if (typeof structuredClone === 'function') {
3888
+ return structuredClone(r);
3889
+ }
3890
+ }
3891
+ catch {
3892
+ /* ignore */
3893
+ }
3894
+ try {
3895
+ return JSON.parse(JSON.stringify(r));
3896
+ }
3897
+ catch {
3898
+ return { ...r, data: r.data };
3899
+ }
3698
3900
  }
3699
- }
3700
-
3701
- function readWebStorage(store, key) {
3702
- try {
3703
- const raw = store.getItem(key);
3704
- if (!raw) {
3705
- return null
3706
- }
3707
- const o = JSON.parse(raw);
3708
- if (!o || typeof o !== 'object') {
3709
- return null
3710
- }
3711
- const exp = o.expiresAt;
3712
- const res = o.result;
3713
- if (typeof exp !== 'number' || getNow() > exp) {
3714
- store.removeItem(key);
3715
- return null
3716
- }
3717
- return /** @type {FetchWebPluginManifestResult} */ (res)
3718
- } catch (_) {
3719
- return null
3901
+ function touchMemory(key) {
3902
+ const e = memory.get(key);
3903
+ if (e) {
3904
+ e.lastRead = getNow();
3905
+ }
3720
3906
  }
3721
- }
3722
-
3723
- function writeWebStorage(store, key, result, expiresAt) {
3724
- try {
3725
- store.setItem(key, JSON.stringify({ expiresAt, result }));
3726
- } catch (_) {
3727
- /* Quota / 不可序列化 */
3907
+ function pruneMemory() {
3908
+ if (memory.size <= maxEntries) {
3909
+ return;
3910
+ }
3911
+ const entries = [...memory.entries()].sort((a, b) => a[1].lastRead - b[1].lastRead);
3912
+ const drop = memory.size - maxEntries;
3913
+ for (let i = 0; i < drop; i++) {
3914
+ memory.delete(entries[i][0]);
3915
+ }
3728
3916
  }
3729
- }
3730
-
3731
- return (next) => {
3732
- return async (ctx) => {
3733
- const key = cacheKeyFn(ctx);
3734
- const now = getNow();
3735
-
3736
- if (storage === 'memory') {
3737
- const hit = memory.get(key);
3738
- if (hit && hit.expiresAt > now) {
3739
- touchMemory(key);
3740
- return cloneResult(hit.result)
3917
+ function readWebStorage(store, key) {
3918
+ try {
3919
+ const raw = store.getItem(key);
3920
+ if (!raw) {
3921
+ return null;
3922
+ }
3923
+ const o = JSON.parse(raw);
3924
+ if (!o || typeof o !== 'object') {
3925
+ return null;
3926
+ }
3927
+ const exp = o.expiresAt;
3928
+ const res = o.result;
3929
+ if (typeof exp !== 'number' || getNow() > exp) {
3930
+ store.removeItem(key);
3931
+ return null;
3932
+ }
3933
+ return res;
3934
+ }
3935
+ catch {
3936
+ return null;
3741
3937
  }
3742
- } else if (storage === 'session' && typeof sessionStorage !== 'undefined') {
3743
- const sk = `${prefix}:${key}`;
3744
- const hit = readWebStorage(sessionStorage, sk);
3745
- if (hit) {
3746
- return cloneResult(hit)
3938
+ }
3939
+ function writeWebStorage(store, key, result, expiresAt) {
3940
+ try {
3941
+ store.setItem(key, JSON.stringify({ expiresAt, result }));
3747
3942
  }
3748
- } else if (storage === 'local' && typeof localStorage !== 'undefined') {
3749
- const sk = `${prefix}:${key}`;
3750
- const hit = readWebStorage(localStorage, sk);
3751
- if (hit) {
3752
- return cloneResult(hit)
3943
+ catch {
3944
+ /* Quota / 不可序列化 */
3753
3945
  }
3754
- }
3755
-
3756
- const result = await next(ctx);
3757
-
3758
- if (!shouldCache(result)) {
3759
- return result
3760
- }
3761
-
3762
- const expiresAt = now + ttlMs;
3763
- const frozen = cloneResult(result);
3764
-
3765
- if (storage === 'memory') {
3766
- memory.set(key, { expiresAt, result: frozen, lastRead: now });
3767
- pruneMemory();
3768
- } else if (storage === 'session' && typeof sessionStorage !== 'undefined') {
3769
- writeWebStorage(sessionStorage, `${prefix}:${key}`, frozen, expiresAt);
3770
- } else if (storage === 'local' && typeof localStorage !== 'undefined') {
3771
- writeWebStorage(localStorage, `${prefix}:${key}`, frozen, expiresAt);
3772
- }
3773
-
3774
- return result
3775
3946
  }
3776
- }
3947
+ return (next) => {
3948
+ return async (ctx) => {
3949
+ const key = cacheKeyFn(ctx);
3950
+ const now = getNow();
3951
+ if (storage === 'memory') {
3952
+ const hit = memory.get(key);
3953
+ if (hit && hit.expiresAt > now) {
3954
+ touchMemory(key);
3955
+ return cloneResult(hit.result);
3956
+ }
3957
+ }
3958
+ else if (storage === 'session' && typeof sessionStorage !== 'undefined') {
3959
+ const sk = `${prefix}:${key}`;
3960
+ const hit = readWebStorage(sessionStorage, sk);
3961
+ if (hit) {
3962
+ return cloneResult(hit);
3963
+ }
3964
+ }
3965
+ else if (storage === 'local' && typeof localStorage !== 'undefined') {
3966
+ const sk = `${prefix}:${key}`;
3967
+ const hit = readWebStorage(localStorage, sk);
3968
+ if (hit) {
3969
+ return cloneResult(hit);
3970
+ }
3971
+ }
3972
+ const result = await next(ctx);
3973
+ if (!shouldCache(result)) {
3974
+ return result;
3975
+ }
3976
+ const expiresAt = now + ttlMs;
3977
+ const frozen = cloneResult(result);
3978
+ if (storage === 'memory') {
3979
+ memory.set(key, { expiresAt, result: frozen, lastRead: now });
3980
+ pruneMemory();
3981
+ }
3982
+ else if (storage === 'session' && typeof sessionStorage !== 'undefined') {
3983
+ writeWebStorage(sessionStorage, `${prefix}:${key}`, frozen, expiresAt);
3984
+ }
3985
+ else if (storage === 'local' && typeof localStorage !== 'undefined') {
3986
+ writeWebStorage(localStorage, `${prefix}:${key}`, frozen, expiresAt);
3987
+ }
3988
+ return result;
3989
+ };
3990
+ };
3777
3991
  }
3778
-
3779
- /**
3780
- * 自右向左组合中间件(与 Koa/Redux 习惯一致:`compose(f,g,h)(inner)` = f(g(h(inner))))。
3781
- *
3782
- * @param {FetchWebPluginManifestFn} inner 最内层拉取实现
3783
- * @param {...function(FetchWebPluginManifestFn): FetchWebPluginManifestFn} middlewares 每个元素签名 `(next) => async (ctx) => result`
3784
- * @returns {FetchWebPluginManifestFn}
3785
- */
3786
3992
  function composeManifestFetch$1(inner, ...middlewares) {
3787
- if (typeof inner !== 'function') {
3788
- throw new Error('[web-extend-plugin-vue2] composeManifestFetch 需要 inner 为函数')
3789
- }
3790
- let f = inner;
3791
- for (let i = middlewares.length - 1; i >= 0; i--) {
3792
- const mw = middlewares[i];
3793
- if (typeof mw !== 'function') {
3794
- throw new Error('[web-extend-plugin-vue2] composeManifestFetch 中间件须为函数')
3993
+ if (typeof inner !== 'function') {
3994
+ throw new Error('[web-extend-plugin-vue2] composeManifestFetch 需要 inner 为函数');
3795
3995
  }
3796
- f = mw(f);
3797
- }
3798
- return f
3996
+ let f = inner;
3997
+ for (let i = middlewares.length - 1; i >= 0; i--) {
3998
+ const mw = middlewares[i];
3999
+ if (typeof mw !== 'function') {
4000
+ throw new Error('[web-extend-plugin-vue2] composeManifestFetch 中间件须为函数');
4001
+ }
4002
+ f = mw(f);
4003
+ }
4004
+ return f;
3799
4005
  }
3800
4006
 
3801
4007
  var manifestComposer = /*#__PURE__*/Object.freeze({
3802
- __proto__: null,
3803
- composeManifestFetch: composeManifestFetch$1,
3804
- manifestFetchCacheMiddleware: manifestFetchCacheMiddleware$1,
3805
- wrapManifestFetchWithCache: wrapManifestFetchWithCache$1
4008
+ __proto__: null,
4009
+ composeManifestFetch: composeManifestFetch$1,
4010
+ manifestFetchCacheMiddleware: manifestFetchCacheMiddleware$1,
4011
+ wrapManifestFetchWithCache: wrapManifestFetchWithCache$1
3806
4012
  });
3807
4013
 
3808
4014
  /**
3809
- * 插件访问后端的受控通道:`fetch` 仅允许落在配置的路径前缀下(默认 `/api/`),默认 `credentials: 'same-origin'`。
3810
- */
3811
-
3812
- /**
3813
- * @param {{ allowedPathPrefixes?: string[] }} [config]
3814
- */
3815
- function createRequestBridge(config = {}) {
3816
- const raw =
3817
- Array.isArray(config.allowedPathPrefixes) && config.allowedPathPrefixes.length > 0
3818
- ? config.allowedPathPrefixes
3819
- : defaultWebExtendPluginRuntime.bridgeAllowedPathPrefixes;
3820
- const allowedPathPrefixes = raw.map((p) => ensureLeadingPath(p));
3821
-
3822
- return {
3823
- /**
3824
- * @param {string} path 必须以 `/` 开头,且匹配某一白名单前缀
3825
- * @param {RequestInit} [init]
3826
- */
3827
- async request(path, init = {}) {
3828
- if (typeof path !== 'string' || !path.startsWith('/')) {
3829
- throw new Error('[wep:bridge] path must start with /')
3830
- }
3831
- const allowed = allowedPathPrefixes.some((p) => path.startsWith(p));
3832
- if (!allowed) {
3833
- throw new Error('[wep:bridge] path not allowed: ' + path)
3834
- }
3835
- return fetch(path, {
3836
- credentials: 'same-origin',
3837
- ...init
3838
- })
3839
- }
3840
- }
3841
- }
3842
-
3843
- /**
3844
- * 宿主侧响应式注册表:插件菜单与扩展点槽位(供布局与 `ExtensionPoint` 消费)。
3845
- */
3846
-
3847
- /**
3848
- * @type {{
3849
- * menus: object[],
3850
- * slots: Record<string, Array<{ pluginId: string, component: import('vue').Component, priority: number, key: string }>>
3851
- * }}
4015
+ * 宿主侧响应式注册表:扩展点槽位(供布局与 `ExtensionPoint` 消费)。
4016
+ * 菜单数据由宿主在 `applyPluginMenuItems` 中自行并入其路由/菜单 state,框架不维护平行菜单列表。
3852
4017
  */
3853
4018
  const registries = Vue.observable({
3854
- menus: [],
3855
- slots: {},
3856
- /** 槽位变更计数;缓解 Vue2 对动态 `Vue.set(slots, key)` 的依赖收集不完整。 */
3857
- slotRevision: 0
4019
+ slots: {},
4020
+ slotRevision: 0
3858
4021
  });
3859
4022
 
3860
4023
  /**
3861
4024
  * 按插件 id 收集 `onTeardown` 回调,供 `disposeWebPlugin` 统一执行。
3862
4025
  */
3863
-
3864
- /** @type {Map<string, Array<() => void>>} */
3865
4026
  const _byPlugin = new Map();
3866
-
3867
- /**
3868
- * @param {string} pluginId
3869
- * @param {() => void} fn
3870
- */
3871
4027
  function registerPluginTeardown(pluginId, fn) {
3872
- if (typeof fn !== 'function') {
3873
- return
3874
- }
3875
- let list = _byPlugin.get(pluginId);
3876
- if (!list) {
3877
- list = [];
3878
- _byPlugin.set(pluginId, list);
3879
- }
3880
- list.push(fn);
4028
+ if (typeof fn !== 'function') {
4029
+ return;
4030
+ }
4031
+ let list = _byPlugin.get(pluginId);
4032
+ if (!list) {
4033
+ list = [];
4034
+ _byPlugin.set(pluginId, list);
4035
+ }
4036
+ list.push(fn);
4037
+ }
4038
+ function runPluginTeardowns(pluginId) {
4039
+ const list = _byPlugin.get(pluginId);
4040
+ if (!list) {
4041
+ return;
4042
+ }
4043
+ _byPlugin.delete(pluginId);
4044
+ for (const fn of list) {
4045
+ try {
4046
+ fn();
4047
+ }
4048
+ catch (e) {
4049
+ console.warn('[wep] teardown failed', pluginId, e);
4050
+ }
4051
+ }
3881
4052
  }
3882
4053
 
3883
4054
  /**
3884
- * @param {string} pluginId
4055
+ * 插件访问后端的受控通道:`fetch` 仅允许落在配置的路径前缀下(默认 `/api/`),默认 `credentials: 'same-origin'`。
3885
4056
  */
3886
- function runPluginTeardowns(pluginId) {
3887
- const list = _byPlugin.get(pluginId);
3888
- if (!list) {
3889
- return
3890
- }
3891
- _byPlugin.delete(pluginId);
3892
- for (const fn of list) {
3893
- try {
3894
- fn();
3895
- } catch (e) {
3896
- console.warn('[wep] teardown failed', pluginId, e);
3897
- }
3898
- }
4057
+ function createRequestBridge(config = {}) {
4058
+ const raw = Array.isArray(config.allowedPathPrefixes) && config.allowedPathPrefixes.length > 0
4059
+ ? config.allowedPathPrefixes
4060
+ : defaultWebExtendPluginRuntime.bridgeAllowedPathPrefixes;
4061
+ const allowedPathPrefixes = raw.map((p) => ensureLeadingPath(p));
4062
+ return {
4063
+ async request(path, init = {}) {
4064
+ if (typeof path !== 'string' || !path.startsWith('/')) {
4065
+ throw new Error('[wep:bridge] path must start with /');
4066
+ }
4067
+ const allowed = allowedPathPrefixes.some((p) => path.startsWith(p));
4068
+ if (!allowed) {
4069
+ throw new Error('[wep:bridge] path not allowed: ' + path);
4070
+ }
4071
+ return fetch(path, {
4072
+ credentials: 'same-origin',
4073
+ ...init
4074
+ });
4075
+ }
4076
+ };
3899
4077
  }
3900
4078
 
3901
4079
  /**
3902
4080
  * 构造插件 `activator(hostApi)` 使用的宿主 API:路由、菜单、扩展点、资源与受控请求桥。
3903
4081
  */
3904
-
3905
4082
  let slotItemKeySeq = 0;
3906
4083
  let routeSynthSeq = 0;
3907
-
3908
- /**
3909
- * @param {unknown[]} nodes
3910
- */
3911
4084
  function analyzeRouteInputTree(nodes) {
3912
- let hasDecl = false;
3913
- let hasCfg = false;
3914
- /** @param {unknown} r */
3915
- function walk(r) {
3916
- if (!r || typeof r !== 'object') {
3917
- return
3918
- }
3919
- const o = /** @type {Record<string, unknown>} */ (r);
3920
- const cfg = o.component != null || o.components != null;
3921
- const decl = typeof o.componentRef === 'string';
3922
- if (cfg) {
3923
- hasCfg = true;
3924
- } else if (decl) {
3925
- hasDecl = true;
4085
+ let hasDecl = false;
4086
+ let hasCfg = false;
4087
+ function walk(r) {
4088
+ if (!r || typeof r !== 'object') {
4089
+ return;
4090
+ }
4091
+ const o = r;
4092
+ const cfg = o.component != null || o.components != null;
4093
+ const decl = typeof o.componentRef === 'string';
4094
+ if (cfg) {
4095
+ hasCfg = true;
4096
+ }
4097
+ else if (decl) {
4098
+ hasDecl = true;
4099
+ }
4100
+ const ch = o.children;
4101
+ if (Array.isArray(ch)) {
4102
+ for (const c of ch) {
4103
+ walk(c);
4104
+ }
4105
+ }
3926
4106
  }
3927
- const ch = o.children;
3928
- if (Array.isArray(ch)) {
3929
- for (const c of ch) {
3930
- walk(c);
3931
- }
4107
+ for (const n of nodes) {
4108
+ walk(n);
3932
4109
  }
3933
- }
3934
- for (const n of nodes) {
3935
- walk(n);
3936
- }
3937
- return { hasDecl, hasCfg }
4110
+ return { hasDecl, hasCfg };
3938
4111
  }
3939
-
3940
4112
  /**
3941
4113
  * 单插件在宿主侧的 API 句柄。工厂请传 `(id, router, kit) => createHostApi(id, r, kit)` 以便 bridge 白名单等到位。
3942
- *
3943
- * @param {string} pluginId
3944
- * @param {import('vue-router').default} router
3945
- * @param {Record<string, unknown>} [hostKitOptions] 与 `resolveRuntimeOptions` 中路由/bridge 等字段一致
3946
4114
  */
4115
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3947
4116
  function createHostApi(pluginId, router, hostKitOptions = {}) {
3948
- const bridgePrefixes =
3949
- Array.isArray(hostKitOptions.bridgeAllowedPathPrefixes) &&
3950
- hostKitOptions.bridgeAllowedPathPrefixes.length > 0
3951
- ? hostKitOptions.bridgeAllowedPathPrefixes
3952
- : defaultWebExtendPluginRuntime.bridgeAllowedPathPrefixes;
3953
- const bridge = createRequestBridge({ allowedPathPrefixes: bridgePrefixes });
3954
-
3955
- const parentName =
3956
- typeof hostKitOptions.pluginRoutesParentName === 'string'
3957
- ? hostKitOptions.pluginRoutesParentName.trim()
3958
- : '';
3959
-
3960
- /** @param {import('vue-router').RouteConfig[]} rawRouteConfigs */
3961
- function applyInternalRegister(rawRouteConfigs) {
3962
- const wrapped = rawRouteConfigs.map((r) => ({
3963
- ...r,
3964
- name: r.name || `__wep_${pluginId}_${routeSynthSeq++}`,
3965
- meta: { ...(r.meta || {}), pluginId }
3966
- }));
3967
- if (typeof router.addRoute === 'function') {
3968
- if (parentName) {
3969
- for (const r of wrapped) {
3970
- router.addRoute(parentName, r);
4117
+ const bridgePrefixes = Array.isArray(hostKitOptions.bridgeAllowedPathPrefixes) &&
4118
+ hostKitOptions.bridgeAllowedPathPrefixes.length > 0
4119
+ ? hostKitOptions.bridgeAllowedPathPrefixes
4120
+ : defaultWebExtendPluginRuntime.bridgeAllowedPathPrefixes;
4121
+ const bridge = createRequestBridge({ allowedPathPrefixes: bridgePrefixes });
4122
+ const parentName = typeof hostKitOptions.pluginRoutesParentName === 'string'
4123
+ ? hostKitOptions.pluginRoutesParentName.trim()
4124
+ : '';
4125
+ function applyInternalRegister(rawRouteConfigs) {
4126
+ const wrapped = rawRouteConfigs.map((r) => ({
4127
+ ...r,
4128
+ name: r.name || `${routeSynthNamePrefix}${pluginId}_${routeSynthSeq++}`,
4129
+ meta: { ...(r.meta || {}), pluginId }
4130
+ }));
4131
+ if (typeof router.addRoute !== 'function') {
4132
+ throw new Error('[wep] vue-router 3.5+ 必需:请使用 router.addRoute(不再支持 addRoutes)');
3971
4133
  }
3972
- } else {
3973
- for (const r of wrapped) {
3974
- router.addRoute(r);
4134
+ if (parentName) {
4135
+ for (const r of wrapped) {
4136
+ router.addRoute(parentName, r);
4137
+ }
3975
4138
  }
3976
- }
3977
- } else {
3978
- if (parentName) {
3979
- console.warn(
3980
- '[wep] pluginRoutesParentName requires vue-router 3.5+ addRoute; falling back to top-level addRoutes'
3981
- );
3982
- }
3983
- router.addRoutes(wrapped);
3984
- }
3985
- }
3986
-
3987
- function injectStylesheet(href) {
3988
- const link = document.createElement('link');
3989
- link.rel = 'stylesheet';
3990
- link.href = href;
3991
- link.setAttribute('data-plugin-asset', pluginId);
3992
- document.head.appendChild(link);
3993
- }
3994
-
3995
- /** @param {string} src */
3996
- function injectScript(src) {
3997
- return new Promise((resolve, reject) => {
3998
- const s = document.createElement('script');
3999
- s.async = true;
4000
- s.src = src;
4001
- s.setAttribute('data-plugin-asset', pluginId);
4002
- s.onload = () => resolve();
4003
- s.onerror = () => reject(new Error('script failed: ' + src));
4004
- document.head.appendChild(s);
4005
- })
4006
- }
4007
-
4008
- return {
4009
- hostPluginApiVersion: HOST_PLUGIN_API_VERSION,
4010
-
4011
- registerRoutes(routes) {
4012
- const list = Array.isArray(routes) ? routes : [];
4013
- if (list.length === 0) {
4014
- return
4015
- }
4016
- const { hasDecl, hasCfg } = analyzeRouteInputTree(list);
4017
- if (hasDecl && hasCfg) {
4018
- throw new Error(
4019
- '[wep] registerRoutes: cannot mix RouteDeclaration (componentRef) with RouteConfig (component)'
4020
- )
4021
- }
4022
- let /** @type {import('vue-router').RouteConfig[]} */ configs;
4023
- if (hasDecl) {
4024
- const adapt = hostKitOptions.adaptRouteDeclarations;
4025
- if (typeof adapt !== 'function') {
4026
- throw new Error(
4027
- '[wep] registerRoutes: RouteDeclaration (componentRef) requires adaptRouteDeclarations on the host'
4028
- )
4139
+ else {
4140
+ for (const r of wrapped) {
4141
+ router.addRoute(r);
4142
+ }
4029
4143
  }
4030
- configs = adapt({
4031
- pluginId,
4032
- router,
4033
- declarations: /** @type {unknown[]} */ (list)
4034
- });
4035
- } else {
4036
- configs = /** @type {import('vue-router').RouteConfig[]} */ (/** @type {unknown} */ (list));
4037
- }
4038
-
4039
- if (typeof hostKitOptions.transformRoutes === 'function') {
4040
- configs = hostKitOptions.transformRoutes({
4041
- pluginId,
4042
- router,
4043
- routes: configs
4044
- });
4045
- }
4046
-
4047
- if (typeof hostKitOptions.interceptRegisterRoutes === 'function') {
4048
- hostKitOptions.interceptRegisterRoutes({
4049
- pluginId,
4050
- router,
4051
- routes: configs,
4052
- applyInternalRegister
4053
- });
4054
- } else {
4055
- applyInternalRegister(configs);
4056
- }
4057
- },
4058
-
4059
- registerMenuItems(items) {
4060
- for (const item of items) {
4061
- registries.menus.push({ ...item, pluginId });
4062
- }
4063
- registries.menus.sort(
4064
- (a, b) => (a.order != null ? a.order : 0) - (b.order != null ? b.order : 0)
4065
- );
4066
- },
4067
-
4068
- registerSlotComponents(pointId, components) {
4069
- if (!pointId) {
4070
- return
4071
- }
4072
- if (!registries.slots[pointId]) {
4073
- Vue.set(registries.slots, pointId, []);
4074
- }
4075
- const list = registries.slots[pointId];
4076
- for (const c of components) {
4077
- list.push({
4078
- pluginId,
4079
- component: c.component,
4080
- priority: c.priority != null ? c.priority : 0,
4081
- key: `${pluginId}-${pointId}-${++slotItemKeySeq}`
4144
+ }
4145
+ function injectStylesheet(href) {
4146
+ const link = document.createElement('link');
4147
+ link.rel = 'stylesheet';
4148
+ link.href = href;
4149
+ link.setAttribute('data-plugin-asset', pluginId);
4150
+ document.head.appendChild(link);
4151
+ }
4152
+ function injectScript(src) {
4153
+ return new Promise((resolve, reject) => {
4154
+ const s = document.createElement('script');
4155
+ s.async = true;
4156
+ s.src = src;
4157
+ s.setAttribute('data-plugin-asset', pluginId);
4158
+ s.onload = () => resolve();
4159
+ s.onerror = () => reject(new Error('script failed: ' + src));
4160
+ document.head.appendChild(s);
4082
4161
  });
4083
- }
4084
- list.sort((a, b) => b.priority - a.priority);
4085
- registries.slotRevision++;
4086
- },
4087
-
4088
- registerStylesheetUrls(urls) {
4089
- for (const u of urls || []) {
4090
- if (typeof u === 'string' && u) {
4091
- injectStylesheet(u);
4092
- }
4093
- }
4094
- },
4095
-
4096
- registerScriptUrls(urls) {
4097
- const chain = (urls || []).filter((u) => typeof u === 'string' && u).reduce(
4098
- (p, u) => p.then(() => injectScript(u)),
4099
- Promise.resolve()
4100
- );
4101
- chain.catch((e) => console.warn('[wep] registerScriptUrls', pluginId, e));
4102
- },
4103
-
4104
- registerSanitizedHtmlSnippet() {
4105
- throw new Error('registerSanitizedHtmlSnippet is not enabled')
4106
- },
4107
-
4108
- getBridge: () => bridge,
4109
-
4110
- onTeardown(_pluginId, fn) {
4111
- if (typeof fn === 'function') {
4112
- registerPluginTeardown(pluginId, fn);
4113
- }
4114
4162
  }
4115
- }
4163
+ const hostContext = hostKitOptions.hostContext != null && typeof hostKitOptions.hostContext === 'object'
4164
+ ? hostKitOptions.hostContext
4165
+ : Object.freeze({});
4166
+ return {
4167
+ hostPluginApiVersion: HOST_PLUGIN_API_VERSION,
4168
+ /** 宿主注入的只读依赖(store、router、开放能力等),见 `resolveRuntimeOptions.hostContext` */
4169
+ hostContext,
4170
+ registerRoutes(routes) {
4171
+ const list = Array.isArray(routes) ? routes : [];
4172
+ if (list.length === 0) {
4173
+ return;
4174
+ }
4175
+ const { hasDecl, hasCfg } = analyzeRouteInputTree(list);
4176
+ if (hasDecl && hasCfg) {
4177
+ throw new Error('[wep] registerRoutes: cannot mix RouteDeclaration (componentRef) with RouteConfig (component)');
4178
+ }
4179
+ let configs;
4180
+ if (hasDecl) {
4181
+ const adapt = hostKitOptions.adaptRouteDeclarations;
4182
+ if (typeof adapt !== 'function') {
4183
+ throw new Error('[wep] registerRoutes: RouteDeclaration (componentRef) requires adaptRouteDeclarations on the host');
4184
+ }
4185
+ configs = adapt({
4186
+ pluginId,
4187
+ router,
4188
+ declarations: list
4189
+ });
4190
+ }
4191
+ else {
4192
+ configs = list;
4193
+ }
4194
+ if (typeof hostKitOptions.transformRoutes === 'function') {
4195
+ configs = hostKitOptions.transformRoutes({
4196
+ pluginId,
4197
+ router,
4198
+ routes: configs
4199
+ });
4200
+ }
4201
+ if (typeof hostKitOptions.interceptRegisterRoutes === 'function') {
4202
+ hostKitOptions.interceptRegisterRoutes({
4203
+ pluginId,
4204
+ router,
4205
+ routes: configs,
4206
+ applyInternalRegister
4207
+ });
4208
+ }
4209
+ else {
4210
+ applyInternalRegister(configs);
4211
+ }
4212
+ },
4213
+ registerMenuItems(items) {
4214
+ const apply = hostKitOptions.applyPluginMenuItems;
4215
+ if (typeof apply !== 'function') {
4216
+ throw new Error('[wep] registerMenuItems 需要宿主在 resolveRuntimeOptions 中提供 applyPluginMenuItems,将菜单数据并入宿主侧栏/目录 state(框架不再维护 registries.menus)');
4217
+ }
4218
+ const list = Array.isArray(items) ? items : [];
4219
+ const enriched = list.map((item) => ({ ...item, pluginId }));
4220
+ enriched.sort((a, b) => (a.order != null ? Number(a.order) : 0) - (b.order != null ? Number(b.order) : 0));
4221
+ apply({ pluginId, items: enriched });
4222
+ },
4223
+ registerSlotComponents(pointId, components) {
4224
+ if (!pointId) {
4225
+ return;
4226
+ }
4227
+ if (!registries.slots[pointId]) {
4228
+ Vue.set(registries.slots, pointId, []);
4229
+ }
4230
+ const list = registries.slots[pointId];
4231
+ for (const c of components) {
4232
+ list.push({
4233
+ pluginId,
4234
+ component: c.component,
4235
+ priority: c.priority != null ? c.priority : 0,
4236
+ key: `${pluginId}-${pointId}-${++slotItemKeySeq}`
4237
+ });
4238
+ }
4239
+ list.sort((a, b) => b.priority - a.priority);
4240
+ registries.slotRevision++;
4241
+ },
4242
+ registerStylesheetUrls(urls) {
4243
+ for (const u of urls || []) {
4244
+ if (typeof u === 'string' && u) {
4245
+ injectStylesheet(u);
4246
+ }
4247
+ }
4248
+ },
4249
+ registerScriptUrls(urls) {
4250
+ const chain = (urls || []).filter((u) => typeof u === 'string' && u).reduce((p, u) => p.then(() => injectScript(u)), Promise.resolve());
4251
+ chain.catch((e) => console.warn('[wep] registerScriptUrls', pluginId, e));
4252
+ },
4253
+ registerSanitizedHtmlSnippet() {
4254
+ throw new Error('registerSanitizedHtmlSnippet is not enabled');
4255
+ },
4256
+ getBridge: () => bridge,
4257
+ onTeardown(_pluginId, fn) {
4258
+ if (typeof fn === 'function') {
4259
+ registerPluginTeardown(pluginId, fn);
4260
+ }
4261
+ }
4262
+ };
4116
4263
  }
4117
4264
 
4118
4265
  /**
4119
4266
  * 卸载单个插件:执行 teardown、清理注册表与 activator、移除带 `data-plugin-asset` 的 DOM。
4120
4267
  * 注意:Vue Router 3 无公开 `removeRoute`,动态路由通常需整页刷新或宿主自行维护。
4121
4268
  */
4122
-
4123
- /**
4124
- * @param {string} pluginId 与 manifest `id` 一致
4125
- */
4126
4269
  function disposeWebPlugin(pluginId) {
4127
- if (!pluginId || typeof pluginId !== 'string') {
4128
- return
4129
- }
4130
-
4131
- runPluginTeardowns(pluginId);
4132
-
4133
- for (let i = registries.menus.length - 1; i >= 0; i--) {
4134
- if (registries.menus[i].pluginId === pluginId) {
4135
- registries.menus.splice(i, 1);
4270
+ if (!pluginId || typeof pluginId !== 'string') {
4271
+ return;
4136
4272
  }
4137
- }
4138
-
4139
- const slots = registries.slots;
4140
- for (const pointId of Object.keys(slots)) {
4141
- const list = slots[pointId];
4142
- if (!Array.isArray(list)) {
4143
- continue
4273
+ runPluginTeardowns(pluginId);
4274
+ revokePluginMenusIfConfigured(pluginId);
4275
+ const slots = registries.slots;
4276
+ for (const pointId of Object.keys(slots)) {
4277
+ const list = slots[pointId];
4278
+ if (!Array.isArray(list)) {
4279
+ continue;
4280
+ }
4281
+ const next = list.filter((x) => x.pluginId !== pluginId);
4282
+ if (next.length === 0) {
4283
+ Vue.delete(slots, pointId);
4284
+ }
4285
+ else if (next.length !== list.length) {
4286
+ Vue.set(slots, pointId, next);
4287
+ }
4144
4288
  }
4145
- const next = list.filter((x) => x.pluginId !== pluginId);
4146
- if (next.length === 0) {
4147
- Vue.delete(slots, pointId);
4148
- } else if (next.length !== list.length) {
4149
- Vue.set(slots, pointId, next);
4289
+ registries.slotRevision++;
4290
+ if (typeof window !== 'undefined' && window.__PLUGIN_ACTIVATORS__) {
4291
+ delete window.__PLUGIN_ACTIVATORS__[pluginId];
4292
+ }
4293
+ if (typeof document !== 'undefined') {
4294
+ document.querySelectorAll('[data-plugin-asset]').forEach((el) => {
4295
+ if (el.getAttribute('data-plugin-asset') === pluginId) {
4296
+ el.remove();
4297
+ }
4298
+ });
4150
4299
  }
4151
- }
4152
- registries.slotRevision++;
4153
-
4154
- if (typeof window !== 'undefined' && window.__PLUGIN_ACTIVATORS__) {
4155
- delete window.__PLUGIN_ACTIVATORS__[pluginId];
4156
- }
4157
-
4158
- if (typeof document !== 'undefined') {
4159
- document.querySelectorAll('[data-plugin-asset]').forEach((el) => {
4160
- if (el.getAttribute('data-plugin-asset') === pluginId) {
4161
- el.remove();
4162
- }
4163
- });
4164
- }
4165
4300
  }
4166
4301
 
4167
4302
  /**
4168
4303
  * 布局中的扩展点占位;插件通过 `hostApi.registerSlotComponents(pointId, ...)` 注入组件。
4304
+ * 样式由宿主全局 CSS 覆盖 `.extension-point` / `.plugin-point-error`。
4169
4305
  */
4170
-
4171
- const SlotErrorBoundary = {
4172
- name: 'SlotErrorBoundary',
4173
- props: { label: String },
4174
- data() {
4175
- return { error: null }
4176
- },
4177
- errorCaptured(err) {
4178
- this.error = err && err.message ? err.message : String(err);
4179
- console.error('[wep:ExtensionPoint]', this.label, err);
4180
- return false
4181
- },
4182
- render(h) {
4183
- if (this.error) {
4184
- return h(
4185
- 'div',
4186
- { class: 'plugin-point-error', style: { color: '#c00', fontSize: '12px' } },
4187
- `[插件 ${this.label}] 渲染失败`
4188
- )
4189
- }
4190
- const d = this.$slots.default;
4191
- return d && d[0] ? d[0] : h('span')
4192
- }
4193
- };
4194
-
4195
- var ExtensionPoint = {
4196
- name: 'ExtensionPoint',
4197
- components: { SlotErrorBoundary },
4198
- props: {
4199
- pointId: { type: String, required: true },
4200
- slotProps: { type: Object, default: () => ({}) }
4201
- },
4202
- computed: {
4203
- items() {
4204
- void registries.slotRevision;
4205
- return registries.slots[this.pointId] || []
4306
+ const SlotErrorBoundary = Vue.extend({
4307
+ name: 'SlotErrorBoundary',
4308
+ props: { label: String },
4309
+ data() {
4310
+ return { error: null };
4206
4311
  },
4207
- forwardProps() {
4208
- return this.slotProps || {}
4312
+ errorCaptured(err) {
4313
+ this.error = err instanceof Error && err.message ? err.message : String(err);
4314
+ console.error('[wep:ExtensionPoint]', this.label, err);
4315
+ return false;
4316
+ },
4317
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4318
+ render(h) {
4319
+ if (this.error) {
4320
+ return h('div', { class: 'plugin-point-error' }, `[插件 ${this.label}] 渲染失败`);
4321
+ }
4322
+ const d = this.$slots.default;
4323
+ return d && d[0] ? d[0] : h('span');
4209
4324
  }
4210
- },
4211
- render(h) {
4212
- return h(
4213
- 'div',
4214
- {
4215
- class: 'extension-point',
4216
- style: { minHeight: '8px' },
4217
- attrs: { 'data-point-id': this.pointId }
4218
- },
4219
- this.items.map((item) =>
4220
- h(
4221
- SlotErrorBoundary,
4222
- {
4325
+ });
4326
+ var ExtensionPoint = Vue.extend({
4327
+ name: 'ExtensionPoint',
4328
+ components: { SlotErrorBoundary },
4329
+ props: {
4330
+ pointId: { type: String, required: true },
4331
+ slotProps: { type: Object, default: () => ({}) }
4332
+ },
4333
+ computed: {
4334
+ items() {
4335
+ void registries.slotRevision;
4336
+ return registries.slots[this.pointId] || [];
4337
+ },
4338
+ forwardProps() {
4339
+ return this.slotProps || {};
4340
+ }
4341
+ },
4342
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4343
+ render(h) {
4344
+ return h('div', {
4345
+ class: 'extension-point',
4346
+ attrs: { 'data-point-id': this.pointId }
4347
+ }, this.items.map((item) => h(SlotErrorBoundary, {
4223
4348
  key: item.key,
4224
4349
  props: { label: item.pluginId }
4225
- },
4226
- [h(item.component, { props: this.forwardProps })]
4227
- )
4228
- )
4229
- )
4230
- }
4231
- };
4350
+ }, [h(item.component, { props: this.forwardProps })])));
4351
+ }
4352
+ });
4232
4353
 
4233
4354
  /**
4234
4355
  * 注册全局 `ExtensionPoint` 并异步拉取清单、激活插件。
4235
4356
  */
4236
-
4237
4357
  /**
4238
- * @param {*} Vue
4239
- * @param {*} router
4240
- * @param {Record<string, unknown>} [options] 传给 `resolveRuntimeOptions`;可含 `env` 以读取 `VITE_*`
4358
+ * @param Vue Vue 构造函数
4359
+ * @param router vue-router 实例
4360
+ * @param options 传给 `resolveRuntimeOptions`;可含 `env` 以读取 `VITE_*`
4241
4361
  */
4362
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4242
4363
  function installWebExtendPluginVue2(Vue, router, options) {
4243
- const opts = options || {};
4244
- const { env: injectedEnv, ...runtimeUser } = opts;
4245
- if (injectedEnv && typeof injectedEnv === 'object') {
4246
- setWebExtendPluginEnv(injectedEnv);
4247
- }
4248
- if (Vue && ExtensionPoint) {
4249
- Vue.component('ExtensionPoint', ExtensionPoint);
4250
- }
4251
- const runtime = resolveRuntimeOptions$1(runtimeUser);
4252
- return bootstrapPlugins$1(router, (id, r, kit) => createHostApi(id, r, kit), runtime)
4364
+ const opts = options || {};
4365
+ const { env: injectedEnv, ...runtimeUser } = opts;
4366
+ if (injectedEnv && typeof injectedEnv === 'object') {
4367
+ setWebExtendPluginEnv(injectedEnv);
4368
+ }
4369
+ if (Vue && ExtensionPoint) {
4370
+ Vue.component('ExtensionPoint', ExtensionPoint);
4371
+ }
4372
+ const runtime = resolveRuntimeOptions$1(runtimeUser);
4373
+ return bootstrapPlugins$1(router, (id, r, kit) => createHostApi(id, r, kit || {}), runtime);
4253
4374
  }
4254
4375
 
4255
4376
  /**
4256
4377
  * Vue CLI + 统一 axios(如 RuoYi `utils/request`)场景的 `install` 预设。
4257
4378
  */
4258
-
4259
- /**
4260
- * @typedef {object} VueCliAxiosPresetDeps
4261
- * @property {(config: { url: string, method?: string }) => Promise<unknown>} request
4262
- */
4263
-
4264
- /**
4265
- * 将完整 manifest URL 转为相对 `apiBase` 的请求 path,供 axios `baseURL` 拼接。
4266
- * @param {string} manifestUrl
4267
- * @param {string} [apiBase]
4268
- */
4269
4379
  function resolveManifestPathUnderApiBase(manifestUrl, apiBase) {
4270
- const base = String(
4271
- apiBase !== undefined
4272
- ? apiBase
4273
- : (typeof process !== 'undefined' && process.env && process.env.VUE_APP_BASE_API) || ''
4274
- ).replace(/\/$/, '');
4275
- if (typeof window === 'undefined') {
4276
- return '/api/frontend-plugins'
4277
- }
4278
- const u = new URL(manifestUrl, window.location.origin);
4279
- let path = u.pathname + u.search;
4280
- if (base && path.startsWith(base)) {
4281
- path = path.slice(base.length) || '/';
4282
- }
4283
- return path
4380
+ const base = String(apiBase !== undefined
4381
+ ? apiBase
4382
+ : typeof process !== 'undefined' && process.env && process.env.VUE_APP_BASE_API
4383
+ ? String(process.env.VUE_APP_BASE_API)
4384
+ : '').replace(/\/$/, '');
4385
+ if (typeof window === 'undefined') {
4386
+ return '/api/frontend-plugins';
4387
+ }
4388
+ const u = new URL(manifestUrl, window.location.origin);
4389
+ let path = u.pathname + u.search;
4390
+ if (base && path.startsWith(base)) {
4391
+ path = path.slice(base.length) || '/';
4392
+ }
4393
+ return path;
4284
4394
  }
4285
-
4286
4395
  /**
4287
- * 将裸 `{ plugins }``{ code, data: { plugins } }` 式响应解包为清单对象。
4288
- * @param {unknown} body
4289
- * @returns {object|null}
4396
+ * 常见 Java 清单路径:与 `VUE_APP_BASE_API` 拼接为 `${base}/frontend-plugins`。
4397
+ * 若后端使用 `/api/frontend-plugins` 段,请在 extra 中显式传入 `manifestListPath`。
4290
4398
  */
4291
- function unwrapNestedManifestBody(body) {
4292
- if (!body || typeof body !== 'object') {
4293
- return null
4294
- }
4295
- const o = /** @type {Record<string, unknown>} */ (body);
4296
- if (Array.isArray(o.plugins)) {
4297
- return o
4298
- }
4299
- const d = o.data;
4300
- if (d && typeof d === 'object') {
4301
- const inner = /** @type {Record<string, unknown>} */ (d);
4302
- if (Array.isArray(inner.plugins)) {
4303
- return inner
4399
+ const defaultVueCliJavaManifestListPath = '/frontend-plugins';
4400
+ function bridgePrefixesFromVueCliEnv() {
4401
+ const base = (typeof process !== 'undefined' && process.env && process.env.VUE_APP_BASE_API
4402
+ ? String(process.env.VUE_APP_BASE_API)
4403
+ : '').replace(/\/$/, '');
4404
+ const raw = [base ? `${base}/` : '', '/api/', '/dev-api/'].filter(Boolean);
4405
+ return [...new Set(raw)];
4406
+ }
4407
+ function createVueCliAxiosInstallOptions(deps, extra = {}) {
4408
+ const { request } = deps;
4409
+ if (typeof request !== 'function') {
4410
+ throw new Error('[wep] createVueCliAxiosInstallOptions requires deps.request');
4304
4411
  }
4305
- if ('plugins' in inner) {
4306
- return inner
4412
+ const { fetchManifest: userFetchManifest, manifestMode: extraManifestMode, staticManifestUrl: extraStaticManifestUrl, ...restExtra } = extra;
4413
+ const envBase = (typeof process !== 'undefined' && process.env && process.env.VUE_APP_BASE_API
4414
+ ? String(process.env.VUE_APP_BASE_API)
4415
+ : '').replace(/\/$/, '');
4416
+ const userBase = extra.manifestBase !== undefined && String(extra.manifestBase).trim() !== ''
4417
+ ? String(extra.manifestBase).replace(/\/$/, '')
4418
+ : '';
4419
+ const stripBase = userBase || envBase;
4420
+ const manifestMode = resolveManifestModeFromInputs(extraManifestMode);
4421
+ const staticManifestUrl = resolveStaticManifestUrlFromInputs(extraStaticManifestUrl);
4422
+ const fetchManifestApi = async (ctx) => {
4423
+ try {
4424
+ const url = resolveManifestPathUnderApiBase(ctx.manifestUrl, stripBase);
4425
+ const body = await request({
4426
+ url,
4427
+ method: 'get'
4428
+ });
4429
+ const data = unwrapNestedManifestBody(body);
4430
+ if (!data || typeof data !== 'object') {
4431
+ return {
4432
+ ok: false,
4433
+ error: new Error('[wep] invalid manifest response'),
4434
+ data: null
4435
+ };
4436
+ }
4437
+ return { ok: true, data };
4438
+ }
4439
+ catch (e) {
4440
+ return { ok: false, error: e, data: null };
4441
+ }
4442
+ };
4443
+ const fetchManifestStatic = (ctx) => fetchStaticManifestViaHttp(ctx);
4444
+ const fetchManifest = typeof userFetchManifest === 'function'
4445
+ ? userFetchManifest
4446
+ : manifestMode === 'static'
4447
+ ? fetchManifestStatic
4448
+ : fetchManifestApi;
4449
+ const opts = {
4450
+ manifestBase: stripBase || undefined,
4451
+ bridgeAllowedPathPrefixes: bridgePrefixesFromVueCliEnv(),
4452
+ manifestMode,
4453
+ staticManifestUrl,
4454
+ ...restExtra,
4455
+ fetchManifest
4456
+ };
4457
+ const listPath = typeof process !== 'undefined' &&
4458
+ process.env &&
4459
+ process.env[webExtendPluginEnvKeys.manifestPathAlt];
4460
+ if (listPath && opts.manifestListPath === undefined && extra.manifestListPath === undefined) {
4461
+ opts.manifestListPath = String(process.env[webExtendPluginEnvKeys.manifestPathAlt]);
4307
4462
  }
4308
- }
4309
- return d !== undefined && d !== null && typeof d === 'object' ? /** @type {object} */ (d) : o
4463
+ return opts;
4310
4464
  }
4311
-
4312
- function bridgePrefixesFromVueCliEnv() {
4313
- const base = (
4314
- typeof process !== 'undefined' && process.env && process.env.VUE_APP_BASE_API
4315
- ? String(process.env.VUE_APP_BASE_API)
4316
- : ''
4317
- ).replace(/\/$/, '');
4318
- const raw = [base ? `${base}/` : '', '/api/', '/dev-api/'].filter(Boolean);
4319
- return [...new Set(raw)]
4465
+ /**
4466
+ * 少样板接入:`hostContext` 自动含 `router`(及可选 `store`)、`isDev` 与常见 `manifestListPath` 默认值。
4467
+ * 更多运行时字段仍可通过 `extra` 覆盖。
4468
+ */
4469
+ function createVueCliAxiosQuickInstallOptions(
4470
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4471
+ router, deps, extra = {}) {
4472
+ const { request, hostLayoutComponent, store, hostContext: depHostContext, applyPluginMenuItems, revokePluginMenuItems } = deps;
4473
+ const { hostContext: extraHostContext, isDev: extraIsDev, manifestListPath: extraListPath, ...restExtra } = extra;
4474
+ const hostContext = {
4475
+ router,
4476
+ ...(store !== undefined ? { store } : {}),
4477
+ ...(depHostContext && typeof depHostContext === 'object' ? depHostContext : {}),
4478
+ ...(extraHostContext && typeof extraHostContext === 'object' ? extraHostContext : {})
4479
+ };
4480
+ const manifestListPath = extraListPath !== undefined && String(extraListPath).trim() !== ''
4481
+ ? String(extraListPath)
4482
+ : defaultVueCliJavaManifestListPath;
4483
+ return createVueCliAxiosInstallOptions({ request }, {
4484
+ hostLayoutComponent,
4485
+ hostContext,
4486
+ applyPluginMenuItems,
4487
+ revokePluginMenuItems,
4488
+ isDev: extraIsDev !== undefined ? Boolean(extraIsDev) : resolveBundledIsDev(),
4489
+ manifestListPath,
4490
+ ...restExtra
4491
+ });
4320
4492
  }
4493
+ const presetVueCliAxios = Object.freeze({
4494
+ id: 'vue-cli-axios',
4495
+ description: 'Vue CLI + axios request for API manifest; optional manifestMode=static uses fetch',
4496
+ createInstallOptions: createVueCliAxiosInstallOptions,
4497
+ createQuickInstallOptions: createVueCliAxiosQuickInstallOptions,
4498
+ defaultJavaManifestListPath: defaultVueCliJavaManifestListPath,
4499
+ manifestPathForApiBase: resolveManifestPathUnderApiBase,
4500
+ unwrapManifestBody: unwrapNestedManifestBody
4501
+ });
4321
4502
 
4322
4503
  /**
4323
- * @param {VueCliAxiosPresetDeps} deps
4324
- * @param {Record<string, unknown>} [extra]
4504
+ * Vue CLI + axios 场景的一键安装:合并 hostContext、默认清单路径与 IIFE 全局 Vue。
4325
4505
  */
4326
- function createVueCliAxiosInstallOptions(deps, extra = {}) {
4327
- const { request } = deps;
4328
- if (typeof request !== 'function') {
4329
- throw new Error('[wep] createVueCliAxiosInstallOptions requires deps.request')
4330
- }
4331
- const envBase = (
4332
- typeof process !== 'undefined' && process.env && process.env.VUE_APP_BASE_API
4333
- ? String(process.env.VUE_APP_BASE_API)
4334
- : ''
4335
- ).replace(/\/$/, '');
4336
- const userBase =
4337
- extra.manifestBase !== undefined && String(extra.manifestBase).trim() !== ''
4338
- ? String(extra.manifestBase).replace(/\/$/, '')
4339
- : '';
4340
- const stripBase = userBase || envBase;
4341
-
4342
- const fetchManifest = async (ctx) => {
4343
- try {
4344
- const url = resolveManifestPathUnderApiBase(ctx.manifestUrl, stripBase);
4345
- const body = await request({
4346
- url,
4347
- method: 'get'
4348
- });
4349
- const data = unwrapNestedManifestBody(body);
4350
- if (!data || typeof data !== 'object') {
4351
- return {
4352
- ok: false,
4353
- error: new Error('[wep] invalid manifest response'),
4354
- data: null
4355
- }
4356
- }
4357
- return { ok: true, data }
4358
- } catch (e) {
4359
- return { ok: false, error: e, data: null }
4506
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4507
+ function installVueCliAxiosWebPlugins(Vue, router, deps, extra) {
4508
+ const exposeGlobalVue = extra?.exposeGlobalVue !== false;
4509
+ if (exposeGlobalVue && typeof window !== 'undefined') {
4510
+ window.Vue = Vue;
4360
4511
  }
4361
- };
4362
-
4363
- const opts = {
4364
- manifestBase: stripBase || undefined,
4365
- bridgeAllowedPathPrefixes: bridgePrefixesFromVueCliEnv(),
4366
- fetchManifest,
4367
- ...extra
4368
- };
4369
-
4370
- const listPath =
4371
- typeof process !== 'undefined' && process.env && process.env.VUE_APP_WEB_PLUGIN_MANIFEST_PATH;
4372
- if (listPath && opts.manifestListPath === undefined && extra.manifestListPath === undefined) {
4373
- opts.manifestListPath = String(listPath);
4374
- }
4375
-
4376
- return opts
4512
+ const { exposeGlobalVue: _skip, ...restExtra } = extra || {};
4513
+ const opts = createVueCliAxiosQuickInstallOptions(router, deps, restExtra);
4514
+ return installWebExtendPluginVue2(Vue, router, opts);
4377
4515
  }
4378
4516
 
4379
- const presetVueCliAxios = Object.freeze({
4380
- id: 'vue-cli-axios',
4381
- description: 'Vue CLI + unified axios request; manifest uses host request()',
4382
- createInstallOptions: createVueCliAxiosInstallOptions,
4383
- manifestPathForApiBase: resolveManifestPathUnderApiBase,
4384
- unwrapManifestBody: unwrapNestedManifestBody
4385
- });
4386
-
4387
4517
  /**
4388
4518
  * 包对外稳定导出与 `WebExtendPluginVue2` 命名空间。
4389
4519
  */
4390
-
4391
- const {
4392
- bootstrapPlugins,
4393
- defaultFetchWebPluginManifest,
4394
- resolveRuntimeOptions
4395
- } = pluginRuntime;
4396
-
4397
- const {
4398
- composeManifestFetch,
4399
- manifestFetchCacheMiddleware,
4400
- wrapManifestFetchWithCache
4401
- } = manifestComposer;
4402
-
4520
+ const { bootstrapPlugins, defaultFetchWebPluginManifest, resolveRuntimeOptions, ensurePluginHostRoute } = pluginRuntime;
4521
+ const { composeManifestFetch, manifestFetchCacheMiddleware, wrapManifestFetchWithCache } = manifestComposer;
4403
4522
  const WebExtendPluginVue2 = Object.freeze({
4404
- install: installWebExtendPluginVue2,
4405
- runtime: Object.freeze({
4406
- bootstrapPlugins: bootstrapPlugins$1,
4407
- resolveRuntimeOptions: resolveRuntimeOptions$1,
4408
- defaultFetchWebPluginManifest: defaultFetchWebPluginManifest$1,
4409
- composeManifestFetch: composeManifestFetch$1,
4410
- manifestFetchCacheMiddleware: manifestFetchCacheMiddleware$1,
4411
- wrapManifestFetchWithCache: wrapManifestFetchWithCache$1
4412
- }),
4413
- host: Object.freeze({
4414
- createHostApi,
4415
- disposeWebPlugin,
4416
- createRequestBridge,
4417
- registries
4418
- }),
4419
- config: Object.freeze({
4420
- defaultWebExtendPluginRuntime,
4421
- setWebExtendPluginEnv
4422
- }),
4423
- constants: Object.freeze({
4424
- HOST_PLUGIN_API_VERSION,
4425
- RUNTIME_CONSOLE_LABEL
4426
- }),
4427
- components: Object.freeze({
4428
- ExtensionPoint
4429
- }),
4430
- presets: Object.freeze({
4431
- vueCliAxios: presetVueCliAxios
4432
- })
4523
+ install: installWebExtendPluginVue2,
4524
+ runtime: Object.freeze({
4525
+ bootstrapPlugins: bootstrapPlugins$1,
4526
+ resolveRuntimeOptions: resolveRuntimeOptions$1,
4527
+ ensurePluginHostRoute: ensurePluginHostRoute$1,
4528
+ defaultFetchWebPluginManifest: defaultFetchWebPluginManifest$1,
4529
+ composeManifestFetch: composeManifestFetch$1,
4530
+ manifestFetchCacheMiddleware: manifestFetchCacheMiddleware$1,
4531
+ wrapManifestFetchWithCache: wrapManifestFetchWithCache$1
4532
+ }),
4533
+ host: Object.freeze({
4534
+ createHostApi,
4535
+ disposeWebPlugin,
4536
+ createRequestBridge,
4537
+ registries
4538
+ }),
4539
+ config: Object.freeze({
4540
+ defaultWebExtendPluginRuntime,
4541
+ setWebExtendPluginEnv,
4542
+ webExtendPluginEnvKeys,
4543
+ defaultManifestFetchCache,
4544
+ defaultManifestMode,
4545
+ routeSynthNamePrefix,
4546
+ peerMinimumVersions
4547
+ }),
4548
+ constants: Object.freeze({
4549
+ HOST_PLUGIN_API_VERSION,
4550
+ RUNTIME_CONSOLE_LABEL
4551
+ }),
4552
+ components: Object.freeze({
4553
+ ExtensionPoint
4554
+ }),
4555
+ presets: Object.freeze({
4556
+ vueCliAxios: presetVueCliAxios
4557
+ })
4433
4558
  });
4434
4559
 
4435
- export { ExtensionPoint, HOST_PLUGIN_API_VERSION, RUNTIME_CONSOLE_LABEL, WebExtendPluginVue2, bootstrapPlugins, composeManifestFetch, createHostApi, createRequestBridge, createVueCliAxiosInstallOptions, defaultFetchWebPluginManifest, defaultWebExtendPluginRuntime, disposeWebPlugin, installWebExtendPluginVue2, manifestFetchCacheMiddleware, presetVueCliAxios, registries, resolveManifestPathUnderApiBase, resolveRuntimeOptions, setWebExtendPluginEnv, unwrapNestedManifestBody, wrapManifestFetchWithCache };
4560
+ export { ExtensionPoint, HOST_PLUGIN_API_VERSION, RUNTIME_CONSOLE_LABEL, WebExtendPluginVue2, bootstrapPlugins, composeManifestFetch, createHostApi, createRequestBridge, createVueCliAxiosInstallOptions, createVueCliAxiosQuickInstallOptions, defaultFetchWebPluginManifest, defaultManifestFetchCache, defaultManifestMode, defaultVueCliJavaManifestListPath, defaultWebExtendPluginRuntime, disposeWebPlugin, ensurePluginHostRoute, installVueCliAxiosWebPlugins, installWebExtendPluginVue2, manifestFetchCacheMiddleware, peerMinimumVersions, presetVueCliAxios, registries, resolveManifestPathUnderApiBase, resolveRuntimeOptions, routeSynthNamePrefix, setWebExtendPluginEnv, unwrapNestedManifestBody, webExtendPluginEnvKeys, wrapManifestFetchWithCache };
4436
4561
  //# sourceMappingURL=index.mjs.map