web-extend-plugin-vue2 0.1.4 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,4036 @@
1
+ 'use strict';
2
+
3
+ var Vue = require('vue');
4
+
5
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
6
+
7
+ var Vue__default = /*#__PURE__*/_interopDefault(Vue);
8
+
9
+ /**
10
+ * 宿主可覆盖的默认运行时配置(路径、白名单、超时等)。
11
+ * 使用方式:`resolveRuntimeOptions({ ...defaultWebExtendPluginRuntime, manifestListPath: '/api/my-plugins' })`
12
+ * 或只传需要改动的字段:`resolveRuntimeOptions({ manifestListPath: '/api/my-plugins' })`。
13
+ *
14
+ * @module default-runtime-config
15
+ */
16
+
17
+ /**
18
+ * @typedef {typeof defaultWebExtendPluginRuntime} WebExtendPluginDefaultRuntime
19
+ */
20
+
21
+ const defaultWebExtendPluginRuntime = {
22
+ /** 清单 HTTP 服务前缀(与后端 context-path 对齐),不含尾部 `/` */
23
+ manifestBase: '/fp-api',
24
+
25
+ /**
26
+ * 拉取插件清单的 **路径段**(以 `/` 开头),拼在 `manifestBase` 之后。
27
+ * 完整 URL:`{manifestBase}{manifestListPath}` → 默认 `/fp-api/api/frontend-plugins`
28
+ */
29
+ manifestListPath: '/api/frontend-plugins',
30
+
31
+ /** 清单 `fetch` 的 `credentials`,需 Cookie 会话时用 `include` */
32
+ manifestFetchCredentials: 'include',
33
+
34
+ /** 插件 dev 服务存活探测路径(拼在 `webPluginDevOrigin` 后) */
35
+ devPingPath: '/__web_plugin_dev_ping',
36
+
37
+ /** 插件 dev 热更新 SSE 路径(拼在插件 dev 的 origin 后) */
38
+ devReloadSsePath: '/__web_plugin_reload_stream',
39
+
40
+ /** 隐式 dev 映射里,每个 id 对应的入口路径(相对插件 dev origin) */
41
+ webPluginDevEntryPath: '/src/plugin-entry.js',
42
+
43
+ /** `fetch(devPingUrl)` 超时毫秒数 */
44
+ devPingTimeoutMs: 500,
45
+
46
+ /**
47
+ * **隐式 dev 映射**(可选):开发模式下若 `webPluginDevOrigin` 上 ping 成功,运行时会为若干插件 id 自动生成
48
+ * `{ id → origin + webPluginDevEntryPath }`,从而用 dev 服务入口替代清单里的 dist,便于热更新联调。
49
+ *
50
+ * 插件 id 来源优先级:`webPluginDevIds`(或 `VITE_WEB_PLUGIN_DEV_IDS`)→ 本字段。**默认 `[]`**,
51
+ * 避免把仓库示例 id 写进通用宿主;联调时在 `.env` 里设 `VITE_WEB_PLUGIN_DEV_IDS=com.xxx,com.yyy`,
52
+ * 或 `resolveRuntimeOptions({ defaultImplicitDevPluginIds: ['com.xxx'] })` 即可。
53
+ */
54
+ defaultImplicitDevPluginIds: [],
55
+
56
+ /**
57
+ * 允许通过 `<script>` / 动态 `import()` 加载的插件脚本所在主机名(小写),防误配公网 URL。
58
+ */
59
+ allowedScriptHosts: ['localhost', '127.0.0.1', '::1'],
60
+
61
+ /**
62
+ * `hostApi.getBridge().request(path)` 允许的 path 前缀;须以 `/` 开头。
63
+ * 需与后端实际 API 前缀一致。
64
+ */
65
+ bridgeAllowedPathPrefixes: ['/api/']
66
+ };
67
+
68
+ function getDefaultExportFromCjs (x) {
69
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
70
+ }
71
+
72
+ var re = {exports: {}};
73
+
74
+ var constants;
75
+ var hasRequiredConstants;
76
+
77
+ function requireConstants () {
78
+ if (hasRequiredConstants) return constants;
79
+ hasRequiredConstants = 1;
80
+
81
+ // Note: this is the semver.org version of the spec that it implements
82
+ // Not necessarily the package version of this code.
83
+ const SEMVER_SPEC_VERSION = '2.0.0';
84
+
85
+ const MAX_LENGTH = 256;
86
+ const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
87
+ /* istanbul ignore next */ 9007199254740991;
88
+
89
+ // Max safe segment length for coercion.
90
+ const MAX_SAFE_COMPONENT_LENGTH = 16;
91
+
92
+ // Max safe length for a build identifier. The max length minus 6 characters for
93
+ // the shortest version with a build 0.0.0+BUILD.
94
+ const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
95
+
96
+ const RELEASE_TYPES = [
97
+ 'major',
98
+ 'premajor',
99
+ 'minor',
100
+ 'preminor',
101
+ 'patch',
102
+ 'prepatch',
103
+ 'prerelease',
104
+ ];
105
+
106
+ constants = {
107
+ MAX_LENGTH,
108
+ MAX_SAFE_COMPONENT_LENGTH,
109
+ MAX_SAFE_BUILD_LENGTH,
110
+ MAX_SAFE_INTEGER,
111
+ RELEASE_TYPES,
112
+ SEMVER_SPEC_VERSION,
113
+ FLAG_INCLUDE_PRERELEASE: 0b001,
114
+ FLAG_LOOSE: 0b010,
115
+ };
116
+ return constants;
117
+ }
118
+
119
+ var debug_1;
120
+ var hasRequiredDebug;
121
+
122
+ function requireDebug () {
123
+ if (hasRequiredDebug) return debug_1;
124
+ hasRequiredDebug = 1;
125
+
126
+ const debug = (
127
+ typeof process === 'object' &&
128
+ process.env &&
129
+ process.env.NODE_DEBUG &&
130
+ /\bsemver\b/i.test(process.env.NODE_DEBUG)
131
+ ) ? (...args) => console.error('SEMVER', ...args)
132
+ : () => {};
133
+
134
+ debug_1 = debug;
135
+ return debug_1;
136
+ }
137
+
138
+ var hasRequiredRe;
139
+
140
+ function requireRe () {
141
+ if (hasRequiredRe) return re.exports;
142
+ hasRequiredRe = 1;
143
+ (function (module, exports$1) {
144
+
145
+ const {
146
+ MAX_SAFE_COMPONENT_LENGTH,
147
+ MAX_SAFE_BUILD_LENGTH,
148
+ MAX_LENGTH,
149
+ } = requireConstants();
150
+ const debug = requireDebug();
151
+ exports$1 = module.exports = {};
152
+
153
+ // The actual regexps go on exports.re
154
+ const re = exports$1.re = [];
155
+ const safeRe = exports$1.safeRe = [];
156
+ const src = exports$1.src = [];
157
+ const safeSrc = exports$1.safeSrc = [];
158
+ const t = exports$1.t = {};
159
+ let R = 0;
160
+
161
+ const LETTERDASHNUMBER = '[a-zA-Z0-9-]';
162
+
163
+ // Replace some greedy regex tokens to prevent regex dos issues. These regex are
164
+ // used internally via the safeRe object since all inputs in this library get
165
+ // normalized first to trim and collapse all extra whitespace. The original
166
+ // regexes are exported for userland consumption and lower level usage. A
167
+ // future breaking change could export the safer regex only with a note that
168
+ // all input should have extra whitespace removed.
169
+ const safeRegexReplacements = [
170
+ ['\\s', 1],
171
+ ['\\d', MAX_LENGTH],
172
+ [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],
173
+ ];
174
+
175
+ const makeSafeRegex = (value) => {
176
+ for (const [token, max] of safeRegexReplacements) {
177
+ value = value
178
+ .split(`${token}*`).join(`${token}{0,${max}}`)
179
+ .split(`${token}+`).join(`${token}{1,${max}}`);
180
+ }
181
+ return value
182
+ };
183
+
184
+ const createToken = (name, value, isGlobal) => {
185
+ const safe = makeSafeRegex(value);
186
+ const index = R++;
187
+ debug(name, index, value);
188
+ t[name] = index;
189
+ src[index] = value;
190
+ safeSrc[index] = safe;
191
+ re[index] = new RegExp(value, isGlobal ? 'g' : undefined);
192
+ safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined);
193
+ };
194
+
195
+ // The following Regular Expressions can be used for tokenizing,
196
+ // validating, and parsing SemVer version strings.
197
+
198
+ // ## Numeric Identifier
199
+ // A single `0`, or a non-zero digit followed by zero or more digits.
200
+
201
+ createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*');
202
+ createToken('NUMERICIDENTIFIERLOOSE', '\\d+');
203
+
204
+ // ## Non-numeric Identifier
205
+ // Zero or more digits, followed by a letter or hyphen, and then zero or
206
+ // more letters, digits, or hyphens.
207
+
208
+ createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
209
+
210
+ // ## Main Version
211
+ // Three dot-separated numeric identifiers.
212
+
213
+ createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
214
+ `(${src[t.NUMERICIDENTIFIER]})\\.` +
215
+ `(${src[t.NUMERICIDENTIFIER]})`);
216
+
217
+ createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
218
+ `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
219
+ `(${src[t.NUMERICIDENTIFIERLOOSE]})`);
220
+
221
+ // ## Pre-release Version Identifier
222
+ // A numeric identifier, or a non-numeric identifier.
223
+ // Non-numeric identifiers include numeric identifiers but can be longer.
224
+ // Therefore non-numeric identifiers must go first.
225
+
226
+ createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]
227
+ }|${src[t.NUMERICIDENTIFIER]})`);
228
+
229
+ createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]
230
+ }|${src[t.NUMERICIDENTIFIERLOOSE]})`);
231
+
232
+ // ## Pre-release Version
233
+ // Hyphen, followed by one or more dot-separated pre-release version
234
+ // identifiers.
235
+
236
+ createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
237
+ }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
238
+
239
+ createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
240
+ }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);
241
+
242
+ // ## Build Metadata Identifier
243
+ // Any combination of digits, letters, or hyphens.
244
+
245
+ createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`);
246
+
247
+ // ## Build Metadata
248
+ // Plus sign, followed by one or more period-separated build metadata
249
+ // identifiers.
250
+
251
+ createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
252
+ }(?:\\.${src[t.BUILDIDENTIFIER]})*))`);
253
+
254
+ // ## Full Version String
255
+ // A main version, followed optionally by a pre-release version and
256
+ // build metadata.
257
+
258
+ // Note that the only major, minor, patch, and pre-release sections of
259
+ // the version string are capturing groups. The build metadata is not a
260
+ // capturing group, because it should not ever be used in version
261
+ // comparison.
262
+
263
+ createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
264
+ }${src[t.PRERELEASE]}?${
265
+ src[t.BUILD]}?`);
266
+
267
+ createToken('FULL', `^${src[t.FULLPLAIN]}$`);
268
+
269
+ // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
270
+ // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
271
+ // common in the npm registry.
272
+ createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
273
+ }${src[t.PRERELEASELOOSE]}?${
274
+ src[t.BUILD]}?`);
275
+
276
+ createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`);
277
+
278
+ createToken('GTLT', '((?:<|>)?=?)');
279
+
280
+ // Something like "2.*" or "1.2.x".
281
+ // Note that "x.x" is a valid xRange identifer, meaning "any version"
282
+ // Only the first item is strictly required.
283
+ createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
284
+ createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
285
+
286
+ createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
287
+ `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
288
+ `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
289
+ `(?:${src[t.PRERELEASE]})?${
290
+ src[t.BUILD]}?` +
291
+ `)?)?`);
292
+
293
+ createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
294
+ `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
295
+ `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
296
+ `(?:${src[t.PRERELEASELOOSE]})?${
297
+ src[t.BUILD]}?` +
298
+ `)?)?`);
299
+
300
+ createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
301
+ createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);
302
+
303
+ // Coercion.
304
+ // Extract anything that could conceivably be a part of a valid semver
305
+ createToken('COERCEPLAIN', `${'(^|[^\\d])' +
306
+ '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
307
+ `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
308
+ `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
309
+ createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`);
310
+ createToken('COERCEFULL', src[t.COERCEPLAIN] +
311
+ `(?:${src[t.PRERELEASE]})?` +
312
+ `(?:${src[t.BUILD]})?` +
313
+ `(?:$|[^\\d])`);
314
+ createToken('COERCERTL', src[t.COERCE], true);
315
+ createToken('COERCERTLFULL', src[t.COERCEFULL], true);
316
+
317
+ // Tilde ranges.
318
+ // Meaning is "reasonably at or greater than"
319
+ createToken('LONETILDE', '(?:~>?)');
320
+
321
+ createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true);
322
+ exports$1.tildeTrimReplace = '$1~';
323
+
324
+ createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
325
+ createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);
326
+
327
+ // Caret ranges.
328
+ // Meaning is "at least and backwards compatible with"
329
+ createToken('LONECARET', '(?:\\^)');
330
+
331
+ createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true);
332
+ exports$1.caretTrimReplace = '$1^';
333
+
334
+ createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
335
+ createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);
336
+
337
+ // A simple gt/lt/eq thing, or just "" to indicate "any version"
338
+ createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
339
+ createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);
340
+
341
+ // An expression to strip any whitespace between the gtlt and the thing
342
+ // it modifies, so that `> 1.2.3` ==> `>1.2.3`
343
+ createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
344
+ }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
345
+ exports$1.comparatorTrimReplace = '$1$2$3';
346
+
347
+ // Something like `1.2.3 - 1.2.4`
348
+ // Note that these all use the loose form, because they'll be
349
+ // checked against either the strict or loose comparator form
350
+ // later.
351
+ createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
352
+ `\\s+-\\s+` +
353
+ `(${src[t.XRANGEPLAIN]})` +
354
+ `\\s*$`);
355
+
356
+ createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
357
+ `\\s+-\\s+` +
358
+ `(${src[t.XRANGEPLAINLOOSE]})` +
359
+ `\\s*$`);
360
+
361
+ // Star ranges basically just allow anything at all.
362
+ createToken('STAR', '(<|>)?=?\\s*\\*');
363
+ // >=0.0.0 is like a star
364
+ createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$');
365
+ createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$');
366
+ } (re, re.exports));
367
+ return re.exports;
368
+ }
369
+
370
+ var parseOptions_1;
371
+ var hasRequiredParseOptions;
372
+
373
+ function requireParseOptions () {
374
+ if (hasRequiredParseOptions) return parseOptions_1;
375
+ hasRequiredParseOptions = 1;
376
+
377
+ // parse out just the options we care about
378
+ const looseOption = Object.freeze({ loose: true });
379
+ const emptyOpts = Object.freeze({ });
380
+ const parseOptions = options => {
381
+ if (!options) {
382
+ return emptyOpts
383
+ }
384
+
385
+ if (typeof options !== 'object') {
386
+ return looseOption
387
+ }
388
+
389
+ return options
390
+ };
391
+ parseOptions_1 = parseOptions;
392
+ return parseOptions_1;
393
+ }
394
+
395
+ var identifiers;
396
+ var hasRequiredIdentifiers;
397
+
398
+ function requireIdentifiers () {
399
+ if (hasRequiredIdentifiers) return identifiers;
400
+ hasRequiredIdentifiers = 1;
401
+
402
+ const numeric = /^[0-9]+$/;
403
+ const compareIdentifiers = (a, b) => {
404
+ if (typeof a === 'number' && typeof b === 'number') {
405
+ return a === b ? 0 : a < b ? -1 : 1
406
+ }
407
+
408
+ const anum = numeric.test(a);
409
+ const bnum = numeric.test(b);
410
+
411
+ if (anum && bnum) {
412
+ a = +a;
413
+ b = +b;
414
+ }
415
+
416
+ return a === b ? 0
417
+ : (anum && !bnum) ? -1
418
+ : (bnum && !anum) ? 1
419
+ : a < b ? -1
420
+ : 1
421
+ };
422
+
423
+ const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
424
+
425
+ identifiers = {
426
+ compareIdentifiers,
427
+ rcompareIdentifiers,
428
+ };
429
+ return identifiers;
430
+ }
431
+
432
+ var semver$2;
433
+ var hasRequiredSemver$1;
434
+
435
+ function requireSemver$1 () {
436
+ if (hasRequiredSemver$1) return semver$2;
437
+ hasRequiredSemver$1 = 1;
438
+
439
+ const debug = requireDebug();
440
+ const { MAX_LENGTH, MAX_SAFE_INTEGER } = requireConstants();
441
+ const { safeRe: re, t } = requireRe();
442
+
443
+ const parseOptions = requireParseOptions();
444
+ const { compareIdentifiers } = requireIdentifiers();
445
+ class SemVer {
446
+ constructor (version, options) {
447
+ options = parseOptions(options);
448
+
449
+ if (version instanceof SemVer) {
450
+ if (version.loose === !!options.loose &&
451
+ version.includePrerelease === !!options.includePrerelease) {
452
+ return version
453
+ } else {
454
+ version = version.version;
455
+ }
456
+ } else if (typeof version !== 'string') {
457
+ throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)
458
+ }
459
+
460
+ if (version.length > MAX_LENGTH) {
461
+ throw new TypeError(
462
+ `version is longer than ${MAX_LENGTH} characters`
463
+ )
464
+ }
465
+
466
+ debug('SemVer', version, options);
467
+ this.options = options;
468
+ this.loose = !!options.loose;
469
+ // this isn't actually relevant for versions, but keep it so that we
470
+ // don't run into trouble passing this.options around.
471
+ this.includePrerelease = !!options.includePrerelease;
472
+
473
+ const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
474
+
475
+ if (!m) {
476
+ throw new TypeError(`Invalid Version: ${version}`)
477
+ }
478
+
479
+ this.raw = version;
480
+
481
+ // these are actually numbers
482
+ this.major = +m[1];
483
+ this.minor = +m[2];
484
+ this.patch = +m[3];
485
+
486
+ if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
487
+ throw new TypeError('Invalid major version')
488
+ }
489
+
490
+ if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
491
+ throw new TypeError('Invalid minor version')
492
+ }
493
+
494
+ if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
495
+ throw new TypeError('Invalid patch version')
496
+ }
497
+
498
+ // numberify any prerelease numeric ids
499
+ if (!m[4]) {
500
+ this.prerelease = [];
501
+ } else {
502
+ this.prerelease = m[4].split('.').map((id) => {
503
+ if (/^[0-9]+$/.test(id)) {
504
+ const num = +id;
505
+ if (num >= 0 && num < MAX_SAFE_INTEGER) {
506
+ return num
507
+ }
508
+ }
509
+ return id
510
+ });
511
+ }
512
+
513
+ this.build = m[5] ? m[5].split('.') : [];
514
+ this.format();
515
+ }
516
+
517
+ format () {
518
+ this.version = `${this.major}.${this.minor}.${this.patch}`;
519
+ if (this.prerelease.length) {
520
+ this.version += `-${this.prerelease.join('.')}`;
521
+ }
522
+ return this.version
523
+ }
524
+
525
+ toString () {
526
+ return this.version
527
+ }
528
+
529
+ compare (other) {
530
+ debug('SemVer.compare', this.version, this.options, other);
531
+ if (!(other instanceof SemVer)) {
532
+ if (typeof other === 'string' && other === this.version) {
533
+ return 0
534
+ }
535
+ other = new SemVer(other, this.options);
536
+ }
537
+
538
+ if (other.version === this.version) {
539
+ return 0
540
+ }
541
+
542
+ return this.compareMain(other) || this.comparePre(other)
543
+ }
544
+
545
+ compareMain (other) {
546
+ if (!(other instanceof SemVer)) {
547
+ other = new SemVer(other, this.options);
548
+ }
549
+
550
+ if (this.major < other.major) {
551
+ return -1
552
+ }
553
+ if (this.major > other.major) {
554
+ return 1
555
+ }
556
+ if (this.minor < other.minor) {
557
+ return -1
558
+ }
559
+ if (this.minor > other.minor) {
560
+ return 1
561
+ }
562
+ if (this.patch < other.patch) {
563
+ return -1
564
+ }
565
+ if (this.patch > other.patch) {
566
+ return 1
567
+ }
568
+ return 0
569
+ }
570
+
571
+ comparePre (other) {
572
+ if (!(other instanceof SemVer)) {
573
+ other = new SemVer(other, this.options);
574
+ }
575
+
576
+ // NOT having a prerelease is > having one
577
+ if (this.prerelease.length && !other.prerelease.length) {
578
+ return -1
579
+ } else if (!this.prerelease.length && other.prerelease.length) {
580
+ return 1
581
+ } else if (!this.prerelease.length && !other.prerelease.length) {
582
+ return 0
583
+ }
584
+
585
+ let i = 0;
586
+ do {
587
+ const a = this.prerelease[i];
588
+ const b = other.prerelease[i];
589
+ debug('prerelease compare', i, a, b);
590
+ if (a === undefined && b === undefined) {
591
+ return 0
592
+ } else if (b === undefined) {
593
+ return 1
594
+ } else if (a === undefined) {
595
+ return -1
596
+ } else if (a === b) {
597
+ continue
598
+ } else {
599
+ return compareIdentifiers(a, b)
600
+ }
601
+ } while (++i)
602
+ }
603
+
604
+ compareBuild (other) {
605
+ if (!(other instanceof SemVer)) {
606
+ other = new SemVer(other, this.options);
607
+ }
608
+
609
+ let i = 0;
610
+ do {
611
+ const a = this.build[i];
612
+ const b = other.build[i];
613
+ debug('build compare', i, a, b);
614
+ if (a === undefined && b === undefined) {
615
+ return 0
616
+ } else if (b === undefined) {
617
+ return 1
618
+ } else if (a === undefined) {
619
+ return -1
620
+ } else if (a === b) {
621
+ continue
622
+ } else {
623
+ return compareIdentifiers(a, b)
624
+ }
625
+ } while (++i)
626
+ }
627
+
628
+ // preminor will bump the version up to the next minor release, and immediately
629
+ // down to pre-release. premajor and prepatch work the same way.
630
+ inc (release, identifier, identifierBase) {
631
+ if (release.startsWith('pre')) {
632
+ if (!identifier && identifierBase === false) {
633
+ throw new Error('invalid increment argument: identifier is empty')
634
+ }
635
+ // Avoid an invalid semver results
636
+ if (identifier) {
637
+ const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]);
638
+ if (!match || match[1] !== identifier) {
639
+ throw new Error(`invalid identifier: ${identifier}`)
640
+ }
641
+ }
642
+ }
643
+
644
+ switch (release) {
645
+ case 'premajor':
646
+ this.prerelease.length = 0;
647
+ this.patch = 0;
648
+ this.minor = 0;
649
+ this.major++;
650
+ this.inc('pre', identifier, identifierBase);
651
+ break
652
+ case 'preminor':
653
+ this.prerelease.length = 0;
654
+ this.patch = 0;
655
+ this.minor++;
656
+ this.inc('pre', identifier, identifierBase);
657
+ break
658
+ case 'prepatch':
659
+ // If this is already a prerelease, it will bump to the next version
660
+ // drop any prereleases that might already exist, since they are not
661
+ // relevant at this point.
662
+ this.prerelease.length = 0;
663
+ this.inc('patch', identifier, identifierBase);
664
+ this.inc('pre', identifier, identifierBase);
665
+ break
666
+ // If the input is a non-prerelease version, this acts the same as
667
+ // prepatch.
668
+ case 'prerelease':
669
+ if (this.prerelease.length === 0) {
670
+ this.inc('patch', identifier, identifierBase);
671
+ }
672
+ this.inc('pre', identifier, identifierBase);
673
+ break
674
+ case 'release':
675
+ if (this.prerelease.length === 0) {
676
+ throw new Error(`version ${this.raw} is not a prerelease`)
677
+ }
678
+ this.prerelease.length = 0;
679
+ break
680
+
681
+ case 'major':
682
+ // If this is a pre-major version, bump up to the same major version.
683
+ // Otherwise increment major.
684
+ // 1.0.0-5 bumps to 1.0.0
685
+ // 1.1.0 bumps to 2.0.0
686
+ if (
687
+ this.minor !== 0 ||
688
+ this.patch !== 0 ||
689
+ this.prerelease.length === 0
690
+ ) {
691
+ this.major++;
692
+ }
693
+ this.minor = 0;
694
+ this.patch = 0;
695
+ this.prerelease = [];
696
+ break
697
+ case 'minor':
698
+ // If this is a pre-minor version, bump up to the same minor version.
699
+ // Otherwise increment minor.
700
+ // 1.2.0-5 bumps to 1.2.0
701
+ // 1.2.1 bumps to 1.3.0
702
+ if (this.patch !== 0 || this.prerelease.length === 0) {
703
+ this.minor++;
704
+ }
705
+ this.patch = 0;
706
+ this.prerelease = [];
707
+ break
708
+ case 'patch':
709
+ // If this is not a pre-release version, it will increment the patch.
710
+ // If it is a pre-release it will bump up to the same patch version.
711
+ // 1.2.0-5 patches to 1.2.0
712
+ // 1.2.0 patches to 1.2.1
713
+ if (this.prerelease.length === 0) {
714
+ this.patch++;
715
+ }
716
+ this.prerelease = [];
717
+ break
718
+ // This probably shouldn't be used publicly.
719
+ // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
720
+ case 'pre': {
721
+ const base = Number(identifierBase) ? 1 : 0;
722
+
723
+ if (this.prerelease.length === 0) {
724
+ this.prerelease = [base];
725
+ } else {
726
+ let i = this.prerelease.length;
727
+ while (--i >= 0) {
728
+ if (typeof this.prerelease[i] === 'number') {
729
+ this.prerelease[i]++;
730
+ i = -2;
731
+ }
732
+ }
733
+ if (i === -1) {
734
+ // didn't increment anything
735
+ if (identifier === this.prerelease.join('.') && identifierBase === false) {
736
+ throw new Error('invalid increment argument: identifier already exists')
737
+ }
738
+ this.prerelease.push(base);
739
+ }
740
+ }
741
+ if (identifier) {
742
+ // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
743
+ // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
744
+ let prerelease = [identifier, base];
745
+ if (identifierBase === false) {
746
+ prerelease = [identifier];
747
+ }
748
+ if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
749
+ if (isNaN(this.prerelease[1])) {
750
+ this.prerelease = prerelease;
751
+ }
752
+ } else {
753
+ this.prerelease = prerelease;
754
+ }
755
+ }
756
+ break
757
+ }
758
+ default:
759
+ throw new Error(`invalid increment argument: ${release}`)
760
+ }
761
+ this.raw = this.format();
762
+ if (this.build.length) {
763
+ this.raw += `+${this.build.join('.')}`;
764
+ }
765
+ return this
766
+ }
767
+ }
768
+
769
+ semver$2 = SemVer;
770
+ return semver$2;
771
+ }
772
+
773
+ var parse_1;
774
+ var hasRequiredParse;
775
+
776
+ function requireParse () {
777
+ if (hasRequiredParse) return parse_1;
778
+ hasRequiredParse = 1;
779
+
780
+ const SemVer = requireSemver$1();
781
+ const parse = (version, options, throwErrors = false) => {
782
+ if (version instanceof SemVer) {
783
+ return version
784
+ }
785
+ try {
786
+ return new SemVer(version, options)
787
+ } catch (er) {
788
+ if (!throwErrors) {
789
+ return null
790
+ }
791
+ throw er
792
+ }
793
+ };
794
+
795
+ parse_1 = parse;
796
+ return parse_1;
797
+ }
798
+
799
+ var valid_1;
800
+ var hasRequiredValid$1;
801
+
802
+ function requireValid$1 () {
803
+ if (hasRequiredValid$1) return valid_1;
804
+ hasRequiredValid$1 = 1;
805
+
806
+ const parse = requireParse();
807
+ const valid = (version, options) => {
808
+ const v = parse(version, options);
809
+ return v ? v.version : null
810
+ };
811
+ valid_1 = valid;
812
+ return valid_1;
813
+ }
814
+
815
+ var clean_1;
816
+ var hasRequiredClean;
817
+
818
+ function requireClean () {
819
+ if (hasRequiredClean) return clean_1;
820
+ hasRequiredClean = 1;
821
+
822
+ const parse = requireParse();
823
+ const clean = (version, options) => {
824
+ const s = parse(version.trim().replace(/^[=v]+/, ''), options);
825
+ return s ? s.version : null
826
+ };
827
+ clean_1 = clean;
828
+ return clean_1;
829
+ }
830
+
831
+ var inc_1;
832
+ var hasRequiredInc;
833
+
834
+ function requireInc () {
835
+ if (hasRequiredInc) return inc_1;
836
+ hasRequiredInc = 1;
837
+
838
+ const SemVer = requireSemver$1();
839
+
840
+ const inc = (version, release, options, identifier, identifierBase) => {
841
+ if (typeof (options) === 'string') {
842
+ identifierBase = identifier;
843
+ identifier = options;
844
+ options = undefined;
845
+ }
846
+
847
+ try {
848
+ return new SemVer(
849
+ version instanceof SemVer ? version.version : version,
850
+ options
851
+ ).inc(release, identifier, identifierBase).version
852
+ } catch (er) {
853
+ return null
854
+ }
855
+ };
856
+ inc_1 = inc;
857
+ return inc_1;
858
+ }
859
+
860
+ var diff_1;
861
+ var hasRequiredDiff;
862
+
863
+ function requireDiff () {
864
+ if (hasRequiredDiff) return diff_1;
865
+ hasRequiredDiff = 1;
866
+
867
+ const parse = requireParse();
868
+
869
+ const diff = (version1, version2) => {
870
+ const v1 = parse(version1, null, true);
871
+ const v2 = parse(version2, null, true);
872
+ const comparison = v1.compare(v2);
873
+
874
+ if (comparison === 0) {
875
+ return null
876
+ }
877
+
878
+ const v1Higher = comparison > 0;
879
+ const highVersion = v1Higher ? v1 : v2;
880
+ const lowVersion = v1Higher ? v2 : v1;
881
+ const highHasPre = !!highVersion.prerelease.length;
882
+ const lowHasPre = !!lowVersion.prerelease.length;
883
+
884
+ if (lowHasPre && !highHasPre) {
885
+ // Going from prerelease -> no prerelease requires some special casing
886
+
887
+ // If the low version has only a major, then it will always be a major
888
+ // Some examples:
889
+ // 1.0.0-1 -> 1.0.0
890
+ // 1.0.0-1 -> 1.1.1
891
+ // 1.0.0-1 -> 2.0.0
892
+ if (!lowVersion.patch && !lowVersion.minor) {
893
+ return 'major'
894
+ }
895
+
896
+ // If the main part has no difference
897
+ if (lowVersion.compareMain(highVersion) === 0) {
898
+ if (lowVersion.minor && !lowVersion.patch) {
899
+ return 'minor'
900
+ }
901
+ return 'patch'
902
+ }
903
+ }
904
+
905
+ // add the `pre` prefix if we are going to a prerelease version
906
+ const prefix = highHasPre ? 'pre' : '';
907
+
908
+ if (v1.major !== v2.major) {
909
+ return prefix + 'major'
910
+ }
911
+
912
+ if (v1.minor !== v2.minor) {
913
+ return prefix + 'minor'
914
+ }
915
+
916
+ if (v1.patch !== v2.patch) {
917
+ return prefix + 'patch'
918
+ }
919
+
920
+ // high and low are prereleases
921
+ return 'prerelease'
922
+ };
923
+
924
+ diff_1 = diff;
925
+ return diff_1;
926
+ }
927
+
928
+ var major_1;
929
+ var hasRequiredMajor;
930
+
931
+ function requireMajor () {
932
+ if (hasRequiredMajor) return major_1;
933
+ hasRequiredMajor = 1;
934
+
935
+ const SemVer = requireSemver$1();
936
+ const major = (a, loose) => new SemVer(a, loose).major;
937
+ major_1 = major;
938
+ return major_1;
939
+ }
940
+
941
+ var minor_1;
942
+ var hasRequiredMinor;
943
+
944
+ function requireMinor () {
945
+ if (hasRequiredMinor) return minor_1;
946
+ hasRequiredMinor = 1;
947
+
948
+ const SemVer = requireSemver$1();
949
+ const minor = (a, loose) => new SemVer(a, loose).minor;
950
+ minor_1 = minor;
951
+ return minor_1;
952
+ }
953
+
954
+ var patch_1;
955
+ var hasRequiredPatch;
956
+
957
+ function requirePatch () {
958
+ if (hasRequiredPatch) return patch_1;
959
+ hasRequiredPatch = 1;
960
+
961
+ const SemVer = requireSemver$1();
962
+ const patch = (a, loose) => new SemVer(a, loose).patch;
963
+ patch_1 = patch;
964
+ return patch_1;
965
+ }
966
+
967
+ var prerelease_1;
968
+ var hasRequiredPrerelease;
969
+
970
+ function requirePrerelease () {
971
+ if (hasRequiredPrerelease) return prerelease_1;
972
+ hasRequiredPrerelease = 1;
973
+
974
+ const parse = requireParse();
975
+ const prerelease = (version, options) => {
976
+ const parsed = parse(version, options);
977
+ return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
978
+ };
979
+ prerelease_1 = prerelease;
980
+ return prerelease_1;
981
+ }
982
+
983
+ var compare_1;
984
+ var hasRequiredCompare;
985
+
986
+ function requireCompare () {
987
+ if (hasRequiredCompare) return compare_1;
988
+ hasRequiredCompare = 1;
989
+
990
+ const SemVer = requireSemver$1();
991
+ const compare = (a, b, loose) =>
992
+ new SemVer(a, loose).compare(new SemVer(b, loose));
993
+
994
+ compare_1 = compare;
995
+ return compare_1;
996
+ }
997
+
998
+ var rcompare_1;
999
+ var hasRequiredRcompare;
1000
+
1001
+ function requireRcompare () {
1002
+ if (hasRequiredRcompare) return rcompare_1;
1003
+ hasRequiredRcompare = 1;
1004
+
1005
+ const compare = requireCompare();
1006
+ const rcompare = (a, b, loose) => compare(b, a, loose);
1007
+ rcompare_1 = rcompare;
1008
+ return rcompare_1;
1009
+ }
1010
+
1011
+ var compareLoose_1;
1012
+ var hasRequiredCompareLoose;
1013
+
1014
+ function requireCompareLoose () {
1015
+ if (hasRequiredCompareLoose) return compareLoose_1;
1016
+ hasRequiredCompareLoose = 1;
1017
+
1018
+ const compare = requireCompare();
1019
+ const compareLoose = (a, b) => compare(a, b, true);
1020
+ compareLoose_1 = compareLoose;
1021
+ return compareLoose_1;
1022
+ }
1023
+
1024
+ var compareBuild_1;
1025
+ var hasRequiredCompareBuild;
1026
+
1027
+ function requireCompareBuild () {
1028
+ if (hasRequiredCompareBuild) return compareBuild_1;
1029
+ hasRequiredCompareBuild = 1;
1030
+
1031
+ const SemVer = requireSemver$1();
1032
+ const compareBuild = (a, b, loose) => {
1033
+ const versionA = new SemVer(a, loose);
1034
+ const versionB = new SemVer(b, loose);
1035
+ return versionA.compare(versionB) || versionA.compareBuild(versionB)
1036
+ };
1037
+ compareBuild_1 = compareBuild;
1038
+ return compareBuild_1;
1039
+ }
1040
+
1041
+ var sort_1;
1042
+ var hasRequiredSort;
1043
+
1044
+ function requireSort () {
1045
+ if (hasRequiredSort) return sort_1;
1046
+ hasRequiredSort = 1;
1047
+
1048
+ const compareBuild = requireCompareBuild();
1049
+ const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose));
1050
+ sort_1 = sort;
1051
+ return sort_1;
1052
+ }
1053
+
1054
+ var rsort_1;
1055
+ var hasRequiredRsort;
1056
+
1057
+ function requireRsort () {
1058
+ if (hasRequiredRsort) return rsort_1;
1059
+ hasRequiredRsort = 1;
1060
+
1061
+ const compareBuild = requireCompareBuild();
1062
+ const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));
1063
+ rsort_1 = rsort;
1064
+ return rsort_1;
1065
+ }
1066
+
1067
+ var gt_1;
1068
+ var hasRequiredGt;
1069
+
1070
+ function requireGt () {
1071
+ if (hasRequiredGt) return gt_1;
1072
+ hasRequiredGt = 1;
1073
+
1074
+ const compare = requireCompare();
1075
+ const gt = (a, b, loose) => compare(a, b, loose) > 0;
1076
+ gt_1 = gt;
1077
+ return gt_1;
1078
+ }
1079
+
1080
+ var lt_1;
1081
+ var hasRequiredLt;
1082
+
1083
+ function requireLt () {
1084
+ if (hasRequiredLt) return lt_1;
1085
+ hasRequiredLt = 1;
1086
+
1087
+ const compare = requireCompare();
1088
+ const lt = (a, b, loose) => compare(a, b, loose) < 0;
1089
+ lt_1 = lt;
1090
+ return lt_1;
1091
+ }
1092
+
1093
+ var eq_1;
1094
+ var hasRequiredEq;
1095
+
1096
+ function requireEq () {
1097
+ if (hasRequiredEq) return eq_1;
1098
+ hasRequiredEq = 1;
1099
+
1100
+ const compare = requireCompare();
1101
+ const eq = (a, b, loose) => compare(a, b, loose) === 0;
1102
+ eq_1 = eq;
1103
+ return eq_1;
1104
+ }
1105
+
1106
+ var neq_1;
1107
+ var hasRequiredNeq;
1108
+
1109
+ function requireNeq () {
1110
+ if (hasRequiredNeq) return neq_1;
1111
+ hasRequiredNeq = 1;
1112
+
1113
+ const compare = requireCompare();
1114
+ const neq = (a, b, loose) => compare(a, b, loose) !== 0;
1115
+ neq_1 = neq;
1116
+ return neq_1;
1117
+ }
1118
+
1119
+ var gte_1;
1120
+ var hasRequiredGte;
1121
+
1122
+ function requireGte () {
1123
+ if (hasRequiredGte) return gte_1;
1124
+ hasRequiredGte = 1;
1125
+
1126
+ const compare = requireCompare();
1127
+ const gte = (a, b, loose) => compare(a, b, loose) >= 0;
1128
+ gte_1 = gte;
1129
+ return gte_1;
1130
+ }
1131
+
1132
+ var lte_1;
1133
+ var hasRequiredLte;
1134
+
1135
+ function requireLte () {
1136
+ if (hasRequiredLte) return lte_1;
1137
+ hasRequiredLte = 1;
1138
+
1139
+ const compare = requireCompare();
1140
+ const lte = (a, b, loose) => compare(a, b, loose) <= 0;
1141
+ lte_1 = lte;
1142
+ return lte_1;
1143
+ }
1144
+
1145
+ var cmp_1;
1146
+ var hasRequiredCmp;
1147
+
1148
+ function requireCmp () {
1149
+ if (hasRequiredCmp) return cmp_1;
1150
+ hasRequiredCmp = 1;
1151
+
1152
+ const eq = requireEq();
1153
+ const neq = requireNeq();
1154
+ const gt = requireGt();
1155
+ const gte = requireGte();
1156
+ const lt = requireLt();
1157
+ const lte = requireLte();
1158
+
1159
+ const cmp = (a, op, b, loose) => {
1160
+ switch (op) {
1161
+ case '===':
1162
+ if (typeof a === 'object') {
1163
+ a = a.version;
1164
+ }
1165
+ if (typeof b === 'object') {
1166
+ b = b.version;
1167
+ }
1168
+ return a === b
1169
+
1170
+ case '!==':
1171
+ if (typeof a === 'object') {
1172
+ a = a.version;
1173
+ }
1174
+ if (typeof b === 'object') {
1175
+ b = b.version;
1176
+ }
1177
+ return a !== b
1178
+
1179
+ case '':
1180
+ case '=':
1181
+ case '==':
1182
+ return eq(a, b, loose)
1183
+
1184
+ case '!=':
1185
+ return neq(a, b, loose)
1186
+
1187
+ case '>':
1188
+ return gt(a, b, loose)
1189
+
1190
+ case '>=':
1191
+ return gte(a, b, loose)
1192
+
1193
+ case '<':
1194
+ return lt(a, b, loose)
1195
+
1196
+ case '<=':
1197
+ return lte(a, b, loose)
1198
+
1199
+ default:
1200
+ throw new TypeError(`Invalid operator: ${op}`)
1201
+ }
1202
+ };
1203
+ cmp_1 = cmp;
1204
+ return cmp_1;
1205
+ }
1206
+
1207
+ var coerce_1;
1208
+ var hasRequiredCoerce;
1209
+
1210
+ function requireCoerce () {
1211
+ if (hasRequiredCoerce) return coerce_1;
1212
+ hasRequiredCoerce = 1;
1213
+
1214
+ const SemVer = requireSemver$1();
1215
+ const parse = requireParse();
1216
+ const { safeRe: re, t } = requireRe();
1217
+
1218
+ const coerce = (version, options) => {
1219
+ if (version instanceof SemVer) {
1220
+ return version
1221
+ }
1222
+
1223
+ if (typeof version === 'number') {
1224
+ version = String(version);
1225
+ }
1226
+
1227
+ if (typeof version !== 'string') {
1228
+ return null
1229
+ }
1230
+
1231
+ options = options || {};
1232
+
1233
+ let match = null;
1234
+ if (!options.rtl) {
1235
+ match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]);
1236
+ } else {
1237
+ // Find the right-most coercible string that does not share
1238
+ // a terminus with a more left-ward coercible string.
1239
+ // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
1240
+ // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'
1241
+ //
1242
+ // Walk through the string checking with a /g regexp
1243
+ // Manually set the index so as to pick up overlapping matches.
1244
+ // Stop when we get a match that ends at the string end, since no
1245
+ // coercible string can be more right-ward without the same terminus.
1246
+ const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL];
1247
+ let next;
1248
+ while ((next = coerceRtlRegex.exec(version)) &&
1249
+ (!match || match.index + match[0].length !== version.length)
1250
+ ) {
1251
+ if (!match ||
1252
+ next.index + next[0].length !== match.index + match[0].length) {
1253
+ match = next;
1254
+ }
1255
+ coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
1256
+ }
1257
+ // leave it in a clean state
1258
+ coerceRtlRegex.lastIndex = -1;
1259
+ }
1260
+
1261
+ if (match === null) {
1262
+ return null
1263
+ }
1264
+
1265
+ const major = match[2];
1266
+ const minor = match[3] || '0';
1267
+ const patch = match[4] || '0';
1268
+ const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '';
1269
+ const build = options.includePrerelease && match[6] ? `+${match[6]}` : '';
1270
+
1271
+ return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)
1272
+ };
1273
+ coerce_1 = coerce;
1274
+ return coerce_1;
1275
+ }
1276
+
1277
+ var lrucache;
1278
+ var hasRequiredLrucache;
1279
+
1280
+ function requireLrucache () {
1281
+ if (hasRequiredLrucache) return lrucache;
1282
+ hasRequiredLrucache = 1;
1283
+
1284
+ class LRUCache {
1285
+ constructor () {
1286
+ this.max = 1000;
1287
+ this.map = new Map();
1288
+ }
1289
+
1290
+ get (key) {
1291
+ const value = this.map.get(key);
1292
+ if (value === undefined) {
1293
+ return undefined
1294
+ } else {
1295
+ // Remove the key from the map and add it to the end
1296
+ this.map.delete(key);
1297
+ this.map.set(key, value);
1298
+ return value
1299
+ }
1300
+ }
1301
+
1302
+ delete (key) {
1303
+ return this.map.delete(key)
1304
+ }
1305
+
1306
+ set (key, value) {
1307
+ const deleted = this.delete(key);
1308
+
1309
+ if (!deleted && value !== undefined) {
1310
+ // If cache is full, delete the least recently used item
1311
+ if (this.map.size >= this.max) {
1312
+ const firstKey = this.map.keys().next().value;
1313
+ this.delete(firstKey);
1314
+ }
1315
+
1316
+ this.map.set(key, value);
1317
+ }
1318
+
1319
+ return this
1320
+ }
1321
+ }
1322
+
1323
+ lrucache = LRUCache;
1324
+ return lrucache;
1325
+ }
1326
+
1327
+ var range;
1328
+ var hasRequiredRange;
1329
+
1330
+ function requireRange () {
1331
+ if (hasRequiredRange) return range;
1332
+ hasRequiredRange = 1;
1333
+
1334
+ const SPACE_CHARACTERS = /\s+/g;
1335
+
1336
+ // hoisted class for cyclic dependency
1337
+ class Range {
1338
+ constructor (range, options) {
1339
+ options = parseOptions(options);
1340
+
1341
+ if (range instanceof Range) {
1342
+ if (
1343
+ range.loose === !!options.loose &&
1344
+ range.includePrerelease === !!options.includePrerelease
1345
+ ) {
1346
+ return range
1347
+ } else {
1348
+ return new Range(range.raw, options)
1349
+ }
1350
+ }
1351
+
1352
+ if (range instanceof Comparator) {
1353
+ // just put it in the set and return
1354
+ this.raw = range.value;
1355
+ this.set = [[range]];
1356
+ this.formatted = undefined;
1357
+ return this
1358
+ }
1359
+
1360
+ this.options = options;
1361
+ this.loose = !!options.loose;
1362
+ this.includePrerelease = !!options.includePrerelease;
1363
+
1364
+ // First reduce all whitespace as much as possible so we do not have to rely
1365
+ // on potentially slow regexes like \s*. This is then stored and used for
1366
+ // future error messages as well.
1367
+ this.raw = range.trim().replace(SPACE_CHARACTERS, ' ');
1368
+
1369
+ // First, split on ||
1370
+ this.set = this.raw
1371
+ .split('||')
1372
+ // map the range to a 2d array of comparators
1373
+ .map(r => this.parseRange(r.trim()))
1374
+ // throw out any comparator lists that are empty
1375
+ // this generally means that it was not a valid range, which is allowed
1376
+ // in loose mode, but will still throw if the WHOLE range is invalid.
1377
+ .filter(c => c.length);
1378
+
1379
+ if (!this.set.length) {
1380
+ throw new TypeError(`Invalid SemVer Range: ${this.raw}`)
1381
+ }
1382
+
1383
+ // if we have any that are not the null set, throw out null sets.
1384
+ if (this.set.length > 1) {
1385
+ // keep the first one, in case they're all null sets
1386
+ const first = this.set[0];
1387
+ this.set = this.set.filter(c => !isNullSet(c[0]));
1388
+ if (this.set.length === 0) {
1389
+ this.set = [first];
1390
+ } else if (this.set.length > 1) {
1391
+ // if we have any that are *, then the range is just *
1392
+ for (const c of this.set) {
1393
+ if (c.length === 1 && isAny(c[0])) {
1394
+ this.set = [c];
1395
+ break
1396
+ }
1397
+ }
1398
+ }
1399
+ }
1400
+
1401
+ this.formatted = undefined;
1402
+ }
1403
+
1404
+ get range () {
1405
+ if (this.formatted === undefined) {
1406
+ this.formatted = '';
1407
+ for (let i = 0; i < this.set.length; i++) {
1408
+ if (i > 0) {
1409
+ this.formatted += '||';
1410
+ }
1411
+ const comps = this.set[i];
1412
+ for (let k = 0; k < comps.length; k++) {
1413
+ if (k > 0) {
1414
+ this.formatted += ' ';
1415
+ }
1416
+ this.formatted += comps[k].toString().trim();
1417
+ }
1418
+ }
1419
+ }
1420
+ return this.formatted
1421
+ }
1422
+
1423
+ format () {
1424
+ return this.range
1425
+ }
1426
+
1427
+ toString () {
1428
+ return this.range
1429
+ }
1430
+
1431
+ parseRange (range) {
1432
+ // memoize range parsing for performance.
1433
+ // this is a very hot path, and fully deterministic.
1434
+ const memoOpts =
1435
+ (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |
1436
+ (this.options.loose && FLAG_LOOSE);
1437
+ const memoKey = memoOpts + ':' + range;
1438
+ const cached = cache.get(memoKey);
1439
+ if (cached) {
1440
+ return cached
1441
+ }
1442
+
1443
+ const loose = this.options.loose;
1444
+ // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
1445
+ const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
1446
+ range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
1447
+ debug('hyphen replace', range);
1448
+
1449
+ // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
1450
+ range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
1451
+ debug('comparator trim', range);
1452
+
1453
+ // `~ 1.2.3` => `~1.2.3`
1454
+ range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
1455
+ debug('tilde trim', range);
1456
+
1457
+ // `^ 1.2.3` => `^1.2.3`
1458
+ range = range.replace(re[t.CARETTRIM], caretTrimReplace);
1459
+ debug('caret trim', range);
1460
+
1461
+ // At this point, the range is completely trimmed and
1462
+ // ready to be split into comparators.
1463
+
1464
+ let rangeList = range
1465
+ .split(' ')
1466
+ .map(comp => parseComparator(comp, this.options))
1467
+ .join(' ')
1468
+ .split(/\s+/)
1469
+ // >=0.0.0 is equivalent to *
1470
+ .map(comp => replaceGTE0(comp, this.options));
1471
+
1472
+ if (loose) {
1473
+ // in loose mode, throw out any that are not valid comparators
1474
+ rangeList = rangeList.filter(comp => {
1475
+ debug('loose invalid filter', comp, this.options);
1476
+ return !!comp.match(re[t.COMPARATORLOOSE])
1477
+ });
1478
+ }
1479
+ debug('range list', rangeList);
1480
+
1481
+ // if any comparators are the null set, then replace with JUST null set
1482
+ // if more than one comparator, remove any * comparators
1483
+ // also, don't include the same comparator more than once
1484
+ const rangeMap = new Map();
1485
+ const comparators = rangeList.map(comp => new Comparator(comp, this.options));
1486
+ for (const comp of comparators) {
1487
+ if (isNullSet(comp)) {
1488
+ return [comp]
1489
+ }
1490
+ rangeMap.set(comp.value, comp);
1491
+ }
1492
+ if (rangeMap.size > 1 && rangeMap.has('')) {
1493
+ rangeMap.delete('');
1494
+ }
1495
+
1496
+ const result = [...rangeMap.values()];
1497
+ cache.set(memoKey, result);
1498
+ return result
1499
+ }
1500
+
1501
+ intersects (range, options) {
1502
+ if (!(range instanceof Range)) {
1503
+ throw new TypeError('a Range is required')
1504
+ }
1505
+
1506
+ return this.set.some((thisComparators) => {
1507
+ return (
1508
+ isSatisfiable(thisComparators, options) &&
1509
+ range.set.some((rangeComparators) => {
1510
+ return (
1511
+ isSatisfiable(rangeComparators, options) &&
1512
+ thisComparators.every((thisComparator) => {
1513
+ return rangeComparators.every((rangeComparator) => {
1514
+ return thisComparator.intersects(rangeComparator, options)
1515
+ })
1516
+ })
1517
+ )
1518
+ })
1519
+ )
1520
+ })
1521
+ }
1522
+
1523
+ // if ANY of the sets match ALL of its comparators, then pass
1524
+ test (version) {
1525
+ if (!version) {
1526
+ return false
1527
+ }
1528
+
1529
+ if (typeof version === 'string') {
1530
+ try {
1531
+ version = new SemVer(version, this.options);
1532
+ } catch (er) {
1533
+ return false
1534
+ }
1535
+ }
1536
+
1537
+ for (let i = 0; i < this.set.length; i++) {
1538
+ if (testSet(this.set[i], version, this.options)) {
1539
+ return true
1540
+ }
1541
+ }
1542
+ return false
1543
+ }
1544
+ }
1545
+
1546
+ range = Range;
1547
+
1548
+ const LRU = requireLrucache();
1549
+ const cache = new LRU();
1550
+
1551
+ const parseOptions = requireParseOptions();
1552
+ const Comparator = requireComparator();
1553
+ const debug = requireDebug();
1554
+ const SemVer = requireSemver$1();
1555
+ const {
1556
+ safeRe: re,
1557
+ t,
1558
+ comparatorTrimReplace,
1559
+ tildeTrimReplace,
1560
+ caretTrimReplace,
1561
+ } = requireRe();
1562
+ const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = requireConstants();
1563
+
1564
+ const isNullSet = c => c.value === '<0.0.0-0';
1565
+ const isAny = c => c.value === '';
1566
+
1567
+ // take a set of comparators and determine whether there
1568
+ // exists a version which can satisfy it
1569
+ const isSatisfiable = (comparators, options) => {
1570
+ let result = true;
1571
+ const remainingComparators = comparators.slice();
1572
+ let testComparator = remainingComparators.pop();
1573
+
1574
+ while (result && remainingComparators.length) {
1575
+ result = remainingComparators.every((otherComparator) => {
1576
+ return testComparator.intersects(otherComparator, options)
1577
+ });
1578
+
1579
+ testComparator = remainingComparators.pop();
1580
+ }
1581
+
1582
+ return result
1583
+ };
1584
+
1585
+ // comprised of xranges, tildes, stars, and gtlt's at this point.
1586
+ // already replaced the hyphen ranges
1587
+ // turn into a set of JUST comparators.
1588
+ const parseComparator = (comp, options) => {
1589
+ comp = comp.replace(re[t.BUILD], '');
1590
+ debug('comp', comp, options);
1591
+ comp = replaceCarets(comp, options);
1592
+ debug('caret', comp);
1593
+ comp = replaceTildes(comp, options);
1594
+ debug('tildes', comp);
1595
+ comp = replaceXRanges(comp, options);
1596
+ debug('xrange', comp);
1597
+ comp = replaceStars(comp, options);
1598
+ debug('stars', comp);
1599
+ return comp
1600
+ };
1601
+
1602
+ const isX = id => !id || id.toLowerCase() === 'x' || id === '*';
1603
+
1604
+ // ~, ~> --> * (any, kinda silly)
1605
+ // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
1606
+ // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
1607
+ // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
1608
+ // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
1609
+ // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
1610
+ // ~0.0.1 --> >=0.0.1 <0.1.0-0
1611
+ const replaceTildes = (comp, options) => {
1612
+ return comp
1613
+ .trim()
1614
+ .split(/\s+/)
1615
+ .map((c) => replaceTilde(c, options))
1616
+ .join(' ')
1617
+ };
1618
+
1619
+ const replaceTilde = (comp, options) => {
1620
+ const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
1621
+ return comp.replace(r, (_, M, m, p, pr) => {
1622
+ debug('tilde', comp, _, M, m, p, pr);
1623
+ let ret;
1624
+
1625
+ if (isX(M)) {
1626
+ ret = '';
1627
+ } else if (isX(m)) {
1628
+ ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
1629
+ } else if (isX(p)) {
1630
+ // ~1.2 == >=1.2.0 <1.3.0-0
1631
+ ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
1632
+ } else if (pr) {
1633
+ debug('replaceTilde pr', pr);
1634
+ ret = `>=${M}.${m}.${p}-${pr
1635
+ } <${M}.${+m + 1}.0-0`;
1636
+ } else {
1637
+ // ~1.2.3 == >=1.2.3 <1.3.0-0
1638
+ ret = `>=${M}.${m}.${p
1639
+ } <${M}.${+m + 1}.0-0`;
1640
+ }
1641
+
1642
+ debug('tilde return', ret);
1643
+ return ret
1644
+ })
1645
+ };
1646
+
1647
+ // ^ --> * (any, kinda silly)
1648
+ // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
1649
+ // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
1650
+ // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
1651
+ // ^1.2.3 --> >=1.2.3 <2.0.0-0
1652
+ // ^1.2.0 --> >=1.2.0 <2.0.0-0
1653
+ // ^0.0.1 --> >=0.0.1 <0.0.2-0
1654
+ // ^0.1.0 --> >=0.1.0 <0.2.0-0
1655
+ const replaceCarets = (comp, options) => {
1656
+ return comp
1657
+ .trim()
1658
+ .split(/\s+/)
1659
+ .map((c) => replaceCaret(c, options))
1660
+ .join(' ')
1661
+ };
1662
+
1663
+ const replaceCaret = (comp, options) => {
1664
+ debug('caret', comp, options);
1665
+ const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
1666
+ const z = options.includePrerelease ? '-0' : '';
1667
+ return comp.replace(r, (_, M, m, p, pr) => {
1668
+ debug('caret', comp, _, M, m, p, pr);
1669
+ let ret;
1670
+
1671
+ if (isX(M)) {
1672
+ ret = '';
1673
+ } else if (isX(m)) {
1674
+ ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
1675
+ } else if (isX(p)) {
1676
+ if (M === '0') {
1677
+ ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
1678
+ } else {
1679
+ ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
1680
+ }
1681
+ } else if (pr) {
1682
+ debug('replaceCaret pr', pr);
1683
+ if (M === '0') {
1684
+ if (m === '0') {
1685
+ ret = `>=${M}.${m}.${p}-${pr
1686
+ } <${M}.${m}.${+p + 1}-0`;
1687
+ } else {
1688
+ ret = `>=${M}.${m}.${p}-${pr
1689
+ } <${M}.${+m + 1}.0-0`;
1690
+ }
1691
+ } else {
1692
+ ret = `>=${M}.${m}.${p}-${pr
1693
+ } <${+M + 1}.0.0-0`;
1694
+ }
1695
+ } else {
1696
+ debug('no pr');
1697
+ if (M === '0') {
1698
+ if (m === '0') {
1699
+ ret = `>=${M}.${m}.${p
1700
+ }${z} <${M}.${m}.${+p + 1}-0`;
1701
+ } else {
1702
+ ret = `>=${M}.${m}.${p
1703
+ }${z} <${M}.${+m + 1}.0-0`;
1704
+ }
1705
+ } else {
1706
+ ret = `>=${M}.${m}.${p
1707
+ } <${+M + 1}.0.0-0`;
1708
+ }
1709
+ }
1710
+
1711
+ debug('caret return', ret);
1712
+ return ret
1713
+ })
1714
+ };
1715
+
1716
+ const replaceXRanges = (comp, options) => {
1717
+ debug('replaceXRanges', comp, options);
1718
+ return comp
1719
+ .split(/\s+/)
1720
+ .map((c) => replaceXRange(c, options))
1721
+ .join(' ')
1722
+ };
1723
+
1724
+ const replaceXRange = (comp, options) => {
1725
+ comp = comp.trim();
1726
+ const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
1727
+ return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
1728
+ debug('xRange', comp, ret, gtlt, M, m, p, pr);
1729
+ const xM = isX(M);
1730
+ const xm = xM || isX(m);
1731
+ const xp = xm || isX(p);
1732
+ const anyX = xp;
1733
+
1734
+ if (gtlt === '=' && anyX) {
1735
+ gtlt = '';
1736
+ }
1737
+
1738
+ // if we're including prereleases in the match, then we need
1739
+ // to fix this to -0, the lowest possible prerelease value
1740
+ pr = options.includePrerelease ? '-0' : '';
1741
+
1742
+ if (xM) {
1743
+ if (gtlt === '>' || gtlt === '<') {
1744
+ // nothing is allowed
1745
+ ret = '<0.0.0-0';
1746
+ } else {
1747
+ // nothing is forbidden
1748
+ ret = '*';
1749
+ }
1750
+ } else if (gtlt && anyX) {
1751
+ // we know patch is an x, because we have any x at all.
1752
+ // replace X with 0
1753
+ if (xm) {
1754
+ m = 0;
1755
+ }
1756
+ p = 0;
1757
+
1758
+ if (gtlt === '>') {
1759
+ // >1 => >=2.0.0
1760
+ // >1.2 => >=1.3.0
1761
+ gtlt = '>=';
1762
+ if (xm) {
1763
+ M = +M + 1;
1764
+ m = 0;
1765
+ p = 0;
1766
+ } else {
1767
+ m = +m + 1;
1768
+ p = 0;
1769
+ }
1770
+ } else if (gtlt === '<=') {
1771
+ // <=0.7.x is actually <0.8.0, since any 0.7.x should
1772
+ // pass. Similarly, <=7.x is actually <8.0.0, etc.
1773
+ gtlt = '<';
1774
+ if (xm) {
1775
+ M = +M + 1;
1776
+ } else {
1777
+ m = +m + 1;
1778
+ }
1779
+ }
1780
+
1781
+ if (gtlt === '<') {
1782
+ pr = '-0';
1783
+ }
1784
+
1785
+ ret = `${gtlt + M}.${m}.${p}${pr}`;
1786
+ } else if (xm) {
1787
+ ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
1788
+ } else if (xp) {
1789
+ ret = `>=${M}.${m}.0${pr
1790
+ } <${M}.${+m + 1}.0-0`;
1791
+ }
1792
+
1793
+ debug('xRange return', ret);
1794
+
1795
+ return ret
1796
+ })
1797
+ };
1798
+
1799
+ // Because * is AND-ed with everything else in the comparator,
1800
+ // and '' means "any version", just remove the *s entirely.
1801
+ const replaceStars = (comp, options) => {
1802
+ debug('replaceStars', comp, options);
1803
+ // Looseness is ignored here. star is always as loose as it gets!
1804
+ return comp
1805
+ .trim()
1806
+ .replace(re[t.STAR], '')
1807
+ };
1808
+
1809
+ const replaceGTE0 = (comp, options) => {
1810
+ debug('replaceGTE0', comp, options);
1811
+ return comp
1812
+ .trim()
1813
+ .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
1814
+ };
1815
+
1816
+ // This function is passed to string.replace(re[t.HYPHENRANGE])
1817
+ // M, m, patch, prerelease, build
1818
+ // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
1819
+ // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
1820
+ // 1.2 - 3.4 => >=1.2.0 <3.5.0-0
1821
+ // TODO build?
1822
+ const hyphenReplace = incPr => ($0,
1823
+ from, fM, fm, fp, fpr, fb,
1824
+ to, tM, tm, tp, tpr) => {
1825
+ if (isX(fM)) {
1826
+ from = '';
1827
+ } else if (isX(fm)) {
1828
+ from = `>=${fM}.0.0${incPr ? '-0' : ''}`;
1829
+ } else if (isX(fp)) {
1830
+ from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`;
1831
+ } else if (fpr) {
1832
+ from = `>=${from}`;
1833
+ } else {
1834
+ from = `>=${from}${incPr ? '-0' : ''}`;
1835
+ }
1836
+
1837
+ if (isX(tM)) {
1838
+ to = '';
1839
+ } else if (isX(tm)) {
1840
+ to = `<${+tM + 1}.0.0-0`;
1841
+ } else if (isX(tp)) {
1842
+ to = `<${tM}.${+tm + 1}.0-0`;
1843
+ } else if (tpr) {
1844
+ to = `<=${tM}.${tm}.${tp}-${tpr}`;
1845
+ } else if (incPr) {
1846
+ to = `<${tM}.${tm}.${+tp + 1}-0`;
1847
+ } else {
1848
+ to = `<=${to}`;
1849
+ }
1850
+
1851
+ return `${from} ${to}`.trim()
1852
+ };
1853
+
1854
+ const testSet = (set, version, options) => {
1855
+ for (let i = 0; i < set.length; i++) {
1856
+ if (!set[i].test(version)) {
1857
+ return false
1858
+ }
1859
+ }
1860
+
1861
+ if (version.prerelease.length && !options.includePrerelease) {
1862
+ // Find the set of versions that are allowed to have prereleases
1863
+ // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
1864
+ // That should allow `1.2.3-pr.2` to pass.
1865
+ // However, `1.2.4-alpha.notready` should NOT be allowed,
1866
+ // even though it's within the range set by the comparators.
1867
+ for (let i = 0; i < set.length; i++) {
1868
+ debug(set[i].semver);
1869
+ if (set[i].semver === Comparator.ANY) {
1870
+ continue
1871
+ }
1872
+
1873
+ if (set[i].semver.prerelease.length > 0) {
1874
+ const allowed = set[i].semver;
1875
+ if (allowed.major === version.major &&
1876
+ allowed.minor === version.minor &&
1877
+ allowed.patch === version.patch) {
1878
+ return true
1879
+ }
1880
+ }
1881
+ }
1882
+
1883
+ // Version has a -pre, but it's not one of the ones we like.
1884
+ return false
1885
+ }
1886
+
1887
+ return true
1888
+ };
1889
+ return range;
1890
+ }
1891
+
1892
+ var comparator;
1893
+ var hasRequiredComparator;
1894
+
1895
+ function requireComparator () {
1896
+ if (hasRequiredComparator) return comparator;
1897
+ hasRequiredComparator = 1;
1898
+
1899
+ const ANY = Symbol('SemVer ANY');
1900
+ // hoisted class for cyclic dependency
1901
+ class Comparator {
1902
+ static get ANY () {
1903
+ return ANY
1904
+ }
1905
+
1906
+ constructor (comp, options) {
1907
+ options = parseOptions(options);
1908
+
1909
+ if (comp instanceof Comparator) {
1910
+ if (comp.loose === !!options.loose) {
1911
+ return comp
1912
+ } else {
1913
+ comp = comp.value;
1914
+ }
1915
+ }
1916
+
1917
+ comp = comp.trim().split(/\s+/).join(' ');
1918
+ debug('comparator', comp, options);
1919
+ this.options = options;
1920
+ this.loose = !!options.loose;
1921
+ this.parse(comp);
1922
+
1923
+ if (this.semver === ANY) {
1924
+ this.value = '';
1925
+ } else {
1926
+ this.value = this.operator + this.semver.version;
1927
+ }
1928
+
1929
+ debug('comp', this);
1930
+ }
1931
+
1932
+ parse (comp) {
1933
+ const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
1934
+ const m = comp.match(r);
1935
+
1936
+ if (!m) {
1937
+ throw new TypeError(`Invalid comparator: ${comp}`)
1938
+ }
1939
+
1940
+ this.operator = m[1] !== undefined ? m[1] : '';
1941
+ if (this.operator === '=') {
1942
+ this.operator = '';
1943
+ }
1944
+
1945
+ // if it literally is just '>' or '' then allow anything.
1946
+ if (!m[2]) {
1947
+ this.semver = ANY;
1948
+ } else {
1949
+ this.semver = new SemVer(m[2], this.options.loose);
1950
+ }
1951
+ }
1952
+
1953
+ toString () {
1954
+ return this.value
1955
+ }
1956
+
1957
+ test (version) {
1958
+ debug('Comparator.test', version, this.options.loose);
1959
+
1960
+ if (this.semver === ANY || version === ANY) {
1961
+ return true
1962
+ }
1963
+
1964
+ if (typeof version === 'string') {
1965
+ try {
1966
+ version = new SemVer(version, this.options);
1967
+ } catch (er) {
1968
+ return false
1969
+ }
1970
+ }
1971
+
1972
+ return cmp(version, this.operator, this.semver, this.options)
1973
+ }
1974
+
1975
+ intersects (comp, options) {
1976
+ if (!(comp instanceof Comparator)) {
1977
+ throw new TypeError('a Comparator is required')
1978
+ }
1979
+
1980
+ if (this.operator === '') {
1981
+ if (this.value === '') {
1982
+ return true
1983
+ }
1984
+ return new Range(comp.value, options).test(this.value)
1985
+ } else if (comp.operator === '') {
1986
+ if (comp.value === '') {
1987
+ return true
1988
+ }
1989
+ return new Range(this.value, options).test(comp.semver)
1990
+ }
1991
+
1992
+ options = parseOptions(options);
1993
+
1994
+ // Special cases where nothing can possibly be lower
1995
+ if (options.includePrerelease &&
1996
+ (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {
1997
+ return false
1998
+ }
1999
+ if (!options.includePrerelease &&
2000
+ (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {
2001
+ return false
2002
+ }
2003
+
2004
+ // Same direction increasing (> or >=)
2005
+ if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {
2006
+ return true
2007
+ }
2008
+ // Same direction decreasing (< or <=)
2009
+ if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {
2010
+ return true
2011
+ }
2012
+ // same SemVer and both sides are inclusive (<= or >=)
2013
+ if (
2014
+ (this.semver.version === comp.semver.version) &&
2015
+ this.operator.includes('=') && comp.operator.includes('=')) {
2016
+ return true
2017
+ }
2018
+ // opposite directions less than
2019
+ if (cmp(this.semver, '<', comp.semver, options) &&
2020
+ this.operator.startsWith('>') && comp.operator.startsWith('<')) {
2021
+ return true
2022
+ }
2023
+ // opposite directions greater than
2024
+ if (cmp(this.semver, '>', comp.semver, options) &&
2025
+ this.operator.startsWith('<') && comp.operator.startsWith('>')) {
2026
+ return true
2027
+ }
2028
+ return false
2029
+ }
2030
+ }
2031
+
2032
+ comparator = Comparator;
2033
+
2034
+ const parseOptions = requireParseOptions();
2035
+ const { safeRe: re, t } = requireRe();
2036
+ const cmp = requireCmp();
2037
+ const debug = requireDebug();
2038
+ const SemVer = requireSemver$1();
2039
+ const Range = requireRange();
2040
+ return comparator;
2041
+ }
2042
+
2043
+ var satisfies_1;
2044
+ var hasRequiredSatisfies;
2045
+
2046
+ function requireSatisfies () {
2047
+ if (hasRequiredSatisfies) return satisfies_1;
2048
+ hasRequiredSatisfies = 1;
2049
+
2050
+ const Range = requireRange();
2051
+ const satisfies = (version, range, options) => {
2052
+ try {
2053
+ range = new Range(range, options);
2054
+ } catch (er) {
2055
+ return false
2056
+ }
2057
+ return range.test(version)
2058
+ };
2059
+ satisfies_1 = satisfies;
2060
+ return satisfies_1;
2061
+ }
2062
+
2063
+ var toComparators_1;
2064
+ var hasRequiredToComparators;
2065
+
2066
+ function requireToComparators () {
2067
+ if (hasRequiredToComparators) return toComparators_1;
2068
+ hasRequiredToComparators = 1;
2069
+
2070
+ const Range = requireRange();
2071
+
2072
+ // Mostly just for testing and legacy API reasons
2073
+ const toComparators = (range, options) =>
2074
+ new Range(range, options).set
2075
+ .map(comp => comp.map(c => c.value).join(' ').trim().split(' '));
2076
+
2077
+ toComparators_1 = toComparators;
2078
+ return toComparators_1;
2079
+ }
2080
+
2081
+ var maxSatisfying_1;
2082
+ var hasRequiredMaxSatisfying;
2083
+
2084
+ function requireMaxSatisfying () {
2085
+ if (hasRequiredMaxSatisfying) return maxSatisfying_1;
2086
+ hasRequiredMaxSatisfying = 1;
2087
+
2088
+ const SemVer = requireSemver$1();
2089
+ const Range = requireRange();
2090
+
2091
+ const maxSatisfying = (versions, range, options) => {
2092
+ let max = null;
2093
+ let maxSV = null;
2094
+ let rangeObj = null;
2095
+ try {
2096
+ rangeObj = new Range(range, options);
2097
+ } catch (er) {
2098
+ return null
2099
+ }
2100
+ versions.forEach((v) => {
2101
+ if (rangeObj.test(v)) {
2102
+ // satisfies(v, range, options)
2103
+ if (!max || maxSV.compare(v) === -1) {
2104
+ // compare(max, v, true)
2105
+ max = v;
2106
+ maxSV = new SemVer(max, options);
2107
+ }
2108
+ }
2109
+ });
2110
+ return max
2111
+ };
2112
+ maxSatisfying_1 = maxSatisfying;
2113
+ return maxSatisfying_1;
2114
+ }
2115
+
2116
+ var minSatisfying_1;
2117
+ var hasRequiredMinSatisfying;
2118
+
2119
+ function requireMinSatisfying () {
2120
+ if (hasRequiredMinSatisfying) return minSatisfying_1;
2121
+ hasRequiredMinSatisfying = 1;
2122
+
2123
+ const SemVer = requireSemver$1();
2124
+ const Range = requireRange();
2125
+ const minSatisfying = (versions, range, options) => {
2126
+ let min = null;
2127
+ let minSV = null;
2128
+ let rangeObj = null;
2129
+ try {
2130
+ rangeObj = new Range(range, options);
2131
+ } catch (er) {
2132
+ return null
2133
+ }
2134
+ versions.forEach((v) => {
2135
+ if (rangeObj.test(v)) {
2136
+ // satisfies(v, range, options)
2137
+ if (!min || minSV.compare(v) === 1) {
2138
+ // compare(min, v, true)
2139
+ min = v;
2140
+ minSV = new SemVer(min, options);
2141
+ }
2142
+ }
2143
+ });
2144
+ return min
2145
+ };
2146
+ minSatisfying_1 = minSatisfying;
2147
+ return minSatisfying_1;
2148
+ }
2149
+
2150
+ var minVersion_1;
2151
+ var hasRequiredMinVersion;
2152
+
2153
+ function requireMinVersion () {
2154
+ if (hasRequiredMinVersion) return minVersion_1;
2155
+ hasRequiredMinVersion = 1;
2156
+
2157
+ const SemVer = requireSemver$1();
2158
+ const Range = requireRange();
2159
+ const gt = requireGt();
2160
+
2161
+ const minVersion = (range, loose) => {
2162
+ range = new Range(range, loose);
2163
+
2164
+ let minver = new SemVer('0.0.0');
2165
+ if (range.test(minver)) {
2166
+ return minver
2167
+ }
2168
+
2169
+ minver = new SemVer('0.0.0-0');
2170
+ if (range.test(minver)) {
2171
+ return minver
2172
+ }
2173
+
2174
+ minver = null;
2175
+ for (let i = 0; i < range.set.length; ++i) {
2176
+ const comparators = range.set[i];
2177
+
2178
+ let setMin = null;
2179
+ comparators.forEach((comparator) => {
2180
+ // Clone to avoid manipulating the comparator's semver object.
2181
+ const compver = new SemVer(comparator.semver.version);
2182
+ switch (comparator.operator) {
2183
+ case '>':
2184
+ if (compver.prerelease.length === 0) {
2185
+ compver.patch++;
2186
+ } else {
2187
+ compver.prerelease.push(0);
2188
+ }
2189
+ compver.raw = compver.format();
2190
+ /* fallthrough */
2191
+ case '':
2192
+ case '>=':
2193
+ if (!setMin || gt(compver, setMin)) {
2194
+ setMin = compver;
2195
+ }
2196
+ break
2197
+ case '<':
2198
+ case '<=':
2199
+ /* Ignore maximum versions */
2200
+ break
2201
+ /* istanbul ignore next */
2202
+ default:
2203
+ throw new Error(`Unexpected operation: ${comparator.operator}`)
2204
+ }
2205
+ });
2206
+ if (setMin && (!minver || gt(minver, setMin))) {
2207
+ minver = setMin;
2208
+ }
2209
+ }
2210
+
2211
+ if (minver && range.test(minver)) {
2212
+ return minver
2213
+ }
2214
+
2215
+ return null
2216
+ };
2217
+ minVersion_1 = minVersion;
2218
+ return minVersion_1;
2219
+ }
2220
+
2221
+ var valid;
2222
+ var hasRequiredValid;
2223
+
2224
+ function requireValid () {
2225
+ if (hasRequiredValid) return valid;
2226
+ hasRequiredValid = 1;
2227
+
2228
+ const Range = requireRange();
2229
+ const validRange = (range, options) => {
2230
+ try {
2231
+ // Return '*' instead of '' so that truthiness works.
2232
+ // This will throw if it's invalid anyway
2233
+ return new Range(range, options).range || '*'
2234
+ } catch (er) {
2235
+ return null
2236
+ }
2237
+ };
2238
+ valid = validRange;
2239
+ return valid;
2240
+ }
2241
+
2242
+ var outside_1;
2243
+ var hasRequiredOutside;
2244
+
2245
+ function requireOutside () {
2246
+ if (hasRequiredOutside) return outside_1;
2247
+ hasRequiredOutside = 1;
2248
+
2249
+ const SemVer = requireSemver$1();
2250
+ const Comparator = requireComparator();
2251
+ const { ANY } = Comparator;
2252
+ const Range = requireRange();
2253
+ const satisfies = requireSatisfies();
2254
+ const gt = requireGt();
2255
+ const lt = requireLt();
2256
+ const lte = requireLte();
2257
+ const gte = requireGte();
2258
+
2259
+ const outside = (version, range, hilo, options) => {
2260
+ version = new SemVer(version, options);
2261
+ range = new Range(range, options);
2262
+
2263
+ let gtfn, ltefn, ltfn, comp, ecomp;
2264
+ switch (hilo) {
2265
+ case '>':
2266
+ gtfn = gt;
2267
+ ltefn = lte;
2268
+ ltfn = lt;
2269
+ comp = '>';
2270
+ ecomp = '>=';
2271
+ break
2272
+ case '<':
2273
+ gtfn = lt;
2274
+ ltefn = gte;
2275
+ ltfn = gt;
2276
+ comp = '<';
2277
+ ecomp = '<=';
2278
+ break
2279
+ default:
2280
+ throw new TypeError('Must provide a hilo val of "<" or ">"')
2281
+ }
2282
+
2283
+ // If it satisfies the range it is not outside
2284
+ if (satisfies(version, range, options)) {
2285
+ return false
2286
+ }
2287
+
2288
+ // From now on, variable terms are as if we're in "gtr" mode.
2289
+ // but note that everything is flipped for the "ltr" function.
2290
+
2291
+ for (let i = 0; i < range.set.length; ++i) {
2292
+ const comparators = range.set[i];
2293
+
2294
+ let high = null;
2295
+ let low = null;
2296
+
2297
+ comparators.forEach((comparator) => {
2298
+ if (comparator.semver === ANY) {
2299
+ comparator = new Comparator('>=0.0.0');
2300
+ }
2301
+ high = high || comparator;
2302
+ low = low || comparator;
2303
+ if (gtfn(comparator.semver, high.semver, options)) {
2304
+ high = comparator;
2305
+ } else if (ltfn(comparator.semver, low.semver, options)) {
2306
+ low = comparator;
2307
+ }
2308
+ });
2309
+
2310
+ // If the edge version comparator has a operator then our version
2311
+ // isn't outside it
2312
+ if (high.operator === comp || high.operator === ecomp) {
2313
+ return false
2314
+ }
2315
+
2316
+ // If the lowest version comparator has an operator and our version
2317
+ // is less than it then it isn't higher than the range
2318
+ if ((!low.operator || low.operator === comp) &&
2319
+ ltefn(version, low.semver)) {
2320
+ return false
2321
+ } else if (low.operator === ecomp && ltfn(version, low.semver)) {
2322
+ return false
2323
+ }
2324
+ }
2325
+ return true
2326
+ };
2327
+
2328
+ outside_1 = outside;
2329
+ return outside_1;
2330
+ }
2331
+
2332
+ var gtr_1;
2333
+ var hasRequiredGtr;
2334
+
2335
+ function requireGtr () {
2336
+ if (hasRequiredGtr) return gtr_1;
2337
+ hasRequiredGtr = 1;
2338
+
2339
+ // Determine if version is greater than all the versions possible in the range.
2340
+ const outside = requireOutside();
2341
+ const gtr = (version, range, options) => outside(version, range, '>', options);
2342
+ gtr_1 = gtr;
2343
+ return gtr_1;
2344
+ }
2345
+
2346
+ var ltr_1;
2347
+ var hasRequiredLtr;
2348
+
2349
+ function requireLtr () {
2350
+ if (hasRequiredLtr) return ltr_1;
2351
+ hasRequiredLtr = 1;
2352
+
2353
+ const outside = requireOutside();
2354
+ // Determine if version is less than all the versions possible in the range
2355
+ const ltr = (version, range, options) => outside(version, range, '<', options);
2356
+ ltr_1 = ltr;
2357
+ return ltr_1;
2358
+ }
2359
+
2360
+ var intersects_1;
2361
+ var hasRequiredIntersects;
2362
+
2363
+ function requireIntersects () {
2364
+ if (hasRequiredIntersects) return intersects_1;
2365
+ hasRequiredIntersects = 1;
2366
+
2367
+ const Range = requireRange();
2368
+ const intersects = (r1, r2, options) => {
2369
+ r1 = new Range(r1, options);
2370
+ r2 = new Range(r2, options);
2371
+ return r1.intersects(r2, options)
2372
+ };
2373
+ intersects_1 = intersects;
2374
+ return intersects_1;
2375
+ }
2376
+
2377
+ var simplify;
2378
+ var hasRequiredSimplify;
2379
+
2380
+ function requireSimplify () {
2381
+ if (hasRequiredSimplify) return simplify;
2382
+ hasRequiredSimplify = 1;
2383
+
2384
+ // given a set of versions and a range, create a "simplified" range
2385
+ // that includes the same versions that the original range does
2386
+ // If the original range is shorter than the simplified one, return that.
2387
+ const satisfies = requireSatisfies();
2388
+ const compare = requireCompare();
2389
+ simplify = (versions, range, options) => {
2390
+ const set = [];
2391
+ let first = null;
2392
+ let prev = null;
2393
+ const v = versions.sort((a, b) => compare(a, b, options));
2394
+ for (const version of v) {
2395
+ const included = satisfies(version, range, options);
2396
+ if (included) {
2397
+ prev = version;
2398
+ if (!first) {
2399
+ first = version;
2400
+ }
2401
+ } else {
2402
+ if (prev) {
2403
+ set.push([first, prev]);
2404
+ }
2405
+ prev = null;
2406
+ first = null;
2407
+ }
2408
+ }
2409
+ if (first) {
2410
+ set.push([first, null]);
2411
+ }
2412
+
2413
+ const ranges = [];
2414
+ for (const [min, max] of set) {
2415
+ if (min === max) {
2416
+ ranges.push(min);
2417
+ } else if (!max && min === v[0]) {
2418
+ ranges.push('*');
2419
+ } else if (!max) {
2420
+ ranges.push(`>=${min}`);
2421
+ } else if (min === v[0]) {
2422
+ ranges.push(`<=${max}`);
2423
+ } else {
2424
+ ranges.push(`${min} - ${max}`);
2425
+ }
2426
+ }
2427
+ const simplified = ranges.join(' || ');
2428
+ const original = typeof range.raw === 'string' ? range.raw : String(range);
2429
+ return simplified.length < original.length ? simplified : range
2430
+ };
2431
+ return simplify;
2432
+ }
2433
+
2434
+ var subset_1;
2435
+ var hasRequiredSubset;
2436
+
2437
+ function requireSubset () {
2438
+ if (hasRequiredSubset) return subset_1;
2439
+ hasRequiredSubset = 1;
2440
+
2441
+ const Range = requireRange();
2442
+ const Comparator = requireComparator();
2443
+ const { ANY } = Comparator;
2444
+ const satisfies = requireSatisfies();
2445
+ const compare = requireCompare();
2446
+
2447
+ // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
2448
+ // - Every simple range `r1, r2, ...` is a null set, OR
2449
+ // - Every simple range `r1, r2, ...` which is not a null set is a subset of
2450
+ // some `R1, R2, ...`
2451
+ //
2452
+ // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
2453
+ // - If c is only the ANY comparator
2454
+ // - If C is only the ANY comparator, return true
2455
+ // - Else if in prerelease mode, return false
2456
+ // - else replace c with `[>=0.0.0]`
2457
+ // - If C is only the ANY comparator
2458
+ // - if in prerelease mode, return true
2459
+ // - else replace C with `[>=0.0.0]`
2460
+ // - Let EQ be the set of = comparators in c
2461
+ // - If EQ is more than one, return true (null set)
2462
+ // - Let GT be the highest > or >= comparator in c
2463
+ // - Let LT be the lowest < or <= comparator in c
2464
+ // - If GT and LT, and GT.semver > LT.semver, return true (null set)
2465
+ // - If any C is a = range, and GT or LT are set, return false
2466
+ // - If EQ
2467
+ // - If GT, and EQ does not satisfy GT, return true (null set)
2468
+ // - If LT, and EQ does not satisfy LT, return true (null set)
2469
+ // - If EQ satisfies every C, return true
2470
+ // - Else return false
2471
+ // - If GT
2472
+ // - If GT.semver is lower than any > or >= comp in C, return false
2473
+ // - If GT is >=, and GT.semver does not satisfy every C, return false
2474
+ // - If GT.semver has a prerelease, and not in prerelease mode
2475
+ // - If no C has a prerelease and the GT.semver tuple, return false
2476
+ // - If LT
2477
+ // - If LT.semver is greater than any < or <= comp in C, return false
2478
+ // - If LT is <=, and LT.semver does not satisfy every C, return false
2479
+ // - If LT.semver has a prerelease, and not in prerelease mode
2480
+ // - If no C has a prerelease and the LT.semver tuple, return false
2481
+ // - Else return true
2482
+
2483
+ const subset = (sub, dom, options = {}) => {
2484
+ if (sub === dom) {
2485
+ return true
2486
+ }
2487
+
2488
+ sub = new Range(sub, options);
2489
+ dom = new Range(dom, options);
2490
+ let sawNonNull = false;
2491
+
2492
+ OUTER: for (const simpleSub of sub.set) {
2493
+ for (const simpleDom of dom.set) {
2494
+ const isSub = simpleSubset(simpleSub, simpleDom, options);
2495
+ sawNonNull = sawNonNull || isSub !== null;
2496
+ if (isSub) {
2497
+ continue OUTER
2498
+ }
2499
+ }
2500
+ // the null set is a subset of everything, but null simple ranges in
2501
+ // a complex range should be ignored. so if we saw a non-null range,
2502
+ // then we know this isn't a subset, but if EVERY simple range was null,
2503
+ // then it is a subset.
2504
+ if (sawNonNull) {
2505
+ return false
2506
+ }
2507
+ }
2508
+ return true
2509
+ };
2510
+
2511
+ const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')];
2512
+ const minimumVersion = [new Comparator('>=0.0.0')];
2513
+
2514
+ const simpleSubset = (sub, dom, options) => {
2515
+ if (sub === dom) {
2516
+ return true
2517
+ }
2518
+
2519
+ if (sub.length === 1 && sub[0].semver === ANY) {
2520
+ if (dom.length === 1 && dom[0].semver === ANY) {
2521
+ return true
2522
+ } else if (options.includePrerelease) {
2523
+ sub = minimumVersionWithPreRelease;
2524
+ } else {
2525
+ sub = minimumVersion;
2526
+ }
2527
+ }
2528
+
2529
+ if (dom.length === 1 && dom[0].semver === ANY) {
2530
+ if (options.includePrerelease) {
2531
+ return true
2532
+ } else {
2533
+ dom = minimumVersion;
2534
+ }
2535
+ }
2536
+
2537
+ const eqSet = new Set();
2538
+ let gt, lt;
2539
+ for (const c of sub) {
2540
+ if (c.operator === '>' || c.operator === '>=') {
2541
+ gt = higherGT(gt, c, options);
2542
+ } else if (c.operator === '<' || c.operator === '<=') {
2543
+ lt = lowerLT(lt, c, options);
2544
+ } else {
2545
+ eqSet.add(c.semver);
2546
+ }
2547
+ }
2548
+
2549
+ if (eqSet.size > 1) {
2550
+ return null
2551
+ }
2552
+
2553
+ let gtltComp;
2554
+ if (gt && lt) {
2555
+ gtltComp = compare(gt.semver, lt.semver, options);
2556
+ if (gtltComp > 0) {
2557
+ return null
2558
+ } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {
2559
+ return null
2560
+ }
2561
+ }
2562
+
2563
+ // will iterate one or zero times
2564
+ for (const eq of eqSet) {
2565
+ if (gt && !satisfies(eq, String(gt), options)) {
2566
+ return null
2567
+ }
2568
+
2569
+ if (lt && !satisfies(eq, String(lt), options)) {
2570
+ return null
2571
+ }
2572
+
2573
+ for (const c of dom) {
2574
+ if (!satisfies(eq, String(c), options)) {
2575
+ return false
2576
+ }
2577
+ }
2578
+
2579
+ return true
2580
+ }
2581
+
2582
+ let higher, lower;
2583
+ let hasDomLT, hasDomGT;
2584
+ // if the subset has a prerelease, we need a comparator in the superset
2585
+ // with the same tuple and a prerelease, or it's not a subset
2586
+ let needDomLTPre = lt &&
2587
+ !options.includePrerelease &&
2588
+ lt.semver.prerelease.length ? lt.semver : false;
2589
+ let needDomGTPre = gt &&
2590
+ !options.includePrerelease &&
2591
+ gt.semver.prerelease.length ? gt.semver : false;
2592
+ // exception: <1.2.3-0 is the same as <1.2.3
2593
+ if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&
2594
+ lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {
2595
+ needDomLTPre = false;
2596
+ }
2597
+
2598
+ for (const c of dom) {
2599
+ hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=';
2600
+ hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=';
2601
+ if (gt) {
2602
+ if (needDomGTPre) {
2603
+ if (c.semver.prerelease && c.semver.prerelease.length &&
2604
+ c.semver.major === needDomGTPre.major &&
2605
+ c.semver.minor === needDomGTPre.minor &&
2606
+ c.semver.patch === needDomGTPre.patch) {
2607
+ needDomGTPre = false;
2608
+ }
2609
+ }
2610
+ if (c.operator === '>' || c.operator === '>=') {
2611
+ higher = higherGT(gt, c, options);
2612
+ if (higher === c && higher !== gt) {
2613
+ return false
2614
+ }
2615
+ } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {
2616
+ return false
2617
+ }
2618
+ }
2619
+ if (lt) {
2620
+ if (needDomLTPre) {
2621
+ if (c.semver.prerelease && c.semver.prerelease.length &&
2622
+ c.semver.major === needDomLTPre.major &&
2623
+ c.semver.minor === needDomLTPre.minor &&
2624
+ c.semver.patch === needDomLTPre.patch) {
2625
+ needDomLTPre = false;
2626
+ }
2627
+ }
2628
+ if (c.operator === '<' || c.operator === '<=') {
2629
+ lower = lowerLT(lt, c, options);
2630
+ if (lower === c && lower !== lt) {
2631
+ return false
2632
+ }
2633
+ } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {
2634
+ return false
2635
+ }
2636
+ }
2637
+ if (!c.operator && (lt || gt) && gtltComp !== 0) {
2638
+ return false
2639
+ }
2640
+ }
2641
+
2642
+ // if there was a < or >, and nothing in the dom, then must be false
2643
+ // UNLESS it was limited by another range in the other direction.
2644
+ // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
2645
+ if (gt && hasDomLT && !lt && gtltComp !== 0) {
2646
+ return false
2647
+ }
2648
+
2649
+ if (lt && hasDomGT && !gt && gtltComp !== 0) {
2650
+ return false
2651
+ }
2652
+
2653
+ // we needed a prerelease range in a specific tuple, but didn't get one
2654
+ // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,
2655
+ // because it includes prereleases in the 1.2.3 tuple
2656
+ if (needDomGTPre || needDomLTPre) {
2657
+ return false
2658
+ }
2659
+
2660
+ return true
2661
+ };
2662
+
2663
+ // >=1.2.3 is lower than >1.2.3
2664
+ const higherGT = (a, b, options) => {
2665
+ if (!a) {
2666
+ return b
2667
+ }
2668
+ const comp = compare(a.semver, b.semver, options);
2669
+ return comp > 0 ? a
2670
+ : comp < 0 ? b
2671
+ : b.operator === '>' && a.operator === '>=' ? b
2672
+ : a
2673
+ };
2674
+
2675
+ // <=1.2.3 is higher than <1.2.3
2676
+ const lowerLT = (a, b, options) => {
2677
+ if (!a) {
2678
+ return b
2679
+ }
2680
+ const comp = compare(a.semver, b.semver, options);
2681
+ return comp < 0 ? a
2682
+ : comp > 0 ? b
2683
+ : b.operator === '<' && a.operator === '<=' ? b
2684
+ : a
2685
+ };
2686
+
2687
+ subset_1 = subset;
2688
+ return subset_1;
2689
+ }
2690
+
2691
+ var semver$1;
2692
+ var hasRequiredSemver;
2693
+
2694
+ function requireSemver () {
2695
+ if (hasRequiredSemver) return semver$1;
2696
+ hasRequiredSemver = 1;
2697
+
2698
+ // just pre-load all the stuff that index.js lazily exports
2699
+ const internalRe = requireRe();
2700
+ const constants = requireConstants();
2701
+ const SemVer = requireSemver$1();
2702
+ const identifiers = requireIdentifiers();
2703
+ const parse = requireParse();
2704
+ const valid = requireValid$1();
2705
+ const clean = requireClean();
2706
+ const inc = requireInc();
2707
+ const diff = requireDiff();
2708
+ const major = requireMajor();
2709
+ const minor = requireMinor();
2710
+ const patch = requirePatch();
2711
+ const prerelease = requirePrerelease();
2712
+ const compare = requireCompare();
2713
+ const rcompare = requireRcompare();
2714
+ const compareLoose = requireCompareLoose();
2715
+ const compareBuild = requireCompareBuild();
2716
+ const sort = requireSort();
2717
+ const rsort = requireRsort();
2718
+ const gt = requireGt();
2719
+ const lt = requireLt();
2720
+ const eq = requireEq();
2721
+ const neq = requireNeq();
2722
+ const gte = requireGte();
2723
+ const lte = requireLte();
2724
+ const cmp = requireCmp();
2725
+ const coerce = requireCoerce();
2726
+ const Comparator = requireComparator();
2727
+ const Range = requireRange();
2728
+ const satisfies = requireSatisfies();
2729
+ const toComparators = requireToComparators();
2730
+ const maxSatisfying = requireMaxSatisfying();
2731
+ const minSatisfying = requireMinSatisfying();
2732
+ const minVersion = requireMinVersion();
2733
+ const validRange = requireValid();
2734
+ const outside = requireOutside();
2735
+ const gtr = requireGtr();
2736
+ const ltr = requireLtr();
2737
+ const intersects = requireIntersects();
2738
+ const simplifyRange = requireSimplify();
2739
+ const subset = requireSubset();
2740
+ semver$1 = {
2741
+ parse,
2742
+ valid,
2743
+ clean,
2744
+ inc,
2745
+ diff,
2746
+ major,
2747
+ minor,
2748
+ patch,
2749
+ prerelease,
2750
+ compare,
2751
+ rcompare,
2752
+ compareLoose,
2753
+ compareBuild,
2754
+ sort,
2755
+ rsort,
2756
+ gt,
2757
+ lt,
2758
+ eq,
2759
+ neq,
2760
+ gte,
2761
+ lte,
2762
+ cmp,
2763
+ coerce,
2764
+ Comparator,
2765
+ Range,
2766
+ satisfies,
2767
+ toComparators,
2768
+ maxSatisfying,
2769
+ minSatisfying,
2770
+ minVersion,
2771
+ validRange,
2772
+ outside,
2773
+ gtr,
2774
+ ltr,
2775
+ intersects,
2776
+ simplifyRange,
2777
+ subset,
2778
+ SemVer,
2779
+ re: internalRe.re,
2780
+ src: internalRe.src,
2781
+ tokens: internalRe.t,
2782
+ SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
2783
+ RELEASE_TYPES: constants.RELEASE_TYPES,
2784
+ compareIdentifiers: identifiers.compareIdentifiers,
2785
+ rcompareIdentifiers: identifiers.rcompareIdentifiers,
2786
+ };
2787
+ return semver$1;
2788
+ }
2789
+
2790
+ var semverExports = requireSemver();
2791
+ var semver = /*@__PURE__*/getDefaultExportFromCjs(semverExports);
2792
+
2793
+ /**
2794
+ * 不依赖 `import.meta`,兼容 Webpack 4/5、Vue CLI、Vite、Rspack 等宿主。
2795
+ * - Webpack / Vue CLI:依赖构建时注入的 `process.env`(如 `VUE_APP_*`、`DefinePlugin` 注入的 `VITE_*`)。
2796
+ * - Vite:在入口调用 `setWebExtendPluginEnv(import.meta.env)`,或 `installWebExtendPluginVue2(..., { env: import.meta.env })`。
2797
+ * - 也可在入口前设置 `globalThis.__WEP_ENV__ = import.meta.env`(与 setWebExtendPluginEnv 二选一即可)。
2798
+ *
2799
+ * @module bundled-env
2800
+ */
2801
+
2802
+ /** @type {Record<string, unknown> | null} */
2803
+ let _explicitEnv = null;
2804
+
2805
+ /**
2806
+ * 显式注入与 `import.meta.env` 同形态的对象(推荐 Vite 宿主在入口调用一次)。
2807
+ * @param {Record<string, unknown> | null | undefined} env
2808
+ */
2809
+ function setWebExtendPluginEnv(env) {
2810
+ _explicitEnv = env && typeof env === 'object' ? env : null;
2811
+ }
2812
+
2813
+ /**
2814
+ * @returns {Record<string, unknown> | null}
2815
+ */
2816
+ function getInjectedEnvObject() {
2817
+ if (_explicitEnv) {
2818
+ return _explicitEnv
2819
+ }
2820
+ try {
2821
+ const g = typeof globalThis !== 'undefined' ? globalThis : undefined;
2822
+ if (g && g.__WEP_ENV__ && typeof g.__WEP_ENV__ === 'object') {
2823
+ return g.__WEP_ENV__
2824
+ }
2825
+ } catch (_) {}
2826
+ return null
2827
+ }
2828
+
2829
+ /**
2830
+ * 从注入环境读取字符串配置键(`VITE_*` / `PLUGIN_*` 等)。
2831
+ * @param {string} key
2832
+ * @returns {string|undefined}
2833
+ */
2834
+ function readInjectedEnvKey(key) {
2835
+ const o = getInjectedEnvObject();
2836
+ if (!o || !(key in o)) {
2837
+ return undefined
2838
+ }
2839
+ const v = o[key];
2840
+ if (v === undefined || v === '') {
2841
+ return undefined
2842
+ }
2843
+ return String(v)
2844
+ }
2845
+
2846
+ /**
2847
+ * @returns {boolean}
2848
+ */
2849
+ function readInjectedEnvDev() {
2850
+ const o = getInjectedEnvObject();
2851
+ return !!(o && o.DEV === true)
2852
+ }
2853
+
2854
+ /**
2855
+ * 与 `plugin-web-starter`(WebPluginsResponse)返回的 `hostPluginApiVersion` 保持一致,用于契约校验。
2856
+ * @type {string}
2857
+ */
2858
+ const HOST_PLUGIN_API_VERSION = '1.0.0';
2859
+
2860
+ /**
2861
+ * 宿主侧插件引导:拉取清单、dev 映射、加载入口脚本、调用 activator。
2862
+ * 路径与白名单等默认值见 `defaultWebExtendPluginRuntime`,可通过 `resolveRuntimeOptions` / 环境变量覆盖。
2863
+ *
2864
+ * **Webpack 宿主**:用 `DefinePlugin` 注入 `process.env.VITE_*` 或 **`PLUGIN_*`**(等价键),或 `resolveRuntimeOptions` 显式传参。
2865
+ * **Vite 宿主**:入口调用 `setWebExtendPluginEnv(import.meta.env)`,或 `installWebExtendPluginVue2(..., { env: import.meta.env })`。
2866
+ *
2867
+ * @module PluginRuntime
2868
+ */
2869
+
2870
+ const DEF = defaultWebExtendPluginRuntime;
2871
+
2872
+ /**
2873
+ * @typedef {object} WebExtendPluginRuntimeOptions
2874
+ * @property {string} [manifestBase] 清单服务 URL 前缀
2875
+ * @property {string} [manifestListPath] 清单接口路径(以 `/` 开头),拼在 manifestBase 后
2876
+ * @property {RequestCredentials} [manifestFetchCredentials] 清单 fetch 的 credentials
2877
+ * @property {boolean} [isDev] 开发模式
2878
+ * @property {string} [webPluginDevOrigin] 插件 dev origin
2879
+ * @property {string} [webPluginDevIds] 逗号分隔 id,隐式 dev 映射
2880
+ * @property {string} [webPluginDevMapJson] 显式 dev 映射 JSON
2881
+ * @property {string} [webPluginDevEntryPath] 隐式 dev 入口路径(相对插件 dev origin)
2882
+ * @property {string} [devPingPath] dev 存活探测路径
2883
+ * @property {string} [devReloadSsePath] dev 热更新 SSE 路径
2884
+ * @property {number} [devPingTimeoutMs] 探测超时
2885
+ * @property {string[]} [defaultImplicitDevPluginIds] 无 `webPluginDevIds`/env 时用于隐式 dev 的 id;包内默认 `[]`
2886
+ * @property {string[]} [allowedScriptHosts] 允许加载脚本的主机名
2887
+ * @property {string[]} [bridgeAllowedPathPrefixes] bridge.request 白名单前缀
2888
+ * @property {boolean} [bootstrapSummary] bootstrap 结束是否打印摘要
2889
+ */
2890
+
2891
+ /**
2892
+ * 从 Webpack `DefinePlugin` 等注入的 `process.env` 读取。
2893
+ * @param {string} key
2894
+ * @returns {string|undefined}
2895
+ */
2896
+ function readProcessEnv(key) {
2897
+ try {
2898
+ if (typeof process !== 'undefined' && process.env && key in process.env) {
2899
+ const v = process.env[key];
2900
+ if (v !== undefined && v !== '') {
2901
+ return String(v)
2902
+ }
2903
+ }
2904
+ } catch (_) {}
2905
+ return undefined
2906
+ }
2907
+
2908
+ /**
2909
+ * `VITE_*` 的并列命名:同值可读 `PLUGIN_*`(`VITE_WEB_PLUGIN_X` → `PLUGIN_WEB_PLUGIN_X`)。
2910
+ * Vite 需在 `defineConfig({ envPrefix: ['VITE_', 'PLUGIN_'] })` 中暴露 `PLUGIN_`;Webpack 用 DefinePlugin 注入即可。
2911
+ * @param {string} viteStyleKey 以 `VITE_` 开头的键名
2912
+ * @returns {string|null}
2913
+ */
2914
+ function viteKeyToPluginAlternate(viteStyleKey) {
2915
+ if (typeof viteStyleKey !== 'string' || !viteStyleKey.startsWith('VITE_')) {
2916
+ return null
2917
+ }
2918
+ return `PLUGIN_${viteStyleKey.slice(5)}`
2919
+ }
2920
+
2921
+ /**
2922
+ * 先读注入环境(`setWebExtendPluginEnv` / `__WEP_ENV__`)中的 `VITE_*` 与并列 `PLUGIN_*`,再读 `process.env`,最后 `fallback`。
2923
+ * @param {string} key 仍以 `VITE_*` 为逻辑名(与文档一致)
2924
+ * @param {string} [fallback='']
2925
+ */
2926
+ function resolveBundledEnv(key, fallback = '') {
2927
+ const alt = viteKeyToPluginAlternate(key);
2928
+ const inj = readInjectedEnvKey(key);
2929
+ const fromInjected =
2930
+ inj === undefined || inj === null ? (alt ? readInjectedEnvKey(alt) : undefined) : inj;
2931
+ const proc = readProcessEnv(key);
2932
+ const fromProcess =
2933
+ proc === undefined || proc === null ? (alt ? readProcessEnv(alt) : undefined) : proc;
2934
+ const first = fromInjected === undefined || fromInjected === null ? fromProcess : fromInjected;
2935
+ return first === undefined || first === null ? fallback : first
2936
+ }
2937
+
2938
+ /**
2939
+ * @returns {boolean}
2940
+ */
2941
+ function resolveBundledIsDev() {
2942
+ try {
2943
+ if (readInjectedEnvDev()) {
2944
+ return true
2945
+ }
2946
+ } catch (_) {}
2947
+ try {
2948
+ if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'development') {
2949
+ return true
2950
+ }
2951
+ } catch (_) {}
2952
+ return false
2953
+ }
2954
+
2955
+ /**
2956
+ * @param {string} p
2957
+ */
2958
+ function ensureLeadingPath(p) {
2959
+ const t = String(p || '').trim();
2960
+ if (!t) {
2961
+ return '/'
2962
+ }
2963
+ return t.startsWith('/') ? t : `/${t}`
2964
+ }
2965
+
2966
+ /**
2967
+ * 解析 `include` | `omit` | `same-origin`,非法时回退默认值。
2968
+ * @param {string|undefined} userVal
2969
+ * @param {string} envKey
2970
+ * @param {RequestCredentials} fallback
2971
+ */
2972
+ function resolveManifestCredentials(userVal, envKey, fallback) {
2973
+ if (userVal !== undefined && userVal !== '') {
2974
+ const s = String(userVal);
2975
+ if (s === 'include' || s === 'omit' || s === 'same-origin') {
2976
+ return s
2977
+ }
2978
+ }
2979
+ const e = resolveBundledEnv(envKey, '');
2980
+ if (e === 'include' || e === 'omit' || e === 'same-origin') {
2981
+ return e
2982
+ }
2983
+ return fallback
2984
+ }
2985
+
2986
+ /**
2987
+ * @param {number|undefined} userVal
2988
+ * @param {string} envKey
2989
+ * @param {number} fallback
2990
+ */
2991
+ function resolvePositiveInt(userVal, envKey, fallback) {
2992
+ if (typeof userVal === 'number' && Number.isFinite(userVal) && userVal > 0) {
2993
+ return Math.floor(userVal)
2994
+ }
2995
+ const raw = resolveBundledEnv(envKey, '');
2996
+ const n = raw ? parseInt(raw, 10) : NaN;
2997
+ if (Number.isFinite(n) && n > 0) {
2998
+ return n
2999
+ }
3000
+ return fallback
3001
+ }
3002
+
3003
+ /**
3004
+ * 合并用户、环境变量与 `defaultWebExtendPluginRuntime`,得到完整运行时选项(宿主可只传需要覆盖的字段)。
3005
+ * @param {WebExtendPluginRuntimeOptions} [user]
3006
+ * @returns {object}
3007
+ */
3008
+ function resolveRuntimeOptions(user = {}) {
3009
+ const manifestBaseRaw =
3010
+ user.manifestBase !== undefined && user.manifestBase !== ''
3011
+ ? String(user.manifestBase)
3012
+ : resolveBundledEnv('VITE_FRONTEND_PLUGIN_BASE', DEF.manifestBase) || DEF.manifestBase;
3013
+
3014
+ const manifestListPath = ensureLeadingPath(
3015
+ user.manifestListPath !== undefined && user.manifestListPath !== ''
3016
+ ? user.manifestListPath
3017
+ : resolveBundledEnv('VITE_WEB_PLUGIN_MANIFEST_PATH', DEF.manifestListPath)
3018
+ );
3019
+
3020
+ const defaultImplicitDevPluginIds =
3021
+ Array.isArray(user.defaultImplicitDevPluginIds)
3022
+ ? user.defaultImplicitDevPluginIds.map(String).filter(Boolean)
3023
+ : (() => {
3024
+ const e = resolveBundledEnv('VITE_WEB_PLUGIN_IMPLICIT_DEV_IDS', '');
3025
+ if (e) {
3026
+ return e
3027
+ .split(',')
3028
+ .map((s) => s.trim())
3029
+ .filter(Boolean)
3030
+ }
3031
+ return [...DEF.defaultImplicitDevPluginIds]
3032
+ })();
3033
+
3034
+ const allowedScriptHosts =
3035
+ Array.isArray(user.allowedScriptHosts) && user.allowedScriptHosts.length > 0
3036
+ ? user.allowedScriptHosts.map((h) => normalizeHost(String(h))).filter(Boolean)
3037
+ : (() => {
3038
+ const e = resolveBundledEnv('VITE_WEB_PLUGIN_ALLOWED_SCRIPT_HOSTS', '');
3039
+ if (e) {
3040
+ return e
3041
+ .split(',')
3042
+ .map((s) => normalizeHost(s.trim()))
3043
+ .filter(Boolean)
3044
+ }
3045
+ return [...DEF.allowedScriptHosts]
3046
+ })();
3047
+
3048
+ const bridgeAllowedPathPrefixes =
3049
+ Array.isArray(user.bridgeAllowedPathPrefixes) && user.bridgeAllowedPathPrefixes.length > 0
3050
+ ? user.bridgeAllowedPathPrefixes.map((p) => ensureLeadingPath(p)).filter(Boolean)
3051
+ : (() => {
3052
+ const e = resolveBundledEnv('VITE_WEB_PLUGIN_BRIDGE_PREFIXES', '');
3053
+ if (e) {
3054
+ return e
3055
+ .split(',')
3056
+ .map((s) => ensureLeadingPath(s.trim()))
3057
+ .filter(Boolean)
3058
+ }
3059
+ return [...DEF.bridgeAllowedPathPrefixes]
3060
+ })();
3061
+
3062
+ return {
3063
+ manifestBase: manifestBaseRaw.replace(/\/$/, '') || DEF.manifestBase.replace(/\/$/, ''),
3064
+ manifestListPath,
3065
+ manifestFetchCredentials: resolveManifestCredentials(
3066
+ user.manifestFetchCredentials,
3067
+ 'VITE_WEB_PLUGIN_MANIFEST_CREDENTIALS',
3068
+ DEF.manifestFetchCredentials
3069
+ ),
3070
+ isDev: user.isDev !== undefined ? user.isDev : resolveBundledIsDev(),
3071
+ webPluginDevOrigin:
3072
+ user.webPluginDevOrigin !== undefined ? user.webPluginDevOrigin : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_ORIGIN', ''),
3073
+ webPluginDevIds:
3074
+ user.webPluginDevIds !== undefined ? user.webPluginDevIds : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_IDS', ''),
3075
+ webPluginDevMapJson:
3076
+ user.webPluginDevMapJson !== undefined
3077
+ ? user.webPluginDevMapJson
3078
+ : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_MAP', ''),
3079
+ webPluginDevEntryPath: ensureLeadingPath(
3080
+ user.webPluginDevEntryPath !== undefined && user.webPluginDevEntryPath !== ''
3081
+ ? user.webPluginDevEntryPath
3082
+ : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_ENTRY', DEF.webPluginDevEntryPath)
3083
+ ),
3084
+ devPingPath: ensureLeadingPath(
3085
+ user.devPingPath !== undefined && user.devPingPath !== ''
3086
+ ? user.devPingPath
3087
+ : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_PING_PATH', DEF.devPingPath)
3088
+ ),
3089
+ devReloadSsePath: ensureLeadingPath(
3090
+ user.devReloadSsePath !== undefined && user.devReloadSsePath !== ''
3091
+ ? user.devReloadSsePath
3092
+ : resolveBundledEnv('VITE_WEB_PLUGIN_DEV_SSE_PATH', DEF.devReloadSsePath)
3093
+ ),
3094
+ devPingTimeoutMs: resolvePositiveInt(user.devPingTimeoutMs, 'VITE_WEB_PLUGIN_DEV_PING_TIMEOUT_MS', DEF.devPingTimeoutMs),
3095
+ defaultImplicitDevPluginIds,
3096
+ allowedScriptHosts,
3097
+ bridgeAllowedPathPrefixes,
3098
+ bootstrapSummary: user.bootstrapSummary
3099
+ }
3100
+ }
3101
+
3102
+ /**
3103
+ * @param {ReturnType<typeof resolveRuntimeOptions>} opts
3104
+ */
3105
+ function shouldShowBootstrapSummary(opts) {
3106
+ if (opts.bootstrapSummary === true) {
3107
+ return true
3108
+ }
3109
+ if (opts.bootstrapSummary === false) {
3110
+ return false
3111
+ }
3112
+ const env = resolveBundledEnv('VITE_PLUGINS_BOOTSTRAP_SUMMARY', '');
3113
+ if (env === '0' || env === 'false') {
3114
+ return false
3115
+ }
3116
+ if (env === '1' || env === 'true') {
3117
+ return true
3118
+ }
3119
+ return resolveBundledIsDev()
3120
+ }
3121
+
3122
+ /**
3123
+ * @param {string} hostname
3124
+ */
3125
+ function normalizeHost(hostname) {
3126
+ if (!hostname) {
3127
+ return ''
3128
+ }
3129
+ const h = hostname.toLowerCase();
3130
+ if (h.startsWith('[') && h.endsWith(']')) {
3131
+ return h.slice(1, -1)
3132
+ }
3133
+ return h
3134
+ }
3135
+
3136
+ /**
3137
+ * @param {string[]} hostnames
3138
+ * @returns {Set<string>}
3139
+ */
3140
+ function buildAllowedScriptHostsSet(hostnames) {
3141
+ const s = new Set();
3142
+ for (const h of hostnames) {
3143
+ const n = normalizeHost(h);
3144
+ if (n) {
3145
+ s.add(n);
3146
+ }
3147
+ }
3148
+ return s
3149
+ }
3150
+
3151
+ /**
3152
+ * @param {string} url
3153
+ * @param {Set<string>} hostSet
3154
+ */
3155
+ function isScriptHostAllowed(url, hostSet) {
3156
+ if (typeof window === 'undefined') {
3157
+ return false
3158
+ }
3159
+ try {
3160
+ const u = new URL(url, window.location.origin);
3161
+ const h = normalizeHost(u.hostname);
3162
+ return hostSet.has(h)
3163
+ } catch {
3164
+ return false
3165
+ }
3166
+ }
3167
+
3168
+ /**
3169
+ * @param {ReturnType<typeof resolveRuntimeOptions>} opts
3170
+ */
3171
+ function parseWebPluginDevMapExplicit(opts) {
3172
+ if (!opts.isDev) {
3173
+ return null
3174
+ }
3175
+ const raw = opts.webPluginDevMapJson;
3176
+ if (raw === undefined || raw === null || String(raw).trim() === '') {
3177
+ return null
3178
+ }
3179
+ try {
3180
+ const map = JSON.parse(String(raw));
3181
+ return map && typeof map === 'object' ? map : null
3182
+ } catch {
3183
+ console.warn('[plugins] webPluginDevMapJson / VITE_WEB_PLUGIN_DEV_MAP is not valid JSON');
3184
+ return null
3185
+ }
3186
+ }
3187
+
3188
+ /**
3189
+ * @param {ReturnType<typeof resolveRuntimeOptions>} opts
3190
+ * @param {Set<string>} hostSet
3191
+ */
3192
+ async function buildImplicitWebPluginDevMap(opts, hostSet) {
3193
+ if (!opts.isDev) {
3194
+ return {}
3195
+ }
3196
+ const origin =
3197
+ opts.webPluginDevOrigin === undefined || opts.webPluginDevOrigin === null
3198
+ ? ''
3199
+ : String(opts.webPluginDevOrigin).trim();
3200
+ if (!origin) {
3201
+ return {}
3202
+ }
3203
+ if (!isScriptHostAllowed(`${origin}/`, hostSet)) {
3204
+ return {}
3205
+ }
3206
+
3207
+ const idsRaw = opts.webPluginDevIds;
3208
+ const ids =
3209
+ idsRaw !== undefined && idsRaw !== null && String(idsRaw).trim() !== ''
3210
+ ? String(idsRaw)
3211
+ .split(',')
3212
+ .map((s) => s.trim())
3213
+ .filter(Boolean)
3214
+ : [...opts.defaultImplicitDevPluginIds];
3215
+
3216
+ if (ids.length === 0) {
3217
+ return {}
3218
+ }
3219
+
3220
+ const base = origin.replace(/\/$/, '');
3221
+ const pingUrl = `${base}${opts.devPingPath}`;
3222
+ try {
3223
+ const ctrl = new AbortController();
3224
+ const timer = setTimeout(() => ctrl.abort(), opts.devPingTimeoutMs);
3225
+ const r = await fetch(pingUrl, {
3226
+ mode: 'cors',
3227
+ cache: 'no-store',
3228
+ signal: ctrl.signal
3229
+ });
3230
+ clearTimeout(timer);
3231
+ if (!r.ok) {
3232
+ return {}
3233
+ }
3234
+ const body = (await r.text()).trim();
3235
+ if (body !== 'ok') {
3236
+ return {}
3237
+ }
3238
+ } catch {
3239
+ return {}
3240
+ }
3241
+
3242
+ const pathPart = opts.webPluginDevEntryPath;
3243
+ const map = {};
3244
+ for (const id of ids) {
3245
+ map[id] = `${base}${pathPart}`;
3246
+ }
3247
+ if (ids.length) {
3248
+ console.info(
3249
+ '[plugins] 已检测到插件 dev 服务(',
3250
+ base,
3251
+ '),下列 id 将加载隐式 dev 入口(',
3252
+ pathPart,
3253
+ ')而非清单 dist:',
3254
+ ids.join(', ')
3255
+ );
3256
+ }
3257
+ return map
3258
+ }
3259
+
3260
+ /**
3261
+ * @param {Record<string, string>} implicit
3262
+ * @param {Record<string, string>|null} explicit
3263
+ */
3264
+ function mergeDevMaps(implicit, explicit) {
3265
+ const i = implicit && typeof implicit === 'object' ? implicit : {};
3266
+ const e = explicit && typeof explicit === 'object' ? explicit : {};
3267
+ return { ...i, ...e }
3268
+ }
3269
+
3270
+ /** @type {Map<string, EventSource>} */
3271
+ const pluginDevEventSources = new Map();
3272
+
3273
+ let pluginDevBeforeUnloadRegistered = false;
3274
+
3275
+ function closeAllPluginDevEventSources() {
3276
+ for (const es of pluginDevEventSources.values()) {
3277
+ try {
3278
+ es.close();
3279
+ } catch (_) {}
3280
+ }
3281
+ pluginDevEventSources.clear();
3282
+ }
3283
+
3284
+ function ensurePluginDevBeforeUnload() {
3285
+ if (pluginDevBeforeUnloadRegistered || typeof window === 'undefined') {
3286
+ return
3287
+ }
3288
+ pluginDevBeforeUnloadRegistered = true;
3289
+ window.addEventListener('beforeunload', closeAllPluginDevEventSources);
3290
+ }
3291
+
3292
+ /**
3293
+ * @param {string} origin
3294
+ * @param {Set<string>} hostSet
3295
+ */
3296
+ function isDevOriginAllowedForSse(origin, hostSet) {
3297
+ try {
3298
+ const u = new URL(origin);
3299
+ return hostSet.has(normalizeHost(u.hostname))
3300
+ } catch {
3301
+ return false
3302
+ }
3303
+ }
3304
+
3305
+ /**
3306
+ * @param {string} origin
3307
+ * @param {boolean} isDev
3308
+ * @param {Set<string>} hostSet
3309
+ * @param {string} ssePath
3310
+ */
3311
+ function startPluginDevReloadSse(origin, isDev, hostSet, ssePath) {
3312
+ if (!isDev || pluginDevEventSources.has(origin)) {
3313
+ return
3314
+ }
3315
+ if (!isDevOriginAllowedForSse(origin, hostSet)) {
3316
+ return
3317
+ }
3318
+ ensurePluginDevBeforeUnload();
3319
+ const base = origin.replace(/\/$/, '');
3320
+ const url = `${base}${ssePath}`;
3321
+ try {
3322
+ const es = new EventSource(url);
3323
+ pluginDevEventSources.set(origin, es);
3324
+ es.addEventListener('reload', () => {
3325
+ window.location.reload();
3326
+ });
3327
+ es.onopen = () => {
3328
+ console.info('[plugins] plugin dev reload SSE:', url);
3329
+ };
3330
+ } catch (e) {
3331
+ console.warn('[plugins] EventSource failed', url, e);
3332
+ }
3333
+ }
3334
+
3335
+ /**
3336
+ * @param {Record<string, string>|null|undefined} devMap
3337
+ * @param {boolean} isDev
3338
+ * @param {Set<string>} hostSet
3339
+ * @param {string} ssePath
3340
+ */
3341
+ function startPluginDevSseForMap(devMap, isDev, hostSet, ssePath) {
3342
+ if (!isDev || !devMap || typeof window === 'undefined') {
3343
+ return
3344
+ }
3345
+ const origins = new Set();
3346
+ for (const entry of Object.values(devMap)) {
3347
+ if (typeof entry !== 'string') {
3348
+ continue
3349
+ }
3350
+ const t = entry.trim();
3351
+ if (!t) {
3352
+ continue
3353
+ }
3354
+ try {
3355
+ origins.add(new URL(t, window.location.href).origin);
3356
+ } catch {
3357
+ /* skip */
3358
+ }
3359
+ }
3360
+ for (const o of origins) {
3361
+ startPluginDevReloadSse(o, isDev, hostSet, ssePath);
3362
+ }
3363
+ }
3364
+
3365
+ const loadScriptMemo = new Map();
3366
+
3367
+ function loadScript(src) {
3368
+ if (typeof document === 'undefined') {
3369
+ return Promise.reject(new Error('loadScript: no document'))
3370
+ }
3371
+ if (loadScriptMemo.has(src)) {
3372
+ return loadScriptMemo.get(src)
3373
+ }
3374
+ const p = new Promise((resolve, reject) => {
3375
+ const scripts = document.getElementsByTagName('script');
3376
+ for (let i = 0; i < scripts.length; i++) {
3377
+ const el = scripts[i];
3378
+ if (el.src === src) {
3379
+ if (el.getAttribute('data-wep-loaded') === 'true') {
3380
+ resolve();
3381
+ return
3382
+ }
3383
+ el.addEventListener(
3384
+ 'load',
3385
+ () => {
3386
+ el.setAttribute('data-wep-loaded', 'true');
3387
+ resolve();
3388
+ },
3389
+ { once: true }
3390
+ );
3391
+ el.addEventListener('error', () => reject(new Error('loadScript failed: ' + src)), { once: true });
3392
+ return
3393
+ }
3394
+ }
3395
+ const s = document.createElement('script');
3396
+ s.async = true;
3397
+ s.src = src;
3398
+ s.onload = () => {
3399
+ s.setAttribute('data-wep-loaded', 'true');
3400
+ resolve();
3401
+ };
3402
+ s.onerror = () => reject(new Error('loadScript failed: ' + src));
3403
+ document.head.appendChild(s);
3404
+ });
3405
+ loadScriptMemo.set(src, p);
3406
+ p.catch(() => loadScriptMemo.delete(src));
3407
+ return p
3408
+ }
3409
+
3410
+ /**
3411
+ * @param {{ id: string }} p
3412
+ * @param {string} [entryUrl]
3413
+ * @param {Record<string, string>|null|undefined} devMap
3414
+ * @param {Set<string>} hostSet
3415
+ */
3416
+ async function loadPluginEntry(p, entryUrl, devMap, hostSet) {
3417
+ const devEntry = devMap && typeof devMap[p.id] === 'string' ? devMap[p.id].trim() : '';
3418
+ if (devEntry) {
3419
+ if (!isScriptHostAllowed(devEntry, hostSet)) {
3420
+ console.warn('[plugins] dev entry URL not allowed', p.id, devEntry);
3421
+ return
3422
+ }
3423
+ try {
3424
+ await import(
3425
+ /* webpackIgnore: true */
3426
+ /* @vite-ignore */
3427
+ devEntry
3428
+ );
3429
+ } catch (e) {
3430
+ console.warn('[plugins] dev module import failed, try manifest entryUrl', p.id, e);
3431
+ if (entryUrl && isScriptHostAllowed(entryUrl, hostSet)) {
3432
+ await loadScript(entryUrl);
3433
+ }
3434
+ return
3435
+ }
3436
+ return
3437
+ }
3438
+ if (!entryUrl || !isScriptHostAllowed(entryUrl, hostSet)) {
3439
+ console.warn('[plugins] skip (entryUrl not allowed)', p.id, entryUrl);
3440
+ return
3441
+ }
3442
+ await loadScript(entryUrl);
3443
+ }
3444
+
3445
+ /**
3446
+ * @param {import('vue-router').default} router
3447
+ * @param {(pluginId: string, router: import('vue-router').default, hostKit?: { bridgeAllowedPathPrefixes: string[] }) => object} createHostApiFactory
3448
+ * 始终传入三个参数;单参工厂 `(id) => createHostApi(id, router)` 仍可用,后两个实参被忽略。
3449
+ * @param {WebExtendPluginRuntimeOptions} [runtimeOptions]
3450
+ */
3451
+ async function bootstrapPlugins(router, createHostApiFactory, runtimeOptions) {
3452
+ if (typeof window === 'undefined') {
3453
+ console.warn('[plugins] bootstrapPlugins skipped: requires browser (window)');
3454
+ return
3455
+ }
3456
+ const opts = resolveRuntimeOptions(runtimeOptions || {});
3457
+ const base = String(opts.manifestBase).replace(/\/$/, '');
3458
+ const manifestUrl = `${base}${opts.manifestListPath}`;
3459
+ const hostSet = buildAllowedScriptHostsSet(opts.allowedScriptHosts);
3460
+ const explicit = parseWebPluginDevMapExplicit(opts);
3461
+
3462
+ const [manifestResult, implicit] = await Promise.all([
3463
+ (async () => {
3464
+ try {
3465
+ const res = await fetch(manifestUrl, { credentials: opts.manifestFetchCredentials });
3466
+ if (!res.ok) {
3467
+ return { ok: false, status: res.status, data: null }
3468
+ }
3469
+ const data = await res.json();
3470
+ return { ok: true, data }
3471
+ } catch (e) {
3472
+ return { ok: false, error: e, data: null }
3473
+ }
3474
+ })(),
3475
+ buildImplicitWebPluginDevMap(opts, hostSet)
3476
+ ]);
3477
+
3478
+ const devMap = mergeDevMaps(implicit, explicit);
3479
+ startPluginDevSseForMap(devMap, opts.isDev, hostSet, opts.devReloadSsePath);
3480
+
3481
+ const hostKit = { bridgeAllowedPathPrefixes: opts.bridgeAllowedPathPrefixes };
3482
+
3483
+ if (!manifestResult.ok) {
3484
+ if (manifestResult.error) {
3485
+ console.warn('[plugins] fetch manifest failed', manifestResult.error);
3486
+ } else {
3487
+ console.warn('[plugins] manifest HTTP', manifestResult.status, manifestUrl);
3488
+ }
3489
+ if (shouldShowBootstrapSummary(opts)) {
3490
+ console.info('[plugins] bootstrap_summary', { ok: false, reason: 'manifest_fetch' });
3491
+ }
3492
+ return
3493
+ }
3494
+ /** @type {{ hostPluginApiVersion?: string, plugins?: object[] }} */
3495
+ const data = manifestResult.data;
3496
+ if (!data) {
3497
+ if (shouldShowBootstrapSummary(opts)) {
3498
+ console.info('[plugins] bootstrap_summary', { ok: false, reason: 'manifest_empty_body' });
3499
+ }
3500
+ return
3501
+ }
3502
+
3503
+ const apiVer = data.hostPluginApiVersion;
3504
+ if (apiVer) {
3505
+ const coerced = semver.coerce(apiVer);
3506
+ const maj = coerced ? coerced.major : 0;
3507
+ const range = `^${maj}.0.0`;
3508
+ if (!semver.satisfies(HOST_PLUGIN_API_VERSION, range, { includePrerelease: true })) {
3509
+ console.warn(
3510
+ '[plugins] host API version mismatch: host implements',
3511
+ HOST_PLUGIN_API_VERSION,
3512
+ 'server declares',
3513
+ apiVer
3514
+ );
3515
+ }
3516
+ }
3517
+
3518
+ window.__PLUGIN_ACTIVATORS__ = window.__PLUGIN_ACTIVATORS__ || {};
3519
+
3520
+ const plugins = data.plugins || [];
3521
+ if (plugins.length === 0) {
3522
+ console.info(
3523
+ '[plugins] 清单为空。请检查:① 后端清单服务(plugin-web-starter)是否已接入;② web-plugin.web-plugins-dir 是否指向含各插件子目录及 manifest.json 的路径;③ 浏览器直接访问',
3524
+ manifestUrl,
3525
+ '是否返回 plugins 条目。'
3526
+ );
3527
+ }
3528
+
3529
+ const summary = {
3530
+ manifestCount: plugins.length,
3531
+ activated: 0,
3532
+ skipEngines: 0,
3533
+ skipLoad: 0,
3534
+ skipNoActivator: 0,
3535
+ activateFail: 0
3536
+ };
3537
+
3538
+ for (const p of plugins) {
3539
+ const range = p.engines && p.engines.host;
3540
+ if (range && !semver.satisfies(HOST_PLUGIN_API_VERSION, range, { includePrerelease: true })) {
3541
+ console.warn('[plugins] skip (engines.host)', p.id, range);
3542
+ summary.skipEngines++;
3543
+ continue
3544
+ }
3545
+ const entryUrl = p.entryUrl;
3546
+ try {
3547
+ await loadPluginEntry(p, entryUrl, devMap, hostSet);
3548
+ } catch (e) {
3549
+ console.warn('[plugins] script load failed', p.id, e);
3550
+ summary.skipLoad++;
3551
+ continue
3552
+ }
3553
+ const activator = window.__PLUGIN_ACTIVATORS__[p.id];
3554
+ if (typeof activator !== 'function') {
3555
+ console.warn('[plugins] no activator for', p.id);
3556
+ summary.skipNoActivator++;
3557
+ continue
3558
+ }
3559
+ const hostApi = createHostApiFactory(p.id, router, hostKit);
3560
+ try {
3561
+ activator(hostApi);
3562
+ summary.activated++;
3563
+ } catch (e) {
3564
+ console.error('[plugins] activate failed', p.id, e);
3565
+ summary.activateFail++;
3566
+ }
3567
+ }
3568
+
3569
+ if (shouldShowBootstrapSummary(opts)) {
3570
+ console.info('[plugins] bootstrap_summary', { ok: true, ...summary });
3571
+ }
3572
+ }
3573
+
3574
+ /**
3575
+ * 插件通过宿主访问后端的受控通道:仅允许配置的前缀路径,默认 `/api/`;强制默认 `same-origin` 携带 Cookie。
3576
+ * 前缀列表由 `createRequestBridge({ allowedPathPrefixes })` 传入,与 `defaultWebExtendPluginRuntime.bridgeAllowedPathPrefixes` 对齐。
3577
+ *
3578
+ * @module bridge
3579
+ */
3580
+
3581
+ /**
3582
+ * @param {string} p
3583
+ */
3584
+ function ensureLeadingSlash(p) {
3585
+ const t = String(p || '').trim();
3586
+ if (!t) {
3587
+ return '/'
3588
+ }
3589
+ return t.startsWith('/') ? t : `/${t}`
3590
+ }
3591
+
3592
+ /**
3593
+ * @param {{ allowedPathPrefixes?: string[] }} [config]
3594
+ */
3595
+ function createRequestBridge(config = {}) {
3596
+ const raw =
3597
+ Array.isArray(config.allowedPathPrefixes) && config.allowedPathPrefixes.length > 0
3598
+ ? config.allowedPathPrefixes
3599
+ : defaultWebExtendPluginRuntime.bridgeAllowedPathPrefixes;
3600
+ const allowedPathPrefixes = raw.map((p) => ensureLeadingSlash(p));
3601
+
3602
+ return {
3603
+ /**
3604
+ * 发起受控 `fetch`。
3605
+ * @param {string} path 必须以 `/` 开头,且匹配某一 `allowedPathPrefixes` 前缀
3606
+ * @param {RequestInit} [init] 会与默认 `{ credentials: 'same-origin' }` 合并(后者可被覆盖)
3607
+ */
3608
+ async request(path, init = {}) {
3609
+ if (typeof path !== 'string' || !path.startsWith('/')) {
3610
+ throw new Error('[bridge] path must be a string starting with /')
3611
+ }
3612
+ const allowed = allowedPathPrefixes.some((p) => path.startsWith(p));
3613
+ if (!allowed) {
3614
+ throw new Error('[bridge] path not allowed: ' + path)
3615
+ }
3616
+ return fetch(path, {
3617
+ credentials: 'same-origin',
3618
+ ...init
3619
+ })
3620
+ }
3621
+ }
3622
+ }
3623
+
3624
+ /**
3625
+ * 宿主全局响应式注册表:菜单与扩展点槽位,供布局与 `ExtensionPoint` 订阅。
3626
+ *
3627
+ * @module registries
3628
+ */
3629
+
3630
+ /**
3631
+ * @type {{
3632
+ * menus: object[],
3633
+ * slots: Record<string, Array<{ pluginId: string, component: import('vue').Component, priority: number, key: string }>>
3634
+ * }}
3635
+ */
3636
+ const registries = Vue__default.default.observable({
3637
+ menus: [],
3638
+ /** 扩展点 id → 已注册组件列表(内容区 / 工具栏等共用模型) */
3639
+ slots: {},
3640
+ /**
3641
+ * 每次变更 slots 时递增,供 ExtensionPoint 计算属性显式依赖。
3642
+ * Vue 2 对「先访问不存在的 slots[key]、后 Vue.set 补 key」的依赖收集不可靠,会导致扩展点不刷新。
3643
+ */
3644
+ slotRevision: 0
3645
+ });
3646
+
3647
+ /**
3648
+ * 按 `pluginId` 收集 `onTeardown` 回调,供 `disposeWebPlugin` 统一执行。
3649
+ *
3650
+ * @module teardown-registry
3651
+ */
3652
+
3653
+ /** @type {Map<string, Function[]>} */
3654
+ const byPlugin = new Map();
3655
+
3656
+ /**
3657
+ * 登记插件卸载时要执行的同步回调(建议只做解绑、清定时器等轻量逻辑)。
3658
+ * @param {string} pluginId
3659
+ * @param {() => void} fn
3660
+ */
3661
+ function registerPluginTeardown(pluginId, fn) {
3662
+ if (typeof fn !== 'function') {
3663
+ return
3664
+ }
3665
+ let arr = byPlugin.get(pluginId);
3666
+ if (!arr) {
3667
+ arr = [];
3668
+ byPlugin.set(pluginId, arr);
3669
+ }
3670
+ arr.push(fn);
3671
+ }
3672
+
3673
+ /**
3674
+ * 执行并清空该插件已登记的全部 teardown;调用后 Map 中不再保留该 id。
3675
+ * @param {string} pluginId
3676
+ */
3677
+ function runPluginTeardowns(pluginId) {
3678
+ const arr = byPlugin.get(pluginId);
3679
+ if (!arr) {
3680
+ return
3681
+ }
3682
+ byPlugin.delete(pluginId);
3683
+ for (const fn of arr) {
3684
+ try {
3685
+ fn();
3686
+ } catch (e) {
3687
+ console.warn('[plugins] teardown failed', pluginId, e);
3688
+ }
3689
+ }
3690
+ }
3691
+
3692
+ /**
3693
+ * 构造供插件 activator 调用的宿主 API(路由、菜单、扩展点、资源注入等)。
3694
+ * 与打包工具无关;Webpack 宿主需已配置 `vue-loader` 以编译本包内的 `.vue` 依赖。
3695
+ *
3696
+ * @module createHostApi
3697
+ */
3698
+
3699
+ /** 扩展点列表项 key 递增,避免用 Date.now() 导致列表重排时误卸载组件 */
3700
+ let slotItemKeySeq = 0;
3701
+ /** 无 name 的动态路由合成名递增,避免多次 registerRoutes 重名 */
3702
+ let routeSynthSeq = 0;
3703
+
3704
+ /**
3705
+ * @typedef {object} RegisterSlotEntry
3706
+ * @property {import('vue').Component} component
3707
+ * @property {number} [priority]
3708
+ */
3709
+
3710
+ /**
3711
+ * @typedef {object} HostApi
3712
+ * @property {string} hostPluginApiVersion 宿主实现的协议版本
3713
+ * @property {(routes: import('vue-router').RouteConfig[]) => void} registerRoutes 注册路由;无 `name` 时自动生成稳定合成名;优先 `router.addRoute`
3714
+ * @property {(items: object[]) => void} registerMenuItems 注册菜单并按 `order` 排序
3715
+ * @property {(pointId: string, components: RegisterSlotEntry[]) => void} registerSlotComponents 向扩展点挂载组件
3716
+ * @property {(urls?: string[]) => void} registerStylesheetUrls 注入 `link[rel=stylesheet]`,带 `data-plugin-asset`
3717
+ * @property {(urls?: string[]) => void} registerScriptUrls 顺序注入外链脚本
3718
+ * @property {() => void} registerSanitizedHtmlSnippet MVP 未实现,调用即抛错
3719
+ * @property {() => ReturnType<typeof createRequestBridge>} getBridge 受控 `fetch` 代理
3720
+ * @property {(pluginId: string, fn: () => void) => void} onTeardown 注册卸载回调;由 `disposeWebPlugin(pluginId)` 触发
3721
+ */
3722
+
3723
+ /**
3724
+ * @typedef {object} HostKitOptions
3725
+ * @property {string[]} [bridgeAllowedPathPrefixes] 覆盖 `getBridge().request` 允许的 URL 前缀;默认见 `defaultWebExtendPluginRuntime.bridgeAllowedPathPrefixes`
3726
+ */
3727
+
3728
+ /**
3729
+ * 创建单个插件在宿主侧的 API 句柄,传入插件 `activator(hostApi)`。
3730
+ *
3731
+ * `bootstrapPlugins` 始终以 `(pluginId, router, hostKitOptions)` 调用工厂;请使用 `(id, r, kit) => createHostApi(id, r, kit)` 传入 `bridgeAllowedPathPrefixes`。
3732
+ * 单参工厂 `(id) => createHostApi(id, router)` 仍可用(忽略后两个实参),此时 bridge 仅用包内默认前缀。
3733
+ *
3734
+ * @param {string} pluginId 与 manifest.id 一致
3735
+ * @param {import('vue-router').default} router 宿主 Vue Router 实例(vue-router@3)
3736
+ * @param {HostKitOptions} [hostKitOptions]
3737
+ * @returns {HostApi}
3738
+ */
3739
+ function createHostApi(pluginId, router, hostKitOptions = {}) {
3740
+ const bridgePrefixes =
3741
+ Array.isArray(hostKitOptions.bridgeAllowedPathPrefixes) &&
3742
+ hostKitOptions.bridgeAllowedPathPrefixes.length > 0
3743
+ ? hostKitOptions.bridgeAllowedPathPrefixes
3744
+ : defaultWebExtendPluginRuntime.bridgeAllowedPathPrefixes;
3745
+ const bridge = createRequestBridge({ allowedPathPrefixes: bridgePrefixes });
3746
+
3747
+ /**
3748
+ * 注入样式表;`disposeWebPlugin` 会按 `data-plugin-asset` 移除对应节点。
3749
+ * @param {string} href
3750
+ */
3751
+ function injectStylesheet(href) {
3752
+ const link = document.createElement('link');
3753
+ link.rel = 'stylesheet';
3754
+ link.href = href;
3755
+ link.setAttribute('data-plugin-asset', pluginId);
3756
+ document.head.appendChild(link);
3757
+ }
3758
+
3759
+ /**
3760
+ * 注入外链脚本(用于插件额外资源,非清单主入口)。
3761
+ * @param {string} src
3762
+ * @returns {Promise<void>}
3763
+ */
3764
+ function injectScript(src) {
3765
+ return new Promise((resolve, reject) => {
3766
+ const s = document.createElement('script');
3767
+ s.async = true;
3768
+ s.src = src;
3769
+ s.setAttribute('data-plugin-asset', pluginId);
3770
+ s.onload = () => resolve();
3771
+ s.onerror = () => reject(new Error('script failed: ' + src));
3772
+ document.head.appendChild(s);
3773
+ })
3774
+ }
3775
+
3776
+ return {
3777
+ hostPluginApiVersion: HOST_PLUGIN_API_VERSION,
3778
+
3779
+ /**
3780
+ * 动态注册路由。Vue Router 3.5+ 推荐 `addRoute`;若不存在则回退已弃用的 `addRoutes`。
3781
+ * @param {import('vue-router').RouteConfig[]} routes
3782
+ */
3783
+ registerRoutes(routes) {
3784
+ const wrapped = routes.map((r) => ({
3785
+ ...r,
3786
+ name: r.name || `__wep_${pluginId}_${routeSynthSeq++}`,
3787
+ meta: { ...(r.meta || {}), pluginId }
3788
+ }));
3789
+ if (typeof router.addRoute === 'function') {
3790
+ for (const r of wrapped) {
3791
+ router.addRoute(r);
3792
+ }
3793
+ } else {
3794
+ router.addRoutes(wrapped);
3795
+ }
3796
+ },
3797
+
3798
+ /**
3799
+ * 写入全局菜单注册表(响应式);按 `order` 升序排列。
3800
+ * @param {object[]} items
3801
+ */
3802
+ registerMenuItems(items) {
3803
+ for (const item of items) {
3804
+ registries.menus.push({ ...item, pluginId });
3805
+ }
3806
+ registries.menus.sort(
3807
+ (a, b) => (a.order != null ? a.order : 0) - (b.order != null ? b.order : 0)
3808
+ );
3809
+ },
3810
+
3811
+ /**
3812
+ * 向指定扩展点 id 注册 Vue 组件;`ExtensionPoint` 按 `priority` 降序渲染。
3813
+ * @param {string} pointId
3814
+ * @param {RegisterSlotEntry[]} components
3815
+ */
3816
+ registerSlotComponents(pointId, components) {
3817
+ if (!pointId) {
3818
+ return
3819
+ }
3820
+ if (!registries.slots[pointId]) {
3821
+ Vue__default.default.set(registries.slots, pointId, []);
3822
+ }
3823
+ const list = registries.slots[pointId];
3824
+ for (const c of components) {
3825
+ list.push({
3826
+ pluginId,
3827
+ component: c.component,
3828
+ priority: c.priority != null ? c.priority : 0,
3829
+ key: `${pluginId}-${pointId}-${++slotItemKeySeq}`
3830
+ });
3831
+ }
3832
+ list.sort((a, b) => b.priority - a.priority);
3833
+ registries.slotRevision++;
3834
+ },
3835
+
3836
+ /**
3837
+ * @param {string[]|undefined} urls
3838
+ */
3839
+ registerStylesheetUrls(urls) {
3840
+ for (const u of urls || []) {
3841
+ if (typeof u === 'string' && u) {
3842
+ injectStylesheet(u);
3843
+ }
3844
+ }
3845
+ },
3846
+
3847
+ /**
3848
+ * 串行加载多个脚本,失败仅告警不中断宿主。
3849
+ * @param {string[]|undefined} urls
3850
+ */
3851
+ registerScriptUrls(urls) {
3852
+ const chain = (urls || []).filter((u) => typeof u === 'string' && u).reduce(
3853
+ (p, u) => p.then(() => injectScript(u)),
3854
+ Promise.resolve()
3855
+ );
3856
+ chain.catch((e) => console.warn('[plugins] registerScriptUrls', pluginId, e));
3857
+ },
3858
+
3859
+ registerSanitizedHtmlSnippet() {
3860
+ throw new Error('registerSanitizedHtmlSnippet is not enabled in MVP')
3861
+ },
3862
+
3863
+ getBridge: () => bridge,
3864
+
3865
+ /**
3866
+ * 插件卸载前清理逻辑;第一个参数为预留与协议对齐,实际以创建 API 时的 `pluginId` 为准。
3867
+ * @param {string} _pluginId 预留,与 manifest.id 一致时可传入
3868
+ * @param {() => void} fn
3869
+ */
3870
+ onTeardown(_pluginId, fn) {
3871
+ if (typeof fn === 'function') {
3872
+ registerPluginTeardown(pluginId, fn);
3873
+ }
3874
+ }
3875
+ }
3876
+ }
3877
+
3878
+ /**
3879
+ * 单插件卸载:与 `bootstrapPlugins` / `createHostApi` 对称,清理注册表与 DOM 副作用。
3880
+ *
3881
+ * @module dispose-plugin
3882
+ */
3883
+
3884
+ /**
3885
+ * 卸载指定 id 的插件:依次执行 teardown、移除菜单与扩展点条目、删除 activator、移除带 `data-plugin-asset` 的节点。
3886
+ *
3887
+ * **路由**:Vue Router 3 无公开 `removeRoute`,此处不改动 matcher;动态路由需整页刷新或自行维护路由表。
3888
+ *
3889
+ * @param {string} pluginId 与 manifest.id 一致
3890
+ */
3891
+ function disposeWebPlugin(pluginId) {
3892
+ if (!pluginId || typeof pluginId !== 'string') {
3893
+ return
3894
+ }
3895
+
3896
+ runPluginTeardowns(pluginId);
3897
+
3898
+ for (let i = registries.menus.length - 1; i >= 0; i--) {
3899
+ if (registries.menus[i].pluginId === pluginId) {
3900
+ registries.menus.splice(i, 1);
3901
+ }
3902
+ }
3903
+
3904
+ const slots = registries.slots;
3905
+ for (const pointId of Object.keys(slots)) {
3906
+ const list = slots[pointId];
3907
+ if (!Array.isArray(list)) {
3908
+ continue
3909
+ }
3910
+ const next = list.filter((x) => x.pluginId !== pluginId);
3911
+ if (next.length === 0) {
3912
+ Vue__default.default.delete(slots, pointId);
3913
+ } else if (next.length !== list.length) {
3914
+ Vue__default.default.set(slots, pointId, next);
3915
+ }
3916
+ }
3917
+ registries.slotRevision++;
3918
+
3919
+ if (typeof window !== 'undefined' && window.__PLUGIN_ACTIVATORS__) {
3920
+ delete window.__PLUGIN_ACTIVATORS__[pluginId];
3921
+ }
3922
+
3923
+ if (typeof document !== 'undefined') {
3924
+ document.querySelectorAll('[data-plugin-asset]').forEach((el) => {
3925
+ if (el.getAttribute('data-plugin-asset') === pluginId) {
3926
+ el.remove();
3927
+ }
3928
+ });
3929
+ }
3930
+ }
3931
+
3932
+ /**
3933
+ * 在宿主布局中声明扩展点;插件通过 `hostApi.registerSlotComponents(pointId, ...)` 注入组件。
3934
+ * 使用纯 render 函数,便于 Rollup 发布 dist,宿主无需再转译 .vue。
3935
+ */
3936
+
3937
+ const SlotErrorBoundary = {
3938
+ name: 'SlotErrorBoundary',
3939
+ props: { label: String },
3940
+ data() {
3941
+ return { error: null }
3942
+ },
3943
+ errorCaptured(err) {
3944
+ this.error = err && err.message ? err.message : String(err);
3945
+ console.error('[ExtensionPoint] render error in', this.label, err);
3946
+ return false
3947
+ },
3948
+ render(h) {
3949
+ if (this.error) {
3950
+ return h(
3951
+ 'div',
3952
+ { class: 'plugin-point-error', style: { color: '#c00', fontSize: '12px' } },
3953
+ `[插件 ${this.label}] 渲染失败`
3954
+ )
3955
+ }
3956
+ const d = this.$slots.default;
3957
+ return d && d[0] ? d[0] : h('span')
3958
+ }
3959
+ };
3960
+
3961
+ var ExtensionPoint = {
3962
+ name: 'ExtensionPoint',
3963
+ components: { SlotErrorBoundary },
3964
+ props: {
3965
+ pointId: { type: String, required: true },
3966
+ slotProps: { type: Object, default: () => ({}) }
3967
+ },
3968
+ computed: {
3969
+ items() {
3970
+ void registries.slotRevision;
3971
+ return registries.slots[this.pointId] || []
3972
+ },
3973
+ forwardProps() {
3974
+ return this.slotProps || {}
3975
+ }
3976
+ },
3977
+ render(h) {
3978
+ return h(
3979
+ 'div',
3980
+ {
3981
+ class: 'extension-point',
3982
+ style: { minHeight: '8px' },
3983
+ attrs: { 'data-point-id': this.pointId }
3984
+ },
3985
+ this.items.map((item) =>
3986
+ h(
3987
+ SlotErrorBoundary,
3988
+ {
3989
+ key: item.key,
3990
+ props: { label: item.pluginId }
3991
+ },
3992
+ [h(item.component, { props: this.forwardProps })]
3993
+ )
3994
+ )
3995
+ )
3996
+ }
3997
+ };
3998
+
3999
+ /**
4000
+ * 一键接入:注册 `ExtensionPoint` 并执行 `bootstrapPlugins`。
4001
+ * @module install
4002
+ */
4003
+
4004
+ /**
4005
+ * 注册全局组件 `ExtensionPoint` 并异步引导插件清单。
4006
+ *
4007
+ * @param {*} Vue
4008
+ * @param {*} router vue-router 实例
4009
+ * @param {Record<string, unknown>} [options] 传给 `resolveRuntimeOptions` 的字段;可含 `env`(Vite 传入 `import.meta.env`)以读取 `VITE_*`。
4010
+ * @returns {Promise<void>}
4011
+ */
4012
+ function installWebExtendPluginVue2(Vue, router, options) {
4013
+ const opts = options || {};
4014
+ const { env: injectedEnv, ...runtimeUser } = opts;
4015
+ if (injectedEnv && typeof injectedEnv === 'object') {
4016
+ setWebExtendPluginEnv(injectedEnv);
4017
+ }
4018
+ if (Vue && ExtensionPoint) {
4019
+ Vue.component('ExtensionPoint', ExtensionPoint);
4020
+ }
4021
+ const runtime = resolveRuntimeOptions(runtimeUser);
4022
+ return bootstrapPlugins(router, (id, r, kit) => createHostApi(id, r, kit), runtime)
4023
+ }
4024
+
4025
+ exports.ExtensionPoint = ExtensionPoint;
4026
+ exports.HOST_PLUGIN_API_VERSION = HOST_PLUGIN_API_VERSION;
4027
+ exports.bootstrapPlugins = bootstrapPlugins;
4028
+ exports.createHostApi = createHostApi;
4029
+ exports.createRequestBridge = createRequestBridge;
4030
+ exports.defaultWebExtendPluginRuntime = defaultWebExtendPluginRuntime;
4031
+ exports.disposeWebPlugin = disposeWebPlugin;
4032
+ exports.installWebExtendPluginVue2 = installWebExtendPluginVue2;
4033
+ exports.registries = registries;
4034
+ exports.resolveRuntimeOptions = resolveRuntimeOptions;
4035
+ exports.setWebExtendPluginEnv = setWebExtendPluginEnv;
4036
+ //# sourceMappingURL=index.cjs.map