@cnguu/vite-plugin-uni-cdn 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1233 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs/promises');
4
+ const path = require('node:path');
5
+ const vite = require('vite');
6
+
7
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
8
+
9
+ const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
10
+ const path__default = /*#__PURE__*/_interopDefaultCompat(path);
11
+
12
+ const ANSI_BACKGROUND_OFFSET = 10;
13
+
14
+ const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`;
15
+
16
+ const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`;
17
+
18
+ const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`;
19
+
20
+ const styles$1 = {
21
+ modifier: {
22
+ reset: [0, 0],
23
+ // 21 isn't widely supported and 22 does the same thing
24
+ bold: [1, 22],
25
+ dim: [2, 22],
26
+ italic: [3, 23],
27
+ underline: [4, 24],
28
+ overline: [53, 55],
29
+ inverse: [7, 27],
30
+ hidden: [8, 28],
31
+ strikethrough: [9, 29],
32
+ },
33
+ color: {
34
+ black: [30, 39],
35
+ red: [31, 39],
36
+ green: [32, 39],
37
+ yellow: [33, 39],
38
+ blue: [34, 39],
39
+ magenta: [35, 39],
40
+ cyan: [36, 39],
41
+ white: [37, 39],
42
+
43
+ // Bright color
44
+ blackBright: [90, 39],
45
+ gray: [90, 39], // Alias of `blackBright`
46
+ grey: [90, 39], // Alias of `blackBright`
47
+ redBright: [91, 39],
48
+ greenBright: [92, 39],
49
+ yellowBright: [93, 39],
50
+ blueBright: [94, 39],
51
+ magentaBright: [95, 39],
52
+ cyanBright: [96, 39],
53
+ whiteBright: [97, 39],
54
+ },
55
+ bgColor: {
56
+ bgBlack: [40, 49],
57
+ bgRed: [41, 49],
58
+ bgGreen: [42, 49],
59
+ bgYellow: [43, 49],
60
+ bgBlue: [44, 49],
61
+ bgMagenta: [45, 49],
62
+ bgCyan: [46, 49],
63
+ bgWhite: [47, 49],
64
+
65
+ // Bright color
66
+ bgBlackBright: [100, 49],
67
+ bgGray: [100, 49], // Alias of `bgBlackBright`
68
+ bgGrey: [100, 49], // Alias of `bgBlackBright`
69
+ bgRedBright: [101, 49],
70
+ bgGreenBright: [102, 49],
71
+ bgYellowBright: [103, 49],
72
+ bgBlueBright: [104, 49],
73
+ bgMagentaBright: [105, 49],
74
+ bgCyanBright: [106, 49],
75
+ bgWhiteBright: [107, 49],
76
+ },
77
+ };
78
+
79
+ Object.keys(styles$1.modifier);
80
+ const foregroundColorNames = Object.keys(styles$1.color);
81
+ const backgroundColorNames = Object.keys(styles$1.bgColor);
82
+ [...foregroundColorNames, ...backgroundColorNames];
83
+
84
+ function assembleStyles() {
85
+ const codes = new Map();
86
+
87
+ for (const [groupName, group] of Object.entries(styles$1)) {
88
+ for (const [styleName, style] of Object.entries(group)) {
89
+ styles$1[styleName] = {
90
+ open: `\u001B[${style[0]}m`,
91
+ close: `\u001B[${style[1]}m`,
92
+ };
93
+
94
+ group[styleName] = styles$1[styleName];
95
+
96
+ codes.set(style[0], style[1]);
97
+ }
98
+
99
+ Object.defineProperty(styles$1, groupName, {
100
+ value: group,
101
+ enumerable: false,
102
+ });
103
+ }
104
+
105
+ Object.defineProperty(styles$1, 'codes', {
106
+ value: codes,
107
+ enumerable: false,
108
+ });
109
+
110
+ styles$1.color.close = '\u001B[39m';
111
+ styles$1.bgColor.close = '\u001B[49m';
112
+
113
+ styles$1.color.ansi = wrapAnsi16();
114
+ styles$1.color.ansi256 = wrapAnsi256();
115
+ styles$1.color.ansi16m = wrapAnsi16m();
116
+ styles$1.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
117
+ styles$1.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
118
+ styles$1.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
119
+
120
+ // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js
121
+ Object.defineProperties(styles$1, {
122
+ rgbToAnsi256: {
123
+ value(red, green, blue) {
124
+ // We use the extended greyscale palette here, with the exception of
125
+ // black and white. normal palette only has 4 greyscale shades.
126
+ if (red === green && green === blue) {
127
+ if (red < 8) {
128
+ return 16;
129
+ }
130
+
131
+ if (red > 248) {
132
+ return 231;
133
+ }
134
+
135
+ return Math.round(((red - 8) / 247) * 24) + 232;
136
+ }
137
+
138
+ return 16
139
+ + (36 * Math.round(red / 255 * 5))
140
+ + (6 * Math.round(green / 255 * 5))
141
+ + Math.round(blue / 255 * 5);
142
+ },
143
+ enumerable: false,
144
+ },
145
+ hexToRgb: {
146
+ value(hex) {
147
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
148
+ if (!matches) {
149
+ return [0, 0, 0];
150
+ }
151
+
152
+ let [colorString] = matches;
153
+
154
+ if (colorString.length === 3) {
155
+ colorString = [...colorString].map(character => character + character).join('');
156
+ }
157
+
158
+ const integer = Number.parseInt(colorString, 16);
159
+
160
+ return [
161
+ /* eslint-disable no-bitwise */
162
+ (integer >> 16) & 0xFF,
163
+ (integer >> 8) & 0xFF,
164
+ integer & 0xFF,
165
+ /* eslint-enable no-bitwise */
166
+ ];
167
+ },
168
+ enumerable: false,
169
+ },
170
+ hexToAnsi256: {
171
+ value: hex => styles$1.rgbToAnsi256(...styles$1.hexToRgb(hex)),
172
+ enumerable: false,
173
+ },
174
+ ansi256ToAnsi: {
175
+ value(code) {
176
+ if (code < 8) {
177
+ return 30 + code;
178
+ }
179
+
180
+ if (code < 16) {
181
+ return 90 + (code - 8);
182
+ }
183
+
184
+ let red;
185
+ let green;
186
+ let blue;
187
+
188
+ if (code >= 232) {
189
+ red = (((code - 232) * 10) + 8) / 255;
190
+ green = red;
191
+ blue = red;
192
+ } else {
193
+ code -= 16;
194
+
195
+ const remainder = code % 36;
196
+
197
+ red = Math.floor(code / 36) / 5;
198
+ green = Math.floor(remainder / 6) / 5;
199
+ blue = (remainder % 6) / 5;
200
+ }
201
+
202
+ const value = Math.max(red, green, blue) * 2;
203
+
204
+ if (value === 0) {
205
+ return 30;
206
+ }
207
+
208
+ // eslint-disable-next-line no-bitwise
209
+ let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));
210
+
211
+ if (value === 2) {
212
+ result += 60;
213
+ }
214
+
215
+ return result;
216
+ },
217
+ enumerable: false,
218
+ },
219
+ rgbToAnsi: {
220
+ value: (red, green, blue) => styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(red, green, blue)),
221
+ enumerable: false,
222
+ },
223
+ hexToAnsi: {
224
+ value: hex => styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(hex)),
225
+ enumerable: false,
226
+ },
227
+ });
228
+
229
+ return styles$1;
230
+ }
231
+
232
+ const ansiStyles = assembleStyles();
233
+
234
+ /* eslint-env browser */
235
+
236
+ const level = (() => {
237
+ if (!('navigator' in globalThis)) {
238
+ return 0;
239
+ }
240
+
241
+ if (globalThis.navigator.userAgentData) {
242
+ const brand = navigator.userAgentData.brands.find(({brand}) => brand === 'Chromium');
243
+ if (brand && brand.version > 93) {
244
+ return 3;
245
+ }
246
+ }
247
+
248
+ if (/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)) {
249
+ return 1;
250
+ }
251
+
252
+ return 0;
253
+ })();
254
+
255
+ const colorSupport = level !== 0 && {
256
+ level};
257
+
258
+ const supportsColor = {
259
+ stdout: colorSupport,
260
+ stderr: colorSupport,
261
+ };
262
+
263
+ // TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.
264
+ function stringReplaceAll(string, substring, replacer) {
265
+ let index = string.indexOf(substring);
266
+ if (index === -1) {
267
+ return string;
268
+ }
269
+
270
+ const substringLength = substring.length;
271
+ let endIndex = 0;
272
+ let returnValue = '';
273
+ do {
274
+ returnValue += string.slice(endIndex, index) + substring + replacer;
275
+ endIndex = index + substringLength;
276
+ index = string.indexOf(substring, endIndex);
277
+ } while (index !== -1);
278
+
279
+ returnValue += string.slice(endIndex);
280
+ return returnValue;
281
+ }
282
+
283
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
284
+ let endIndex = 0;
285
+ let returnValue = '';
286
+ do {
287
+ const gotCR = string[index - 1] === '\r';
288
+ returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
289
+ endIndex = index + 1;
290
+ index = string.indexOf('\n', endIndex);
291
+ } while (index !== -1);
292
+
293
+ returnValue += string.slice(endIndex);
294
+ return returnValue;
295
+ }
296
+
297
+ const {stdout: stdoutColor, stderr: stderrColor} = supportsColor;
298
+
299
+ const GENERATOR = Symbol('GENERATOR');
300
+ const STYLER = Symbol('STYLER');
301
+ const IS_EMPTY = Symbol('IS_EMPTY');
302
+
303
+ // `supportsColor.level` → `ansiStyles.color[name]` mapping
304
+ const levelMapping = [
305
+ 'ansi',
306
+ 'ansi',
307
+ 'ansi256',
308
+ 'ansi16m',
309
+ ];
310
+
311
+ const styles = Object.create(null);
312
+
313
+ const applyOptions = (object, options = {}) => {
314
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
315
+ throw new Error('The `level` option should be an integer from 0 to 3');
316
+ }
317
+
318
+ // Detect level if not set manually
319
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
320
+ object.level = options.level === undefined ? colorLevel : options.level;
321
+ };
322
+
323
+ const chalkFactory = options => {
324
+ const chalk = (...strings) => strings.join(' ');
325
+ applyOptions(chalk, options);
326
+
327
+ Object.setPrototypeOf(chalk, createChalk.prototype);
328
+
329
+ return chalk;
330
+ };
331
+
332
+ function createChalk(options) {
333
+ return chalkFactory(options);
334
+ }
335
+
336
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
337
+
338
+ for (const [styleName, style] of Object.entries(ansiStyles)) {
339
+ styles[styleName] = {
340
+ get() {
341
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
342
+ Object.defineProperty(this, styleName, {value: builder});
343
+ return builder;
344
+ },
345
+ };
346
+ }
347
+
348
+ styles.visible = {
349
+ get() {
350
+ const builder = createBuilder(this, this[STYLER], true);
351
+ Object.defineProperty(this, 'visible', {value: builder});
352
+ return builder;
353
+ },
354
+ };
355
+
356
+ const getModelAnsi = (model, level, type, ...arguments_) => {
357
+ if (model === 'rgb') {
358
+ if (level === 'ansi16m') {
359
+ return ansiStyles[type].ansi16m(...arguments_);
360
+ }
361
+
362
+ if (level === 'ansi256') {
363
+ return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));
364
+ }
365
+
366
+ return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));
367
+ }
368
+
369
+ if (model === 'hex') {
370
+ return getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_));
371
+ }
372
+
373
+ return ansiStyles[type][model](...arguments_);
374
+ };
375
+
376
+ const usedModels = ['rgb', 'hex', 'ansi256'];
377
+
378
+ for (const model of usedModels) {
379
+ styles[model] = {
380
+ get() {
381
+ const {level} = this;
382
+ return function (...arguments_) {
383
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);
384
+ return createBuilder(this, styler, this[IS_EMPTY]);
385
+ };
386
+ },
387
+ };
388
+
389
+ const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
390
+ styles[bgModel] = {
391
+ get() {
392
+ const {level} = this;
393
+ return function (...arguments_) {
394
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);
395
+ return createBuilder(this, styler, this[IS_EMPTY]);
396
+ };
397
+ },
398
+ };
399
+ }
400
+
401
+ const proto = Object.defineProperties(() => {}, {
402
+ ...styles,
403
+ level: {
404
+ enumerable: true,
405
+ get() {
406
+ return this[GENERATOR].level;
407
+ },
408
+ set(level) {
409
+ this[GENERATOR].level = level;
410
+ },
411
+ },
412
+ });
413
+
414
+ const createStyler = (open, close, parent) => {
415
+ let openAll;
416
+ let closeAll;
417
+ if (parent === undefined) {
418
+ openAll = open;
419
+ closeAll = close;
420
+ } else {
421
+ openAll = parent.openAll + open;
422
+ closeAll = close + parent.closeAll;
423
+ }
424
+
425
+ return {
426
+ open,
427
+ close,
428
+ openAll,
429
+ closeAll,
430
+ parent,
431
+ };
432
+ };
433
+
434
+ const createBuilder = (self, _styler, _isEmpty) => {
435
+ // Single argument is hot path, implicit coercion is faster than anything
436
+ // eslint-disable-next-line no-implicit-coercion
437
+ const builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
438
+
439
+ // We alter the prototype because we must return a function, but there is
440
+ // no way to create a function with a different prototype
441
+ Object.setPrototypeOf(builder, proto);
442
+
443
+ builder[GENERATOR] = self;
444
+ builder[STYLER] = _styler;
445
+ builder[IS_EMPTY] = _isEmpty;
446
+
447
+ return builder;
448
+ };
449
+
450
+ const applyStyle = (self, string) => {
451
+ if (self.level <= 0 || !string) {
452
+ return self[IS_EMPTY] ? '' : string;
453
+ }
454
+
455
+ let styler = self[STYLER];
456
+
457
+ if (styler === undefined) {
458
+ return string;
459
+ }
460
+
461
+ const {openAll, closeAll} = styler;
462
+ if (string.includes('\u001B')) {
463
+ while (styler !== undefined) {
464
+ // Replace any instances already present with a re-opening code
465
+ // otherwise only the part of the string until said closing code
466
+ // will be colored, and the rest will simply be 'plain'.
467
+ string = stringReplaceAll(string, styler.close, styler.open);
468
+
469
+ styler = styler.parent;
470
+ }
471
+ }
472
+
473
+ // We can move both next actions out of loop, because remaining actions in loop won't have
474
+ // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
475
+ // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
476
+ const lfIndex = string.indexOf('\n');
477
+ if (lfIndex !== -1) {
478
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
479
+ }
480
+
481
+ return openAll + string + closeAll;
482
+ };
483
+
484
+ Object.defineProperties(createChalk.prototype, styles);
485
+
486
+ const chalk = createChalk();
487
+ createChalk({level: stderrColor ? stderrColor.level : 0});
488
+
489
+ const LogLevels = {
490
+ fatal: 0,
491
+ error: 0,
492
+ warn: 1,
493
+ log: 2,
494
+ info: 3,
495
+ success: 3,
496
+ fail: 3,
497
+ debug: 4,
498
+ trace: 5,
499
+ verbose: Number.POSITIVE_INFINITY
500
+ };
501
+ const LogTypes = {
502
+ // Silent
503
+ silent: {
504
+ level: -1
505
+ },
506
+ // Level 0
507
+ fatal: {
508
+ level: LogLevels.fatal
509
+ },
510
+ error: {
511
+ level: LogLevels.error
512
+ },
513
+ // Level 1
514
+ warn: {
515
+ level: LogLevels.warn
516
+ },
517
+ // Level 2
518
+ log: {
519
+ level: LogLevels.log
520
+ },
521
+ // Level 3
522
+ info: {
523
+ level: LogLevels.info
524
+ },
525
+ success: {
526
+ level: LogLevels.success
527
+ },
528
+ fail: {
529
+ level: LogLevels.fail
530
+ },
531
+ ready: {
532
+ level: LogLevels.info
533
+ },
534
+ start: {
535
+ level: LogLevels.info
536
+ },
537
+ box: {
538
+ level: LogLevels.info
539
+ },
540
+ // Level 4
541
+ debug: {
542
+ level: LogLevels.debug
543
+ },
544
+ // Level 5
545
+ trace: {
546
+ level: LogLevels.trace
547
+ },
548
+ // Verbose
549
+ verbose: {
550
+ level: LogLevels.verbose
551
+ }
552
+ };
553
+
554
+ function isPlainObject$1(value) {
555
+ if (value === null || typeof value !== "object") {
556
+ return false;
557
+ }
558
+ const prototype = Object.getPrototypeOf(value);
559
+ if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
560
+ return false;
561
+ }
562
+ if (Symbol.iterator in value) {
563
+ return false;
564
+ }
565
+ if (Symbol.toStringTag in value) {
566
+ return Object.prototype.toString.call(value) === "[object Module]";
567
+ }
568
+ return true;
569
+ }
570
+
571
+ function _defu(baseObject, defaults, namespace = ".", merger) {
572
+ if (!isPlainObject$1(defaults)) {
573
+ return _defu(baseObject, {}, namespace);
574
+ }
575
+ const object = Object.assign({}, defaults);
576
+ for (const key in baseObject) {
577
+ if (key === "__proto__" || key === "constructor") {
578
+ continue;
579
+ }
580
+ const value = baseObject[key];
581
+ if (value === null || value === void 0) {
582
+ continue;
583
+ }
584
+ if (Array.isArray(value) && Array.isArray(object[key])) {
585
+ object[key] = [...value, ...object[key]];
586
+ } else if (isPlainObject$1(value) && isPlainObject$1(object[key])) {
587
+ object[key] = _defu(
588
+ value,
589
+ object[key],
590
+ (namespace ? `${namespace}.` : "") + key.toString());
591
+ } else {
592
+ object[key] = value;
593
+ }
594
+ }
595
+ return object;
596
+ }
597
+ function createDefu(merger) {
598
+ return (...arguments_) => (
599
+ // eslint-disable-next-line unicorn/no-array-reduce
600
+ arguments_.reduce((p, c) => _defu(p, c, ""), {})
601
+ );
602
+ }
603
+ const defu = createDefu();
604
+
605
+ function isPlainObject(obj) {
606
+ return Object.prototype.toString.call(obj) === "[object Object]";
607
+ }
608
+ function isLogObj(arg) {
609
+ if (!isPlainObject(arg)) {
610
+ return false;
611
+ }
612
+ if (!arg.message && !arg.args) {
613
+ return false;
614
+ }
615
+ if (arg.stack) {
616
+ return false;
617
+ }
618
+ return true;
619
+ }
620
+
621
+ let paused = false;
622
+ const queue = [];
623
+ class Consola {
624
+ options;
625
+ _lastLog;
626
+ _mockFn;
627
+ /**
628
+ * Creates an instance of Consola with specified options or defaults.
629
+ *
630
+ * @param {Partial<ConsolaOptions>} [options={}] - Configuration options for the Consola instance.
631
+ */
632
+ constructor(options = {}) {
633
+ const types = options.types || LogTypes;
634
+ this.options = defu(
635
+ {
636
+ ...options,
637
+ defaults: { ...options.defaults },
638
+ level: _normalizeLogLevel(options.level, types),
639
+ reporters: [...options.reporters || []]
640
+ },
641
+ {
642
+ types: LogTypes,
643
+ throttle: 1e3,
644
+ throttleMin: 5,
645
+ formatOptions: {
646
+ date: true,
647
+ colors: false,
648
+ compact: true
649
+ }
650
+ }
651
+ );
652
+ for (const type in types) {
653
+ const defaults = {
654
+ type,
655
+ ...this.options.defaults,
656
+ ...types[type]
657
+ };
658
+ this[type] = this._wrapLogFn(defaults);
659
+ this[type].raw = this._wrapLogFn(
660
+ defaults,
661
+ true
662
+ );
663
+ }
664
+ if (this.options.mockFn) {
665
+ this.mockTypes();
666
+ }
667
+ this._lastLog = {};
668
+ }
669
+ /**
670
+ * Gets the current log level of the Consola instance.
671
+ *
672
+ * @returns {number} The current log level.
673
+ */
674
+ get level() {
675
+ return this.options.level;
676
+ }
677
+ /**
678
+ * Sets the minimum log level that will be output by the instance.
679
+ *
680
+ * @param {number} level - The new log level to set.
681
+ */
682
+ set level(level) {
683
+ this.options.level = _normalizeLogLevel(
684
+ level,
685
+ this.options.types,
686
+ this.options.level
687
+ );
688
+ }
689
+ /**
690
+ * Displays a prompt to the user and returns the response.
691
+ * Throw an error if `prompt` is not supported by the current configuration.
692
+ *
693
+ * @template T
694
+ * @param {string} message - The message to display in the prompt.
695
+ * @param {T} [opts] - Optional options for the prompt. See {@link PromptOptions}.
696
+ * @returns {promise<T>} A promise that infer with the prompt options. See {@link PromptOptions}.
697
+ */
698
+ prompt(message, opts) {
699
+ if (!this.options.prompt) {
700
+ throw new Error("prompt is not supported!");
701
+ }
702
+ return this.options.prompt(message, opts);
703
+ }
704
+ /**
705
+ * Creates a new instance of Consola, inheriting options from the current instance, with possible overrides.
706
+ *
707
+ * @param {Partial<ConsolaOptions>} options - Optional overrides for the new instance. See {@link ConsolaOptions}.
708
+ * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
709
+ */
710
+ create(options) {
711
+ const instance = new Consola({
712
+ ...this.options,
713
+ ...options
714
+ });
715
+ if (this._mockFn) {
716
+ instance.mockTypes(this._mockFn);
717
+ }
718
+ return instance;
719
+ }
720
+ /**
721
+ * Creates a new Consola instance with the specified default log object properties.
722
+ *
723
+ * @param {InputLogObject} defaults - Default properties to include in any log from the new instance. See {@link InputLogObject}.
724
+ * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
725
+ */
726
+ withDefaults(defaults) {
727
+ return this.create({
728
+ ...this.options,
729
+ defaults: {
730
+ ...this.options.defaults,
731
+ ...defaults
732
+ }
733
+ });
734
+ }
735
+ /**
736
+ * Creates a new Consola instance with a specified tag, which will be included in every log.
737
+ *
738
+ * @param {string} tag - The tag to include in each log of the new instance.
739
+ * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
740
+ */
741
+ withTag(tag) {
742
+ return this.withDefaults({
743
+ tag: this.options.defaults.tag ? this.options.defaults.tag + ":" + tag : tag
744
+ });
745
+ }
746
+ /**
747
+ * Adds a custom reporter to the Consola instance.
748
+ * Reporters will be called for each log message, depending on their implementation and log level.
749
+ *
750
+ * @param {ConsolaReporter} reporter - The reporter to add. See {@link ConsolaReporter}.
751
+ * @returns {Consola} The current Consola instance.
752
+ */
753
+ addReporter(reporter) {
754
+ this.options.reporters.push(reporter);
755
+ return this;
756
+ }
757
+ /**
758
+ * Removes a custom reporter from the Consola instance.
759
+ * If no reporter is specified, all reporters will be removed.
760
+ *
761
+ * @param {ConsolaReporter} reporter - The reporter to remove. See {@link ConsolaReporter}.
762
+ * @returns {Consola} The current Consola instance.
763
+ */
764
+ removeReporter(reporter) {
765
+ if (reporter) {
766
+ const i = this.options.reporters.indexOf(reporter);
767
+ if (i !== -1) {
768
+ return this.options.reporters.splice(i, 1);
769
+ }
770
+ } else {
771
+ this.options.reporters.splice(0);
772
+ }
773
+ return this;
774
+ }
775
+ /**
776
+ * Replaces all reporters of the Consola instance with the specified array of reporters.
777
+ *
778
+ * @param {ConsolaReporter[]} reporters - The new reporters to set. See {@link ConsolaReporter}.
779
+ * @returns {Consola} The current Consola instance.
780
+ */
781
+ setReporters(reporters) {
782
+ this.options.reporters = Array.isArray(reporters) ? reporters : [reporters];
783
+ return this;
784
+ }
785
+ wrapAll() {
786
+ this.wrapConsole();
787
+ this.wrapStd();
788
+ }
789
+ restoreAll() {
790
+ this.restoreConsole();
791
+ this.restoreStd();
792
+ }
793
+ /**
794
+ * Overrides console methods with Consola logging methods for consistent logging.
795
+ */
796
+ wrapConsole() {
797
+ for (const type in this.options.types) {
798
+ if (!console["__" + type]) {
799
+ console["__" + type] = console[type];
800
+ }
801
+ console[type] = this[type].raw;
802
+ }
803
+ }
804
+ /**
805
+ * Restores the original console methods, removing Consola overrides.
806
+ */
807
+ restoreConsole() {
808
+ for (const type in this.options.types) {
809
+ if (console["__" + type]) {
810
+ console[type] = console["__" + type];
811
+ delete console["__" + type];
812
+ }
813
+ }
814
+ }
815
+ /**
816
+ * Overrides standard output and error streams to redirect them through Consola.
817
+ */
818
+ wrapStd() {
819
+ this._wrapStream(this.options.stdout, "log");
820
+ this._wrapStream(this.options.stderr, "log");
821
+ }
822
+ _wrapStream(stream, type) {
823
+ if (!stream) {
824
+ return;
825
+ }
826
+ if (!stream.__write) {
827
+ stream.__write = stream.write;
828
+ }
829
+ stream.write = (data) => {
830
+ this[type].raw(String(data).trim());
831
+ };
832
+ }
833
+ /**
834
+ * Restores the original standard output and error streams, removing the Consola redirection.
835
+ */
836
+ restoreStd() {
837
+ this._restoreStream(this.options.stdout);
838
+ this._restoreStream(this.options.stderr);
839
+ }
840
+ _restoreStream(stream) {
841
+ if (!stream) {
842
+ return;
843
+ }
844
+ if (stream.__write) {
845
+ stream.write = stream.__write;
846
+ delete stream.__write;
847
+ }
848
+ }
849
+ /**
850
+ * Pauses logging, queues incoming logs until resumed.
851
+ */
852
+ pauseLogs() {
853
+ paused = true;
854
+ }
855
+ /**
856
+ * Resumes logging, processing any queued logs.
857
+ */
858
+ resumeLogs() {
859
+ paused = false;
860
+ const _queue = queue.splice(0);
861
+ for (const item of _queue) {
862
+ item[0]._logFn(item[1], item[2]);
863
+ }
864
+ }
865
+ /**
866
+ * Replaces logging methods with mocks if a mock function is provided.
867
+ *
868
+ * @param {ConsolaOptions["mockFn"]} mockFn - The function to use for mocking logging methods. See {@link ConsolaOptions["mockFn"]}.
869
+ */
870
+ mockTypes(mockFn) {
871
+ const _mockFn = mockFn || this.options.mockFn;
872
+ this._mockFn = _mockFn;
873
+ if (typeof _mockFn !== "function") {
874
+ return;
875
+ }
876
+ for (const type in this.options.types) {
877
+ this[type] = _mockFn(type, this.options.types[type]) || this[type];
878
+ this[type].raw = this[type];
879
+ }
880
+ }
881
+ _wrapLogFn(defaults, isRaw) {
882
+ return (...args) => {
883
+ if (paused) {
884
+ queue.push([this, defaults, args, isRaw]);
885
+ return;
886
+ }
887
+ return this._logFn(defaults, args, isRaw);
888
+ };
889
+ }
890
+ _logFn(defaults, args, isRaw) {
891
+ if ((defaults.level || 0) > this.level) {
892
+ return false;
893
+ }
894
+ const logObj = {
895
+ date: /* @__PURE__ */ new Date(),
896
+ args: [],
897
+ ...defaults,
898
+ level: _normalizeLogLevel(defaults.level, this.options.types)
899
+ };
900
+ if (!isRaw && args.length === 1 && isLogObj(args[0])) {
901
+ Object.assign(logObj, args[0]);
902
+ } else {
903
+ logObj.args = [...args];
904
+ }
905
+ if (logObj.message) {
906
+ logObj.args.unshift(logObj.message);
907
+ delete logObj.message;
908
+ }
909
+ if (logObj.additional) {
910
+ if (!Array.isArray(logObj.additional)) {
911
+ logObj.additional = logObj.additional.split("\n");
912
+ }
913
+ logObj.args.push("\n" + logObj.additional.join("\n"));
914
+ delete logObj.additional;
915
+ }
916
+ logObj.type = typeof logObj.type === "string" ? logObj.type.toLowerCase() : "log";
917
+ logObj.tag = typeof logObj.tag === "string" ? logObj.tag : "";
918
+ const resolveLog = (newLog = false) => {
919
+ const repeated = (this._lastLog.count || 0) - this.options.throttleMin;
920
+ if (this._lastLog.object && repeated > 0) {
921
+ const args2 = [...this._lastLog.object.args];
922
+ if (repeated > 1) {
923
+ args2.push(`(repeated ${repeated} times)`);
924
+ }
925
+ this._log({ ...this._lastLog.object, args: args2 });
926
+ this._lastLog.count = 1;
927
+ }
928
+ if (newLog) {
929
+ this._lastLog.object = logObj;
930
+ this._log(logObj);
931
+ }
932
+ };
933
+ clearTimeout(this._lastLog.timeout);
934
+ const diffTime = this._lastLog.time && logObj.date ? logObj.date.getTime() - this._lastLog.time.getTime() : 0;
935
+ this._lastLog.time = logObj.date;
936
+ if (diffTime < this.options.throttle) {
937
+ try {
938
+ const serializedLog = JSON.stringify([
939
+ logObj.type,
940
+ logObj.tag,
941
+ logObj.args
942
+ ]);
943
+ const isSameLog = this._lastLog.serialized === serializedLog;
944
+ this._lastLog.serialized = serializedLog;
945
+ if (isSameLog) {
946
+ this._lastLog.count = (this._lastLog.count || 0) + 1;
947
+ if (this._lastLog.count > this.options.throttleMin) {
948
+ this._lastLog.timeout = setTimeout(
949
+ resolveLog,
950
+ this.options.throttle
951
+ );
952
+ return;
953
+ }
954
+ }
955
+ } catch {
956
+ }
957
+ }
958
+ resolveLog(true);
959
+ }
960
+ _log(logObj) {
961
+ for (const reporter of this.options.reporters) {
962
+ reporter.log(logObj, {
963
+ options: this.options
964
+ });
965
+ }
966
+ }
967
+ }
968
+ function _normalizeLogLevel(input, types = {}, defaultLevel = 3) {
969
+ if (input === void 0) {
970
+ return defaultLevel;
971
+ }
972
+ if (typeof input === "number") {
973
+ return input;
974
+ }
975
+ if (types[input] && types[input].level !== void 0) {
976
+ return types[input].level;
977
+ }
978
+ return defaultLevel;
979
+ }
980
+ Consola.prototype.add = Consola.prototype.addReporter;
981
+ Consola.prototype.remove = Consola.prototype.removeReporter;
982
+ Consola.prototype.clear = Consola.prototype.removeReporter;
983
+ Consola.prototype.withScope = Consola.prototype.withTag;
984
+ Consola.prototype.mock = Consola.prototype.mockTypes;
985
+ Consola.prototype.pause = Consola.prototype.pauseLogs;
986
+ Consola.prototype.resume = Consola.prototype.resumeLogs;
987
+ function createConsola$1(options = {}) {
988
+ return new Consola(options);
989
+ }
990
+
991
+ class BrowserReporter {
992
+ options;
993
+ defaultColor;
994
+ levelColorMap;
995
+ typeColorMap;
996
+ constructor(options) {
997
+ this.options = { ...options };
998
+ this.defaultColor = "#7f8c8d";
999
+ this.levelColorMap = {
1000
+ 0: "#c0392b",
1001
+ // Red
1002
+ 1: "#f39c12",
1003
+ // Yellow
1004
+ 3: "#00BCD4"
1005
+ // Cyan
1006
+ };
1007
+ this.typeColorMap = {
1008
+ success: "#2ecc71"
1009
+ // Green
1010
+ };
1011
+ }
1012
+ _getLogFn(level) {
1013
+ if (level < 1) {
1014
+ return console.__error || console.error;
1015
+ }
1016
+ if (level === 1) {
1017
+ return console.__warn || console.warn;
1018
+ }
1019
+ return console.__log || console.log;
1020
+ }
1021
+ log(logObj) {
1022
+ const consoleLogFn = this._getLogFn(logObj.level);
1023
+ const type = logObj.type === "log" ? "" : logObj.type;
1024
+ const tag = logObj.tag || "";
1025
+ const color = this.typeColorMap[logObj.type] || this.levelColorMap[logObj.level] || this.defaultColor;
1026
+ const style = `
1027
+ background: ${color};
1028
+ border-radius: 0.5em;
1029
+ color: white;
1030
+ font-weight: bold;
1031
+ padding: 2px 0.5em;
1032
+ `;
1033
+ const badge = `%c${[tag, type].filter(Boolean).join(":")}`;
1034
+ if (typeof logObj.args[0] === "string") {
1035
+ consoleLogFn(
1036
+ `${badge}%c ${logObj.args[0]}`,
1037
+ style,
1038
+ // Empty string as style resets to default console style
1039
+ "",
1040
+ ...logObj.args.slice(1)
1041
+ );
1042
+ } else {
1043
+ consoleLogFn(badge, style, ...logObj.args);
1044
+ }
1045
+ }
1046
+ }
1047
+
1048
+ function createConsola(options = {}) {
1049
+ const consola2 = createConsola$1({
1050
+ reporters: options.reporters || [new BrowserReporter({})],
1051
+ prompt(message, options2 = {}) {
1052
+ if (options2.type === "confirm") {
1053
+ return Promise.resolve(confirm(message));
1054
+ }
1055
+ return Promise.resolve(prompt(message));
1056
+ },
1057
+ ...options
1058
+ });
1059
+ return consola2;
1060
+ }
1061
+ const consola = createConsola();
1062
+
1063
+ function createLogger(PLUGIN_NAME, verbose) {
1064
+ const prefix = chalk.blue.bold(`
1065
+ [${PLUGIN_NAME}]`);
1066
+ return {
1067
+ log: (message) => {
1068
+ if (verbose) {
1069
+ consola.log(`${prefix} ${chalk.white(message)}`);
1070
+ }
1071
+ },
1072
+ success: (message) => {
1073
+ if (verbose) {
1074
+ consola.success(`${prefix} ${chalk.green(message)}`);
1075
+ }
1076
+ },
1077
+ error: (message, error) => {
1078
+ consola.error(`${prefix} ${chalk.red(message)}`, error);
1079
+ },
1080
+ pathReplace: (from, to) => {
1081
+ if (verbose) {
1082
+ consola.log(`${prefix} ${chalk.gray(from)} ${chalk.yellow("======>")} ${chalk.cyan(to)}`);
1083
+ }
1084
+ }
1085
+ };
1086
+ }
1087
+ function escapeRegExp(str) {
1088
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1089
+ }
1090
+ function replaceStaticToCdn(code, assetDir, cdnBasePath, logger) {
1091
+ const escapedStaticPrefix = escapeRegExp(assetDir);
1092
+ const cssUrlRE = new RegExp(
1093
+ `url\\(\\s*(['"]?)(${escapedStaticPrefix}[^'")\\s]+)\\1\\s*\\)`,
1094
+ "g"
1095
+ );
1096
+ let transformed = code.replace(cssUrlRE, (match, quote, originalPath) => {
1097
+ try {
1098
+ if (originalPath.startsWith("http") || originalPath.startsWith("data:")) {
1099
+ return match;
1100
+ }
1101
+ const outputFileName = `${cdnBasePath}${originalPath}`;
1102
+ logger.pathReplace(originalPath, outputFileName);
1103
+ return `url(${quote || ""}${outputFileName}${quote || ""})`;
1104
+ } catch (error) {
1105
+ logger.error(`\u5904\u7406 CSS \u5931\u8D25`, error);
1106
+ return match;
1107
+ }
1108
+ });
1109
+ const stringRE = new RegExp(
1110
+ `(['"])(${escapedStaticPrefix}[^'"]*)\\1`,
1111
+ "g"
1112
+ );
1113
+ transformed = transformed.replace(stringRE, (match, quote, originalPath) => {
1114
+ try {
1115
+ if (originalPath.startsWith("http") || originalPath.startsWith("data:")) {
1116
+ return match;
1117
+ }
1118
+ const outputFileName = `${cdnBasePath}${originalPath}`;
1119
+ logger.pathReplace(originalPath, outputFileName);
1120
+ return `${quote}${outputFileName}${quote}`;
1121
+ } catch (error) {
1122
+ logger.error(`\u5904\u7406\u5B57\u7B26\u4E32\u5931\u8D25`, error);
1123
+ return match;
1124
+ }
1125
+ });
1126
+ return transformed;
1127
+ }
1128
+ function UniCdn(opt) {
1129
+ const PLUGIN_NAME = "vite-plugin-uni-cdn";
1130
+ const defaultOption = {
1131
+ cdn: "",
1132
+ sourceDir: "static/cdn",
1133
+ include: ["**/*.{vue,css,scss,sass,less,styl}"],
1134
+ exclude: ["**/node_modules/**", "**/uni_modules/**", "**/dist/**", "**/unpackage/**"],
1135
+ deleteOutputFiles: true,
1136
+ verbose: true
1137
+ };
1138
+ const options = { ...defaultOption, ...opt };
1139
+ const cdnBasePath = options.cdn ? options.cdn.endsWith("/") ? options.cdn.slice(0, -1) : options.cdn : "";
1140
+ if (!cdnBasePath || !options.sourceDir) {
1141
+ return { name: PLUGIN_NAME };
1142
+ }
1143
+ const logger = createLogger(PLUGIN_NAME, options.verbose ?? true);
1144
+ const filter = vite.createFilter(options.include, options.exclude);
1145
+ let isSrc = false;
1146
+ let projectRoot = "";
1147
+ let sourceDirAbs = "";
1148
+ let assetDir = "";
1149
+ let outputDir = "";
1150
+ return {
1151
+ name: PLUGIN_NAME,
1152
+ async configResolved(resolvedConfig) {
1153
+ projectRoot = resolvedConfig.root;
1154
+ const normalizeSourceDir = vite.normalizePath(path__default.normalize(options.sourceDir));
1155
+ const relSourceDir = normalizeSourceDir.replace(/^\/+/, "");
1156
+ sourceDirAbs = vite.normalizePath(path__default.resolve(projectRoot, relSourceDir));
1157
+ try {
1158
+ await fs__default.access(sourceDirAbs);
1159
+ } catch (error) {
1160
+ const err = error;
1161
+ logger.error("\u66FF\u6362\u8D44\u6E90\u76EE\u5F55\u4E0D\u5B58\u5728", err);
1162
+ return;
1163
+ }
1164
+ isSrc = relSourceDir.startsWith("src/");
1165
+ const staticSubPath = isSrc ? relSourceDir.slice("src/".length) : relSourceDir;
1166
+ assetDir = `/${staticSubPath.replace(/^\/+/, "")}`;
1167
+ logger.log(`\u5DE5\u7A0B\u6839\u76EE\u5F55: ${projectRoot}`);
1168
+ logger.log(`\u66FF\u6362\u8D44\u6E90\u76EE\u5F55: ${sourceDirAbs}`);
1169
+ logger.log(`\u5339\u914D\u8D44\u6E90\u524D\u7F00: ${assetDir}`);
1170
+ outputDir = vite.normalizePath(
1171
+ path__default.resolve(
1172
+ resolvedConfig.build.outDir,
1173
+ staticSubPath
1174
+ )
1175
+ );
1176
+ logger.log(`\u8F93\u51FA\u76EE\u5F55: ${outputDir}`);
1177
+ },
1178
+ transform(code, id) {
1179
+ if (!sourceDirAbs || !assetDir || !code) {
1180
+ return { code };
1181
+ }
1182
+ const [filepath] = id.split("?", 2);
1183
+ if (!filter(filepath)) {
1184
+ return { code };
1185
+ }
1186
+ const transformed = replaceStaticToCdn(code, assetDir, cdnBasePath, logger);
1187
+ return { code: transformed };
1188
+ },
1189
+ generateBundle(_options, bundle) {
1190
+ if (!sourceDirAbs || !assetDir) {
1191
+ return;
1192
+ }
1193
+ for (const [fileName, chunk] of Object.entries(bundle)) {
1194
+ if (chunk.type === "asset") {
1195
+ if (typeof chunk.source !== "string") {
1196
+ continue;
1197
+ }
1198
+ if (!/\.(?:css|js|mjs|html)$/.test(fileName)) {
1199
+ continue;
1200
+ }
1201
+ const before = chunk.source;
1202
+ chunk.source = replaceStaticToCdn(before, assetDir, cdnBasePath, logger);
1203
+ } else if (chunk.type === "chunk") {
1204
+ const before = chunk.code;
1205
+ chunk.code = replaceStaticToCdn(before, assetDir, cdnBasePath, logger);
1206
+ }
1207
+ }
1208
+ },
1209
+ async closeBundle() {
1210
+ if (!sourceDirAbs || !assetDir) {
1211
+ return;
1212
+ }
1213
+ if (!options.deleteOutputFiles) {
1214
+ logger.log("\u5DF2\u7981\u7528\u8F93\u51FA\u6587\u4EF6\u5220\u9664\u529F\u80FD");
1215
+ return;
1216
+ }
1217
+ try {
1218
+ await fs__default.access(outputDir);
1219
+ await fs__default.rm(outputDir, { recursive: true, force: true, maxRetries: 2 });
1220
+ logger.success(`\u5DF2\u6210\u529F\u5220\u9664\u76EE\u5F55: ${outputDir}`);
1221
+ } catch (error) {
1222
+ const err = error;
1223
+ if (err.code === "ENOENT") {
1224
+ logger.log(`\u76EE\u5F55\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u5220\u9664: ${outputDir}`);
1225
+ } else {
1226
+ logger.error(`\u5220\u9664\u76EE\u5F55\u5931\u8D25: ${outputDir}`, err);
1227
+ }
1228
+ }
1229
+ }
1230
+ };
1231
+ }
1232
+
1233
+ module.exports = UniCdn;