@heybox/hb-sdk 0.8.2-alpha.2 → 0.8.2-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +32 -1
  2. package/README.md +5 -1
  3. package/dist/cli-chunks/{build-bVThH3Z5.cjs → build-D2T3ky_9.cjs} +5 -5
  4. package/dist/cli-chunks/{context-DpKqGnjp.cjs → context-DEgmdpSL.cjs} +326 -104
  5. package/dist/cli-chunks/{create-BWC2343y.cjs → create-DKqQhrG5.cjs} +5 -1
  6. package/dist/cli-chunks/{dev-t14YpHHY.cjs → dev-BEXM7cmq.cjs} +17 -9
  7. package/dist/cli-chunks/{doctor-BWkrE0Hj.cjs → doctor-B7UixGrd.cjs} +1 -1
  8. package/dist/cli-chunks/{index-CDtcZVWv.cjs → index-BtwfuoWI.cjs} +15 -17
  9. package/dist/cli-chunks/{index-D3FMcOZq.cjs → index-C69OtRug.cjs} +2 -2
  10. package/dist/cli-chunks/{index.esm-BrJBaJWS.cjs → index.esm-C86KlVdK.cjs} +11 -10
  11. package/dist/cli-chunks/{login-DRMl7nFH.cjs → login-Bp_HMx-i.cjs} +2 -2
  12. package/dist/cli-chunks/{project-vite-CXgdzIYw.cjs → project-vite-DZxipd13.cjs} +1 -1
  13. package/dist/cli-chunks/{remote-ibQybNiM.cjs → remote-B_sVsbQP.cjs} +80 -60
  14. package/dist/cli-chunks/runtime-gate-GR9jZd37.cjs +58 -0
  15. package/dist/cli-chunks/{runtime-gate-BWb8QIcX.cjs → runtime-permission-env-COWketgE.cjs} +4533 -40
  16. package/dist/cli-chunks/{session-CIoBspg-.cjs → session-6-AApcTZ.cjs} +1 -1
  17. package/dist/cli-chunks/{skill-5labzuWk.cjs → skill-CPDLk7t7.cjs} +2 -2
  18. package/dist/cli-chunks/{version-QiVEs76a.cjs → version-hHrSPRwW.cjs} +1 -1
  19. package/dist/cli.cjs +1 -1
  20. package/dist/devtools/browser-dev-host/assets/browser-dev-host-CpwQQhA1.js +101 -0
  21. package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-B4KsgItx.js → desktop-app-launch-BdWBOIvY.js} +1 -1
  22. package/dist/devtools/browser-dev-host/assets/{index-9Nb3XhtI.js → index-BQSEynx6.js} +3 -3
  23. package/dist/devtools/browser-dev-host/index.html +2 -2
  24. package/dist/index.cjs.js +1 -1
  25. package/dist/index.esm.js +1 -1
  26. package/dist/miniapp-publish.cjs.js +8782 -0
  27. package/dist/miniapp-publish.esm.js +8778 -1
  28. package/dist/templates/vanilla-vite-js/assets/heybox-placeholder.png +0 -0
  29. package/dist/templates/vanilla-vite-js/package.json.ejs +3 -0
  30. package/dist/vite.cjs.js +499 -346
  31. package/dist/vite.esm.js +500 -347
  32. package/package.json +7 -6
  33. package/skill/SKILL.md +5 -1
  34. package/skill/references/api-root.md +5 -4
  35. package/skill/references/cli.md +3 -3
  36. package/skill/references/recipes.md +3 -2
  37. package/skill/skill.json +5 -5
  38. package/types/miniapp-manifest/basic-info-browser.d.ts +9 -0
  39. package/types/miniapp-manifest/basic-info-image-header.d.ts +6 -0
  40. package/types/miniapp-manifest/basic-info-node.d.ts +17 -0
  41. package/types/miniapp-manifest/basic-info-placeholder.d.ts +1 -0
  42. package/types/miniapp-manifest/basic-info.d.ts +12 -0
  43. package/types/miniapp-manifest/schema.d.ts +7 -1
  44. package/types/miniapp-publish/index.d.ts +8 -0
  45. package/dist/cli-chunks/runtime-permission-env-DiTeD75Q.cjs +0 -4498
  46. package/dist/devtools/browser-dev-host/assets/browser-dev-host-DxzOkljJ.js +0 -101
  47. /package/types/{vite → miniapp-manifest}/runtime-gate.d.ts +0 -0
@@ -1,5 +1,3673 @@
1
1
  'use strict';
2
2
 
3
+ var fs = require('node:fs');
4
+ var path = require('node:path');
5
+ var version = require('./version-hHrSPRwW.cjs');
6
+ require('node:crypto');
7
+ var node_async_hooks = require('node:async_hooks');
8
+
9
+ var re = {exports: {}};
10
+
11
+ var constants;
12
+ var hasRequiredConstants;
13
+
14
+ function requireConstants () {
15
+ if (hasRequiredConstants) return constants;
16
+ hasRequiredConstants = 1;
17
+
18
+ // Note: this is the semver.org version of the spec that it implements
19
+ // Not necessarily the package version of this code.
20
+ const SEMVER_SPEC_VERSION = '2.0.0';
21
+
22
+ const MAX_LENGTH = 256;
23
+ const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
24
+ /* istanbul ignore next */ 9007199254740991;
25
+
26
+ // Max safe segment length for coercion.
27
+ const MAX_SAFE_COMPONENT_LENGTH = 16;
28
+
29
+ // Max safe length for a build identifier. The max length minus 6 characters for
30
+ // the shortest version with a build 0.0.0+BUILD.
31
+ const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
32
+
33
+ const RELEASE_TYPES = [
34
+ 'major',
35
+ 'premajor',
36
+ 'minor',
37
+ 'preminor',
38
+ 'patch',
39
+ 'prepatch',
40
+ 'prerelease',
41
+ ];
42
+
43
+ constants = {
44
+ MAX_LENGTH,
45
+ MAX_SAFE_COMPONENT_LENGTH,
46
+ MAX_SAFE_BUILD_LENGTH,
47
+ MAX_SAFE_INTEGER,
48
+ RELEASE_TYPES,
49
+ SEMVER_SPEC_VERSION,
50
+ FLAG_INCLUDE_PRERELEASE: 0b001,
51
+ FLAG_LOOSE: 0b010,
52
+ };
53
+ return constants;
54
+ }
55
+
56
+ var debug_1;
57
+ var hasRequiredDebug;
58
+
59
+ function requireDebug () {
60
+ if (hasRequiredDebug) return debug_1;
61
+ hasRequiredDebug = 1;
62
+
63
+ const debug = (
64
+ typeof process === 'object' &&
65
+ process.env &&
66
+ process.env.NODE_DEBUG &&
67
+ /\bsemver\b/i.test(process.env.NODE_DEBUG)
68
+ ) ? (...args) => console.error('SEMVER', ...args)
69
+ : () => {};
70
+
71
+ debug_1 = debug;
72
+ return debug_1;
73
+ }
74
+
75
+ var hasRequiredRe;
76
+
77
+ function requireRe () {
78
+ if (hasRequiredRe) return re.exports;
79
+ hasRequiredRe = 1;
80
+ (function (module, exports) {
81
+
82
+ const {
83
+ MAX_SAFE_COMPONENT_LENGTH,
84
+ MAX_SAFE_BUILD_LENGTH,
85
+ MAX_LENGTH,
86
+ } = requireConstants();
87
+ const debug = requireDebug();
88
+ exports = module.exports = {};
89
+
90
+ // The actual regexps go on exports.re
91
+ const re = exports.re = [];
92
+ const safeRe = exports.safeRe = [];
93
+ const src = exports.src = [];
94
+ const safeSrc = exports.safeSrc = [];
95
+ const t = exports.t = {};
96
+ let R = 0;
97
+
98
+ const LETTERDASHNUMBER = '[a-zA-Z0-9-]';
99
+
100
+ // Replace some greedy regex tokens to prevent regex dos issues. These regex are
101
+ // used internally via the safeRe object since all inputs in this library get
102
+ // normalized first to trim and collapse all extra whitespace. The original
103
+ // regexes are exported for userland consumption and lower level usage. A
104
+ // future breaking change could export the safer regex only with a note that
105
+ // all input should have extra whitespace removed.
106
+ const safeRegexReplacements = [
107
+ ['\\s', 1],
108
+ ['\\d', MAX_LENGTH],
109
+ [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],
110
+ ];
111
+
112
+ const makeSafeRegex = (value) => {
113
+ for (const [token, max] of safeRegexReplacements) {
114
+ value = value
115
+ .split(`${token}*`).join(`${token}{0,${max}}`)
116
+ .split(`${token}+`).join(`${token}{1,${max}}`);
117
+ }
118
+ return value
119
+ };
120
+
121
+ const createToken = (name, value, isGlobal) => {
122
+ const safe = makeSafeRegex(value);
123
+ const index = R++;
124
+ debug(name, index, value);
125
+ t[name] = index;
126
+ src[index] = value;
127
+ safeSrc[index] = safe;
128
+ re[index] = new RegExp(value, isGlobal ? 'g' : undefined);
129
+ safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined);
130
+ };
131
+
132
+ // The following Regular Expressions can be used for tokenizing,
133
+ // validating, and parsing SemVer version strings.
134
+
135
+ // ## Numeric Identifier
136
+ // A single `0`, or a non-zero digit followed by zero or more digits.
137
+
138
+ createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*');
139
+ createToken('NUMERICIDENTIFIERLOOSE', '\\d+');
140
+
141
+ // ## Non-numeric Identifier
142
+ // Zero or more digits, followed by a letter or hyphen, and then zero or
143
+ // more letters, digits, or hyphens.
144
+
145
+ createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
146
+
147
+ // ## Main Version
148
+ // Three dot-separated numeric identifiers.
149
+
150
+ createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
151
+ `(${src[t.NUMERICIDENTIFIER]})\\.` +
152
+ `(${src[t.NUMERICIDENTIFIER]})`);
153
+
154
+ createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
155
+ `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
156
+ `(${src[t.NUMERICIDENTIFIERLOOSE]})`);
157
+
158
+ // ## Pre-release Version Identifier
159
+ // A numeric identifier, or a non-numeric identifier.
160
+ // Non-numeric identifiers include numeric identifiers but can be longer.
161
+ // Therefore non-numeric identifiers must go first.
162
+
163
+ createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]
164
+ }|${src[t.NUMERICIDENTIFIER]})`);
165
+
166
+ createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]
167
+ }|${src[t.NUMERICIDENTIFIERLOOSE]})`);
168
+
169
+ // ## Pre-release Version
170
+ // Hyphen, followed by one or more dot-separated pre-release version
171
+ // identifiers.
172
+
173
+ createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
174
+ }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
175
+
176
+ createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
177
+ }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);
178
+
179
+ // ## Build Metadata Identifier
180
+ // Any combination of digits, letters, or hyphens.
181
+
182
+ createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`);
183
+
184
+ // ## Build Metadata
185
+ // Plus sign, followed by one or more period-separated build metadata
186
+ // identifiers.
187
+
188
+ createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
189
+ }(?:\\.${src[t.BUILDIDENTIFIER]})*))`);
190
+
191
+ // ## Full Version String
192
+ // A main version, followed optionally by a pre-release version and
193
+ // build metadata.
194
+
195
+ // Note that the only major, minor, patch, and pre-release sections of
196
+ // the version string are capturing groups. The build metadata is not a
197
+ // capturing group, because it should not ever be used in version
198
+ // comparison.
199
+
200
+ createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
201
+ }${src[t.PRERELEASE]}?${
202
+ src[t.BUILD]}?`);
203
+
204
+ createToken('FULL', `^${src[t.FULLPLAIN]}$`);
205
+
206
+ // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
207
+ // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
208
+ // common in the npm registry.
209
+ createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
210
+ }${src[t.PRERELEASELOOSE]}?${
211
+ src[t.BUILD]}?`);
212
+
213
+ createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`);
214
+
215
+ createToken('GTLT', '((?:<|>)?=?)');
216
+
217
+ // Something like "2.*" or "1.2.x".
218
+ // Note that "x.x" is a valid xRange identifier, meaning "any version"
219
+ // Only the first item is strictly required.
220
+ createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
221
+ createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
222
+
223
+ createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
224
+ `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
225
+ `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
226
+ `(?:${src[t.PRERELEASE]})?${
227
+ src[t.BUILD]}?` +
228
+ `)?)?`);
229
+
230
+ createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
231
+ `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
232
+ `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
233
+ `(?:${src[t.PRERELEASELOOSE]})?${
234
+ src[t.BUILD]}?` +
235
+ `)?)?`);
236
+
237
+ createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
238
+ createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);
239
+
240
+ // Coercion.
241
+ // Extract anything that could conceivably be a part of a valid semver
242
+ createToken('COERCEPLAIN', `${'(^|[^\\d])' +
243
+ '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
244
+ `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
245
+ `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
246
+ createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`);
247
+ createToken('COERCEFULL', src[t.COERCEPLAIN] +
248
+ `(?:${src[t.PRERELEASE]})?` +
249
+ `(?:${src[t.BUILD]})?` +
250
+ `(?:$|[^\\d])`);
251
+ createToken('COERCERTL', src[t.COERCE], true);
252
+ createToken('COERCERTLFULL', src[t.COERCEFULL], true);
253
+
254
+ // Tilde ranges.
255
+ // Meaning is "reasonably at or greater than"
256
+ createToken('LONETILDE', '(?:~>?)');
257
+
258
+ createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true);
259
+ exports.tildeTrimReplace = '$1~';
260
+
261
+ createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
262
+ createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);
263
+
264
+ // Caret ranges.
265
+ // Meaning is "at least and backwards compatible with"
266
+ createToken('LONECARET', '(?:\\^)');
267
+
268
+ createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true);
269
+ exports.caretTrimReplace = '$1^';
270
+
271
+ createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
272
+ createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);
273
+
274
+ // A simple gt/lt/eq thing, or just "" to indicate "any version"
275
+ createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
276
+ createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);
277
+
278
+ // An expression to strip any whitespace between the gtlt and the thing
279
+ // it modifies, so that `> 1.2.3` ==> `>1.2.3`
280
+ createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
281
+ }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
282
+ exports.comparatorTrimReplace = '$1$2$3';
283
+
284
+ // Something like `1.2.3 - 1.2.4`
285
+ // Note that these all use the loose form, because they'll be
286
+ // checked against either the strict or loose comparator form
287
+ // later.
288
+ createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
289
+ `\\s+-\\s+` +
290
+ `(${src[t.XRANGEPLAIN]})` +
291
+ `\\s*$`);
292
+
293
+ createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
294
+ `\\s+-\\s+` +
295
+ `(${src[t.XRANGEPLAINLOOSE]})` +
296
+ `\\s*$`);
297
+
298
+ // Star ranges basically just allow anything at all.
299
+ createToken('STAR', '(<|>)?=?\\s*\\*');
300
+ // >=0.0.0 is like a star
301
+ createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$');
302
+ createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$');
303
+ } (re, re.exports));
304
+ return re.exports;
305
+ }
306
+
307
+ var parseOptions_1;
308
+ var hasRequiredParseOptions;
309
+
310
+ function requireParseOptions () {
311
+ if (hasRequiredParseOptions) return parseOptions_1;
312
+ hasRequiredParseOptions = 1;
313
+
314
+ // parse out just the options we care about
315
+ const looseOption = Object.freeze({ loose: true });
316
+ const emptyOpts = Object.freeze({ });
317
+ const parseOptions = options => {
318
+ if (!options) {
319
+ return emptyOpts
320
+ }
321
+
322
+ if (typeof options !== 'object') {
323
+ return looseOption
324
+ }
325
+
326
+ return options
327
+ };
328
+ parseOptions_1 = parseOptions;
329
+ return parseOptions_1;
330
+ }
331
+
332
+ var identifiers;
333
+ var hasRequiredIdentifiers;
334
+
335
+ function requireIdentifiers () {
336
+ if (hasRequiredIdentifiers) return identifiers;
337
+ hasRequiredIdentifiers = 1;
338
+
339
+ const numeric = /^[0-9]+$/;
340
+ const compareIdentifiers = (a, b) => {
341
+ if (typeof a === 'number' && typeof b === 'number') {
342
+ return a === b ? 0 : a < b ? -1 : 1
343
+ }
344
+
345
+ const anum = numeric.test(a);
346
+ const bnum = numeric.test(b);
347
+
348
+ if (anum && bnum) {
349
+ a = +a;
350
+ b = +b;
351
+ }
352
+
353
+ return a === b ? 0
354
+ : (anum && !bnum) ? -1
355
+ : (bnum && !anum) ? 1
356
+ : a < b ? -1
357
+ : 1
358
+ };
359
+
360
+ const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
361
+
362
+ identifiers = {
363
+ compareIdentifiers,
364
+ rcompareIdentifiers,
365
+ };
366
+ return identifiers;
367
+ }
368
+
369
+ var semver$1;
370
+ var hasRequiredSemver$1;
371
+
372
+ function requireSemver$1 () {
373
+ if (hasRequiredSemver$1) return semver$1;
374
+ hasRequiredSemver$1 = 1;
375
+
376
+ const debug = requireDebug();
377
+ const { MAX_LENGTH, MAX_SAFE_INTEGER } = requireConstants();
378
+ const { safeRe: re, t } = requireRe();
379
+
380
+ const parseOptions = requireParseOptions();
381
+ const { compareIdentifiers } = requireIdentifiers();
382
+ class SemVer {
383
+ constructor (version, options) {
384
+ options = parseOptions(options);
385
+
386
+ if (version instanceof SemVer) {
387
+ if (version.loose === !!options.loose &&
388
+ version.includePrerelease === !!options.includePrerelease) {
389
+ return version
390
+ } else {
391
+ version = version.version;
392
+ }
393
+ } else if (typeof version !== 'string') {
394
+ throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)
395
+ }
396
+
397
+ if (version.length > MAX_LENGTH) {
398
+ throw new TypeError(
399
+ `version is longer than ${MAX_LENGTH} characters`
400
+ )
401
+ }
402
+
403
+ debug('SemVer', version, options);
404
+ this.options = options;
405
+ this.loose = !!options.loose;
406
+ // this isn't actually relevant for versions, but keep it so that we
407
+ // don't run into trouble passing this.options around.
408
+ this.includePrerelease = !!options.includePrerelease;
409
+
410
+ const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
411
+
412
+ if (!m) {
413
+ throw new TypeError(`Invalid Version: ${version}`)
414
+ }
415
+
416
+ this.raw = version;
417
+
418
+ // these are actually numbers
419
+ this.major = +m[1];
420
+ this.minor = +m[2];
421
+ this.patch = +m[3];
422
+
423
+ if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
424
+ throw new TypeError('Invalid major version')
425
+ }
426
+
427
+ if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
428
+ throw new TypeError('Invalid minor version')
429
+ }
430
+
431
+ if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
432
+ throw new TypeError('Invalid patch version')
433
+ }
434
+
435
+ // numberify any prerelease numeric ids
436
+ if (!m[4]) {
437
+ this.prerelease = [];
438
+ } else {
439
+ this.prerelease = m[4].split('.').map((id) => {
440
+ if (/^[0-9]+$/.test(id)) {
441
+ const num = +id;
442
+ if (num >= 0 && num < MAX_SAFE_INTEGER) {
443
+ return num
444
+ }
445
+ }
446
+ return id
447
+ });
448
+ }
449
+
450
+ this.build = m[5] ? m[5].split('.') : [];
451
+ this.format();
452
+ }
453
+
454
+ format () {
455
+ this.version = `${this.major}.${this.minor}.${this.patch}`;
456
+ if (this.prerelease.length) {
457
+ this.version += `-${this.prerelease.join('.')}`;
458
+ }
459
+ return this.version
460
+ }
461
+
462
+ toString () {
463
+ return this.version
464
+ }
465
+
466
+ compare (other) {
467
+ debug('SemVer.compare', this.version, this.options, other);
468
+ if (!(other instanceof SemVer)) {
469
+ if (typeof other === 'string' && other === this.version) {
470
+ return 0
471
+ }
472
+ other = new SemVer(other, this.options);
473
+ }
474
+
475
+ if (other.version === this.version) {
476
+ return 0
477
+ }
478
+
479
+ return this.compareMain(other) || this.comparePre(other)
480
+ }
481
+
482
+ compareMain (other) {
483
+ if (!(other instanceof SemVer)) {
484
+ other = new SemVer(other, this.options);
485
+ }
486
+
487
+ if (this.major < other.major) {
488
+ return -1
489
+ }
490
+ if (this.major > other.major) {
491
+ return 1
492
+ }
493
+ if (this.minor < other.minor) {
494
+ return -1
495
+ }
496
+ if (this.minor > other.minor) {
497
+ return 1
498
+ }
499
+ if (this.patch < other.patch) {
500
+ return -1
501
+ }
502
+ if (this.patch > other.patch) {
503
+ return 1
504
+ }
505
+ return 0
506
+ }
507
+
508
+ comparePre (other) {
509
+ if (!(other instanceof SemVer)) {
510
+ other = new SemVer(other, this.options);
511
+ }
512
+
513
+ // NOT having a prerelease is > having one
514
+ if (this.prerelease.length && !other.prerelease.length) {
515
+ return -1
516
+ } else if (!this.prerelease.length && other.prerelease.length) {
517
+ return 1
518
+ } else if (!this.prerelease.length && !other.prerelease.length) {
519
+ return 0
520
+ }
521
+
522
+ let i = 0;
523
+ do {
524
+ const a = this.prerelease[i];
525
+ const b = other.prerelease[i];
526
+ debug('prerelease compare', i, a, b);
527
+ if (a === undefined && b === undefined) {
528
+ return 0
529
+ } else if (b === undefined) {
530
+ return 1
531
+ } else if (a === undefined) {
532
+ return -1
533
+ } else if (a === b) {
534
+ continue
535
+ } else {
536
+ return compareIdentifiers(a, b)
537
+ }
538
+ } while (++i)
539
+ }
540
+
541
+ compareBuild (other) {
542
+ if (!(other instanceof SemVer)) {
543
+ other = new SemVer(other, this.options);
544
+ }
545
+
546
+ let i = 0;
547
+ do {
548
+ const a = this.build[i];
549
+ const b = other.build[i];
550
+ debug('build compare', i, a, b);
551
+ if (a === undefined && b === undefined) {
552
+ return 0
553
+ } else if (b === undefined) {
554
+ return 1
555
+ } else if (a === undefined) {
556
+ return -1
557
+ } else if (a === b) {
558
+ continue
559
+ } else {
560
+ return compareIdentifiers(a, b)
561
+ }
562
+ } while (++i)
563
+ }
564
+
565
+ // preminor will bump the version up to the next minor release, and immediately
566
+ // down to pre-release. premajor and prepatch work the same way.
567
+ inc (release, identifier, identifierBase) {
568
+ if (release.startsWith('pre')) {
569
+ if (!identifier && identifierBase === false) {
570
+ throw new Error('invalid increment argument: identifier is empty')
571
+ }
572
+ // Avoid an invalid semver results
573
+ if (identifier) {
574
+ const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]);
575
+ if (!match || match[1] !== identifier) {
576
+ throw new Error(`invalid identifier: ${identifier}`)
577
+ }
578
+ }
579
+ }
580
+
581
+ switch (release) {
582
+ case 'premajor':
583
+ this.prerelease.length = 0;
584
+ this.patch = 0;
585
+ this.minor = 0;
586
+ this.major++;
587
+ this.inc('pre', identifier, identifierBase);
588
+ break
589
+ case 'preminor':
590
+ this.prerelease.length = 0;
591
+ this.patch = 0;
592
+ this.minor++;
593
+ this.inc('pre', identifier, identifierBase);
594
+ break
595
+ case 'prepatch':
596
+ // If this is already a prerelease, it will bump to the next version
597
+ // drop any prereleases that might already exist, since they are not
598
+ // relevant at this point.
599
+ this.prerelease.length = 0;
600
+ this.inc('patch', identifier, identifierBase);
601
+ this.inc('pre', identifier, identifierBase);
602
+ break
603
+ // If the input is a non-prerelease version, this acts the same as
604
+ // prepatch.
605
+ case 'prerelease':
606
+ if (this.prerelease.length === 0) {
607
+ this.inc('patch', identifier, identifierBase);
608
+ }
609
+ this.inc('pre', identifier, identifierBase);
610
+ break
611
+ case 'release':
612
+ if (this.prerelease.length === 0) {
613
+ throw new Error(`version ${this.raw} is not a prerelease`)
614
+ }
615
+ this.prerelease.length = 0;
616
+ break
617
+
618
+ case 'major':
619
+ // If this is a pre-major version, bump up to the same major version.
620
+ // Otherwise increment major.
621
+ // 1.0.0-5 bumps to 1.0.0
622
+ // 1.1.0 bumps to 2.0.0
623
+ if (
624
+ this.minor !== 0 ||
625
+ this.patch !== 0 ||
626
+ this.prerelease.length === 0
627
+ ) {
628
+ this.major++;
629
+ }
630
+ this.minor = 0;
631
+ this.patch = 0;
632
+ this.prerelease = [];
633
+ break
634
+ case 'minor':
635
+ // If this is a pre-minor version, bump up to the same minor version.
636
+ // Otherwise increment minor.
637
+ // 1.2.0-5 bumps to 1.2.0
638
+ // 1.2.1 bumps to 1.3.0
639
+ if (this.patch !== 0 || this.prerelease.length === 0) {
640
+ this.minor++;
641
+ }
642
+ this.patch = 0;
643
+ this.prerelease = [];
644
+ break
645
+ case 'patch':
646
+ // If this is not a pre-release version, it will increment the patch.
647
+ // If it is a pre-release it will bump up to the same patch version.
648
+ // 1.2.0-5 patches to 1.2.0
649
+ // 1.2.0 patches to 1.2.1
650
+ if (this.prerelease.length === 0) {
651
+ this.patch++;
652
+ }
653
+ this.prerelease = [];
654
+ break
655
+ // This probably shouldn't be used publicly.
656
+ // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
657
+ case 'pre': {
658
+ const base = Number(identifierBase) ? 1 : 0;
659
+
660
+ if (this.prerelease.length === 0) {
661
+ this.prerelease = [base];
662
+ } else {
663
+ let i = this.prerelease.length;
664
+ while (--i >= 0) {
665
+ if (typeof this.prerelease[i] === 'number') {
666
+ this.prerelease[i]++;
667
+ i = -2;
668
+ }
669
+ }
670
+ if (i === -1) {
671
+ // didn't increment anything
672
+ if (identifier === this.prerelease.join('.') && identifierBase === false) {
673
+ throw new Error('invalid increment argument: identifier already exists')
674
+ }
675
+ this.prerelease.push(base);
676
+ }
677
+ }
678
+ if (identifier) {
679
+ // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
680
+ // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
681
+ let prerelease = [identifier, base];
682
+ if (identifierBase === false) {
683
+ prerelease = [identifier];
684
+ }
685
+ if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
686
+ if (isNaN(this.prerelease[1])) {
687
+ this.prerelease = prerelease;
688
+ }
689
+ } else {
690
+ this.prerelease = prerelease;
691
+ }
692
+ }
693
+ break
694
+ }
695
+ default:
696
+ throw new Error(`invalid increment argument: ${release}`)
697
+ }
698
+ this.raw = this.format();
699
+ if (this.build.length) {
700
+ this.raw += `+${this.build.join('.')}`;
701
+ }
702
+ return this
703
+ }
704
+ }
705
+
706
+ semver$1 = SemVer;
707
+ return semver$1;
708
+ }
709
+
710
+ var parse_1;
711
+ var hasRequiredParse;
712
+
713
+ function requireParse () {
714
+ if (hasRequiredParse) return parse_1;
715
+ hasRequiredParse = 1;
716
+
717
+ const SemVer = requireSemver$1();
718
+ const parse = (version, options, throwErrors = false) => {
719
+ if (version instanceof SemVer) {
720
+ return version
721
+ }
722
+ try {
723
+ return new SemVer(version, options)
724
+ } catch (er) {
725
+ if (!throwErrors) {
726
+ return null
727
+ }
728
+ throw er
729
+ }
730
+ };
731
+
732
+ parse_1 = parse;
733
+ return parse_1;
734
+ }
735
+
736
+ var valid_1;
737
+ var hasRequiredValid$1;
738
+
739
+ function requireValid$1 () {
740
+ if (hasRequiredValid$1) return valid_1;
741
+ hasRequiredValid$1 = 1;
742
+
743
+ const parse = requireParse();
744
+ const valid = (version, options) => {
745
+ const v = parse(version, options);
746
+ return v ? v.version : null
747
+ };
748
+ valid_1 = valid;
749
+ return valid_1;
750
+ }
751
+
752
+ var clean_1;
753
+ var hasRequiredClean;
754
+
755
+ function requireClean () {
756
+ if (hasRequiredClean) return clean_1;
757
+ hasRequiredClean = 1;
758
+
759
+ const parse = requireParse();
760
+ const clean = (version, options) => {
761
+ const s = parse(version.trim().replace(/^[=v]+/, ''), options);
762
+ return s ? s.version : null
763
+ };
764
+ clean_1 = clean;
765
+ return clean_1;
766
+ }
767
+
768
+ var inc_1;
769
+ var hasRequiredInc;
770
+
771
+ function requireInc () {
772
+ if (hasRequiredInc) return inc_1;
773
+ hasRequiredInc = 1;
774
+
775
+ const SemVer = requireSemver$1();
776
+
777
+ const inc = (version, release, options, identifier, identifierBase) => {
778
+ if (typeof (options) === 'string') {
779
+ identifierBase = identifier;
780
+ identifier = options;
781
+ options = undefined;
782
+ }
783
+
784
+ try {
785
+ return new SemVer(
786
+ version instanceof SemVer ? version.version : version,
787
+ options
788
+ ).inc(release, identifier, identifierBase).version
789
+ } catch (er) {
790
+ return null
791
+ }
792
+ };
793
+ inc_1 = inc;
794
+ return inc_1;
795
+ }
796
+
797
+ var diff_1;
798
+ var hasRequiredDiff;
799
+
800
+ function requireDiff () {
801
+ if (hasRequiredDiff) return diff_1;
802
+ hasRequiredDiff = 1;
803
+
804
+ const parse = requireParse();
805
+
806
+ const diff = (version1, version2) => {
807
+ const v1 = parse(version1, null, true);
808
+ const v2 = parse(version2, null, true);
809
+ const comparison = v1.compare(v2);
810
+
811
+ if (comparison === 0) {
812
+ return null
813
+ }
814
+
815
+ const v1Higher = comparison > 0;
816
+ const highVersion = v1Higher ? v1 : v2;
817
+ const lowVersion = v1Higher ? v2 : v1;
818
+ const highHasPre = !!highVersion.prerelease.length;
819
+ const lowHasPre = !!lowVersion.prerelease.length;
820
+
821
+ if (lowHasPre && !highHasPre) {
822
+ // Going from prerelease -> no prerelease requires some special casing
823
+
824
+ // If the low version has only a major, then it will always be a major
825
+ // Some examples:
826
+ // 1.0.0-1 -> 1.0.0
827
+ // 1.0.0-1 -> 1.1.1
828
+ // 1.0.0-1 -> 2.0.0
829
+ if (!lowVersion.patch && !lowVersion.minor) {
830
+ return 'major'
831
+ }
832
+
833
+ // If the main part has no difference
834
+ if (lowVersion.compareMain(highVersion) === 0) {
835
+ if (lowVersion.minor && !lowVersion.patch) {
836
+ return 'minor'
837
+ }
838
+ return 'patch'
839
+ }
840
+ }
841
+
842
+ // add the `pre` prefix if we are going to a prerelease version
843
+ const prefix = highHasPre ? 'pre' : '';
844
+
845
+ if (v1.major !== v2.major) {
846
+ return prefix + 'major'
847
+ }
848
+
849
+ if (v1.minor !== v2.minor) {
850
+ return prefix + 'minor'
851
+ }
852
+
853
+ if (v1.patch !== v2.patch) {
854
+ return prefix + 'patch'
855
+ }
856
+
857
+ // high and low are prereleases
858
+ return 'prerelease'
859
+ };
860
+
861
+ diff_1 = diff;
862
+ return diff_1;
863
+ }
864
+
865
+ var major_1;
866
+ var hasRequiredMajor;
867
+
868
+ function requireMajor () {
869
+ if (hasRequiredMajor) return major_1;
870
+ hasRequiredMajor = 1;
871
+
872
+ const SemVer = requireSemver$1();
873
+ const major = (a, loose) => new SemVer(a, loose).major;
874
+ major_1 = major;
875
+ return major_1;
876
+ }
877
+
878
+ var minor_1;
879
+ var hasRequiredMinor;
880
+
881
+ function requireMinor () {
882
+ if (hasRequiredMinor) return minor_1;
883
+ hasRequiredMinor = 1;
884
+
885
+ const SemVer = requireSemver$1();
886
+ const minor = (a, loose) => new SemVer(a, loose).minor;
887
+ minor_1 = minor;
888
+ return minor_1;
889
+ }
890
+
891
+ var patch_1;
892
+ var hasRequiredPatch;
893
+
894
+ function requirePatch () {
895
+ if (hasRequiredPatch) return patch_1;
896
+ hasRequiredPatch = 1;
897
+
898
+ const SemVer = requireSemver$1();
899
+ const patch = (a, loose) => new SemVer(a, loose).patch;
900
+ patch_1 = patch;
901
+ return patch_1;
902
+ }
903
+
904
+ var prerelease_1;
905
+ var hasRequiredPrerelease;
906
+
907
+ function requirePrerelease () {
908
+ if (hasRequiredPrerelease) return prerelease_1;
909
+ hasRequiredPrerelease = 1;
910
+
911
+ const parse = requireParse();
912
+ const prerelease = (version, options) => {
913
+ const parsed = parse(version, options);
914
+ return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
915
+ };
916
+ prerelease_1 = prerelease;
917
+ return prerelease_1;
918
+ }
919
+
920
+ var compare_1;
921
+ var hasRequiredCompare;
922
+
923
+ function requireCompare () {
924
+ if (hasRequiredCompare) return compare_1;
925
+ hasRequiredCompare = 1;
926
+
927
+ const SemVer = requireSemver$1();
928
+ const compare = (a, b, loose) =>
929
+ new SemVer(a, loose).compare(new SemVer(b, loose));
930
+
931
+ compare_1 = compare;
932
+ return compare_1;
933
+ }
934
+
935
+ var rcompare_1;
936
+ var hasRequiredRcompare;
937
+
938
+ function requireRcompare () {
939
+ if (hasRequiredRcompare) return rcompare_1;
940
+ hasRequiredRcompare = 1;
941
+
942
+ const compare = requireCompare();
943
+ const rcompare = (a, b, loose) => compare(b, a, loose);
944
+ rcompare_1 = rcompare;
945
+ return rcompare_1;
946
+ }
947
+
948
+ var compareLoose_1;
949
+ var hasRequiredCompareLoose;
950
+
951
+ function requireCompareLoose () {
952
+ if (hasRequiredCompareLoose) return compareLoose_1;
953
+ hasRequiredCompareLoose = 1;
954
+
955
+ const compare = requireCompare();
956
+ const compareLoose = (a, b) => compare(a, b, true);
957
+ compareLoose_1 = compareLoose;
958
+ return compareLoose_1;
959
+ }
960
+
961
+ var compareBuild_1;
962
+ var hasRequiredCompareBuild;
963
+
964
+ function requireCompareBuild () {
965
+ if (hasRequiredCompareBuild) return compareBuild_1;
966
+ hasRequiredCompareBuild = 1;
967
+
968
+ const SemVer = requireSemver$1();
969
+ const compareBuild = (a, b, loose) => {
970
+ const versionA = new SemVer(a, loose);
971
+ const versionB = new SemVer(b, loose);
972
+ return versionA.compare(versionB) || versionA.compareBuild(versionB)
973
+ };
974
+ compareBuild_1 = compareBuild;
975
+ return compareBuild_1;
976
+ }
977
+
978
+ var sort_1;
979
+ var hasRequiredSort;
980
+
981
+ function requireSort () {
982
+ if (hasRequiredSort) return sort_1;
983
+ hasRequiredSort = 1;
984
+
985
+ const compareBuild = requireCompareBuild();
986
+ const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose));
987
+ sort_1 = sort;
988
+ return sort_1;
989
+ }
990
+
991
+ var rsort_1;
992
+ var hasRequiredRsort;
993
+
994
+ function requireRsort () {
995
+ if (hasRequiredRsort) return rsort_1;
996
+ hasRequiredRsort = 1;
997
+
998
+ const compareBuild = requireCompareBuild();
999
+ const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));
1000
+ rsort_1 = rsort;
1001
+ return rsort_1;
1002
+ }
1003
+
1004
+ var gt_1;
1005
+ var hasRequiredGt;
1006
+
1007
+ function requireGt () {
1008
+ if (hasRequiredGt) return gt_1;
1009
+ hasRequiredGt = 1;
1010
+
1011
+ const compare = requireCompare();
1012
+ const gt = (a, b, loose) => compare(a, b, loose) > 0;
1013
+ gt_1 = gt;
1014
+ return gt_1;
1015
+ }
1016
+
1017
+ var lt_1;
1018
+ var hasRequiredLt;
1019
+
1020
+ function requireLt () {
1021
+ if (hasRequiredLt) return lt_1;
1022
+ hasRequiredLt = 1;
1023
+
1024
+ const compare = requireCompare();
1025
+ const lt = (a, b, loose) => compare(a, b, loose) < 0;
1026
+ lt_1 = lt;
1027
+ return lt_1;
1028
+ }
1029
+
1030
+ var eq_1;
1031
+ var hasRequiredEq;
1032
+
1033
+ function requireEq () {
1034
+ if (hasRequiredEq) return eq_1;
1035
+ hasRequiredEq = 1;
1036
+
1037
+ const compare = requireCompare();
1038
+ const eq = (a, b, loose) => compare(a, b, loose) === 0;
1039
+ eq_1 = eq;
1040
+ return eq_1;
1041
+ }
1042
+
1043
+ var neq_1;
1044
+ var hasRequiredNeq;
1045
+
1046
+ function requireNeq () {
1047
+ if (hasRequiredNeq) return neq_1;
1048
+ hasRequiredNeq = 1;
1049
+
1050
+ const compare = requireCompare();
1051
+ const neq = (a, b, loose) => compare(a, b, loose) !== 0;
1052
+ neq_1 = neq;
1053
+ return neq_1;
1054
+ }
1055
+
1056
+ var gte_1;
1057
+ var hasRequiredGte;
1058
+
1059
+ function requireGte () {
1060
+ if (hasRequiredGte) return gte_1;
1061
+ hasRequiredGte = 1;
1062
+
1063
+ const compare = requireCompare();
1064
+ const gte = (a, b, loose) => compare(a, b, loose) >= 0;
1065
+ gte_1 = gte;
1066
+ return gte_1;
1067
+ }
1068
+
1069
+ var lte_1;
1070
+ var hasRequiredLte;
1071
+
1072
+ function requireLte () {
1073
+ if (hasRequiredLte) return lte_1;
1074
+ hasRequiredLte = 1;
1075
+
1076
+ const compare = requireCompare();
1077
+ const lte = (a, b, loose) => compare(a, b, loose) <= 0;
1078
+ lte_1 = lte;
1079
+ return lte_1;
1080
+ }
1081
+
1082
+ var cmp_1;
1083
+ var hasRequiredCmp;
1084
+
1085
+ function requireCmp () {
1086
+ if (hasRequiredCmp) return cmp_1;
1087
+ hasRequiredCmp = 1;
1088
+
1089
+ const eq = requireEq();
1090
+ const neq = requireNeq();
1091
+ const gt = requireGt();
1092
+ const gte = requireGte();
1093
+ const lt = requireLt();
1094
+ const lte = requireLte();
1095
+
1096
+ const cmp = (a, op, b, loose) => {
1097
+ switch (op) {
1098
+ case '===':
1099
+ if (typeof a === 'object') {
1100
+ a = a.version;
1101
+ }
1102
+ if (typeof b === 'object') {
1103
+ b = b.version;
1104
+ }
1105
+ return a === b
1106
+
1107
+ case '!==':
1108
+ if (typeof a === 'object') {
1109
+ a = a.version;
1110
+ }
1111
+ if (typeof b === 'object') {
1112
+ b = b.version;
1113
+ }
1114
+ return a !== b
1115
+
1116
+ case '':
1117
+ case '=':
1118
+ case '==':
1119
+ return eq(a, b, loose)
1120
+
1121
+ case '!=':
1122
+ return neq(a, b, loose)
1123
+
1124
+ case '>':
1125
+ return gt(a, b, loose)
1126
+
1127
+ case '>=':
1128
+ return gte(a, b, loose)
1129
+
1130
+ case '<':
1131
+ return lt(a, b, loose)
1132
+
1133
+ case '<=':
1134
+ return lte(a, b, loose)
1135
+
1136
+ default:
1137
+ throw new TypeError(`Invalid operator: ${op}`)
1138
+ }
1139
+ };
1140
+ cmp_1 = cmp;
1141
+ return cmp_1;
1142
+ }
1143
+
1144
+ var coerce_1;
1145
+ var hasRequiredCoerce;
1146
+
1147
+ function requireCoerce () {
1148
+ if (hasRequiredCoerce) return coerce_1;
1149
+ hasRequiredCoerce = 1;
1150
+
1151
+ const SemVer = requireSemver$1();
1152
+ const parse = requireParse();
1153
+ const { safeRe: re, t } = requireRe();
1154
+
1155
+ const coerce = (version, options) => {
1156
+ if (version instanceof SemVer) {
1157
+ return version
1158
+ }
1159
+
1160
+ if (typeof version === 'number') {
1161
+ version = String(version);
1162
+ }
1163
+
1164
+ if (typeof version !== 'string') {
1165
+ return null
1166
+ }
1167
+
1168
+ options = options || {};
1169
+
1170
+ let match = null;
1171
+ if (!options.rtl) {
1172
+ match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]);
1173
+ } else {
1174
+ // Find the right-most coercible string that does not share
1175
+ // a terminus with a more left-ward coercible string.
1176
+ // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
1177
+ // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'
1178
+ //
1179
+ // Walk through the string checking with a /g regexp
1180
+ // Manually set the index so as to pick up overlapping matches.
1181
+ // Stop when we get a match that ends at the string end, since no
1182
+ // coercible string can be more right-ward without the same terminus.
1183
+ const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL];
1184
+ let next;
1185
+ while ((next = coerceRtlRegex.exec(version)) &&
1186
+ (!match || match.index + match[0].length !== version.length)
1187
+ ) {
1188
+ if (!match ||
1189
+ next.index + next[0].length !== match.index + match[0].length) {
1190
+ match = next;
1191
+ }
1192
+ coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
1193
+ }
1194
+ // leave it in a clean state
1195
+ coerceRtlRegex.lastIndex = -1;
1196
+ }
1197
+
1198
+ if (match === null) {
1199
+ return null
1200
+ }
1201
+
1202
+ const major = match[2];
1203
+ const minor = match[3] || '0';
1204
+ const patch = match[4] || '0';
1205
+ const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '';
1206
+ const build = options.includePrerelease && match[6] ? `+${match[6]}` : '';
1207
+
1208
+ return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)
1209
+ };
1210
+ coerce_1 = coerce;
1211
+ return coerce_1;
1212
+ }
1213
+
1214
+ var truncate_1;
1215
+ var hasRequiredTruncate;
1216
+
1217
+ function requireTruncate () {
1218
+ if (hasRequiredTruncate) return truncate_1;
1219
+ hasRequiredTruncate = 1;
1220
+
1221
+ const parse = requireParse();
1222
+ const constants = requireConstants();
1223
+ const SemVer = requireSemver$1();
1224
+
1225
+ const truncate = (version, truncation, options) => {
1226
+ if (!constants.RELEASE_TYPES.includes(truncation)) {
1227
+ return null
1228
+ }
1229
+
1230
+ const clonedVersion = cloneInputVersion(version, options);
1231
+ return clonedVersion && doTruncation(clonedVersion, truncation)
1232
+ };
1233
+
1234
+ const cloneInputVersion = (version, options) => {
1235
+ const versionStringToParse = (
1236
+ version instanceof SemVer ? version.version : version
1237
+ );
1238
+
1239
+ return parse(versionStringToParse, options)
1240
+ };
1241
+
1242
+ const doTruncation = (version, truncation) => {
1243
+ if (isPrerelease(truncation)) {
1244
+ return version.version
1245
+ }
1246
+
1247
+ version.prerelease = [];
1248
+
1249
+ switch (truncation) {
1250
+ case 'major':
1251
+ version.minor = 0;
1252
+ version.patch = 0;
1253
+ break
1254
+ case 'minor':
1255
+ version.patch = 0;
1256
+ break
1257
+ }
1258
+
1259
+ return version.format()
1260
+ };
1261
+
1262
+ const isPrerelease = (type) => {
1263
+ return type.startsWith('pre')
1264
+ };
1265
+
1266
+ truncate_1 = truncate;
1267
+ return truncate_1;
1268
+ }
1269
+
1270
+ var lrucache;
1271
+ var hasRequiredLrucache;
1272
+
1273
+ function requireLrucache () {
1274
+ if (hasRequiredLrucache) return lrucache;
1275
+ hasRequiredLrucache = 1;
1276
+
1277
+ class LRUCache {
1278
+ constructor () {
1279
+ this.max = 1000;
1280
+ this.map = new Map();
1281
+ }
1282
+
1283
+ get (key) {
1284
+ const value = this.map.get(key);
1285
+ if (value === undefined) {
1286
+ return undefined
1287
+ } else {
1288
+ // Remove the key from the map and add it to the end
1289
+ this.map.delete(key);
1290
+ this.map.set(key, value);
1291
+ return value
1292
+ }
1293
+ }
1294
+
1295
+ delete (key) {
1296
+ return this.map.delete(key)
1297
+ }
1298
+
1299
+ set (key, value) {
1300
+ const deleted = this.delete(key);
1301
+
1302
+ if (!deleted && value !== undefined) {
1303
+ // If cache is full, delete the least recently used item
1304
+ if (this.map.size >= this.max) {
1305
+ const firstKey = this.map.keys().next().value;
1306
+ this.delete(firstKey);
1307
+ }
1308
+
1309
+ this.map.set(key, value);
1310
+ }
1311
+
1312
+ return this
1313
+ }
1314
+ }
1315
+
1316
+ lrucache = LRUCache;
1317
+ return lrucache;
1318
+ }
1319
+
1320
+ var range;
1321
+ var hasRequiredRange;
1322
+
1323
+ function requireRange () {
1324
+ if (hasRequiredRange) return range;
1325
+ hasRequiredRange = 1;
1326
+
1327
+ const SPACE_CHARACTERS = /\s+/g;
1328
+
1329
+ // hoisted class for cyclic dependency
1330
+ class Range {
1331
+ constructor (range, options) {
1332
+ options = parseOptions(options);
1333
+
1334
+ if (range instanceof Range) {
1335
+ if (
1336
+ range.loose === !!options.loose &&
1337
+ range.includePrerelease === !!options.includePrerelease
1338
+ ) {
1339
+ return range
1340
+ } else {
1341
+ return new Range(range.raw, options)
1342
+ }
1343
+ }
1344
+
1345
+ if (range instanceof Comparator) {
1346
+ // just put it in the set and return
1347
+ this.raw = range.value;
1348
+ this.set = [[range]];
1349
+ this.formatted = undefined;
1350
+ return this
1351
+ }
1352
+
1353
+ this.options = options;
1354
+ this.loose = !!options.loose;
1355
+ this.includePrerelease = !!options.includePrerelease;
1356
+
1357
+ // First reduce all whitespace as much as possible so we do not have to rely
1358
+ // on potentially slow regexes like \s*. This is then stored and used for
1359
+ // future error messages as well.
1360
+ this.raw = range.trim().replace(SPACE_CHARACTERS, ' ');
1361
+
1362
+ // First, split on ||
1363
+ this.set = this.raw
1364
+ .split('||')
1365
+ // map the range to a 2d array of comparators
1366
+ .map(r => this.parseRange(r.trim()))
1367
+ // throw out any comparator lists that are empty
1368
+ // this generally means that it was not a valid range, which is allowed
1369
+ // in loose mode, but will still throw if the WHOLE range is invalid.
1370
+ .filter(c => c.length);
1371
+
1372
+ if (!this.set.length) {
1373
+ throw new TypeError(`Invalid SemVer Range: ${this.raw}`)
1374
+ }
1375
+
1376
+ // if we have any that are not the null set, throw out null sets.
1377
+ if (this.set.length > 1) {
1378
+ // keep the first one, in case they're all null sets
1379
+ const first = this.set[0];
1380
+ this.set = this.set.filter(c => !isNullSet(c[0]));
1381
+ if (this.set.length === 0) {
1382
+ this.set = [first];
1383
+ } else if (this.set.length > 1) {
1384
+ // if we have any that are *, then the range is just *
1385
+ for (const c of this.set) {
1386
+ if (c.length === 1 && isAny(c[0])) {
1387
+ this.set = [c];
1388
+ break
1389
+ }
1390
+ }
1391
+ }
1392
+ }
1393
+
1394
+ this.formatted = undefined;
1395
+ }
1396
+
1397
+ get range () {
1398
+ if (this.formatted === undefined) {
1399
+ this.formatted = '';
1400
+ for (let i = 0; i < this.set.length; i++) {
1401
+ if (i > 0) {
1402
+ this.formatted += '||';
1403
+ }
1404
+ const comps = this.set[i];
1405
+ for (let k = 0; k < comps.length; k++) {
1406
+ if (k > 0) {
1407
+ this.formatted += ' ';
1408
+ }
1409
+ this.formatted += comps[k].toString().trim();
1410
+ }
1411
+ }
1412
+ }
1413
+ return this.formatted
1414
+ }
1415
+
1416
+ format () {
1417
+ return this.range
1418
+ }
1419
+
1420
+ toString () {
1421
+ return this.range
1422
+ }
1423
+
1424
+ parseRange (range) {
1425
+ // strip build metadata so it can't bleed into the version
1426
+ range = range.replace(BUILDSTRIPRE, '');
1427
+
1428
+ // memoize range parsing for performance.
1429
+ // this is a very hot path, and fully deterministic.
1430
+ const memoOpts =
1431
+ (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |
1432
+ (this.options.loose && FLAG_LOOSE);
1433
+ const memoKey = memoOpts + ':' + range;
1434
+ const cached = cache.get(memoKey);
1435
+ if (cached) {
1436
+ return cached
1437
+ }
1438
+
1439
+ const loose = this.options.loose;
1440
+ // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
1441
+ const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
1442
+ range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
1443
+ debug('hyphen replace', range);
1444
+
1445
+ // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
1446
+ range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
1447
+ debug('comparator trim', range);
1448
+
1449
+ // `~ 1.2.3` => `~1.2.3`
1450
+ range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
1451
+ debug('tilde trim', range);
1452
+
1453
+ // `^ 1.2.3` => `^1.2.3`
1454
+ range = range.replace(re[t.CARETTRIM], caretTrimReplace);
1455
+ debug('caret trim', range);
1456
+
1457
+ // At this point, the range is completely trimmed and
1458
+ // ready to be split into comparators.
1459
+
1460
+ let rangeList = range
1461
+ .split(' ')
1462
+ .map(comp => parseComparator(comp, this.options))
1463
+ .join(' ')
1464
+ .split(/\s+/)
1465
+ // >=0.0.0 is equivalent to *
1466
+ .map(comp => replaceGTE0(comp, this.options));
1467
+
1468
+ if (loose) {
1469
+ // in loose mode, throw out any that are not valid comparators
1470
+ rangeList = rangeList.filter(comp => {
1471
+ debug('loose invalid filter', comp, this.options);
1472
+ return !!comp.match(re[t.COMPARATORLOOSE])
1473
+ });
1474
+ }
1475
+ debug('range list', rangeList);
1476
+
1477
+ // if any comparators are the null set, then replace with JUST null set
1478
+ // if more than one comparator, remove any * comparators
1479
+ // also, don't include the same comparator more than once
1480
+ const rangeMap = new Map();
1481
+ const comparators = rangeList.map(comp => new Comparator(comp, this.options));
1482
+ for (const comp of comparators) {
1483
+ if (isNullSet(comp)) {
1484
+ return [comp]
1485
+ }
1486
+ rangeMap.set(comp.value, comp);
1487
+ }
1488
+ if (rangeMap.size > 1 && rangeMap.has('')) {
1489
+ rangeMap.delete('');
1490
+ }
1491
+
1492
+ const result = [...rangeMap.values()];
1493
+ cache.set(memoKey, result);
1494
+ return result
1495
+ }
1496
+
1497
+ intersects (range, options) {
1498
+ if (!(range instanceof Range)) {
1499
+ throw new TypeError('a Range is required')
1500
+ }
1501
+
1502
+ return this.set.some((thisComparators) => {
1503
+ return (
1504
+ isSatisfiable(thisComparators, options) &&
1505
+ range.set.some((rangeComparators) => {
1506
+ return (
1507
+ isSatisfiable(rangeComparators, options) &&
1508
+ thisComparators.every((thisComparator) => {
1509
+ return rangeComparators.every((rangeComparator) => {
1510
+ return thisComparator.intersects(rangeComparator, options)
1511
+ })
1512
+ })
1513
+ )
1514
+ })
1515
+ )
1516
+ })
1517
+ }
1518
+
1519
+ // if ANY of the sets match ALL of its comparators, then pass
1520
+ test (version) {
1521
+ if (!version) {
1522
+ return false
1523
+ }
1524
+
1525
+ if (typeof version === 'string') {
1526
+ try {
1527
+ version = new SemVer(version, this.options);
1528
+ } catch (er) {
1529
+ return false
1530
+ }
1531
+ }
1532
+
1533
+ for (let i = 0; i < this.set.length; i++) {
1534
+ if (testSet(this.set[i], version, this.options)) {
1535
+ return true
1536
+ }
1537
+ }
1538
+ return false
1539
+ }
1540
+ }
1541
+
1542
+ range = Range;
1543
+
1544
+ const LRU = requireLrucache();
1545
+ const cache = new LRU();
1546
+
1547
+ const parseOptions = requireParseOptions();
1548
+ const Comparator = requireComparator();
1549
+ const debug = requireDebug();
1550
+ const SemVer = requireSemver$1();
1551
+ const {
1552
+ safeRe: re,
1553
+ src,
1554
+ t,
1555
+ comparatorTrimReplace,
1556
+ tildeTrimReplace,
1557
+ caretTrimReplace,
1558
+ } = requireRe();
1559
+ const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = requireConstants();
1560
+
1561
+ // unbounded global build-metadata stripper used by parseRange
1562
+ const BUILDSTRIPRE = new RegExp(src[t.BUILD], 'g');
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 === '>=' && !c.test(gt.semver)) {
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 === '<=' && !c.test(lt.semver)) {
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;
2692
+ var hasRequiredSemver;
2693
+
2694
+ function requireSemver () {
2695
+ if (hasRequiredSemver) return semver;
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 truncate = requireTruncate();
2727
+ const Comparator = requireComparator();
2728
+ const Range = requireRange();
2729
+ const satisfies = requireSatisfies();
2730
+ const toComparators = requireToComparators();
2731
+ const maxSatisfying = requireMaxSatisfying();
2732
+ const minSatisfying = requireMinSatisfying();
2733
+ const minVersion = requireMinVersion();
2734
+ const validRange = requireValid();
2735
+ const outside = requireOutside();
2736
+ const gtr = requireGtr();
2737
+ const ltr = requireLtr();
2738
+ const intersects = requireIntersects();
2739
+ const simplifyRange = requireSimplify();
2740
+ const subset = requireSubset();
2741
+ semver = {
2742
+ parse,
2743
+ valid,
2744
+ clean,
2745
+ inc,
2746
+ diff,
2747
+ major,
2748
+ minor,
2749
+ patch,
2750
+ prerelease,
2751
+ compare,
2752
+ rcompare,
2753
+ compareLoose,
2754
+ compareBuild,
2755
+ sort,
2756
+ rsort,
2757
+ gt,
2758
+ lt,
2759
+ eq,
2760
+ neq,
2761
+ gte,
2762
+ lte,
2763
+ cmp,
2764
+ coerce,
2765
+ truncate,
2766
+ Comparator,
2767
+ Range,
2768
+ satisfies,
2769
+ toComparators,
2770
+ maxSatisfying,
2771
+ minSatisfying,
2772
+ minVersion,
2773
+ validRange,
2774
+ outside,
2775
+ gtr,
2776
+ ltr,
2777
+ intersects,
2778
+ simplifyRange,
2779
+ subset,
2780
+ SemVer,
2781
+ re: internalRe.re,
2782
+ src: internalRe.src,
2783
+ tokens: internalRe.t,
2784
+ SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
2785
+ RELEASE_TYPES: constants.RELEASE_TYPES,
2786
+ compareIdentifiers: identifiers.compareIdentifiers,
2787
+ rcompareIdentifiers: identifiers.rcompareIdentifiers,
2788
+ };
2789
+ return semver;
2790
+ }
2791
+
2792
+ var semverExports = requireSemver();
2793
+
2794
+ const BASIC_INFO_MAX_BYTES = 10 * 1024 * 1024;
2795
+ const BASIC_INFO_MAX_PIXELS = 40_000_000;
2796
+ /** 按 NFKC 和 Unicode 空白规范化名称,并校验 1–40 个字符及禁用字符。 */
2797
+ function normalizeBasicInfoName(raw) {
2798
+ if (typeof raw !== 'string')
2799
+ throw new Error('heybox.name 必须是字符串');
2800
+ // 与 Go TrimSpace 一致(JS trim 额外移除 BOM,故使用 Unicode White_Space)。
2801
+ const name = raw.normalize('NFKC').replace(/^\p{White_Space}+|\p{White_Space}+$/gu, '');
2802
+ if (Array.from(name).length < 1 || Array.from(name).length > 40 || /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}<>&"']/u.test(name) || !/[\p{L}\p{N}]/u.test(name)) {
2803
+ throw new Error('名称须包含 1–40 个字符及文字或数字,不能包含控制字符或 HTML 特殊字符');
2804
+ }
2805
+ return name;
2806
+ }
2807
+ function validateBasicInfoPath(raw) {
2808
+ if (typeof raw !== 'string' || !raw || /[\\:%?#\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(raw))
2809
+ throw new Error('资料图片必须是项目内的规范相对路径');
2810
+ const forbidden = new Set(['', '.', '..', '.git', 'node_modules', 'dist', '.hb-sdk', '.vite', '.cache', '.tmp', 'tmp']);
2811
+ if (raw.split('/').some((part) => forbidden.has(part)))
2812
+ throw new Error('资料图片路径包含禁止的目录');
2813
+ if (!/\.(png|jpe?g|gif|webp)$/i.test(raw))
2814
+ throw new Error('资料图片仅支持 JPEG、PNG、GIF、WebP');
2815
+ return raw;
2816
+ }
2817
+ /** 解析项目或构建资料;仅早于 0.8.2 且三项全部缺失时返回 undefined。 */
2818
+ function parseMiniappBasicInfo(value, sdkVersion = '0.8.2') {
2819
+ sdkVersion = sdkVersion.trim();
2820
+ if (!semverExports.valid(sdkVersion) || sdkVersion.startsWith('v') || sdkVersion.includes('+'))
2821
+ throw new Error('manifest.sdkVersion 必须是合法 SemVer');
2822
+ const fields = ['name', 'icon', 'coverImages'];
2823
+ const present = fields.filter((key) => Object.prototype.hasOwnProperty.call(value, key));
2824
+ if (!present.length && semverExports.lt(sdkVersion, '0.8.2'))
2825
+ return undefined;
2826
+ if (present.length !== fields.length)
2827
+ throw new Error('请配置 heybox.name、heybox.icon、heybox.coverImages,或运行 remote bind/dev/remote deploy 迁移已发布资料');
2828
+ const name = normalizeBasicInfoName(value.name);
2829
+ const icon = validateBasicInfoPath(value.icon);
2830
+ if (!Array.isArray(value.coverImages) || value.coverImages.length < 1 || value.coverImages.length > 5)
2831
+ throw new Error('coverImages 必须包含 1–5 张图片');
2832
+ const coverImages = value.coverImages.map(validateBasicInfoPath);
2833
+ if (new Set(coverImages).size !== coverImages.length)
2834
+ throw new Error('封面路径不能重复');
2835
+ return { name, icon, coverImages };
2836
+ }
2837
+
2838
+ /** 单个小程序版本最多声明的关联游戏数量。 */
2839
+ const MINIAPP_BIND_APP_IDS_MAX_COUNT = 20;
2840
+ /**
2841
+ * 校验并规范化小程序关联的游戏 App ID。
2842
+ *
2843
+ * @param value - 不可信声明。`undefined` 和 `[]` 均返回空绑定;其他值必须是最多 20 项的
2844
+ * 字符串数组,不接受 `null`、单个字符串、number 数组或类数组对象。
2845
+ * @param options - 可选诊断来源;`sourceLabel` 默认 `package.json#heybox.bindAppIds`,并原样
2846
+ * 作为所有错误消息的前缀。
2847
+ * @returns 新建、按 appid 数值升序排列且经 `Object.freeze` 冻结的 `readonly string[]`。
2848
+ * 输入数组及其顺序不会被修改;空输入也返回新的冻结空数组。
2849
+ * @throws `Error` `${sourceLabel} 必须是字符串数组`:`value` 不是数组。
2850
+ * @throws `Error` `${sourceLabel} 最多包含 20 个游戏 appid`:输入数组超过 20 项;数量检查
2851
+ * 先于逐项格式检查。
2852
+ * @throws `Error` `${sourceLabel} 包含非法游戏 appid:<value>`:任一项不是 string,或不匹配
2853
+ * `/^[1-9]\d*$/`。因此空串、首尾空白、`0`、前导零、正负号、小数、指数和非十进制字符
2854
+ * 都不会被自动修正。
2855
+ * @throws `Error` `${sourceLabel} 包含超出正 int32 范围的游戏 appid:<value>`:十进制值
2856
+ * 大于 `2147483647` 或不能成为安全整数。
2857
+ * @throws `Error` `${sourceLabel} 包含重复游戏 appid:<value>`:规范字符串在同一数组重复。
2858
+ *
2859
+ * @remarks
2860
+ * 合法范围是闭区间 `1..2147483647`,每项在输出中仍保持十进制 string。排序按数值而不是
2861
+ * 字典序执行,所以 `['3513350', '730', '10']` 输出为 `['10', '730', '3513350']`。
2862
+ * 函数先复制后排序并冻结结果,不排序或冻结调用方传入的数组。
2863
+ *
2864
+ * 这是同步、纯离线的格式规范化函数,不访问网络,也不确认 appid 是否真实存在、可绑定或
2865
+ * 属于当前开发者。`miniappManifest()` 用它校验 `package.json#heybox.bindAppIds` 并把非空结果
2866
+ * 写入 Manifest;远端 deploy 预检和提审才校验游戏可用性。缺失和空数组在普通构建中都表示
2867
+ * 无绑定,函数本身不处理 `remote deploy --from-version` 的历史快照继承语义。
2868
+ *
2869
+ * `bindAppIds` 是版本发布元数据,不是 Runtime 权限,也不会因调用
2870
+ * [navigation.openAppPage](/reference/sdk/navigation/openAppPage) 而变化。后者的 `appId` 是一次
2871
+ * 页面导航参数,允许 string 或 number、只要求字符串化后非空,不适用本函数的数组、int32、
2872
+ * 前导零、去重、20 项或排序规则。
2873
+ *
2874
+ * @example
2875
+ * ```ts
2876
+ * import { parseMiniappBindAppIds } from '@heybox/hb-sdk/miniapp-publish'
2877
+ *
2878
+ * const declared = ['3513350', '730', '10']
2879
+ * const appIds = parseMiniappBindAppIds(declared)
2880
+ *
2881
+ * console.log(appIds) // ['10', '730', '3513350']
2882
+ * console.log(declared) // ['3513350', '730', '10'],输入顺序不变
2883
+ * console.log(Object.isFrozen(appIds)) // true
2884
+ * ```
2885
+ *
2886
+ * @see [miniappManifest](/reference/symbols/vite/functions/miniappManifest)
2887
+ * @see [navigation.openAppPage](/reference/sdk/navigation/openAppPage)
2888
+ * @see [CLI 与远端发布](/guide/cli#生产构建)
2889
+ */
2890
+ function parseMiniappBindAppIds(value, options = {}) {
2891
+ const sourceLabel = options.sourceLabel ?? 'package.json#heybox.bindAppIds';
2892
+ if (value === undefined)
2893
+ return Object.freeze([]);
2894
+ if (!Array.isArray(value))
2895
+ throw new Error(`${sourceLabel} 必须是字符串数组`);
2896
+ if (value.length > MINIAPP_BIND_APP_IDS_MAX_COUNT) {
2897
+ throw new Error(`${sourceLabel} 最多包含 ${MINIAPP_BIND_APP_IDS_MAX_COUNT} 个游戏 appid`);
2898
+ }
2899
+ const seen = new Set();
2900
+ const appIds = [];
2901
+ for (const item of value) {
2902
+ if (typeof item !== 'string' || !/^[1-9]\d*$/.test(item)) {
2903
+ throw new Error(`${sourceLabel} 包含非法游戏 appid:${String(item)}`);
2904
+ }
2905
+ const numeric = Number(item);
2906
+ if (!Number.isSafeInteger(numeric) || numeric > 2_147_483_647) {
2907
+ throw new Error(`${sourceLabel} 包含超出正 int32 范围的游戏 appid:${item}`);
2908
+ }
2909
+ if (seen.has(item))
2910
+ throw new Error(`${sourceLabel} 包含重复游戏 appid:${item}`);
2911
+ seen.add(item);
2912
+ appIds.push(item);
2913
+ }
2914
+ appIds.sort((left, right) => Number(left) - Number(right));
2915
+ return Object.freeze(appIds);
2916
+ }
2917
+
2918
+ /**
2919
+ * 所有小程序 iframe bridge envelope 共用的固定 namespace。
2920
+ *
2921
+ * @remarks 该值用于排除无关 `postMessage` 数据,不负责验证消息来源;接收方仍须校验 source 和 nonce,
2922
+ * 并在 origin 可以固定且协议模式要求时校验 origin。
2923
+ */
2924
+
2925
+ const MINI_PROGRAM_PERMISSION_KEYS = [
2926
+ 'userInfo',
2927
+ 'steamLibrary',
2928
+ 'share',
2929
+ 'storage',
2930
+ 'filesystem',
2931
+ 'clipboard',
2932
+ 'leaderboard',
2933
+ 'network',
2934
+ 'companion',
2935
+ ];
2936
+ const MINI_PROGRAM_PERMISSION_CATALOG = [
2937
+ {
2938
+ key: 'userInfo',
2939
+ name: '用户信息',
2940
+ description: '登录小程序并读取当前用户的授权信息。',
2941
+ access: 'declaration',
2942
+ risk: 'medium',
2943
+ config: {},
2944
+ methods: ['auth.login', 'user.getInfo'],
2945
+ conditions: ['继续执行黑盒登录、用户授权和可信手势规则。'],
2946
+ },
2947
+ {
2948
+ key: 'steamLibrary',
2949
+ name: 'Steam 游戏库',
2950
+ description: '读取当前用户授权的 Steam 游戏库。',
2951
+ access: 'declaration',
2952
+ risk: 'high',
2953
+ config: {},
2954
+ methods: ['user.getSteamGameList'],
2955
+ conditions: ['继续执行账号绑定和数据可用性规则。'],
2956
+ },
2957
+ {
2958
+ key: 'share',
2959
+ name: '分享',
2960
+ description: '使用小程序分享、分享菜单和截图能力。',
2961
+ access: 'declaration',
2962
+ risk: 'medium',
2963
+ config: {},
2964
+ methods: ['share.copyLink', 'share.showShareMenu', 'share.screenshot'],
2965
+ conditions: ['继续执行分享参数校验和 Host 支持检查。'],
2966
+ },
2967
+ {
2968
+ key: 'storage',
2969
+ name: '键值存储',
2970
+ description: '读写按小程序隔离的简单键值数据。',
2971
+ access: 'declaration',
2972
+ risk: 'medium',
2973
+ config: {},
2974
+ methods: ['storage.getStorage', 'storage.setStorage'],
2975
+ conditions: ['仅用于简单键值存储,不包含文件系统。'],
2976
+ },
2977
+ {
2978
+ key: 'filesystem',
2979
+ name: '文件系统',
2980
+ description: '访问小程序沙盒文件和用户选择的外部文件。',
2981
+ access: 'declaration',
2982
+ risk: 'high',
2983
+ config: {},
2984
+ methods: [
2985
+ 'network.download',
2986
+ 'files.pickFiles',
2987
+ 'files.pickDirectory',
2988
+ 'files.saveFile',
2989
+ 'file.create',
2990
+ 'file.remove',
2991
+ 'file.exists',
2992
+ 'file.readText',
2993
+ 'file.writeText',
2994
+ 'file.readBytes',
2995
+ 'file.writeBytes',
2996
+ 'file.stat',
2997
+ 'directory.create',
2998
+ 'directory.remove',
2999
+ 'directory.exists',
3000
+ 'directory.list',
3001
+ ],
3002
+ conditions: ['外部文件继续要求有效的用户选择、会话句柄和匹配的读写模式。'],
3003
+ },
3004
+ {
3005
+ key: 'clipboard',
3006
+ name: '剪贴板',
3007
+ description: '向系统剪贴板写入文本。',
3008
+ access: 'declaration',
3009
+ risk: 'medium',
3010
+ config: {},
3011
+ methods: ['device.setClipboard'],
3012
+ conditions: ['继续执行文本长度和 Host 支持限制。'],
3013
+ },
3014
+ {
3015
+ key: 'leaderboard',
3016
+ name: '排行榜',
3017
+ description: '读写小程序云排行榜。',
3018
+ access: 'declaration',
3019
+ risk: 'medium',
3020
+ config: {},
3021
+ methods: [
3022
+ 'cloud.leaderboard.submit',
3023
+ 'cloud.leaderboard.getList',
3024
+ 'cloud.leaderboard.getCurrentUserEntry',
3025
+ 'cloud.leaderboard.deleteCurrentUserEntry',
3026
+ 'cloud.leaderboard.getInfo',
3027
+ ],
3028
+ conditions: ['排行榜必须已创建,用户和资源规则保持不变。'],
3029
+ },
3030
+ {
3031
+ key: 'network',
3032
+ name: '网络',
3033
+ description: '通过 network 模块请求或下载外部资源。',
3034
+ access: 'platform-approval',
3035
+ risk: 'high',
3036
+ config: {
3037
+ useOfficialDomain: {
3038
+ type: 'boolean',
3039
+ required: false,
3040
+ default: false,
3041
+ description: '是否申请访问小黑盒官方域名。',
3042
+ },
3043
+ },
3044
+ methods: ['network.request', 'network.download'],
3045
+ conditions: ['声明后仍需平台批准,并继续执行网络安全策略。'],
3046
+ },
3047
+ {
3048
+ key: 'companion',
3049
+ name: '桌面辅助应用',
3050
+ description: '下载、准备并运行随当前小程序版本发布的受管桌面程序。',
3051
+ access: 'platform-approval',
3052
+ risk: 'high',
3053
+ config: {},
3054
+ methods: [
3055
+ 'companion.getInfo',
3056
+ 'companion.getPreparationStatus',
3057
+ 'companion.prepare',
3058
+ 'companion.cancelPreparation',
3059
+ 'companion.getActiveSession',
3060
+ 'companion.launch',
3061
+ 'companion.session.write',
3062
+ 'companion.session.closeStdin',
3063
+ 'companion.session.terminate',
3064
+ 'companion.session.ackOutput',
3065
+ 'companion.openAttachment',
3066
+ 'companion.showNotification',
3067
+ ],
3068
+ conditions: ['声明后仍需平台批准,并继续执行可信用户手势、Host 能力和当前版本 Manifest 校验。'],
3069
+ },
3070
+ ];
3071
+ new Set(MINI_PROGRAM_PERMISSION_KEYS);
3072
+
3073
+ const MANAGED_RUNTIME_PERMISSION_KEYS = new Set(MINI_PROGRAM_PERMISSION_KEYS);
3074
+ /**
3075
+ * 判断字符串是否是当前协议目录管理的 canonical runtime permission key。
3076
+ *
3077
+ * @param key - 已确认类型为 `string` 的候选权限 key;若输入来自 `unknown` 边界,调用方须先完成字符串检查。
3078
+ * @returns 与 `MINI_PROGRAM_PERMISSION_KEYS` 中某项精确相等时返回 `true`,并将 TypeScript 类型收窄为
3079
+ * `MiniProgramPermissionKey`;未知、历史或格式不同的字符串返回 `false`。
3080
+ *
3081
+ * @remarks
3082
+ * 当前 canonical key 集合固定为:
3083
+ *
3084
+ * - `userInfo`
3085
+ * - `steamLibrary`
3086
+ * - `share`
3087
+ * - `storage`
3088
+ * - `filesystem`
3089
+ * - `clipboard`
3090
+ * - `leaderboard`
3091
+ * - `network`
3092
+ * - `companion`
3093
+ *
3094
+ * 匹配大小写敏感且按原字符串执行。该 guard 不 trim,因此 `' network '` 返回 `false`;历史权限 key
3095
+ * `network.request` 也返回 `false`,即使同名 capability method 仍是公开 method。消费完整 schema v1 权限快照时
3096
+ * 应使用 {@link parseMiniProgramRuntimePermissions},由解析边界统一 trim,并把历史 `network.request` 归一为
3097
+ * canonical `network`。未知的 future key 同样返回 `false`;本 guard 不负责 parser 的前向兼容忽略策略。
3098
+ *
3099
+ * 类型谓词只把字符串收窄为 `MiniProgramPermissionKey` union,不读取权限 entry、status 或 config,也不检查
3100
+ * Manifest。返回 `true` 不表示权限已声明、平台已批准、Runtime snapshot 中存在、status 为 `enabled`、Host 支持,
3101
+ * 或当前 capability 已获准执行。尤其 `network` 与 `companion` 还需要平台批准;其他 declaration 权限也继续受
3102
+ * 各自适用的 Host、用户授权、可信手势、参数与业务策略约束。
3103
+ *
3104
+ * `MINI_PROGRAM_PERMISSION_CATALOG` 提供每个 key 的展示信息、access、风险、配置字段和 method 集合;具体 bridge
3105
+ * method 是否要求某项权限应以 {@link MINI_PROGRAM_PROTOCOL_CAPABILITIES} 的 `requirement` 为准。`kind: 'none'`
3106
+ * 的 method 不会因为某个 key 被本 guard 识别而新增权限要求。
3107
+ *
3108
+ * @example
3109
+ * ```ts
3110
+ * import { isManagedMiniProgramRuntimePermissionKey } from '@heybox/hb-sdk/protocol';
3111
+ *
3112
+ * function acceptPermissionKey(candidate: unknown) {
3113
+ * if (typeof candidate !== 'string') return undefined;
3114
+ * return isManagedMiniProgramRuntimePermissionKey(candidate) ? candidate : undefined;
3115
+ * }
3116
+ *
3117
+ * acceptPermissionKey('filesystem'); // 'filesystem'
3118
+ * acceptPermissionKey('network'); // 'network'
3119
+ * acceptPermissionKey(' network '); // undefined:guard 不 trim
3120
+ * acceptPermissionKey('network.request'); // undefined:legacy key 只由 snapshot parser 归一化
3121
+ * ```
3122
+ *
3123
+ * @see [parseMiniProgramRuntimePermissions](/reference/symbols/protocol/functions/parseMiniProgramRuntimePermissions) 完整 snapshot 的 trim、legacy 归一化与 config 校验。
3124
+ * @see [MINI_PROGRAM_PROTOCOL_CAPABILITIES](/reference/symbols/protocol/constants/MINI_PROGRAM_PROTOCOL_CAPABILITIES) method 到 permission requirement 的权威映射。
3125
+ * @see [权限声明](/guide/permissions) Manifest 声明、平台批准与 Runtime 状态的完整流程。
3126
+ */
3127
+ function isManagedMiniProgramRuntimePermissionKey(key) {
3128
+ return MANAGED_RUNTIME_PERMISSION_KEYS.has(key);
3129
+ }
3130
+ /**
3131
+ * 将不可信的 schema v1 runtime permission snapshot 解析为独立的 canonical 权限映射。
3132
+ *
3133
+ * @param snapshot - Host、服务端、dev context 或持久化边界提供的普通反序列化数据;调用方不需要先做
3134
+ * 类型断言。Proxy trap 或 getter 自身抛出的异常会原样传播。
3135
+ * @returns {@link ParsedMiniProgramRuntimePermissions}。完整 snapshot 合法时返回
3136
+ * `{ valid: true, permissions }`;顶层、entry、状态、重复 key 或已知 config 任一校验失败时统一
3137
+ * 返回 `{ valid: false, permissions: {} }`,不会保留部分权限。
3138
+ *
3139
+ * @remarks
3140
+ * 顶层必须是对象,`schema_version` 必须严格等于数字 `1`,`entries` 必须是数组。`revision`
3141
+ * 可省略;存在时必须是大于或等于 `0` 的整数。revision 只参与输入校验,不会复制到返回值。
3142
+ * 顶层与 entry 的其他字段会被忽略,以便 schema v1 内前向扩展。
3143
+ *
3144
+ * 每个 entry 必须是对象,`key` 必须是 trim 后非空的字符串,`status` 必须严格为
3145
+ * `'enabled'` 或 `'disabled'`。解析器先 trim key,再把唯一的历史别名 `network.request`
3146
+ * 归一为 canonical `network`;大小写不会转换。重复检查基于归一化后的所有 key,因此
3147
+ * `network` 与 ` network.request ` 冲突,两个相同未知 future key 也会让整个 snapshot fail
3148
+ * closed。
3149
+ *
3150
+ * 是否属于当前受管 key 由 {@link isManagedMiniProgramRuntimePermissionKey} 与权限目录决定。
3151
+ * 为兼容较新服务端,非空、状态合法且不重复的未知 key 会被忽略;其 `config` 可以缺失、为
3152
+ * `null`、数组或任意未来结构,均不会使已认识的权限失效。未知 entry 不会出现在返回映射中。
3153
+ *
3154
+ * 已知权限严格执行当前 schema:`network` 必须提供对象 config,且
3155
+ * `useOfficialDomain` 必须是 boolean;其他额外 network config 字段会丢弃,返回值只复制该
3156
+ * boolean。其余当前权限是无配置项权限,输入 config 可以缺失、为 `null` 或 `{}`,并统一输出
3157
+ * `{}`;非空对象、数组或其他值会使整个 snapshot 无效。Runtime snapshot 必须显式包含
3158
+ * network 的有效 boolean,即使 Manifest 目录把省略 `useOfficialDomain` 的开发者默认值定义为
3159
+ * `false`。
3160
+ *
3161
+ * 返回的 canonical entry/config 都是新对象;修改原 snapshot、entry 或嵌套 network config
3162
+ * 不会改变解析结果。`permissions` 是 Partial map:合法空 entries、只包含未知权限,或没有某个
3163
+ * canonical key 时,解析仍可 `valid: true`,对应属性保持缺失。
3164
+ *
3165
+ * `valid: true` 只表示 snapshot 可安全消费,不代表 entry 已启用,更不代表某个 capability 已获
3166
+ * 授权。Runtime consumer 应先查 {@link MINI_PROGRAM_PROTOCOL_CAPABILITIES} 中目标 method 的
3167
+ * `requirement`:`kind: 'none'` 不读取权限;`kind: 'all'` 要求列出的每个 canonical entry 都存在
3168
+ * 且 `status === 'enabled'`。之后仍需通过 Host capability、可信手势、用户授权、参数和业务
3169
+ * policy。当前 Runtime 对 `valid: false` 按空权限表 fail closed,受保护 method 会得到
3170
+ * `PERMISSION_NOT_DECLARED`,而不是沿用输入中的部分 enabled entry。
3171
+ *
3172
+ * @example
3173
+ * ```ts
3174
+ * import { parseMiniProgramRuntimePermissions } from '@heybox/hb-sdk/protocol';
3175
+ *
3176
+ * const parsed = parseMiniProgramRuntimePermissions({
3177
+ * schema_version: 1,
3178
+ * revision: 4,
3179
+ * entries: [
3180
+ * {
3181
+ * key: ' network.request ',
3182
+ * status: 'enabled',
3183
+ * config: { useOfficialDomain: false, futureField: 'discarded' },
3184
+ * },
3185
+ * { key: 'future.permission', status: 'disabled', config: null },
3186
+ * ],
3187
+ * });
3188
+ *
3189
+ * // legacy key 已归一化;未知 future key 被忽略。
3190
+ * if (parsed.valid && parsed.permissions.network?.status === 'enabled') {
3191
+ * console.log(parsed.permissions.network.config.useOfficialDomain); // false
3192
+ * // 继续执行 capability requirement、Host 与业务 policy 校验。
3193
+ * }
3194
+ * ```
3195
+ *
3196
+ * @see {@link ParsedMiniProgramRuntimePermissions}
3197
+ * @see {@link MiniProgramRuntimePermissionsSnapshot}
3198
+ * @see {@link isManagedMiniProgramRuntimePermissionKey}
3199
+ * @see {@link MINI_PROGRAM_PROTOCOL_CAPABILITIES}
3200
+ * @see {@link https://docs.xiaoheihe.cn/hb_sdk/guide/permissions | 权限声明}
3201
+ */
3202
+ function parseMiniProgramRuntimePermissions(snapshot) {
3203
+ if (!isRecord$4(snapshot) || snapshot.schema_version !== 1 || !Array.isArray(snapshot.entries)) {
3204
+ return { valid: false, permissions: {} };
3205
+ }
3206
+ if (snapshot.revision !== undefined && (typeof snapshot.revision !== 'number' || !Number.isInteger(snapshot.revision) || snapshot.revision < 0)) {
3207
+ return { valid: false, permissions: {} };
3208
+ }
3209
+ const seenKeys = new Set();
3210
+ const permissions = {};
3211
+ for (const rawEntry of snapshot.entries) {
3212
+ if (!isRecord$4(rawEntry) || typeof rawEntry.key !== 'string' || !rawEntry.key.trim()) {
3213
+ return { valid: false, permissions: {} };
3214
+ }
3215
+ const inputKey = rawEntry.key.trim();
3216
+ const key = inputKey === 'network.request' ? 'network' : inputKey;
3217
+ if (seenKeys.has(key) || (rawEntry.status !== 'enabled' && rawEntry.status !== 'disabled')) {
3218
+ return { valid: false, permissions: {} };
3219
+ }
3220
+ seenKeys.add(key);
3221
+ if (!isManagedMiniProgramRuntimePermissionKey(key)) {
3222
+ // 未知权限必须忽略,不能让 config:null / 缺字段把已认识的批准一起否掉。
3223
+ // 服务端会对无 config 的 message 字段输出 null(Rylai EmitUnpopulated)。
3224
+ continue;
3225
+ }
3226
+ if (key === 'network') {
3227
+ const config = rawEntry.config;
3228
+ if (!isRecord$4(config) || typeof config.useOfficialDomain !== 'boolean') {
3229
+ return { valid: false, permissions: {} };
3230
+ }
3231
+ permissions[key] = {
3232
+ key,
3233
+ status: rawEntry.status,
3234
+ config: { useOfficialDomain: config.useOfficialDomain },
3235
+ };
3236
+ continue;
3237
+ }
3238
+ if (rawEntry.config !== null && rawEntry.config !== undefined && (!isRecord$4(rawEntry.config) || Object.keys(rawEntry.config).length > 0)) {
3239
+ return { valid: false, permissions: {} };
3240
+ }
3241
+ permissions[key] = {
3242
+ key,
3243
+ status: rawEntry.status,
3244
+ config: {},
3245
+ };
3246
+ }
3247
+ return { valid: true, permissions };
3248
+ }
3249
+ function isRecord$4(value) {
3250
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
3251
+ }
3252
+
3253
+ const MINIAPP_PERMISSION_KEYS = MINI_PROGRAM_PERMISSION_KEYS;
3254
+ function parseMiniappPermissions(value, options) {
3255
+ const sourceLabel = options.sourceLabel ?? 'package.json#heybox.permissions';
3256
+ if (!options.present) {
3257
+ if (requiresExplicitPermissions(options.sdkVersion)) {
3258
+ throw new Error(`${sourceLabel} 在 @heybox/hb-sdk ${options.sdkVersion} 中必须声明;无权限需求时请配置空对象 {}`);
3259
+ }
3260
+ return { declared: false };
3261
+ }
3262
+ if (!isRecord$3(value)) {
3263
+ throw new Error(`${sourceLabel} 必须是 JSON 对象`);
3264
+ }
3265
+ const knownKeys = new Set(MINIAPP_PERMISSION_KEYS);
3266
+ for (const key of Object.keys(value)) {
3267
+ if (!knownKeys.has(key))
3268
+ throw new Error(`${sourceLabel} 包含未知权限:${key}`);
3269
+ }
3270
+ const permissions = {};
3271
+ for (const key of MINIAPP_PERMISSION_KEYS) {
3272
+ if (!Object.prototype.hasOwnProperty.call(value, key))
3273
+ continue;
3274
+ const declaration = value[key];
3275
+ const itemLabel = `${sourceLabel}.${key}`;
3276
+ if (!isRecord$3(declaration))
3277
+ throw new Error(`${itemLabel} 必须是 JSON 对象`);
3278
+ const definition = MINI_PROGRAM_PERMISSION_CATALOG.find((item) => item.key === key);
3279
+ if (!definition)
3280
+ throw new Error(`权限目录缺少定义:${key}`);
3281
+ const allowedFields = new Set(['enabled', ...Object.keys(definition.config)]);
3282
+ for (const field of Object.keys(declaration)) {
3283
+ if (!allowedFields.has(field))
3284
+ throw new Error(`${itemLabel} 包含未知字段:${field}`);
3285
+ }
3286
+ if (typeof declaration.enabled !== 'boolean')
3287
+ throw new Error(`${itemLabel}.enabled 必须是 boolean`);
3288
+ let useOfficialDomain = false;
3289
+ if (key === 'network') {
3290
+ if (declaration.useOfficialDomain !== undefined && typeof declaration.useOfficialDomain !== 'boolean') {
3291
+ throw new Error(`${itemLabel}.useOfficialDomain 必须是 boolean`);
3292
+ }
3293
+ useOfficialDomain = declaration.useOfficialDomain === true;
3294
+ }
3295
+ if (!declaration.enabled)
3296
+ continue;
3297
+ permissions[key] = key === 'network' ? { enabled: true, useOfficialDomain } : { enabled: true };
3298
+ }
3299
+ return { declared: true, permissions: permissions };
3300
+ }
3301
+ function requiresExplicitPermissions(sdkVersion) {
3302
+ const parsed = semverExports.parse(sdkVersion);
3303
+ if (!parsed)
3304
+ throw new Error(`sdkVersion 必须是合法 SemVer:${sdkVersion}`);
3305
+ return parsed.major > 0 || parsed.minor >= 9;
3306
+ }
3307
+ function getMissingPermissionsWarning(sourceLabel = 'package.json#heybox.permissions') {
3308
+ return `${sourceLabel} 尚未声明。当前按 0.8 兼容行为构建;0.9.0 起将拒绝构建,请尽快补充权限声明(无权限需求时配置 {})。`;
3309
+ }
3310
+ function composeMiniappRuntimePermissions(local, approvals) {
3311
+ const parsedApprovals = parseMiniProgramRuntimePermissions(approvals);
3312
+ const approvalRevision = isRecord$3(approvals) && Number.isInteger(approvals.revision) ? approvals.revision : undefined;
3313
+ const views = [];
3314
+ const entries = [];
3315
+ for (const definition of MINI_PROGRAM_PERMISSION_CATALOG) {
3316
+ const declaration = local.permissions?.[definition.key];
3317
+ const declared = !local.declared || declaration?.enabled === true;
3318
+ if (definition.access === 'declaration') {
3319
+ views.push({ key: definition.key, access: definition.access, declared, approved: null, effective: declared });
3320
+ if (declared)
3321
+ entries.push({ key: definition.key, status: 'enabled', config: {} });
3322
+ continue;
3323
+ }
3324
+ const approval = parsedApprovals.valid ? parsedApprovals.permissions[definition.key] : undefined;
3325
+ const approved = approval?.status === 'enabled';
3326
+ const effective = declared && approved;
3327
+ if (definition.key !== 'network') {
3328
+ views.push({
3329
+ key: definition.key,
3330
+ access: definition.access,
3331
+ declared,
3332
+ approved,
3333
+ effective,
3334
+ });
3335
+ if (declared) {
3336
+ entries.push({ key: definition.key, status: effective ? 'enabled' : 'disabled', config: {} });
3337
+ }
3338
+ continue;
3339
+ }
3340
+ const requestedOfficialDomain = declaration?.enabled === true && 'useOfficialDomain' in declaration && declaration.useOfficialDomain;
3341
+ const approvedOfficialDomain = approval?.config.useOfficialDomain === true;
3342
+ const effectiveOfficialDomain = effective && (local.declared ? requestedOfficialDomain : true) && approvedOfficialDomain;
3343
+ views.push({
3344
+ key: definition.key,
3345
+ access: definition.access,
3346
+ declared,
3347
+ approved,
3348
+ requestedConfig: { useOfficialDomain: requestedOfficialDomain },
3349
+ approvedConfig: { useOfficialDomain: approvedOfficialDomain },
3350
+ effective,
3351
+ effectiveConfig: { useOfficialDomain: effectiveOfficialDomain },
3352
+ });
3353
+ if (declared) {
3354
+ entries.push({ key: definition.key, status: effective ? 'enabled' : 'disabled', config: { useOfficialDomain: effectiveOfficialDomain } });
3355
+ }
3356
+ }
3357
+ return {
3358
+ runtimePermissions: { schema_version: 1, ...(approvalRevision === undefined ? {} : { revision: approvalRevision }), entries },
3359
+ views,
3360
+ };
3361
+ }
3362
+ function isRecord$3(value) {
3363
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
3364
+ }
3365
+
3366
+ /**
3367
+ * `package.json#heybox.platforms` 接受的平台值,顺序同时是 Manifest 的规范化输出顺序。
3368
+ *
3369
+ * @remarks 项目仍应只声明实际完成适配并经过验收的平台;模板默认值不是自动兼容承诺。
3370
+ */
3371
+ const MINIAPP_PLATFORM_VALUES = ['android', 'ios', 'ohos', 'windows', 'macos', 'linux'];
3372
+ /** 窗口尺寸字段的脏值兜底上限;真正的上限是宿主侧显示器 workArea。 */
3373
+ const MINIAPP_WINDOW_SIZE_MAX = 16_384;
3374
+ const MINIAPP_WINDOW_NUMBER_FIELDS = ['defaultWidth', 'defaultHeight', 'minWidth', 'minHeight'];
3375
+ const MINIAPP_WINDOW_ALLOWED_FIELDS = [...MINIAPP_WINDOW_NUMBER_FIELDS, 'resizable'];
3376
+ /**
3377
+ * 桌面平台子集:从唯一平台词表 `MINIAPP_PLATFORM_VALUES` 派生,`satisfies` 阻止它漂移出词表。
3378
+ * 小程序声明其中任一平台,即视为该项目承诺适配 PC / 桌面端;调试台据此取舍桌面调试入口。
3379
+ *
3380
+ * 注意:子集只表达「声明为桌面」,不保证已有可用的客户端基线——例如 `linux` 目前既没有 `@hbPlatform` 声明,
3381
+ * 也没有 Companion target,仅声明 `linux` 的项目会展示入口但未必能真正打开。
3382
+ */
3383
+ const MINIAPP_DESKTOP_PLATFORM_VALUES = ['windows', 'macos', 'linux'];
3384
+ function hasMiniappDesktopPlatform(platforms) {
3385
+ if (!platforms)
3386
+ return false;
3387
+ return MINIAPP_DESKTOP_PLATFORM_VALUES.some((platform) => platforms.includes(platform));
3388
+ }
3389
+ /**
3390
+ * 判断小程序版本是否符合公开 Manifest 版本规则。
3391
+ *
3392
+ * @param version - 待判断的 `package.json.version` / Manifest 版本字符串;首尾空白会先被
3393
+ * 移除,但函数不会把规范化后的字符串返回给调用方。
3394
+ * @returns trim 后满足小程序严格版本规则时返回 `true`,否则返回 `false`。对类型声明允许的
3395
+ * 字符串输入,该函数只返回布尔值,不抛出校验错误。
3396
+ *
3397
+ * @remarks
3398
+ * 接受形式为 canonical SemVer `MAJOR.MINOR.PATCH[-PRERELEASE]`。trim 后的输入必须与
3399
+ * `semver` 严格解析得到的 `version` 完全相同,因此不完整版本(如 `1.2`)、`v` / `=`
3400
+ * 前缀、范围表达式、额外段,以及 major/minor/patch 或纯数字 prerelease 标识中的前导零
3401
+ * 都返回 `false`。只有首尾空白会被忽略,内部空白不会被修复。
3402
+ *
3403
+ * 合法 prerelease(如 `1.2.3-alpha.1`、`0.0.1-rc.0`)可以使用。build metadata 即使符合
3404
+ * 标准 SemVer(如 `1.2.3+build.1`)也被小程序发布合同显式禁止。模板占位 core
3405
+ * `0.0.0` 同样禁止,包括 `0.0.0-alpha` 等 prerelease;至少应提升 patch/minor/major
3406
+ * 之一,例如 `0.0.1-alpha.1`。
3407
+ *
3408
+ * 这是无 I/O、无状态修改的 predicate,适合表单即时判断。实际 Vite / `hb-sdk build`
3409
+ * 流程会调用同规则的 package version validator:成功时返回 trim 后版本并写入 Manifest,
3410
+ * 失败时抛出带 `package.json.version` 来源的错误;调用本函数为 `true` 不能跳过正式构建。
3411
+ *
3412
+ * {@link resolveMiniappManifestPlatforms} 处理的是 Manifest `sdkVersion` 对平台声明策略的
3413
+ * SemVer precedence,不是当前小程序的发布 `version`。不要用本函数替代平台解析,也不要
3414
+ * 把项目 version 当作 sdkVersion 传入。
3415
+ *
3416
+ * @example
3417
+ * ```ts
3418
+ * import { isValidVersion } from '@heybox/hb-sdk/miniapp-publish'
3419
+ *
3420
+ * isValidVersion(' 1.2.3 ') // true
3421
+ * isValidVersion('1.2.3-alpha.1') // true
3422
+ * isValidVersion('0.0.1-alpha.1') // true
3423
+ * isValidVersion('1.2') // false
3424
+ * isValidVersion('v1.2.3') // false
3425
+ * isValidVersion('1.2.3+build.1') // false
3426
+ * isValidVersion('0.0.0-alpha') // false
3427
+ * ```
3428
+ *
3429
+ * @see {@link resolveMiniappManifestPlatforms}
3430
+ * @see {@link https://docs.xiaoheihe.cn/hb_sdk/reference/symbols/vite/functions/miniappManifest | miniappManifest}
3431
+ */
3432
+ function isValidMiniappManifestVersion(version) {
3433
+ return getMiniappManifestVersionError(version) === undefined;
3434
+ }
3435
+ function validateMiniappManifestVersion(version, sourceLabel = 'manifest.version') {
3436
+ const error = getMiniappManifestVersionError(version);
3437
+ if (error) {
3438
+ throw new Error(`${sourceLabel} ${error}`);
3439
+ }
3440
+ return String(version).trim();
3441
+ }
3442
+ function parseMiniappManifestJson(raw, sourceLabel = 'manifest.json') {
3443
+ const hadBom = raw.charCodeAt(0) === 0xfeff;
3444
+ const text = hadBom ? raw.slice(1) : raw;
3445
+ let parsed;
3446
+ try {
3447
+ parsed = JSON.parse(text);
3448
+ }
3449
+ catch (error) {
3450
+ throw new Error(`${sourceLabel} 不是合法 JSON:${formatReason$1(error)}`);
3451
+ }
3452
+ if (!isManifestRecord(parsed)) {
3453
+ throw new Error(`${sourceLabel} 必须是 JSON 对象`);
3454
+ }
3455
+ return {
3456
+ manifest: parsed,
3457
+ hadBom,
3458
+ };
3459
+ }
3460
+ function validateMiniappManifestForDeploy(manifest) {
3461
+ const version = validateMiniappManifestVersion(manifest.version, 'manifest.version');
3462
+ const sdkVersion = validateSdkVersion(manifest.sdkVersion, 'manifest.sdkVersion');
3463
+ const permissions = parseMiniappPermissions(manifest.permissions, {
3464
+ present: Object.prototype.hasOwnProperty.call(manifest, 'permissions'),
3465
+ sdkVersion,
3466
+ sourceLabel: 'manifest.permissions',
3467
+ });
3468
+ const companions = validateGeneratedCompanions(manifest.companions);
3469
+ const window = validateMiniappWindow(manifest.window, 'manifest.window');
3470
+ const bindAppIds = parseMiniappBindAppIds(manifest.bindAppIds, { sourceLabel: 'manifest.bindAppIds' });
3471
+ return {
3472
+ version,
3473
+ sdkVersion,
3474
+ ...parseMiniappBasicInfo(manifest, sdkVersion),
3475
+ platforms: validateMiniappPlatforms(manifest.platforms, 'manifest.platforms'),
3476
+ ...(permissions.permissions === undefined ? {} : { permissions: permissions.permissions }),
3477
+ ...(companions === undefined ? {} : { companions }),
3478
+ ...(window === undefined ? {} : { window }),
3479
+ ...(bindAppIds.length === 0 ? {} : { bindAppIds }),
3480
+ };
3481
+ }
3482
+ function validateGeneratedCompanions(value) {
3483
+ if (value === undefined)
3484
+ return undefined;
3485
+ if (!isRecord$2(value) || Object.keys(value).length === 0)
3486
+ throw new Error('manifest.companions 必须是非空对象');
3487
+ for (const [alias, definition] of Object.entries(value)) {
3488
+ if (!/^[a-z][a-z0-9-]{0,31}$/.test(alias) ||
3489
+ !isRecord$2(definition) ||
3490
+ typeof definition.displayName !== 'string' ||
3491
+ !definition.displayName ||
3492
+ Array.from(definition.displayName).length > 120 ||
3493
+ !Array.isArray(definition.capabilities) ||
3494
+ definition.capabilities.some((capability) => capability !== 'stdio' && capability !== 'attachments' && capability !== 'notifications') ||
3495
+ new Set(definition.capabilities).size !== definition.capabilities.length ||
3496
+ !isRecord$2(definition.targets) ||
3497
+ Object.keys(definition.targets).length === 0)
3498
+ throw new Error(`manifest.companions.${alias} 不合法`);
3499
+ for (const [target, artifact] of Object.entries(definition.targets)) {
3500
+ if (isRecord$2(artifact) && artifact.elevation === 'required') {
3501
+ throw new Error(`manifest.companions.${alias}.targets.${target}.elevation V1 仅支持 none,暂不支持管理员权限启动`);
3502
+ }
3503
+ if ((target !== 'windows-x64' && target !== 'macos-arm64') ||
3504
+ !isRecord$2(artifact) ||
3505
+ artifact.path !== `companions/${alias}/${target}.zip` ||
3506
+ !Number.isSafeInteger(artifact.size) ||
3507
+ Number(artifact.size) <= 0 ||
3508
+ typeof artifact.sha256 !== 'string' ||
3509
+ !/^[a-f0-9]{64}$/.test(artifact.sha256) ||
3510
+ !isRecord$2(artifact.entrypoint) ||
3511
+ (artifact.entrypoint.kind !== 'executable' && artifact.entrypoint.kind !== 'app-bundle') ||
3512
+ typeof artifact.entrypoint.path !== 'string' ||
3513
+ !artifact.entrypoint.path ||
3514
+ artifact.elevation !== 'none' ||
3515
+ !isValidGeneratedCompanionArgs(artifact.args)) {
3516
+ throw new Error(`manifest.companions.${alias}.targets.${target} 不合法`);
3517
+ }
3518
+ }
3519
+ }
3520
+ return value;
3521
+ }
3522
+ function isValidGeneratedCompanionArgs(value) {
3523
+ if (!Array.isArray(value) || value.length > 64)
3524
+ return false;
3525
+ let totalBytes = 0;
3526
+ for (const arg of value) {
3527
+ if (typeof arg !== 'string' || /[\u0000\r\n]/.test(arg))
3528
+ return false;
3529
+ const bytes = new TextEncoder().encode(arg).length;
3530
+ if (bytes > 1024)
3531
+ return false;
3532
+ totalBytes += bytes;
3533
+ }
3534
+ return totalBytes <= 16_384;
3535
+ }
3536
+ function validateMiniappPlatforms(platforms, sourceLabel = 'platforms') {
3537
+ if (!Array.isArray(platforms) || platforms.length === 0) {
3538
+ throw new Error(`${sourceLabel} 必须是非空平台数组`);
3539
+ }
3540
+ const allowedPlatforms = new Set(MINIAPP_PLATFORM_VALUES);
3541
+ const seen = new Set();
3542
+ for (const platform of platforms) {
3543
+ if (typeof platform !== 'string' || !allowedPlatforms.has(platform)) {
3544
+ throw new Error(`${sourceLabel} 包含不支持的平台:${String(platform)}`);
3545
+ }
3546
+ if (seen.has(platform)) {
3547
+ throw new Error(`${sourceLabel} 包含重复平台:${platform}`);
3548
+ }
3549
+ seen.add(platform);
3550
+ }
3551
+ return Object.freeze(MINIAPP_PLATFORM_VALUES.filter((platform) => seen.has(platform)));
3552
+ }
3553
+ function areMiniappPlatformsEqual(left, right) {
3554
+ return left.length === right.length && left.every((platform, index) => platform === right[index]);
3555
+ }
3556
+ /**
3557
+ * 校验并归一化 `package.json#heybox.window` / `manifest.window` 声明。
3558
+ *
3559
+ * @remarks
3560
+ * 与 `heybox.permissions` 同样的严格风格:未知字段报错,不做静默忽略。
3561
+ * `width` / `height` 显式给出改名提示;`x` / `y` 按未知字段显式报错(`INV-NO-DEV-POSITION`)。
3562
+ * 未声明时返回 `undefined`,由调用方决定不写入产物。
3563
+ * @param value - 待校验的原始声明(不可信输入)。
3564
+ * @param sourceLabel - 报错前缀,默认指向开发者声明路径。
3565
+ * @throws 当声明不是非空对象、含未知字段、数值/布尔类型不合法或 min/default 不配对时抛出。
3566
+ */
3567
+ function validateMiniappWindow(value, sourceLabel = 'package.json#heybox.window') {
3568
+ if (value === undefined)
3569
+ return undefined;
3570
+ if (!isRecord$2(value) || Object.keys(value).length === 0) {
3571
+ throw new Error(`${sourceLabel} 至少需要声明 defaultWidth/defaultHeight/minWidth/minHeight/resizable 之一`);
3572
+ }
3573
+ if (Object.prototype.hasOwnProperty.call(value, 'width') || Object.prototype.hasOwnProperty.call(value, 'height')) {
3574
+ throw new Error(`${sourceLabel} 请使用 defaultWidth/defaultHeight,而不是 width/height`);
3575
+ }
3576
+ for (const key of Object.keys(value)) {
3577
+ if (!MINIAPP_WINDOW_ALLOWED_FIELDS.includes(key)) {
3578
+ throw new Error(`${sourceLabel} 包含未知字段:${key}`);
3579
+ }
3580
+ }
3581
+ const window = {};
3582
+ for (const field of MINIAPP_WINDOW_NUMBER_FIELDS) {
3583
+ if (!Object.prototype.hasOwnProperty.call(value, field))
3584
+ continue;
3585
+ const size = value[field];
3586
+ if (typeof size !== 'number' || !Number.isSafeInteger(size) || size <= 0) {
3587
+ throw new Error(`${sourceLabel}.${field} 必须是正整数`);
3588
+ }
3589
+ if (size > MINIAPP_WINDOW_SIZE_MAX) {
3590
+ throw new Error(`${sourceLabel}.${field} 不能大于 ${MINIAPP_WINDOW_SIZE_MAX}`);
3591
+ }
3592
+ window[field] = size;
3593
+ }
3594
+ if (Object.prototype.hasOwnProperty.call(value, 'resizable')) {
3595
+ if (typeof value.resizable !== 'boolean') {
3596
+ throw new Error(`${sourceLabel}.resizable 必须是 boolean`);
3597
+ }
3598
+ window.resizable = value.resizable;
3599
+ }
3600
+ for (const [minimum, fallback] of [
3601
+ ['minWidth', 'defaultWidth'],
3602
+ ['minHeight', 'defaultHeight'],
3603
+ ]) {
3604
+ const minimumValue = window[minimum];
3605
+ if (minimumValue === undefined)
3606
+ continue;
3607
+ const fallbackValue = window[fallback];
3608
+ if (fallbackValue === undefined) {
3609
+ throw new Error(`${sourceLabel}.${minimum} 必须与 ${fallback} 同时声明`);
3610
+ }
3611
+ if (minimumValue > fallbackValue) {
3612
+ throw new Error(`${sourceLabel}.${minimum} 必须小于等于 ${fallback}`);
3613
+ }
3614
+ }
3615
+ return window;
3616
+ }
3617
+ /** 比较两份窗口声明是否逐字段一致;未声明视同 `undefined`。 */
3618
+ function areMiniappWindowsEqual(left, right) {
3619
+ if (left === undefined || right === undefined)
3620
+ return left === right;
3621
+ return (left.defaultWidth === right.defaultWidth &&
3622
+ left.defaultHeight === right.defaultHeight &&
3623
+ left.minWidth === right.minWidth &&
3624
+ left.minHeight === right.minHeight &&
3625
+ left.resizable === right.resizable);
3626
+ }
3627
+ function validateSdkVersion(version, sourceLabel = 'sdkVersion') {
3628
+ if (typeof version !== 'string' || version.trim() === '') {
3629
+ throw new Error(`${sourceLabel} 必须是合法 SemVer:${String(version)}`);
3630
+ }
3631
+ const normalized = version.trim();
3632
+ const parsed = semverExports.parse(normalized);
3633
+ if (!parsed || parsed.version !== normalized || parsed.build.length > 0) {
3634
+ throw new Error(`${sourceLabel} 必须是合法 SemVer:${normalized}`);
3635
+ }
3636
+ return normalized;
3637
+ }
3638
+ function isManifestRecord(value) {
3639
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
3640
+ }
3641
+ function isRecord$2(value) {
3642
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
3643
+ }
3644
+ function getMiniappManifestVersionError(version) {
3645
+ if (typeof version !== 'string' || version.trim() === '') {
3646
+ return `必须是合法 SemVer:${String(version)}`;
3647
+ }
3648
+ const normalized = version.trim();
3649
+ const parsed = semverExports.parse(normalized);
3650
+ if (!parsed) {
3651
+ return `必须是合法 SemVer:${normalized}`;
3652
+ }
3653
+ if (parsed.build.length > 0) {
3654
+ return `不能包含 build metadata:${normalized}`;
3655
+ }
3656
+ if (parsed.version !== normalized) {
3657
+ return `必须是合法 SemVer:${normalized}`;
3658
+ }
3659
+ if (parsed.major === 0 && parsed.minor === 0 && parsed.patch === 0) {
3660
+ return '不能是模板默认版本 0.0.0';
3661
+ }
3662
+ return undefined;
3663
+ }
3664
+ function formatReason$1(error) {
3665
+ if (error instanceof Error && error.message) {
3666
+ return error.message;
3667
+ }
3668
+ return String(error);
3669
+ }
3670
+
3
3671
  const UNDEFINED_CODE_POINTS = new Set([
4
3672
  65534, 65535, 131070, 131071, 196606, 196607, 262142, 262143, 327678, 327679, 393214,
5
3673
  393215, 458750, 458751, 524286, 524287, 589822, 589823, 655358, 655359, 720894,
@@ -8232,57 +11900,882 @@ new Set([
8232
11900
  TAG_NAMES.WBR,
8233
11901
  ]);
8234
11902
 
8235
- // Shorthands
11903
+ /** CDN 上传接口使用的小程序产物业务 scope。 */
11904
+ const MINIAPP_UPLOAD_SCOPE = 'activity';
11905
+ /** 完整 CDN 上传 key 的默认长度上限;旧固定版本流程按字符计数,上传会话流程按 UTF-8 bytes 计数。 */
11906
+ const ACTIVITY_UPLOAD_KEY_MAX_LENGTH = 64;
11907
+ /** 单次向 CDN 申请上传信息时包含的最大文件数;当前合同固定为 `50`。 */
11908
+ const MINIAPP_UPLOAD_BATCH_SIZE = 50;
11909
+ /** Web 构建产物的默认总大小上限,单位为 bytes;当前为 100 MiB。 */
11910
+ const MINIAPP_UPLOAD_TOTAL_SIZE_LIMIT_BYTES = 100 * 1024 * 1024;
11911
+ /** Companion 归档的临时总大小上限,单位为 bytes;当前为 500 MiB。 */
11912
+ const MINIAPP_COMPANION_UPLOAD_TEMPORARY_SIZE_LIMIT_BYTES = 500 * 1024 * 1024;
11913
+ /** 查询当前开发者账号是否具备小程序访问资格的开放平台 API 路径。 */
11914
+ const USER_MINIPROGRAM_ACCESS_STATUS_API_PATH = '/mall/developer/user_miniprogram/access_status';
11915
+ /** 查询当前开发者可管理主体列表的开放平台 API 路径。 */
11916
+ const DEVELOPER_ENTITY_LIST_API_PATH = '/mall/developer/entity/list';
11917
+ /** 切换当前开发者主体的开放平台 API 路径。 */
11918
+ const DEVELOPER_ENTITY_SWITCH_API_PATH = '/mall/developer/entity/switch';
11919
+ /** 查询当前主体下小程序列表的开放平台 API 路径。 */
11920
+ const LIST_USER_MINIPROGRAM_API_PATH = '/mall/developer/user_miniprogram/list';
11921
+ /** 创建小程序的开放平台 API 路径。 */
11922
+ const CREATE_USER_MINIPROGRAM_API_PATH = '/mall/developer/user_miniprogram/create';
11923
+ /** 查询单个小程序详情的开放平台 API 路径。 */
11924
+ const DETAIL_USER_MINIPROGRAM_API_PATH = '/mall/developer/user_miniprogram/detail';
11925
+ /** 创建本地开发启动凭据的开放平台 API 路径。 */
11926
+ const CREATE_USER_MINIPROGRAM_LOCAL_DEV_LAUNCH_TOKEN_API_PATH = '/mall/developer/user_miniprogram/local_dev_launch_token';
11927
+ /** 查询小程序预览白名单的开放平台 API 路径。 */
11928
+ const USER_MINIPROGRAM_PREVIEW_ALLOWLIST_API_PATH = '/mall/developer/user_miniprogram/preview_allowlist';
11929
+ /** 更新小程序预览白名单的开放平台 API 路径。 */
11930
+ const UPDATE_USER_MINIPROGRAM_PREVIEW_ALLOWLIST_API_PATH = '/mall/developer/user_miniprogram/preview_allowlist/update';
11931
+ /** 创建小程序云排行榜的开放平台 API 路径。 */
11932
+ const CREATE_USER_MINIPROGRAM_LEADERBOARD_API_PATH = '/mall/developer/user_miniprogram/leaderboard/create';
11933
+ /** 查询单个小程序云排行榜详情的开放平台 API 路径。 */
11934
+ const DETAIL_USER_MINIPROGRAM_LEADERBOARD_API_PATH = '/mall/developer/user_miniprogram/leaderboard/detail';
11935
+ /** 查询小程序云排行榜列表的开放平台 API 路径。 */
11936
+ const LIST_USER_MINIPROGRAM_LEADERBOARD_API_PATH = '/mall/developer/user_miniprogram/leaderboard/list';
11937
+ /** 删除小程序云排行榜的开放平台 API 路径。 */
11938
+ const DELETE_USER_MINIPROGRAM_LEADERBOARD_API_PATH = '/mall/developer/user_miniprogram/leaderboard/delete';
11939
+ /** 在上传或复用版本前执行发布预检的开放平台 API 路径。 */
11940
+ const PRECHECK_USER_MINIPROGRAM_VERSION_API_PATH = '/mall/developer/user_miniprogram/version/precheck';
11941
+ /** 将小程序版本提交审核的开放平台 API 路径。 */
11942
+ const SUBMIT_USER_MINIPROGRAM_AUDIT_API_PATH = '/mall/developer/user_miniprogram/version/submit_audit';
11943
+ /** 查询小程序版本预览信息的开放平台 API 路径。 */
11944
+ const USER_MINIPROGRAM_VERSION_PREVIEW_INFO_API_PATH = '/mall/developer/user_miniprogram/version/preview_info';
11945
+ /** 撤回待审核小程序版本的开放平台 API 路径。 */
11946
+ const WITHDRAW_USER_MINIPROGRAM_VERSION_API_PATH = '/mall/developer/user_miniprogram/version/withdraw';
11947
+ /** 发布审核通过的小程序版本的开放平台 API 路径。 */
11948
+ const RELEASE_USER_MINIPROGRAM_VERSION_API_PATH = '/mall/developer/user_miniprogram/version/release';
11949
+ /** 下架当前线上小程序的开放平台 API 路径。 */
11950
+ const TAKE_DOWN_USER_MINIPROGRAM_API_PATH = '/mall/developer/user_miniprogram/take_down';
11951
+ /** 重新开放已下架小程序的开放平台 API 路径。 */
11952
+ const REOPEN_USER_MINIPROGRAM_API_PATH = '/mall/developer/user_miniprogram/reopen';
11953
+ /** 更新小程序广场展示状态的开放平台 API 路径。 */
11954
+ const UPDATE_SQUARE_DISPLAY_API_PATH = '/mall/developer/user_miniprogram/square_display/update';
11955
+ /** 查询小程序历史版本列表的开放平台 API 路径。 */
11956
+ const LIST_USER_MINIPROGRAM_VERSION_API_PATH = '/mall/developer/user_miniprogram/version/list';
11957
+ const FNV_OFFSET = 0x811c9dc5;
11958
+ const FNV_PRIME = 0x01000193;
11959
+ const MINIAPP_UPLOAD_SESSION_REF_LENGTH = 10;
11960
+ const MINIAPP_ARTIFACT_SIGNATURE_MAGIC = 'heybox-user-miniprogram-artifact\0v1\0';
11961
+ const UNPAIRED_SURROGATE_PATTERN = /[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/;
11962
+ const textEncoder = new TextEncoder();
11963
+ /**
11964
+ * 将扫描到的相对路径转换为统一的 `/` 分隔形式。
11965
+ *
11966
+ * @param relativePath - 待整理的构建产物路径。TypeScript 入口声明为字符串;JavaScript 运行时会
11967
+ * 先计算 `relativePath || ''`,再通过 `String(...)` 强制转换。
11968
+ * @returns 仅统一分隔符形态的新字符串:所有 `\\` 转为 `/`,所有前导 `/` 被删除,其余连续
11969
+ * `/` 合并为一个。空字符串以及运行时传入的 `undefined`、`null`、`false`、`0`、`NaN` 等
11970
+ * falsy 值返回 `''`;truthy 非字符串按标准 `String(value)` 结果继续整理。
11971
+ *
11972
+ * @remarks
11973
+ * 这是面向 build/deploy 文件扫描结果的**格式 helper**,不是路径安全校验或 canonical path
11974
+ * parser。它不会 trim、URL decode、Unicode normalize、解析盘符,也不会拒绝或消解 `.` / `..`
11975
+ * segment、控制字符、Windows drive prefix 或尾随 `/`。例如 `/etc/passwd` 会变成
11976
+ * `etc/passwd`,`C:\\temp\\app.js` 会变成 `C:/temp/app.js`,`assets/../secret/` 仍保留点段
11977
+ * 和尾随 slash;调用方不能根据返回值推断原输入是安全相对路径。
11978
+ *
11979
+ * SDK 的 build/deploy 流程会把扫描路径先用本函数统一分隔符,再分别使用
11980
+ * {@link relativePathContainsNodeModulesSegment} 排除完整 `node_modules` 目录段、用
11981
+ * {@link shouldUploadDistFile} 过滤根 `manifest.json` / `.DS_Store` / source map。`hb-sdk build`
11982
+ * 随后校验大小预算;`hb-sdk remote deploy` 还会在签名和上传前通过
11983
+ * `validateUploadPaths()`、`prepareMiniappArtifactFiles()` 或
11984
+ * `validateMiniappUploadPathLengths()` 执行真正的空路径、点段、控制字符、重复和长度校验。
11985
+ * 这些步骤不能由本函数单独替代;`shouldUploadDistFile()` 也不会自行检查 `node_modules`。
11986
+ *
11987
+ * 不要把本函数与 `@heybox/hb-sdk/protocol` 的 `isMiniProgramRelativePath()` 混用:协议 guard
11988
+ * 不做转换,只接受已经规范的非空字符串,并拒绝前导/尾随 `/`、反斜杠、空 segment、`.`、
11989
+ * `..` 与控制字符;本函数则会改写部分非法形态并保留其余不安全内容。
11990
+ *
11991
+ * @example
11992
+ * ```ts
11993
+ * import { normalizeRelativePath } from '@heybox/hb-sdk/miniapp-publish';
11994
+ *
11995
+ * normalizeRelativePath('///dist\\assets//app.js'); // 'dist/assets/app.js'
11996
+ * normalizeRelativePath('assets/../secret///'); // 'assets/../secret/',仍需安全校验
11997
+ * normalizeRelativePath(123 as unknown as string); // '123',JavaScript 运行时强制转换
11998
+ * normalizeRelativePath(0 as unknown as string); // '',falsy 值先回退为空串
11999
+ * ```
12000
+ *
12001
+ * @see {@link relativePathContainsNodeModulesSegment}
12002
+ * @see {@link shouldUploadDistFile}
12003
+ * @see {@link https://docs.xiaoheihe.cn/hb_sdk/reference/symbols/protocol/functions/isMiniProgramRelativePath | isMiniProgramRelativePath}
12004
+ */
12005
+ function normalizeRelativePath(relativePath) {
12006
+ return String(relativePath || '')
12007
+ .replace(/\\/g, '/')
12008
+ .replace(/^\/+/, '')
12009
+ .replace(/\/+/g, '/');
12010
+ }
12011
+ /**
12012
+ * 判断路径中是否包含大小写不敏感的完整 `node_modules` 目录段。
12013
+ *
12014
+ * @param relativePath - 待检查的构建产物路径。函数先通过 {@link normalizeRelativePath} 把
12015
+ * 反斜杠改为 `/`、删除前导 `/` 并合并连续 `/`,再按 `/` 分段。
12016
+ * @returns 至少一个非空段大小写不敏感地等于完整 `node_modules` 时返回 `true`;空路径、
12017
+ * 空段及 `node_modules.txt`、`node_modules-old`、`@node_modules` 等相似名称返回 `false`。
12018
+ *
12019
+ * @remarks
12020
+ * 比较使用每个非空 segment 的 `toLowerCase() === 'node_modules'`,因此根目录或任意深度的
12021
+ * `node_modules`、`NODE_MODULES`、`Node_Modules` 都会命中。前导和重复 slash 会先被
12022
+ * `normalizeRelativePath` 整理;尾随 slash 产生的空段会被忽略。
12023
+ *
12024
+ * 这是同步、无副作用的**单一 predicate**,只回答“规范化后的文本是否包含该完整段”。它
12025
+ * 不 trim segment、不进行 URL/percent decode、Unicode normalize 或文件系统解析。例如
12026
+ * `node_modules%2Fpkg/index.js`、`%6eode_modules/pkg.js` 和 `node_modules.txt` 都不会命中;调用方
12027
+ * 不应传 URL,也不能把未命中解释为路径安全。
12028
+ *
12029
+ * 本函数不会拒绝或消解 `.` / `..`、绝对路径、Windows drive prefix、控制字符、空路径、
12030
+ * symlink、重复路径或超长路径。`assets/../node_modules/pkg.js` 仍会命中,因为点段保持原样;
12031
+ * 不含 `node_modules` 的危险路径则仍可能返回 `false`。签名或上传前必须继续执行对应的上传
12032
+ * 路径规范、唯一性和长度校验。
12033
+ *
12034
+ * SDK build/deploy 会在文件扫描后用本函数拒绝整个 `node_modules` 树,再用
12035
+ * {@link shouldUploadDistFile} 排除根 `manifest.json`、`.DS_Store` 和 source map。build 随后
12036
+ * 校验大小预算;deploy 还会执行上传路径安全、唯一性、长度与签名校验。这些步骤互不替代:`shouldUploadDistFile()` 本身不检查
12037
+ * `node_modules`,本函数也不决定普通文件是否应该上传。
12038
+ *
12039
+ * @example
12040
+ * ```ts
12041
+ * import { relativePathContainsNodeModulesSegment } from '@heybox/hb-sdk/miniapp-publish';
12042
+ *
12043
+ * relativePathContainsNodeModulesSegment('dist\\NODE_MODULES/pkg/index.js'); // true
12044
+ * relativePathContainsNodeModulesSegment('dist//vendor///node_modules/'); // true
12045
+ * relativePathContainsNodeModulesSegment('dist/node_modules.txt'); // false
12046
+ * relativePathContainsNodeModulesSegment('dist/node_modules%2Fpkg.js'); // false,不做 URL decode
12047
+ * relativePathContainsNodeModulesSegment('assets/../secret.js'); // false,但这不代表路径安全
12048
+ * ```
12049
+ *
12050
+ * @see [normalizeRelativePath](/reference/symbols/miniapp-publish/functions/normalizeRelativePath)
12051
+ * @see [shouldUploadDistFile](/reference/symbols/miniapp-publish/functions/shouldUploadDistFile)
12052
+ * @see [miniapp-publish](/reference/miniapp-publish/)
12053
+ */
12054
+ function relativePathContainsNodeModulesSegment(relativePath) {
12055
+ return normalizeRelativePath(relativePath)
12056
+ .split('/')
12057
+ .some((segment) => segment.length > 0 && segment.toLowerCase() === 'node_modules');
12058
+ }
12059
+ /**
12060
+ * 为小程序 ID 计算稳定、紧凑的上传路径别名。
12061
+ *
12062
+ * @param miniProgramId - 小程序 ID。
12063
+ * @returns 基于 32-bit FNV-1a 结果生成的 base36 字符串。
12064
+ * @remarks 该别名只用于缩短上传 key,不是加密摘要,也不能用于鉴权或隐藏小程序身份。
12065
+ * @example
12066
+ * ```ts
12067
+ * const alias = getMiniProgramUploadAlias('mp_example');
12068
+ * console.log(/^[a-z0-9]+$/.test(alias)); // true
12069
+ * ```
12070
+ */
12071
+ function getMiniProgramUploadAlias(miniProgramId) {
12072
+ let hash = FNV_OFFSET;
12073
+ const input = String(miniProgramId || '');
12074
+ for (let i = 0; i < input.length; i += 1) {
12075
+ hash ^= input.charCodeAt(i);
12076
+ hash = Math.imul(hash, FNV_PRIME) >>> 0;
12077
+ }
12078
+ return hash.toString(36);
12079
+ }
8236
12080
  /**
8237
- * Parses an HTML string.
12081
+ * 校验一组构建产物的总大小是否超过给定上限。
8238
12082
  *
8239
- * @param html Input HTML string.
8240
- * @param options Parsing options.
8241
- * @returns Document
12083
+ * @param items - 要累计的条目。函数按数组顺序读取每项 `size`,经 `Number(...)` 转换后仅
12084
+ * 累加有限且大于 `0` 的值;不修改、过滤或排序输入数组,也不读取 `relativePath`。
12085
+ * @param options - 可选 byte 上限;默认 `104857600` bytes(100 MiB)。自定义上限不会改变
12086
+ * 固定错误文案。
12087
+ * @returns 总和严格大于上限时返回唯一固定字符串
12088
+ * `构建产物总大小超过 100MB,请删除未引用资源或压缩图片后重新 deploy`;总和小于或等于
12089
+ * 上限时返回 `undefined`。函数不会因超限抛异常,调用方决定是否把返回文本转成 `Error`。
8242
12090
  *
12091
+ * @remarks
12092
+ * 计算等价于把每项规范成 `Number.isFinite(Number(size)) && Number(size) > 0 ? Number(size) : 0`
12093
+ * 后求和,不取整、不去重,也不设置单文件上限。因此一个文件可以占满全部预算,多个同路径
12094
+ * 条目会重复计数,正小数会按 JavaScript number 原值加入;总和恰等 `limitBytes` 时通过,
12095
+ * 多 1 byte 才返回错误。
12096
+ *
12097
+ * 在声明的 TypeScript 输入契约内,该函数以返回值报告预算结果,不为非有限/非正 size 抛错。
12098
+ * 固定错误文本不包含首个文件、实际总量或自定义上限,即使测试/集成传了其他 `limitBytes`,
12099
+ * 文案仍写 `100MB` 和 `重新 deploy`。`hb-sdk build` 的调用方会把末尾提示改成 `重新 build`。
12100
+ *
12101
+ * 该函数只校验一个未分组列表的总量,不读取文件系统,不执行 stat,也不校验路径、安全性、
12102
+ * 文件数量、重复项、单文件大小或内容。调用方应先用
12103
+ * [shouldUploadDistFile](/reference/symbols/miniapp-publish/functions/shouldUploadDistFile) 选择真正
12104
+ * 上传的文件,并完成 `node_modules`、路径规范/唯一性/长度等校验;被提前过滤的 Manifest、
12105
+ * `.DS_Store` 和 source map 才不会计入总量。
12106
+ *
12107
+ * Web 与 Companion 需要独立预算时使用 `validateMiniappUploadSizeBudgets()`:它按
12108
+ * `relativePath` 的 `companions/` 前缀分组,Web 组复用本函数的默认 100 MiB 规则,Companion
12109
+ * 组使用独立 500 MiB 上限。直接调用本函数不会识别或分开这些路径。
12110
+ *
12111
+ * @example
12112
+ * ```ts
12113
+ * import { validateUploadTotalSize } from '@heybox/hb-sdk/miniapp-publish';
12114
+ *
12115
+ * const atLimit = validateUploadTotalSize(
12116
+ * [
12117
+ * { relativePath: 'assets/app.js', size: 1_024 },
12118
+ * { relativePath: 'assets/ignored-negative.js', size: -1 },
12119
+ * { relativePath: 'assets/ignored-nan.js', size: Number.NaN },
12120
+ * ],
12121
+ * { limitBytes: 1_024 },
12122
+ * )
12123
+ * console.log(atLimit) // undefined,恰等上限
12124
+ *
12125
+ * const overLimit = validateUploadTotalSize(
12126
+ * [{ relativePath: 'assets/app.js', size: 1_025 }],
12127
+ * { limitBytes: 1_024 },
12128
+ * )
12129
+ * if (overLimit) throw new Error(overLimit)
12130
+ * ```
12131
+ *
12132
+ * @see {@link UploadSizeItem}
12133
+ * @see {@link ValidateUploadTotalSizeOptions}
12134
+ * @see [shouldUploadDistFile](/reference/symbols/miniapp-publish/functions/shouldUploadDistFile)
12135
+ * @see [miniapp-publish](/reference/miniapp-publish/)
12136
+ */
12137
+ function validateUploadTotalSize(items, options = {}) {
12138
+ const limit = options.limitBytes ?? MINIAPP_UPLOAD_TOTAL_SIZE_LIMIT_BYTES;
12139
+ const total = items.reduce((sum, item) => {
12140
+ const size = Number(item.size);
12141
+ return sum + (Number.isFinite(size) && size > 0 ? size : 0);
12142
+ }, 0);
12143
+ if (total > limit) {
12144
+ return '构建产物总大小超过 100MB,请删除未引用资源或压缩图片后重新 deploy';
12145
+ }
12146
+ return undefined;
12147
+ }
12148
+ /**
12149
+ * 分别校验 Web 构建产物与 Companion 归档的总大小预算。
12150
+ *
12151
+ * @param items - 全部待上传文件;规范化后以 `companions/` 开头的路径计入 Companion 预算,其余计入 Web 预算。
12152
+ * @param options - 可选测试或集成覆盖项:`webLimitBytes` 为 Web 上限,`companionLimitBytes` 为 Companion 上限,单位均为 bytes。
12153
+ * @returns Web 或 Companion 的第一个超限提示;两类总量均不超过各自上限时返回 `undefined`。
12154
+ * @remarks Web 默认上限为 100 MiB,Companion 默认上限为 500 MiB;两类预算不会相互借用。
12155
+ * @example
12156
+ * ```ts
12157
+ * const error = validateMiniappUploadSizeBudgets([
12158
+ * { relativePath: 'index.html', size: 1_024 },
12159
+ * { relativePath: 'companions/runner/windows-x64.zip', size: 8_192 },
12160
+ * ]);
12161
+ * if (error) throw new Error(error);
12162
+ * ```
12163
+ */
12164
+ function validateMiniappUploadSizeBudgets(items, options = {}) {
12165
+ const companionItems = items.filter((item) => normalizeRelativePath(item.relativePath).startsWith('companions/'));
12166
+ const webItems = items.filter((item) => !normalizeRelativePath(item.relativePath).startsWith('companions/'));
12167
+ const webError = validateUploadTotalSize(webItems, { limitBytes: options.webLimitBytes ?? MINIAPP_UPLOAD_TOTAL_SIZE_LIMIT_BYTES });
12168
+ if (webError)
12169
+ return webError;
12170
+ const companionTotal = companionItems.reduce((sum, item) => sum + (Number.isFinite(item.size) && item.size > 0 ? item.size : 0), 0);
12171
+ const companionLimit = options.companionLimitBytes ?? MINIAPP_COMPANION_UPLOAD_TEMPORARY_SIZE_LIMIT_BYTES;
12172
+ if (companionTotal > companionLimit)
12173
+ return 'Companion 归档总大小超过 500MiB 上限,请缩减归档后重新 deploy';
12174
+ return undefined;
12175
+ }
12176
+ /**
12177
+ * 判断 `dist` 中的文件是否应作为版本产物上传。
12178
+ *
12179
+ * @param relativePath - `dist` 根目录下的文件路径。判断前先经 {@link normalizeRelativePath}
12180
+ * 统一斜杠、删除前导 `/` 并合并连续 `/`;函数不读取文件系统或文件内容。
12181
+ * @returns 以下规范化结果返回 `false`:空路径、精确等于根 `manifest.json`、精确 basename 为
12182
+ * `.DS_Store` 的任意层级路径,以及以大小写不敏感 `.map` 结尾的路径。其他值返回 `true`。
12183
+ *
12184
+ * @remarks
12185
+ * 过滤顺序以 `normalizeRelativePath(relativePath)` 的结果为准:
12186
+ *
12187
+ * - `''` 返回 `false`。
12188
+ * - 只有精确根路径 `manifest.json` 返回 `false`;`/manifest.json` 规范化后也会命中。
12189
+ * `assets/manifest.json` 会保留,因为它不是根文件。匹配大小写敏感,所以
12190
+ * `Manifest.json` 不会作为生成 Manifest 被过滤。
12191
+ * - 根或任意子目录中精确名为 `.DS_Store` 的最终 segment 返回 `false`,匹配大小写敏感;
12192
+ * `.ds_store`、`.DS_Store.bak` 会保留。
12193
+ * - 整条规范化路径经 `toLowerCase()` 后以 `.map` 结尾即返回 `false`,因此 `.map`、
12194
+ * `app.js.map`、`app.js.MAP` 都会过滤,而 `app.js.map.txt` 会保留。
12195
+ *
12196
+ * 根 `manifest.json` 是发布流水线单独读取并上送后台的版本元数据,不作为 CDN 文件上传;
12197
+ * 子目录同名文件仍被视为普通业务产物。该 predicate 只做上传集合选择,不验证输入确实是
12198
+ * 文件,也不检查扩展名白名单、文件存在性或内容。
12199
+ *
12200
+ * `true` 不代表路径安全。本函数不会 URL decode,也不会拒绝 `node_modules`、symlink、绝对
12201
+ * 路径、Windows drive prefix、`.` / `..`、空 segment、控制字符、重复路径或超长路径。
12202
+ * build/deploy 必须另外使用 {@link relativePathContainsNodeModulesSegment} 拒绝依赖目录;deploy
12203
+ * 还需在签名/上传前执行路径规范、唯一性和长度校验。
12204
+ *
12205
+ * build/deploy 会先扫描并完成上述独立边界,再以本函数过滤候选文件。build 对保留文件校验
12206
+ * 上传大小预算;deploy 额外执行 artifact 排序/签名与路径长度校验。因此被过滤的根 Manifest、Finder
12207
+ * 元数据和 source map 不计入上传文件数或大小;本函数自身不读取 `size`,也不能替代
12208
+ * `validateUploadTotalSize()` / `validateMiniappUploadSizeBudgets()`。
12209
+ *
12210
+ * @example
12211
+ * ```ts
12212
+ * import { shouldUploadDistFile } from '@heybox/hb-sdk/miniapp-publish';
12213
+ *
12214
+ * shouldUploadDistFile('/manifest.json'); // false,规范化后是根 manifest.json
12215
+ * shouldUploadDistFile('assets/manifest.json'); // true
12216
+ * shouldUploadDistFile('assets/.DS_Store'); // false
12217
+ * shouldUploadDistFile('assets/.ds_store'); // true,.DS_Store 区分大小写
12218
+ * shouldUploadDistFile('assets/app.js.MAP'); // false,.map 后缀不区分大小写
12219
+ * shouldUploadDistFile('assets/app.js.map.txt'); // true
12220
+ * shouldUploadDistFile('node_modules/pkg/index.js'); // true,必须另做 node_modules 检查
12221
+ * shouldUploadDistFile('assets/../secret.js'); // true,但这不代表路径安全
12222
+ * ```
12223
+ *
12224
+ * @see [normalizeRelativePath](/reference/symbols/miniapp-publish/functions/normalizeRelativePath)
12225
+ * @see [relativePathContainsNodeModulesSegment](/reference/symbols/miniapp-publish/functions/relativePathContainsNodeModulesSegment)
12226
+ * @see [validateUploadTotalSize](/reference/symbols/miniapp-publish/functions/validateUploadTotalSize)
12227
+ * @see [miniapp-publish](/reference/miniapp-publish/)
12228
+ */
12229
+ function shouldUploadDistFile(relativePath) {
12230
+ const normalized = normalizeRelativePath(relativePath);
12231
+ if (!normalized) {
12232
+ return false;
12233
+ }
12234
+ if (normalized === 'manifest.json') {
12235
+ return false;
12236
+ }
12237
+ if (normalized === '.DS_Store' || normalized.endsWith('/.DS_Store')) {
12238
+ return false;
12239
+ }
12240
+ if (normalized.toLowerCase().endsWith('.map')) {
12241
+ return false;
12242
+ }
12243
+ return true;
12244
+ }
12245
+ /**
12246
+ * 校验构建产物路径和大小,并按路径的 UTF-8 字节序稳定排序。
12247
+ *
12248
+ * @param files - 待处理的构建产物文件;允许携带 `absolutePath`、`sha256` 等附加字段。
12249
+ * @returns 新建的有序文件列表;每个结果保留输入条目的附加字段,输入数组顺序不变。
12250
+ * @throws `Error` 当文件数超过 uint32、路径为空或不规范、路径重复,或大小不是非负 safe integer 时抛出。
12251
+ * @remarks 路径必须已经使用规范 `/` 分隔形式;此函数不会把反斜杠或点目录段自动改写为其他路径。
12252
+ * @example
12253
+ * ```ts
12254
+ * const files = prepareMiniappArtifactFiles([
12255
+ * { relativePath: 'index.html', size: 15, absolutePath: '/tmp/dist/index.html' },
12256
+ * { relativePath: 'assets/app.js', size: 42, absolutePath: '/tmp/dist/assets/app.js' },
12257
+ * ]);
12258
+ *
12259
+ * console.log(files.map((file) => file.relativePath));
12260
+ * // ['assets/app.js', 'index.html']
12261
+ * ```
12262
+ */
12263
+ function prepareMiniappArtifactFiles(files) {
12264
+ if (files.length > 0xffffffff) {
12265
+ throw new Error('构建产物文件数量超出签名协议上限');
12266
+ }
12267
+ const usedPaths = new Set();
12268
+ const prepared = files.map((file) => {
12269
+ const relativePath = normalizeMiniappArtifactRelativePath(file.relativePath);
12270
+ if (usedPaths.has(relativePath)) {
12271
+ throw new Error(`构建产物包含重复文件路径:${relativePath}`);
12272
+ }
12273
+ usedPaths.add(relativePath);
12274
+ validateArtifactFileSize(file.size, relativePath);
12275
+ return { ...file, relativePath };
12276
+ });
12277
+ return prepared.sort((left, right) => compareBytes(textEncoder.encode(left.relativePath), textEncoder.encode(right.relativePath)));
12278
+ }
12279
+ /**
12280
+ * 按服务端 session key 前缀校验最终上传路径的 UTF-8 字节长度。
12281
+ *
12282
+ * @param files - 待上传的构建产物文件;每个路径都必须是规范相对路径。
12283
+ * @param options - `miniProgramId` 用于计算上传别名,`maxLength` 是完整 key 的最大 UTF-8 bytes,默认 {@link ACTIVITY_UPLOAD_KEY_MAX_LENGTH}。
12284
+ * @returns 第一个超长路径的错误提示;全部合法时返回 `undefined`。
12285
+ * @throws `Error` 当任一文件路径为空或不符合构建产物路径规则时抛出。
12286
+ * @remarks 会话引用按固定 10 个 ASCII 字符估算,因此该校验不依赖真实 session ID。
12287
+ * @example
12288
+ * ```ts
12289
+ * const error = validateMiniappUploadPathLengths(
12290
+ * [{ relativePath: 'assets/app.js' }],
12291
+ * { miniProgramId: 'mp_example' },
12292
+ * );
12293
+ * if (error) throw new Error(error);
12294
+ * ```
12295
+ */
12296
+ function validateMiniappUploadPathLengths(files, options) {
12297
+ const maxLength = options.maxLength ?? ACTIVITY_UPLOAD_KEY_MAX_LENGTH;
12298
+ const prefix = `/u/${getMiniProgramUploadAlias(options.miniProgramId)}/${'x'.repeat(MINIAPP_UPLOAD_SESSION_REF_LENGTH)}/`;
12299
+ const prefixLength = textEncoder.encode(prefix).length;
12300
+ const tooLongFile = files.find((file) => {
12301
+ const relativePath = normalizeMiniappArtifactRelativePath(file.relativePath);
12302
+ return prefixLength + textEncoder.encode(relativePath).length > maxLength;
12303
+ });
12304
+ return tooLongFile ? `文件路径过长,请缩短构建产物文件名或目录层级:${tooLongFile.relativePath}` : undefined;
12305
+ }
12306
+ /**
12307
+ * 创建 v1 整包签名头。
12308
+ *
12309
+ * @param fileCount - 参与签名的文件数量;必须是 `0` 到 `0xffffffff` 的整数。
12310
+ * @returns 新的字节数组,依次包含固定协议标识和 big-endian uint32 文件数。
12311
+ * @throws `Error` 当文件数不是整数、为负数或超出 uint32 范围时抛出。
12312
+ * @example
12313
+ * ```ts
12314
+ * const header = createMiniappArtifactSignatureHeader(2);
12315
+ * // 将 header 写入 SHA-256,再按排序结果依次写入文件 header 和内容。
12316
+ * ```
12317
+ */
12318
+ function createMiniappArtifactSignatureHeader(fileCount) {
12319
+ if (!Number.isInteger(fileCount) || fileCount < 0 || fileCount > 0xffffffff) {
12320
+ throw new Error('构建产物文件数量超出签名协议上限');
12321
+ }
12322
+ return concatBytes(textEncoder.encode(MINIAPP_ARTIFACT_SIGNATURE_MAGIC), encodeUint32BE(fileCount));
12323
+ }
12324
+ /**
12325
+ * 创建单个文件的 v1 framing header。
12326
+ *
12327
+ * @param file - 构建产物文件;路径必须规范,大小必须是非负 safe integer。
12328
+ * @returns 新的字节数组,依次包含 big-endian uint32 路径字节数、UTF-8 路径和 big-endian uint64 文件大小。
12329
+ * @throws `Error` 当路径为空或不规范,或大小不是非负 safe integer 时抛出。
12330
+ * @example
12331
+ * ```ts
12332
+ * const header = createMiniappArtifactFileHeader({
12333
+ * relativePath: 'assets/app.js',
12334
+ * size: 42,
12335
+ * });
12336
+ * ```
12337
+ */
12338
+ function createMiniappArtifactFileHeader(file) {
12339
+ const relativePath = normalizeMiniappArtifactRelativePath(file.relativePath);
12340
+ validateArtifactFileSize(file.size, relativePath);
12341
+ const pathBytes = textEncoder.encode(relativePath);
12342
+ return concatBytes(encodeUint32BE(pathBytes.length), pathBytes, encodeUint64BE(file.size));
12343
+ }
12344
+ /**
12345
+ * 校验服务端 session 文件映射,并计算仍需上传的文件。
12346
+ *
12347
+ * @param localFiles - 本地构建产物 receipt;除 `relativePath` 和 `size` 外,每项必须包含 64 位小写十六进制 `sha256`。
12348
+ * @param serverFiles - 服务端签发的文件映射;数量、路径、大小和 SHA-256 必须与本地产物一一一致。
12349
+ * @param uploadedKeys - 服务端已确认上传成功的 key;每个值都必须属于当前会话,重复值会被去重。
12350
+ * @returns
12351
+ * 包含三个字段的对象:`files` 是按路径 UTF-8 字节序排列的全部 `{ file, key }` 映射,
12352
+ * `missingFiles` 是其中尚未确认上传的映射,`uploadedKeys` 是去重后的已上传 key。
12353
+ * @throws `Error` 当本地产物不规范,服务端映射数量或字段无效、重复或不匹配,或已上传 key 不属于当前产物时抛出。
8243
12354
  * @example
12355
+ * ```ts
12356
+ * const resolved = resolveMiniappUploadSessionFiles(
12357
+ * [{ relativePath: 'index.html', size: 15, sha256: 'a'.repeat(64) }],
12358
+ * [{
12359
+ * relative_path: 'index.html',
12360
+ * key: '/u/abc/sessionref/index.html',
12361
+ * size: 15,
12362
+ * sha256: 'a'.repeat(64),
12363
+ * }],
12364
+ * [],
12365
+ * );
12366
+ *
12367
+ * console.log(resolved.missingFiles.length); // 1
12368
+ * ```
12369
+ */
12370
+ function resolveMiniappUploadSessionFiles(localFiles, serverFiles, uploadedKeys) {
12371
+ const preparedFiles = prepareMiniappArtifactFiles(localFiles);
12372
+ if (serverFiles.length !== preparedFiles.length) {
12373
+ throw new Error(`上传会话文件数量异常:期望 ${preparedFiles.length},实际 ${serverFiles.length}`);
12374
+ }
12375
+ const mappings = new Map();
12376
+ const serverSizes = new Map();
12377
+ const serverHashes = new Map();
12378
+ const knownKeys = new Set();
12379
+ for (const serverFile of serverFiles) {
12380
+ const relativePath = normalizeMiniappArtifactRelativePath(serverFile.relative_path);
12381
+ if (mappings.has(relativePath)) {
12382
+ throw new Error(`上传会话返回重复文件路径:${relativePath}`);
12383
+ }
12384
+ const key = String(serverFile.key || '');
12385
+ if (!key) {
12386
+ throw new Error(`上传会话未返回文件 key:${relativePath}`);
12387
+ }
12388
+ if (knownKeys.has(key)) {
12389
+ throw new Error(`上传会话返回重复文件 key:${relativePath}`);
12390
+ }
12391
+ const size = Number(serverFile.size);
12392
+ if (!Number.isSafeInteger(size) || size < 0) {
12393
+ throw new Error(`上传会话返回文件大小异常:${relativePath}`);
12394
+ }
12395
+ const sha256 = String(serverFile.sha256 || '');
12396
+ if (!/^[a-f0-9]{64}$/.test(sha256)) {
12397
+ throw new Error(`上传会话返回文件 SHA-256 异常:${relativePath}`);
12398
+ }
12399
+ mappings.set(relativePath, key);
12400
+ serverSizes.set(relativePath, size);
12401
+ serverHashes.set(relativePath, sha256);
12402
+ knownKeys.add(key);
12403
+ }
12404
+ const files = preparedFiles.map((file) => {
12405
+ const key = mappings.get(file.relativePath);
12406
+ if (!key) {
12407
+ throw new Error(`上传会话缺少文件映射:${file.relativePath}`);
12408
+ }
12409
+ if (serverSizes.get(file.relativePath) !== file.size) {
12410
+ throw new Error(`上传会话文件大小与本地构建不一致:${file.relativePath}`);
12411
+ }
12412
+ if (!('sha256' in file) || serverHashes.get(file.relativePath) !== file.sha256) {
12413
+ throw new Error(`上传会话文件 SHA-256 与本地构建不一致:${file.relativePath}`);
12414
+ }
12415
+ return { file, key };
12416
+ });
12417
+ const completed = new Set();
12418
+ for (const rawKey of uploadedKeys) {
12419
+ const key = String(rawKey || '');
12420
+ if (!knownKeys.has(key)) {
12421
+ throw new Error('上传会话返回了不属于当前产物的已上传文件');
12422
+ }
12423
+ completed.add(key);
12424
+ }
12425
+ return {
12426
+ files,
12427
+ missingFiles: files.filter((file) => !completed.has(file.key)),
12428
+ uploadedKeys: [...completed],
12429
+ };
12430
+ }
12431
+ /**
12432
+ * 校验 Manifest 中所有 Companion 归档都精确属于当前上传 receipt。
8244
12433
  *
8245
- * ```js
8246
- * const parse5 = require('parse5');
12434
+ * @param companions - `manifest.companions` 原始值;没有 Companion 时传 `undefined`。
12435
+ * @param files - 当前版本的逐文件上传 receipt;只有 `companions/` 前缀文件参与本校验。
12436
+ * @returns 校验成功时不返回值。
12437
+ * @throws `Error` 当必要的 `targets`/artifact 字段缺失,引用不存在的归档、大小或 SHA-256 不一致,
12438
+ * 或 receipt 中存在未被 Manifest 引用的 Companion 归档时抛出。
12439
+ * @remarks 本函数只交叉校验 Companion 声明与上传 receipt,不替代完整 Manifest schema 校验。
12440
+ * 非 Companion Web 文件会被忽略;`companions` 省略时 receipt 中也不能存在 Companion 归档。
12441
+ * @example
12442
+ * ```ts
12443
+ * const receipt = [{
12444
+ * relativePath: 'companions/runner/windows-x64.zip',
12445
+ * size: 42,
12446
+ * sha256: 'a'.repeat(64),
12447
+ * }];
8247
12448
  *
8248
- * const document = parse5.parse('<!DOCTYPE html><html><head></head><body>Hi there!</body></html>');
12449
+ * validateMiniappCompanionFileReceipts({
12450
+ * runner: {
12451
+ * targets: {
12452
+ * 'windows-x64': { path: receipt[0].relativePath, size: 42, sha256: receipt[0].sha256 },
12453
+ * },
12454
+ * },
12455
+ * }, receipt);
12456
+ * ```
12457
+ */
12458
+ function validateMiniappCompanionFileReceipts(companions, files) {
12459
+ const companionFiles = new Map(files.filter((file) => file.relativePath.startsWith('companions/')).map((file) => [file.relativePath, file]));
12460
+ if (companions === undefined) {
12461
+ if (companionFiles.size > 0)
12462
+ throw new Error('dist 包含未被 manifest.companions 引用的 Companion 归档');
12463
+ return;
12464
+ }
12465
+ if (!isRecord$1(companions))
12466
+ throw new Error('manifest.companions 必须是对象');
12467
+ const referenced = new Set();
12468
+ for (const definition of Object.values(companions)) {
12469
+ if (!isRecord$1(definition) || !isRecord$1(definition.targets))
12470
+ throw new Error('manifest.companions targets 不合法');
12471
+ for (const artifact of Object.values(definition.targets)) {
12472
+ if (!isRecord$1(artifact) || typeof artifact.path !== 'string' || typeof artifact.size !== 'number' || typeof artifact.sha256 !== 'string') {
12473
+ throw new Error('manifest.companions artifact 不合法');
12474
+ }
12475
+ const file = companionFiles.get(artifact.path);
12476
+ if (!file)
12477
+ throw new Error(`manifest.companions 引用的归档不在当前上传 receipt:${artifact.path}`);
12478
+ if (file.size !== artifact.size)
12479
+ throw new Error(`Companion 归档大小与 manifest 不一致:${artifact.path}`);
12480
+ if (file.sha256 !== artifact.sha256)
12481
+ throw new Error(`Companion 归档 SHA-256 与 manifest 不一致:${artifact.path}`);
12482
+ referenced.add(artifact.path);
12483
+ }
12484
+ }
12485
+ const extra = [...companionFiles.keys()].find((relativePath) => !referenced.has(relativePath));
12486
+ if (extra)
12487
+ throw new Error(`Companion 归档未被 manifest.companions 引用:${extra}`);
12488
+ }
12489
+ function isRecord$1(value) {
12490
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
12491
+ }
12492
+ function normalizeMiniappArtifactRelativePath(relativePath) {
12493
+ const value = String(relativePath || '');
12494
+ if (!value) {
12495
+ throw new Error('构建产物包含空文件路径');
12496
+ }
12497
+ if (value.includes('\\')) {
12498
+ throw new Error(`构建产物路径不能包含反斜杠:${value}`);
12499
+ }
12500
+ if (value.startsWith('/') || value.endsWith('/') || /^[a-zA-Z]:\//.test(value)) {
12501
+ throw new Error(`构建产物必须使用相对文件路径:${value}`);
12502
+ }
12503
+ if (containsControlCharacter(value) || UNPAIRED_SURROGATE_PATTERN.test(value)) {
12504
+ throw new Error(`构建产物路径包含非法字符:${value}`);
12505
+ }
12506
+ if (value.split('/').some((segment) => !segment || segment === '.' || segment === '..')) {
12507
+ throw new Error(`构建产物路径包含非法目录段:${value}`);
12508
+ }
12509
+ if (value.includes(',')) {
12510
+ throw new Error(`构建产物路径不能包含逗号:${value}`);
12511
+ }
12512
+ if (value.includes('*') || value.includes('?')) {
12513
+ throw new Error(`构建产物路径不能包含通配符:${value}`);
12514
+ }
12515
+ return value;
12516
+ }
12517
+ function containsControlCharacter(value) {
12518
+ for (const character of value) {
12519
+ const code = character.charCodeAt(0);
12520
+ if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) {
12521
+ return true;
12522
+ }
12523
+ }
12524
+ return false;
12525
+ }
12526
+ function validateArtifactFileSize(size, relativePath) {
12527
+ if (!Number.isSafeInteger(size) || size < 0) {
12528
+ throw new Error(`构建产物文件大小无效:${relativePath}`);
12529
+ }
12530
+ }
12531
+ function encodeUint32BE(value) {
12532
+ const bytes = new Uint8Array(4);
12533
+ new DataView(bytes.buffer).setUint32(0, value, false);
12534
+ return bytes;
12535
+ }
12536
+ function encodeUint64BE(value) {
12537
+ const bytes = new Uint8Array(8);
12538
+ const view = new DataView(bytes.buffer);
12539
+ view.setUint32(0, Math.floor(value / 0x100000000), false);
12540
+ view.setUint32(4, value % 0x100000000, false);
12541
+ return bytes;
12542
+ }
12543
+ function concatBytes(...parts) {
12544
+ const result = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
12545
+ let offset = 0;
12546
+ for (const part of parts) {
12547
+ result.set(part, offset);
12548
+ offset += part.length;
12549
+ }
12550
+ return result;
12551
+ }
12552
+ function compareBytes(left, right) {
12553
+ const length = Math.min(left.length, right.length);
12554
+ for (let index = 0; index < length; index += 1) {
12555
+ if (left[index] !== right[index]) {
12556
+ return left[index] - right[index];
12557
+ }
12558
+ }
12559
+ return left.length - right.length;
12560
+ }
12561
+
12562
+ function findNearestPackageJsonPath(startDir) {
12563
+ let current = path.resolve(startDir);
12564
+ while (true) {
12565
+ const packageJsonPath = path.join(current, 'package.json');
12566
+ if (fs.existsSync(packageJsonPath)) {
12567
+ return packageJsonPath;
12568
+ }
12569
+ const parent = path.dirname(current);
12570
+ if (parent === current) {
12571
+ return path.join(path.resolve(startDir), 'package.json');
12572
+ }
12573
+ current = parent;
12574
+ }
12575
+ }
12576
+ function readMiniappPlatformsFromPackageJson(root) {
12577
+ const { packageJson } = readMiniappPackageJson(root);
12578
+ const heybox = readMiniappHeyboxConfig(packageJson);
12579
+ return validateMiniappPlatforms(heybox?.platforms, 'package.json#heybox.platforms');
12580
+ }
12581
+ /**
12582
+ * 读取并校验 `package.json#heybox.window`。
8249
12583
  *
8250
- * console.log(document.childNodes[1].tagName); //> 'html'
8251
- *```
12584
+ * @returns 合法声明;未声明时返回 `undefined`,调用方不得向 manifest 写入空对象或 `null`。
12585
+ * @throws 当声明违反 {@link validateMiniappWindow} 的规则时抛出,报错前缀为 `package.json#heybox.window`。
8252
12586
  */
8253
- function parse(html, options) {
8254
- return Parser.parse(html, options);
8255
- }
8256
-
8257
- const RUNTIME_GATE_MARKER = 'data-heybox-runtime-gate';
8258
- const RUNTIME_GATE_STYLE_MARKER = 'data-heybox-runtime-gate-style';
8259
- const RUNTIME_GATE_BOOTSTRAP_MARKER = 'data-heybox-runtime-gate-bootstrap';
8260
- function hasMiniappRuntimeGate(html) {
8261
- const document = parse(html);
8262
- let hasGate = false;
8263
- let hasGateStyle = false;
8264
- let hasGateBootstrap = false;
8265
- walk(document, element => {
8266
- hasGate ||= hasAttr(element, RUNTIME_GATE_MARKER);
8267
- hasGateStyle ||= hasAttr(element, RUNTIME_GATE_STYLE_MARKER);
8268
- hasGateBootstrap ||= hasAttr(element, RUNTIME_GATE_BOOTSTRAP_MARKER);
12587
+ function readMiniappWindowFromPackageJson(root) {
12588
+ const { packageJson } = readMiniappPackageJson(root);
12589
+ const heybox = readMiniappHeyboxConfig(packageJson);
12590
+ return validateMiniappWindow(heybox?.window, 'package.json#heybox.window');
12591
+ }
12592
+ function readMiniappPermissionsFromPackageJson(root, sdkVersion) {
12593
+ const { packageJson } = readMiniappPackageJson(root);
12594
+ const heybox = readMiniappHeyboxConfig(packageJson);
12595
+ const present = heybox !== undefined && Object.prototype.hasOwnProperty.call(heybox, 'permissions');
12596
+ return parseMiniappPermissions(heybox?.permissions, {
12597
+ present,
12598
+ sdkVersion,
8269
12599
  });
8270
- return hasGate && hasGateStyle && hasGateBootstrap;
8271
12600
  }
8272
- function readAttr(element, name) {
8273
- return element.attrs.find(attr => attr.name.toLowerCase() === name)?.value;
12601
+ function readMiniappBindAppIdsFromPackageJson(root) {
12602
+ const { packageJson } = readMiniappPackageJson(root);
12603
+ const heybox = readMiniappHeyboxConfig(packageJson);
12604
+ return parseMiniappBindAppIds(heybox?.bindAppIds);
12605
+ }
12606
+ function resolveMiniappSdkVersion() {
12607
+ if (!version.HB_SDK_VERSION.startsWith('__HB_SDK_'))
12608
+ return version.HB_SDK_VERSION;
12609
+ const packageJson = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', '..', 'package.json'), 'utf8'));
12610
+ if (typeof packageJson.version !== 'string' || !packageJson.version)
12611
+ throw new Error('未能读取 @heybox/hb-sdk 当前版本号');
12612
+ return packageJson.version;
12613
+ }
12614
+ function readMiniappPackageJson(root, requireVersion) {
12615
+ const packageJsonPath = findNearestPackageJsonPath(root);
12616
+ let content;
12617
+ try {
12618
+ content = fs.readFileSync(packageJsonPath, 'utf8');
12619
+ }
12620
+ catch (error) {
12621
+ throw new Error(`@heybox/hb-sdk 读取 package.json 失败:${formatReason(error)}`);
12622
+ }
12623
+ let packageJson;
12624
+ try {
12625
+ packageJson = JSON.parse(content);
12626
+ }
12627
+ catch (error) {
12628
+ throw new Error(`@heybox/hb-sdk 解析 package.json 失败:${formatReason(error)}`);
12629
+ }
12630
+ return { packageJson, packageJsonPath, version: typeof packageJson.version === 'string' ? packageJson.version.trim() : '' };
12631
+ }
12632
+ function readMiniappHeyboxConfig(packageJson) {
12633
+ if (packageJson.heybox === undefined)
12634
+ return undefined;
12635
+ if (!isRecord(packageJson.heybox)) {
12636
+ throw new Error('@heybox/hb-sdk 提示:package.json#heybox 必须是 JSON 对象');
12637
+ }
12638
+ return packageJson.heybox;
12639
+ }
12640
+ function isRecord(value) {
12641
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
8274
12642
  }
8275
- function hasAttr(element, name) {
8276
- return readAttr(element, name) !== undefined;
12643
+ function formatReason(error) {
12644
+ if (error instanceof Error && error.message) {
12645
+ return error.message;
12646
+ }
12647
+ return String(error);
8277
12648
  }
8278
- function walk(node, visit) {
8279
- if ('tagName' in node)
8280
- visit(node);
8281
- if ('childNodes' in node)
8282
- for (const child of node.childNodes)
8283
- walk(child, visit);
8284
- if ('content' in node && node.content)
8285
- walk(node.content, visit);
12649
+
12650
+ Array.from({ length: 256 }, (_, value) => {
12651
+ let crc = value;
12652
+ for (let bit = 0; bit < 8; bit++)
12653
+ crc = (crc >>> 1) ^ ((crc & 1) ? 0xedb88320 : 0);
12654
+ return crc >>> 0;
12655
+ });
12656
+
12657
+ const HB_SDK_RUNTIME_USE_OFFICIAL_DOMAIN_ENV = 'HB_SDK_RUNTIME_USE_OFFICIAL_DOMAIN';
12658
+ const HB_SDK_RUNTIME_PERMISSION_CONTEXT_ENV = 'HB_SDK_RUNTIME_PERMISSION_CONTEXT';
12659
+ const VERIFIED_RUNTIME_PERMISSION_CONTEXT = 'verified';
12660
+ const environmentScopeStorage = new node_async_hooks.AsyncLocalStorage();
12661
+ let environmentScopeTail = Promise.resolve();
12662
+ function shouldSkipMiniappPlatformCspFromEnv(env = process.env) {
12663
+ return env[HB_SDK_RUNTIME_PERMISSION_CONTEXT_ENV] === VERIFIED_RUNTIME_PERMISSION_CONTEXT && env[HB_SDK_RUNTIME_USE_OFFICIAL_DOMAIN_ENV] === '1';
12664
+ }
12665
+ function createMiniappPlatformCspEnv(env, skipPlatformCsp) {
12666
+ return {
12667
+ ...env,
12668
+ [HB_SDK_RUNTIME_PERMISSION_CONTEXT_ENV]: VERIFIED_RUNTIME_PERMISSION_CONTEXT,
12669
+ [HB_SDK_RUNTIME_USE_OFFICIAL_DOMAIN_ENV]: skipPlatformCsp ? '1' : '0',
12670
+ };
12671
+ }
12672
+ async function withMiniappPlatformCspEnv(skipPlatformCsp, action, env = process.env) {
12673
+ if (environmentScopeStorage.getStore()?.active) {
12674
+ return runMiniappPlatformCspEnvScope(skipPlatformCsp, action, env);
12675
+ }
12676
+ let releaseScope = () => undefined;
12677
+ const previousScope = environmentScopeTail;
12678
+ environmentScopeTail = new Promise((resolve) => {
12679
+ releaseScope = resolve;
12680
+ });
12681
+ await previousScope;
12682
+ const scope = { active: true };
12683
+ try {
12684
+ return await environmentScopeStorage.run(scope, () => runMiniappPlatformCspEnvScope(skipPlatformCsp, action, env));
12685
+ }
12686
+ finally {
12687
+ scope.active = false;
12688
+ releaseScope();
12689
+ }
12690
+ }
12691
+ async function runMiniappPlatformCspEnvScope(skipPlatformCsp, action, env) {
12692
+ const targets = env === process.env ? [env] : [env, process.env];
12693
+ const previousValues = targets.map((target) => ({
12694
+ context: target[HB_SDK_RUNTIME_PERMISSION_CONTEXT_ENV],
12695
+ officialDomain: target[HB_SDK_RUNTIME_USE_OFFICIAL_DOMAIN_ENV],
12696
+ }));
12697
+ for (const target of targets) {
12698
+ target[HB_SDK_RUNTIME_PERMISSION_CONTEXT_ENV] = VERIFIED_RUNTIME_PERMISSION_CONTEXT;
12699
+ target[HB_SDK_RUNTIME_USE_OFFICIAL_DOMAIN_ENV] = skipPlatformCsp ? '1' : '0';
12700
+ }
12701
+ try {
12702
+ return await action();
12703
+ }
12704
+ finally {
12705
+ targets.forEach((target, index) => {
12706
+ const previousValue = previousValues[index];
12707
+ if (previousValue?.context === undefined) {
12708
+ delete target[HB_SDK_RUNTIME_PERMISSION_CONTEXT_ENV];
12709
+ }
12710
+ else {
12711
+ target[HB_SDK_RUNTIME_PERMISSION_CONTEXT_ENV] = previousValue.context;
12712
+ }
12713
+ if (previousValue?.officialDomain === undefined) {
12714
+ delete target[HB_SDK_RUNTIME_USE_OFFICIAL_DOMAIN_ENV];
12715
+ }
12716
+ else {
12717
+ target[HB_SDK_RUNTIME_USE_OFFICIAL_DOMAIN_ENV] = previousValue.officialDomain;
12718
+ }
12719
+ });
12720
+ }
8286
12721
  }
8287
12722
 
8288
- exports.hasMiniappRuntimeGate = hasMiniappRuntimeGate;
12723
+ exports.BASIC_INFO_MAX_BYTES = BASIC_INFO_MAX_BYTES;
12724
+ exports.BASIC_INFO_MAX_PIXELS = BASIC_INFO_MAX_PIXELS;
12725
+ exports.CREATE_USER_MINIPROGRAM_API_PATH = CREATE_USER_MINIPROGRAM_API_PATH;
12726
+ exports.CREATE_USER_MINIPROGRAM_LEADERBOARD_API_PATH = CREATE_USER_MINIPROGRAM_LEADERBOARD_API_PATH;
12727
+ exports.CREATE_USER_MINIPROGRAM_LOCAL_DEV_LAUNCH_TOKEN_API_PATH = CREATE_USER_MINIPROGRAM_LOCAL_DEV_LAUNCH_TOKEN_API_PATH;
12728
+ exports.DELETE_USER_MINIPROGRAM_LEADERBOARD_API_PATH = DELETE_USER_MINIPROGRAM_LEADERBOARD_API_PATH;
12729
+ exports.DETAIL_USER_MINIPROGRAM_API_PATH = DETAIL_USER_MINIPROGRAM_API_PATH;
12730
+ exports.DETAIL_USER_MINIPROGRAM_LEADERBOARD_API_PATH = DETAIL_USER_MINIPROGRAM_LEADERBOARD_API_PATH;
12731
+ exports.DEVELOPER_ENTITY_LIST_API_PATH = DEVELOPER_ENTITY_LIST_API_PATH;
12732
+ exports.DEVELOPER_ENTITY_SWITCH_API_PATH = DEVELOPER_ENTITY_SWITCH_API_PATH;
12733
+ exports.LIST_USER_MINIPROGRAM_API_PATH = LIST_USER_MINIPROGRAM_API_PATH;
12734
+ exports.LIST_USER_MINIPROGRAM_LEADERBOARD_API_PATH = LIST_USER_MINIPROGRAM_LEADERBOARD_API_PATH;
12735
+ exports.LIST_USER_MINIPROGRAM_VERSION_API_PATH = LIST_USER_MINIPROGRAM_VERSION_API_PATH;
12736
+ exports.MINIAPP_UPLOAD_BATCH_SIZE = MINIAPP_UPLOAD_BATCH_SIZE;
12737
+ exports.MINIAPP_UPLOAD_SCOPE = MINIAPP_UPLOAD_SCOPE;
12738
+ exports.MINI_PROGRAM_PERMISSION_KEYS = MINI_PROGRAM_PERMISSION_KEYS;
12739
+ exports.PRECHECK_USER_MINIPROGRAM_VERSION_API_PATH = PRECHECK_USER_MINIPROGRAM_VERSION_API_PATH;
12740
+ exports.Parser = Parser;
12741
+ exports.RELEASE_USER_MINIPROGRAM_VERSION_API_PATH = RELEASE_USER_MINIPROGRAM_VERSION_API_PATH;
12742
+ exports.REOPEN_USER_MINIPROGRAM_API_PATH = REOPEN_USER_MINIPROGRAM_API_PATH;
12743
+ exports.SUBMIT_USER_MINIPROGRAM_AUDIT_API_PATH = SUBMIT_USER_MINIPROGRAM_AUDIT_API_PATH;
12744
+ exports.TAKE_DOWN_USER_MINIPROGRAM_API_PATH = TAKE_DOWN_USER_MINIPROGRAM_API_PATH;
12745
+ exports.UPDATE_SQUARE_DISPLAY_API_PATH = UPDATE_SQUARE_DISPLAY_API_PATH;
12746
+ exports.UPDATE_USER_MINIPROGRAM_PREVIEW_ALLOWLIST_API_PATH = UPDATE_USER_MINIPROGRAM_PREVIEW_ALLOWLIST_API_PATH;
12747
+ exports.USER_MINIPROGRAM_ACCESS_STATUS_API_PATH = USER_MINIPROGRAM_ACCESS_STATUS_API_PATH;
12748
+ exports.USER_MINIPROGRAM_PREVIEW_ALLOWLIST_API_PATH = USER_MINIPROGRAM_PREVIEW_ALLOWLIST_API_PATH;
12749
+ exports.USER_MINIPROGRAM_VERSION_PREVIEW_INFO_API_PATH = USER_MINIPROGRAM_VERSION_PREVIEW_INFO_API_PATH;
12750
+ exports.WITHDRAW_USER_MINIPROGRAM_VERSION_API_PATH = WITHDRAW_USER_MINIPROGRAM_VERSION_API_PATH;
12751
+ exports.areMiniappPlatformsEqual = areMiniappPlatformsEqual;
12752
+ exports.areMiniappWindowsEqual = areMiniappWindowsEqual;
12753
+ exports.composeMiniappRuntimePermissions = composeMiniappRuntimePermissions;
12754
+ exports.createMiniappArtifactFileHeader = createMiniappArtifactFileHeader;
12755
+ exports.createMiniappArtifactSignatureHeader = createMiniappArtifactSignatureHeader;
12756
+ exports.createMiniappPlatformCspEnv = createMiniappPlatformCspEnv;
12757
+ exports.getMissingPermissionsWarning = getMissingPermissionsWarning;
12758
+ exports.hasMiniappDesktopPlatform = hasMiniappDesktopPlatform;
12759
+ exports.isValidMiniappManifestVersion = isValidMiniappManifestVersion;
12760
+ exports.normalizeBasicInfoName = normalizeBasicInfoName;
12761
+ exports.normalizeRelativePath = normalizeRelativePath;
12762
+ exports.parseMiniProgramRuntimePermissions = parseMiniProgramRuntimePermissions;
12763
+ exports.parseMiniappBasicInfo = parseMiniappBasicInfo;
12764
+ exports.parseMiniappManifestJson = parseMiniappManifestJson;
12765
+ exports.prepareMiniappArtifactFiles = prepareMiniappArtifactFiles;
12766
+ exports.readMiniappBindAppIdsFromPackageJson = readMiniappBindAppIdsFromPackageJson;
12767
+ exports.readMiniappPermissionsFromPackageJson = readMiniappPermissionsFromPackageJson;
12768
+ exports.readMiniappPlatformsFromPackageJson = readMiniappPlatformsFromPackageJson;
12769
+ exports.readMiniappWindowFromPackageJson = readMiniappWindowFromPackageJson;
12770
+ exports.relativePathContainsNodeModulesSegment = relativePathContainsNodeModulesSegment;
12771
+ exports.requireSemver = requireSemver;
12772
+ exports.resolveMiniappSdkVersion = resolveMiniappSdkVersion;
12773
+ exports.resolveMiniappUploadSessionFiles = resolveMiniappUploadSessionFiles;
12774
+ exports.shouldSkipMiniappPlatformCspFromEnv = shouldSkipMiniappPlatformCspFromEnv;
12775
+ exports.shouldUploadDistFile = shouldUploadDistFile;
12776
+ exports.validateBasicInfoPath = validateBasicInfoPath;
12777
+ exports.validateMiniappCompanionFileReceipts = validateMiniappCompanionFileReceipts;
12778
+ exports.validateMiniappManifestForDeploy = validateMiniappManifestForDeploy;
12779
+ exports.validateMiniappUploadPathLengths = validateMiniappUploadPathLengths;
12780
+ exports.validateMiniappUploadSizeBudgets = validateMiniappUploadSizeBudgets;
12781
+ exports.withMiniappPlatformCspEnv = withMiniappPlatformCspEnv;