kirbyup 2.0.1 → 2.0.2-beta.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.
@@ -1,3633 +0,0 @@
1
- import { existsSync as existsSync$1, unlinkSync } from 'node:fs';
2
- import { writeFile, readFile } from 'node:fs/promises';
3
- import { normalize, relative, resolve as resolve$1, dirname, basename } from 'pathe';
4
- import { transformWithEsbuild, formatPostcssSourceMap, createServer, mergeConfig, build as build$1 } from 'vite';
5
- import fs, { existsSync, statSync } from 'fs';
6
- import path$2, { win32, posix, isAbsolute, resolve } from 'path';
7
- import { createRequire } from 'module';
8
- import { createHash } from 'crypto';
9
- import postcssrc from 'postcss-load-config';
10
- import postcssLogical from 'postcss-logical';
11
- import postcssDirPseudoClass from 'postcss-dir-pseudo-class';
12
- import consola from 'consola';
13
- import { debounce } from 'perfect-debounce';
14
- import colors from 'picocolors';
15
- import fullReloadPlugin from 'vite-plugin-full-reload';
16
- import { gzip } from 'zlib';
17
- import { promisify } from 'util';
18
- import { createConfigLoader } from 'unconfig';
19
- import MagicString from 'magic-string';
20
- import { detect } from 'detect-package-manager';
21
-
22
- var utils$3 = {};
23
-
24
- const path$1 = path$2;
25
- const WIN_SLASH = '\\\\/';
26
- const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
27
-
28
- /**
29
- * Posix glob regex
30
- */
31
-
32
- const DOT_LITERAL = '\\.';
33
- const PLUS_LITERAL = '\\+';
34
- const QMARK_LITERAL = '\\?';
35
- const SLASH_LITERAL = '\\/';
36
- const ONE_CHAR = '(?=.)';
37
- const QMARK = '[^/]';
38
- const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
39
- const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
40
- const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
41
- const NO_DOT = `(?!${DOT_LITERAL})`;
42
- const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
43
- const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
44
- const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
45
- const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
46
- const STAR = `${QMARK}*?`;
47
-
48
- const POSIX_CHARS = {
49
- DOT_LITERAL,
50
- PLUS_LITERAL,
51
- QMARK_LITERAL,
52
- SLASH_LITERAL,
53
- ONE_CHAR,
54
- QMARK,
55
- END_ANCHOR,
56
- DOTS_SLASH,
57
- NO_DOT,
58
- NO_DOTS,
59
- NO_DOT_SLASH,
60
- NO_DOTS_SLASH,
61
- QMARK_NO_DOT,
62
- STAR,
63
- START_ANCHOR
64
- };
65
-
66
- /**
67
- * Windows glob regex
68
- */
69
-
70
- const WINDOWS_CHARS = {
71
- ...POSIX_CHARS,
72
-
73
- SLASH_LITERAL: `[${WIN_SLASH}]`,
74
- QMARK: WIN_NO_SLASH,
75
- STAR: `${WIN_NO_SLASH}*?`,
76
- DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
77
- NO_DOT: `(?!${DOT_LITERAL})`,
78
- NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
79
- NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
80
- NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
81
- QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
82
- START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
83
- END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
84
- };
85
-
86
- /**
87
- * POSIX Bracket Regex
88
- */
89
-
90
- const POSIX_REGEX_SOURCE$1 = {
91
- alnum: 'a-zA-Z0-9',
92
- alpha: 'a-zA-Z',
93
- ascii: '\\x00-\\x7F',
94
- blank: ' \\t',
95
- cntrl: '\\x00-\\x1F\\x7F',
96
- digit: '0-9',
97
- graph: '\\x21-\\x7E',
98
- lower: 'a-z',
99
- print: '\\x20-\\x7E ',
100
- punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
101
- space: ' \\t\\r\\n\\v\\f',
102
- upper: 'A-Z',
103
- word: 'A-Za-z0-9_',
104
- xdigit: 'A-Fa-f0-9'
105
- };
106
-
107
- var constants$2 = {
108
- MAX_LENGTH: 1024 * 64,
109
- POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
110
-
111
- // regular expressions
112
- REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
113
- REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
114
- REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
115
- REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
116
- REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
117
- REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
118
-
119
- // Replace globs with equivalent patterns to reduce parsing time.
120
- REPLACEMENTS: {
121
- '***': '*',
122
- '**/**': '**',
123
- '**/**/**': '**'
124
- },
125
-
126
- // Digits
127
- CHAR_0: 48, /* 0 */
128
- CHAR_9: 57, /* 9 */
129
-
130
- // Alphabet chars.
131
- CHAR_UPPERCASE_A: 65, /* A */
132
- CHAR_LOWERCASE_A: 97, /* a */
133
- CHAR_UPPERCASE_Z: 90, /* Z */
134
- CHAR_LOWERCASE_Z: 122, /* z */
135
-
136
- CHAR_LEFT_PARENTHESES: 40, /* ( */
137
- CHAR_RIGHT_PARENTHESES: 41, /* ) */
138
-
139
- CHAR_ASTERISK: 42, /* * */
140
-
141
- // Non-alphabetic chars.
142
- CHAR_AMPERSAND: 38, /* & */
143
- CHAR_AT: 64, /* @ */
144
- CHAR_BACKWARD_SLASH: 92, /* \ */
145
- CHAR_CARRIAGE_RETURN: 13, /* \r */
146
- CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
147
- CHAR_COLON: 58, /* : */
148
- CHAR_COMMA: 44, /* , */
149
- CHAR_DOT: 46, /* . */
150
- CHAR_DOUBLE_QUOTE: 34, /* " */
151
- CHAR_EQUAL: 61, /* = */
152
- CHAR_EXCLAMATION_MARK: 33, /* ! */
153
- CHAR_FORM_FEED: 12, /* \f */
154
- CHAR_FORWARD_SLASH: 47, /* / */
155
- CHAR_GRAVE_ACCENT: 96, /* ` */
156
- CHAR_HASH: 35, /* # */
157
- CHAR_HYPHEN_MINUS: 45, /* - */
158
- CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
159
- CHAR_LEFT_CURLY_BRACE: 123, /* { */
160
- CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
161
- CHAR_LINE_FEED: 10, /* \n */
162
- CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
163
- CHAR_PERCENT: 37, /* % */
164
- CHAR_PLUS: 43, /* + */
165
- CHAR_QUESTION_MARK: 63, /* ? */
166
- CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
167
- CHAR_RIGHT_CURLY_BRACE: 125, /* } */
168
- CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
169
- CHAR_SEMICOLON: 59, /* ; */
170
- CHAR_SINGLE_QUOTE: 39, /* ' */
171
- CHAR_SPACE: 32, /* */
172
- CHAR_TAB: 9, /* \t */
173
- CHAR_UNDERSCORE: 95, /* _ */
174
- CHAR_VERTICAL_LINE: 124, /* | */
175
- CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
176
-
177
- SEP: path$1.sep,
178
-
179
- /**
180
- * Create EXTGLOB_CHARS
181
- */
182
-
183
- extglobChars(chars) {
184
- return {
185
- '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
186
- '?': { type: 'qmark', open: '(?:', close: ')?' },
187
- '+': { type: 'plus', open: '(?:', close: ')+' },
188
- '*': { type: 'star', open: '(?:', close: ')*' },
189
- '@': { type: 'at', open: '(?:', close: ')' }
190
- };
191
- },
192
-
193
- /**
194
- * Create GLOB_CHARS
195
- */
196
-
197
- globChars(win32) {
198
- return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
199
- }
200
- };
201
-
202
- (function (exports) {
203
-
204
- const path = path$2;
205
- const win32 = process.platform === 'win32';
206
- const {
207
- REGEX_BACKSLASH,
208
- REGEX_REMOVE_BACKSLASH,
209
- REGEX_SPECIAL_CHARS,
210
- REGEX_SPECIAL_CHARS_GLOBAL
211
- } = constants$2;
212
-
213
- exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
214
- exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
215
- exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
216
- exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
217
- exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
218
-
219
- exports.removeBackslashes = str => {
220
- return str.replace(REGEX_REMOVE_BACKSLASH, match => {
221
- return match === '\\' ? '' : match;
222
- });
223
- };
224
-
225
- exports.supportsLookbehinds = () => {
226
- const segs = process.version.slice(1).split('.').map(Number);
227
- if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
228
- return true;
229
- }
230
- return false;
231
- };
232
-
233
- exports.isWindows = options => {
234
- if (options && typeof options.windows === 'boolean') {
235
- return options.windows;
236
- }
237
- return win32 === true || path.sep === '\\';
238
- };
239
-
240
- exports.escapeLast = (input, char, lastIdx) => {
241
- const idx = input.lastIndexOf(char, lastIdx);
242
- if (idx === -1) return input;
243
- if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
244
- return `${input.slice(0, idx)}\\${input.slice(idx)}`;
245
- };
246
-
247
- exports.removePrefix = (input, state = {}) => {
248
- let output = input;
249
- if (output.startsWith('./')) {
250
- output = output.slice(2);
251
- state.prefix = './';
252
- }
253
- return output;
254
- };
255
-
256
- exports.wrapOutput = (input, state = {}, options = {}) => {
257
- const prepend = options.contains ? '' : '^';
258
- const append = options.contains ? '' : '$';
259
-
260
- let output = `${prepend}(?:${input})${append}`;
261
- if (state.negated === true) {
262
- output = `(?:^(?!${output}).*$)`;
263
- }
264
- return output;
265
- };
266
- }(utils$3));
267
-
268
- const utils$2 = utils$3;
269
- const {
270
- CHAR_ASTERISK, /* * */
271
- CHAR_AT, /* @ */
272
- CHAR_BACKWARD_SLASH, /* \ */
273
- CHAR_COMMA, /* , */
274
- CHAR_DOT, /* . */
275
- CHAR_EXCLAMATION_MARK, /* ! */
276
- CHAR_FORWARD_SLASH, /* / */
277
- CHAR_LEFT_CURLY_BRACE, /* { */
278
- CHAR_LEFT_PARENTHESES, /* ( */
279
- CHAR_LEFT_SQUARE_BRACKET, /* [ */
280
- CHAR_PLUS, /* + */
281
- CHAR_QUESTION_MARK, /* ? */
282
- CHAR_RIGHT_CURLY_BRACE, /* } */
283
- CHAR_RIGHT_PARENTHESES, /* ) */
284
- CHAR_RIGHT_SQUARE_BRACKET /* ] */
285
- } = constants$2;
286
-
287
- const isPathSeparator = code => {
288
- return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
289
- };
290
-
291
- const depth = token => {
292
- if (token.isPrefix !== true) {
293
- token.depth = token.isGlobstar ? Infinity : 1;
294
- }
295
- };
296
-
297
- /**
298
- * Quickly scans a glob pattern and returns an object with a handful of
299
- * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
300
- * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
301
- * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
302
- *
303
- * ```js
304
- * const pm = require('picomatch');
305
- * console.log(pm.scan('foo/bar/*.js'));
306
- * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
307
- * ```
308
- * @param {String} `str`
309
- * @param {Object} `options`
310
- * @return {Object} Returns an object with tokens and regex source string.
311
- * @api public
312
- */
313
-
314
- const scan$1 = (input, options) => {
315
- const opts = options || {};
316
-
317
- const length = input.length - 1;
318
- const scanToEnd = opts.parts === true || opts.scanToEnd === true;
319
- const slashes = [];
320
- const tokens = [];
321
- const parts = [];
322
-
323
- let str = input;
324
- let index = -1;
325
- let start = 0;
326
- let lastIndex = 0;
327
- let isBrace = false;
328
- let isBracket = false;
329
- let isGlob = false;
330
- let isExtglob = false;
331
- let isGlobstar = false;
332
- let braceEscaped = false;
333
- let backslashes = false;
334
- let negated = false;
335
- let negatedExtglob = false;
336
- let finished = false;
337
- let braces = 0;
338
- let prev;
339
- let code;
340
- let token = { value: '', depth: 0, isGlob: false };
341
-
342
- const eos = () => index >= length;
343
- const peek = () => str.charCodeAt(index + 1);
344
- const advance = () => {
345
- prev = code;
346
- return str.charCodeAt(++index);
347
- };
348
-
349
- while (index < length) {
350
- code = advance();
351
- let next;
352
-
353
- if (code === CHAR_BACKWARD_SLASH) {
354
- backslashes = token.backslashes = true;
355
- code = advance();
356
-
357
- if (code === CHAR_LEFT_CURLY_BRACE) {
358
- braceEscaped = true;
359
- }
360
- continue;
361
- }
362
-
363
- if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
364
- braces++;
365
-
366
- while (eos() !== true && (code = advance())) {
367
- if (code === CHAR_BACKWARD_SLASH) {
368
- backslashes = token.backslashes = true;
369
- advance();
370
- continue;
371
- }
372
-
373
- if (code === CHAR_LEFT_CURLY_BRACE) {
374
- braces++;
375
- continue;
376
- }
377
-
378
- if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
379
- isBrace = token.isBrace = true;
380
- isGlob = token.isGlob = true;
381
- finished = true;
382
-
383
- if (scanToEnd === true) {
384
- continue;
385
- }
386
-
387
- break;
388
- }
389
-
390
- if (braceEscaped !== true && code === CHAR_COMMA) {
391
- isBrace = token.isBrace = true;
392
- isGlob = token.isGlob = true;
393
- finished = true;
394
-
395
- if (scanToEnd === true) {
396
- continue;
397
- }
398
-
399
- break;
400
- }
401
-
402
- if (code === CHAR_RIGHT_CURLY_BRACE) {
403
- braces--;
404
-
405
- if (braces === 0) {
406
- braceEscaped = false;
407
- isBrace = token.isBrace = true;
408
- finished = true;
409
- break;
410
- }
411
- }
412
- }
413
-
414
- if (scanToEnd === true) {
415
- continue;
416
- }
417
-
418
- break;
419
- }
420
-
421
- if (code === CHAR_FORWARD_SLASH) {
422
- slashes.push(index);
423
- tokens.push(token);
424
- token = { value: '', depth: 0, isGlob: false };
425
-
426
- if (finished === true) continue;
427
- if (prev === CHAR_DOT && index === (start + 1)) {
428
- start += 2;
429
- continue;
430
- }
431
-
432
- lastIndex = index + 1;
433
- continue;
434
- }
435
-
436
- if (opts.noext !== true) {
437
- const isExtglobChar = code === CHAR_PLUS
438
- || code === CHAR_AT
439
- || code === CHAR_ASTERISK
440
- || code === CHAR_QUESTION_MARK
441
- || code === CHAR_EXCLAMATION_MARK;
442
-
443
- if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
444
- isGlob = token.isGlob = true;
445
- isExtglob = token.isExtglob = true;
446
- finished = true;
447
- if (code === CHAR_EXCLAMATION_MARK && index === start) {
448
- negatedExtglob = true;
449
- }
450
-
451
- if (scanToEnd === true) {
452
- while (eos() !== true && (code = advance())) {
453
- if (code === CHAR_BACKWARD_SLASH) {
454
- backslashes = token.backslashes = true;
455
- code = advance();
456
- continue;
457
- }
458
-
459
- if (code === CHAR_RIGHT_PARENTHESES) {
460
- isGlob = token.isGlob = true;
461
- finished = true;
462
- break;
463
- }
464
- }
465
- continue;
466
- }
467
- break;
468
- }
469
- }
470
-
471
- if (code === CHAR_ASTERISK) {
472
- if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
473
- isGlob = token.isGlob = true;
474
- finished = true;
475
-
476
- if (scanToEnd === true) {
477
- continue;
478
- }
479
- break;
480
- }
481
-
482
- if (code === CHAR_QUESTION_MARK) {
483
- isGlob = token.isGlob = true;
484
- finished = true;
485
-
486
- if (scanToEnd === true) {
487
- continue;
488
- }
489
- break;
490
- }
491
-
492
- if (code === CHAR_LEFT_SQUARE_BRACKET) {
493
- while (eos() !== true && (next = advance())) {
494
- if (next === CHAR_BACKWARD_SLASH) {
495
- backslashes = token.backslashes = true;
496
- advance();
497
- continue;
498
- }
499
-
500
- if (next === CHAR_RIGHT_SQUARE_BRACKET) {
501
- isBracket = token.isBracket = true;
502
- isGlob = token.isGlob = true;
503
- finished = true;
504
- break;
505
- }
506
- }
507
-
508
- if (scanToEnd === true) {
509
- continue;
510
- }
511
-
512
- break;
513
- }
514
-
515
- if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
516
- negated = token.negated = true;
517
- start++;
518
- continue;
519
- }
520
-
521
- if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
522
- isGlob = token.isGlob = true;
523
-
524
- if (scanToEnd === true) {
525
- while (eos() !== true && (code = advance())) {
526
- if (code === CHAR_LEFT_PARENTHESES) {
527
- backslashes = token.backslashes = true;
528
- code = advance();
529
- continue;
530
- }
531
-
532
- if (code === CHAR_RIGHT_PARENTHESES) {
533
- finished = true;
534
- break;
535
- }
536
- }
537
- continue;
538
- }
539
- break;
540
- }
541
-
542
- if (isGlob === true) {
543
- finished = true;
544
-
545
- if (scanToEnd === true) {
546
- continue;
547
- }
548
-
549
- break;
550
- }
551
- }
552
-
553
- if (opts.noext === true) {
554
- isExtglob = false;
555
- isGlob = false;
556
- }
557
-
558
- let base = str;
559
- let prefix = '';
560
- let glob = '';
561
-
562
- if (start > 0) {
563
- prefix = str.slice(0, start);
564
- str = str.slice(start);
565
- lastIndex -= start;
566
- }
567
-
568
- if (base && isGlob === true && lastIndex > 0) {
569
- base = str.slice(0, lastIndex);
570
- glob = str.slice(lastIndex);
571
- } else if (isGlob === true) {
572
- base = '';
573
- glob = str;
574
- } else {
575
- base = str;
576
- }
577
-
578
- if (base && base !== '' && base !== '/' && base !== str) {
579
- if (isPathSeparator(base.charCodeAt(base.length - 1))) {
580
- base = base.slice(0, -1);
581
- }
582
- }
583
-
584
- if (opts.unescape === true) {
585
- if (glob) glob = utils$2.removeBackslashes(glob);
586
-
587
- if (base && backslashes === true) {
588
- base = utils$2.removeBackslashes(base);
589
- }
590
- }
591
-
592
- const state = {
593
- prefix,
594
- input,
595
- start,
596
- base,
597
- glob,
598
- isBrace,
599
- isBracket,
600
- isGlob,
601
- isExtglob,
602
- isGlobstar,
603
- negated,
604
- negatedExtglob
605
- };
606
-
607
- if (opts.tokens === true) {
608
- state.maxDepth = 0;
609
- if (!isPathSeparator(code)) {
610
- tokens.push(token);
611
- }
612
- state.tokens = tokens;
613
- }
614
-
615
- if (opts.parts === true || opts.tokens === true) {
616
- let prevIndex;
617
-
618
- for (let idx = 0; idx < slashes.length; idx++) {
619
- const n = prevIndex ? prevIndex + 1 : start;
620
- const i = slashes[idx];
621
- const value = input.slice(n, i);
622
- if (opts.tokens) {
623
- if (idx === 0 && start !== 0) {
624
- tokens[idx].isPrefix = true;
625
- tokens[idx].value = prefix;
626
- } else {
627
- tokens[idx].value = value;
628
- }
629
- depth(tokens[idx]);
630
- state.maxDepth += tokens[idx].depth;
631
- }
632
- if (idx !== 0 || value !== '') {
633
- parts.push(value);
634
- }
635
- prevIndex = i;
636
- }
637
-
638
- if (prevIndex && prevIndex + 1 < input.length) {
639
- const value = input.slice(prevIndex + 1);
640
- parts.push(value);
641
-
642
- if (opts.tokens) {
643
- tokens[tokens.length - 1].value = value;
644
- depth(tokens[tokens.length - 1]);
645
- state.maxDepth += tokens[tokens.length - 1].depth;
646
- }
647
- }
648
-
649
- state.slashes = slashes;
650
- state.parts = parts;
651
- }
652
-
653
- return state;
654
- };
655
-
656
- var scan_1 = scan$1;
657
-
658
- const constants$1 = constants$2;
659
- const utils$1 = utils$3;
660
-
661
- /**
662
- * Constants
663
- */
664
-
665
- const {
666
- MAX_LENGTH,
667
- POSIX_REGEX_SOURCE,
668
- REGEX_NON_SPECIAL_CHARS,
669
- REGEX_SPECIAL_CHARS_BACKREF,
670
- REPLACEMENTS
671
- } = constants$1;
672
-
673
- /**
674
- * Helpers
675
- */
676
-
677
- const expandRange = (args, options) => {
678
- if (typeof options.expandRange === 'function') {
679
- return options.expandRange(...args, options);
680
- }
681
-
682
- args.sort();
683
- const value = `[${args.join('-')}]`;
684
-
685
- try {
686
- /* eslint-disable-next-line no-new */
687
- new RegExp(value);
688
- } catch (ex) {
689
- return args.map(v => utils$1.escapeRegex(v)).join('..');
690
- }
691
-
692
- return value;
693
- };
694
-
695
- /**
696
- * Create the message for a syntax error
697
- */
698
-
699
- const syntaxError = (type, char) => {
700
- return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
701
- };
702
-
703
- /**
704
- * Parse the given input string.
705
- * @param {String} input
706
- * @param {Object} options
707
- * @return {Object}
708
- */
709
-
710
- const parse$1 = (input, options) => {
711
- if (typeof input !== 'string') {
712
- throw new TypeError('Expected a string');
713
- }
714
-
715
- input = REPLACEMENTS[input] || input;
716
-
717
- const opts = { ...options };
718
- const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
719
-
720
- let len = input.length;
721
- if (len > max) {
722
- throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
723
- }
724
-
725
- const bos = { type: 'bos', value: '', output: opts.prepend || '' };
726
- const tokens = [bos];
727
-
728
- const capture = opts.capture ? '' : '?:';
729
- const win32 = utils$1.isWindows(options);
730
-
731
- // create constants based on platform, for windows or posix
732
- const PLATFORM_CHARS = constants$1.globChars(win32);
733
- const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
734
-
735
- const {
736
- DOT_LITERAL,
737
- PLUS_LITERAL,
738
- SLASH_LITERAL,
739
- ONE_CHAR,
740
- DOTS_SLASH,
741
- NO_DOT,
742
- NO_DOT_SLASH,
743
- NO_DOTS_SLASH,
744
- QMARK,
745
- QMARK_NO_DOT,
746
- STAR,
747
- START_ANCHOR
748
- } = PLATFORM_CHARS;
749
-
750
- const globstar = opts => {
751
- return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
752
- };
753
-
754
- const nodot = opts.dot ? '' : NO_DOT;
755
- const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
756
- let star = opts.bash === true ? globstar(opts) : STAR;
757
-
758
- if (opts.capture) {
759
- star = `(${star})`;
760
- }
761
-
762
- // minimatch options support
763
- if (typeof opts.noext === 'boolean') {
764
- opts.noextglob = opts.noext;
765
- }
766
-
767
- const state = {
768
- input,
769
- index: -1,
770
- start: 0,
771
- dot: opts.dot === true,
772
- consumed: '',
773
- output: '',
774
- prefix: '',
775
- backtrack: false,
776
- negated: false,
777
- brackets: 0,
778
- braces: 0,
779
- parens: 0,
780
- quotes: 0,
781
- globstar: false,
782
- tokens
783
- };
784
-
785
- input = utils$1.removePrefix(input, state);
786
- len = input.length;
787
-
788
- const extglobs = [];
789
- const braces = [];
790
- const stack = [];
791
- let prev = bos;
792
- let value;
793
-
794
- /**
795
- * Tokenizing helpers
796
- */
797
-
798
- const eos = () => state.index === len - 1;
799
- const peek = state.peek = (n = 1) => input[state.index + n];
800
- const advance = state.advance = () => input[++state.index] || '';
801
- const remaining = () => input.slice(state.index + 1);
802
- const consume = (value = '', num = 0) => {
803
- state.consumed += value;
804
- state.index += num;
805
- };
806
-
807
- const append = token => {
808
- state.output += token.output != null ? token.output : token.value;
809
- consume(token.value);
810
- };
811
-
812
- const negate = () => {
813
- let count = 1;
814
-
815
- while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
816
- advance();
817
- state.start++;
818
- count++;
819
- }
820
-
821
- if (count % 2 === 0) {
822
- return false;
823
- }
824
-
825
- state.negated = true;
826
- state.start++;
827
- return true;
828
- };
829
-
830
- const increment = type => {
831
- state[type]++;
832
- stack.push(type);
833
- };
834
-
835
- const decrement = type => {
836
- state[type]--;
837
- stack.pop();
838
- };
839
-
840
- /**
841
- * Push tokens onto the tokens array. This helper speeds up
842
- * tokenizing by 1) helping us avoid backtracking as much as possible,
843
- * and 2) helping us avoid creating extra tokens when consecutive
844
- * characters are plain text. This improves performance and simplifies
845
- * lookbehinds.
846
- */
847
-
848
- const push = tok => {
849
- if (prev.type === 'globstar') {
850
- const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
851
- const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
852
-
853
- if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
854
- state.output = state.output.slice(0, -prev.output.length);
855
- prev.type = 'star';
856
- prev.value = '*';
857
- prev.output = star;
858
- state.output += prev.output;
859
- }
860
- }
861
-
862
- if (extglobs.length && tok.type !== 'paren') {
863
- extglobs[extglobs.length - 1].inner += tok.value;
864
- }
865
-
866
- if (tok.value || tok.output) append(tok);
867
- if (prev && prev.type === 'text' && tok.type === 'text') {
868
- prev.value += tok.value;
869
- prev.output = (prev.output || '') + tok.value;
870
- return;
871
- }
872
-
873
- tok.prev = prev;
874
- tokens.push(tok);
875
- prev = tok;
876
- };
877
-
878
- const extglobOpen = (type, value) => {
879
- const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
880
-
881
- token.prev = prev;
882
- token.parens = state.parens;
883
- token.output = state.output;
884
- const output = (opts.capture ? '(' : '') + token.open;
885
-
886
- increment('parens');
887
- push({ type, value, output: state.output ? '' : ONE_CHAR });
888
- push({ type: 'paren', extglob: true, value: advance(), output });
889
- extglobs.push(token);
890
- };
891
-
892
- const extglobClose = token => {
893
- let output = token.close + (opts.capture ? ')' : '');
894
- let rest;
895
-
896
- if (token.type === 'negate') {
897
- let extglobStar = star;
898
-
899
- if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
900
- extglobStar = globstar(opts);
901
- }
902
-
903
- if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
904
- output = token.close = `)$))${extglobStar}`;
905
- }
906
-
907
- if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
908
- // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
909
- // In this case, we need to parse the string and use it in the output of the original pattern.
910
- // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
911
- //
912
- // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
913
- const expression = parse$1(rest, { ...options, fastpaths: false }).output;
914
-
915
- output = token.close = `)${expression})${extglobStar})`;
916
- }
917
-
918
- if (token.prev.type === 'bos') {
919
- state.negatedExtglob = true;
920
- }
921
- }
922
-
923
- push({ type: 'paren', extglob: true, value, output });
924
- decrement('parens');
925
- };
926
-
927
- /**
928
- * Fast paths
929
- */
930
-
931
- if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
932
- let backslashes = false;
933
-
934
- let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
935
- if (first === '\\') {
936
- backslashes = true;
937
- return m;
938
- }
939
-
940
- if (first === '?') {
941
- if (esc) {
942
- return esc + first + (rest ? QMARK.repeat(rest.length) : '');
943
- }
944
- if (index === 0) {
945
- return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
946
- }
947
- return QMARK.repeat(chars.length);
948
- }
949
-
950
- if (first === '.') {
951
- return DOT_LITERAL.repeat(chars.length);
952
- }
953
-
954
- if (first === '*') {
955
- if (esc) {
956
- return esc + first + (rest ? star : '');
957
- }
958
- return star;
959
- }
960
- return esc ? m : `\\${m}`;
961
- });
962
-
963
- if (backslashes === true) {
964
- if (opts.unescape === true) {
965
- output = output.replace(/\\/g, '');
966
- } else {
967
- output = output.replace(/\\+/g, m => {
968
- return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
969
- });
970
- }
971
- }
972
-
973
- if (output === input && opts.contains === true) {
974
- state.output = input;
975
- return state;
976
- }
977
-
978
- state.output = utils$1.wrapOutput(output, state, options);
979
- return state;
980
- }
981
-
982
- /**
983
- * Tokenize input until we reach end-of-string
984
- */
985
-
986
- while (!eos()) {
987
- value = advance();
988
-
989
- if (value === '\u0000') {
990
- continue;
991
- }
992
-
993
- /**
994
- * Escaped characters
995
- */
996
-
997
- if (value === '\\') {
998
- const next = peek();
999
-
1000
- if (next === '/' && opts.bash !== true) {
1001
- continue;
1002
- }
1003
-
1004
- if (next === '.' || next === ';') {
1005
- continue;
1006
- }
1007
-
1008
- if (!next) {
1009
- value += '\\';
1010
- push({ type: 'text', value });
1011
- continue;
1012
- }
1013
-
1014
- // collapse slashes to reduce potential for exploits
1015
- const match = /^\\+/.exec(remaining());
1016
- let slashes = 0;
1017
-
1018
- if (match && match[0].length > 2) {
1019
- slashes = match[0].length;
1020
- state.index += slashes;
1021
- if (slashes % 2 !== 0) {
1022
- value += '\\';
1023
- }
1024
- }
1025
-
1026
- if (opts.unescape === true) {
1027
- value = advance();
1028
- } else {
1029
- value += advance();
1030
- }
1031
-
1032
- if (state.brackets === 0) {
1033
- push({ type: 'text', value });
1034
- continue;
1035
- }
1036
- }
1037
-
1038
- /**
1039
- * If we're inside a regex character class, continue
1040
- * until we reach the closing bracket.
1041
- */
1042
-
1043
- if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
1044
- if (opts.posix !== false && value === ':') {
1045
- const inner = prev.value.slice(1);
1046
- if (inner.includes('[')) {
1047
- prev.posix = true;
1048
-
1049
- if (inner.includes(':')) {
1050
- const idx = prev.value.lastIndexOf('[');
1051
- const pre = prev.value.slice(0, idx);
1052
- const rest = prev.value.slice(idx + 2);
1053
- const posix = POSIX_REGEX_SOURCE[rest];
1054
- if (posix) {
1055
- prev.value = pre + posix;
1056
- state.backtrack = true;
1057
- advance();
1058
-
1059
- if (!bos.output && tokens.indexOf(prev) === 1) {
1060
- bos.output = ONE_CHAR;
1061
- }
1062
- continue;
1063
- }
1064
- }
1065
- }
1066
- }
1067
-
1068
- if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
1069
- value = `\\${value}`;
1070
- }
1071
-
1072
- if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
1073
- value = `\\${value}`;
1074
- }
1075
-
1076
- if (opts.posix === true && value === '!' && prev.value === '[') {
1077
- value = '^';
1078
- }
1079
-
1080
- prev.value += value;
1081
- append({ value });
1082
- continue;
1083
- }
1084
-
1085
- /**
1086
- * If we're inside a quoted string, continue
1087
- * until we reach the closing double quote.
1088
- */
1089
-
1090
- if (state.quotes === 1 && value !== '"') {
1091
- value = utils$1.escapeRegex(value);
1092
- prev.value += value;
1093
- append({ value });
1094
- continue;
1095
- }
1096
-
1097
- /**
1098
- * Double quotes
1099
- */
1100
-
1101
- if (value === '"') {
1102
- state.quotes = state.quotes === 1 ? 0 : 1;
1103
- if (opts.keepQuotes === true) {
1104
- push({ type: 'text', value });
1105
- }
1106
- continue;
1107
- }
1108
-
1109
- /**
1110
- * Parentheses
1111
- */
1112
-
1113
- if (value === '(') {
1114
- increment('parens');
1115
- push({ type: 'paren', value });
1116
- continue;
1117
- }
1118
-
1119
- if (value === ')') {
1120
- if (state.parens === 0 && opts.strictBrackets === true) {
1121
- throw new SyntaxError(syntaxError('opening', '('));
1122
- }
1123
-
1124
- const extglob = extglobs[extglobs.length - 1];
1125
- if (extglob && state.parens === extglob.parens + 1) {
1126
- extglobClose(extglobs.pop());
1127
- continue;
1128
- }
1129
-
1130
- push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
1131
- decrement('parens');
1132
- continue;
1133
- }
1134
-
1135
- /**
1136
- * Square brackets
1137
- */
1138
-
1139
- if (value === '[') {
1140
- if (opts.nobracket === true || !remaining().includes(']')) {
1141
- if (opts.nobracket !== true && opts.strictBrackets === true) {
1142
- throw new SyntaxError(syntaxError('closing', ']'));
1143
- }
1144
-
1145
- value = `\\${value}`;
1146
- } else {
1147
- increment('brackets');
1148
- }
1149
-
1150
- push({ type: 'bracket', value });
1151
- continue;
1152
- }
1153
-
1154
- if (value === ']') {
1155
- if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
1156
- push({ type: 'text', value, output: `\\${value}` });
1157
- continue;
1158
- }
1159
-
1160
- if (state.brackets === 0) {
1161
- if (opts.strictBrackets === true) {
1162
- throw new SyntaxError(syntaxError('opening', '['));
1163
- }
1164
-
1165
- push({ type: 'text', value, output: `\\${value}` });
1166
- continue;
1167
- }
1168
-
1169
- decrement('brackets');
1170
-
1171
- const prevValue = prev.value.slice(1);
1172
- if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
1173
- value = `/${value}`;
1174
- }
1175
-
1176
- prev.value += value;
1177
- append({ value });
1178
-
1179
- // when literal brackets are explicitly disabled
1180
- // assume we should match with a regex character class
1181
- if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
1182
- continue;
1183
- }
1184
-
1185
- const escaped = utils$1.escapeRegex(prev.value);
1186
- state.output = state.output.slice(0, -prev.value.length);
1187
-
1188
- // when literal brackets are explicitly enabled
1189
- // assume we should escape the brackets to match literal characters
1190
- if (opts.literalBrackets === true) {
1191
- state.output += escaped;
1192
- prev.value = escaped;
1193
- continue;
1194
- }
1195
-
1196
- // when the user specifies nothing, try to match both
1197
- prev.value = `(${capture}${escaped}|${prev.value})`;
1198
- state.output += prev.value;
1199
- continue;
1200
- }
1201
-
1202
- /**
1203
- * Braces
1204
- */
1205
-
1206
- if (value === '{' && opts.nobrace !== true) {
1207
- increment('braces');
1208
-
1209
- const open = {
1210
- type: 'brace',
1211
- value,
1212
- output: '(',
1213
- outputIndex: state.output.length,
1214
- tokensIndex: state.tokens.length
1215
- };
1216
-
1217
- braces.push(open);
1218
- push(open);
1219
- continue;
1220
- }
1221
-
1222
- if (value === '}') {
1223
- const brace = braces[braces.length - 1];
1224
-
1225
- if (opts.nobrace === true || !brace) {
1226
- push({ type: 'text', value, output: value });
1227
- continue;
1228
- }
1229
-
1230
- let output = ')';
1231
-
1232
- if (brace.dots === true) {
1233
- const arr = tokens.slice();
1234
- const range = [];
1235
-
1236
- for (let i = arr.length - 1; i >= 0; i--) {
1237
- tokens.pop();
1238
- if (arr[i].type === 'brace') {
1239
- break;
1240
- }
1241
- if (arr[i].type !== 'dots') {
1242
- range.unshift(arr[i].value);
1243
- }
1244
- }
1245
-
1246
- output = expandRange(range, opts);
1247
- state.backtrack = true;
1248
- }
1249
-
1250
- if (brace.comma !== true && brace.dots !== true) {
1251
- const out = state.output.slice(0, brace.outputIndex);
1252
- const toks = state.tokens.slice(brace.tokensIndex);
1253
- brace.value = brace.output = '\\{';
1254
- value = output = '\\}';
1255
- state.output = out;
1256
- for (const t of toks) {
1257
- state.output += (t.output || t.value);
1258
- }
1259
- }
1260
-
1261
- push({ type: 'brace', value, output });
1262
- decrement('braces');
1263
- braces.pop();
1264
- continue;
1265
- }
1266
-
1267
- /**
1268
- * Pipes
1269
- */
1270
-
1271
- if (value === '|') {
1272
- if (extglobs.length > 0) {
1273
- extglobs[extglobs.length - 1].conditions++;
1274
- }
1275
- push({ type: 'text', value });
1276
- continue;
1277
- }
1278
-
1279
- /**
1280
- * Commas
1281
- */
1282
-
1283
- if (value === ',') {
1284
- let output = value;
1285
-
1286
- const brace = braces[braces.length - 1];
1287
- if (brace && stack[stack.length - 1] === 'braces') {
1288
- brace.comma = true;
1289
- output = '|';
1290
- }
1291
-
1292
- push({ type: 'comma', value, output });
1293
- continue;
1294
- }
1295
-
1296
- /**
1297
- * Slashes
1298
- */
1299
-
1300
- if (value === '/') {
1301
- // if the beginning of the glob is "./", advance the start
1302
- // to the current index, and don't add the "./" characters
1303
- // to the state. This greatly simplifies lookbehinds when
1304
- // checking for BOS characters like "!" and "." (not "./")
1305
- if (prev.type === 'dot' && state.index === state.start + 1) {
1306
- state.start = state.index + 1;
1307
- state.consumed = '';
1308
- state.output = '';
1309
- tokens.pop();
1310
- prev = bos; // reset "prev" to the first token
1311
- continue;
1312
- }
1313
-
1314
- push({ type: 'slash', value, output: SLASH_LITERAL });
1315
- continue;
1316
- }
1317
-
1318
- /**
1319
- * Dots
1320
- */
1321
-
1322
- if (value === '.') {
1323
- if (state.braces > 0 && prev.type === 'dot') {
1324
- if (prev.value === '.') prev.output = DOT_LITERAL;
1325
- const brace = braces[braces.length - 1];
1326
- prev.type = 'dots';
1327
- prev.output += value;
1328
- prev.value += value;
1329
- brace.dots = true;
1330
- continue;
1331
- }
1332
-
1333
- if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
1334
- push({ type: 'text', value, output: DOT_LITERAL });
1335
- continue;
1336
- }
1337
-
1338
- push({ type: 'dot', value, output: DOT_LITERAL });
1339
- continue;
1340
- }
1341
-
1342
- /**
1343
- * Question marks
1344
- */
1345
-
1346
- if (value === '?') {
1347
- const isGroup = prev && prev.value === '(';
1348
- if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
1349
- extglobOpen('qmark', value);
1350
- continue;
1351
- }
1352
-
1353
- if (prev && prev.type === 'paren') {
1354
- const next = peek();
1355
- let output = value;
1356
-
1357
- if (next === '<' && !utils$1.supportsLookbehinds()) {
1358
- throw new Error('Node.js v10 or higher is required for regex lookbehinds');
1359
- }
1360
-
1361
- if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
1362
- output = `\\${value}`;
1363
- }
1364
-
1365
- push({ type: 'text', value, output });
1366
- continue;
1367
- }
1368
-
1369
- if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
1370
- push({ type: 'qmark', value, output: QMARK_NO_DOT });
1371
- continue;
1372
- }
1373
-
1374
- push({ type: 'qmark', value, output: QMARK });
1375
- continue;
1376
- }
1377
-
1378
- /**
1379
- * Exclamation
1380
- */
1381
-
1382
- if (value === '!') {
1383
- if (opts.noextglob !== true && peek() === '(') {
1384
- if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
1385
- extglobOpen('negate', value);
1386
- continue;
1387
- }
1388
- }
1389
-
1390
- if (opts.nonegate !== true && state.index === 0) {
1391
- negate();
1392
- continue;
1393
- }
1394
- }
1395
-
1396
- /**
1397
- * Plus
1398
- */
1399
-
1400
- if (value === '+') {
1401
- if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
1402
- extglobOpen('plus', value);
1403
- continue;
1404
- }
1405
-
1406
- if ((prev && prev.value === '(') || opts.regex === false) {
1407
- push({ type: 'plus', value, output: PLUS_LITERAL });
1408
- continue;
1409
- }
1410
-
1411
- if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
1412
- push({ type: 'plus', value });
1413
- continue;
1414
- }
1415
-
1416
- push({ type: 'plus', value: PLUS_LITERAL });
1417
- continue;
1418
- }
1419
-
1420
- /**
1421
- * Plain text
1422
- */
1423
-
1424
- if (value === '@') {
1425
- if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
1426
- push({ type: 'at', extglob: true, value, output: '' });
1427
- continue;
1428
- }
1429
-
1430
- push({ type: 'text', value });
1431
- continue;
1432
- }
1433
-
1434
- /**
1435
- * Plain text
1436
- */
1437
-
1438
- if (value !== '*') {
1439
- if (value === '$' || value === '^') {
1440
- value = `\\${value}`;
1441
- }
1442
-
1443
- const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
1444
- if (match) {
1445
- value += match[0];
1446
- state.index += match[0].length;
1447
- }
1448
-
1449
- push({ type: 'text', value });
1450
- continue;
1451
- }
1452
-
1453
- /**
1454
- * Stars
1455
- */
1456
-
1457
- if (prev && (prev.type === 'globstar' || prev.star === true)) {
1458
- prev.type = 'star';
1459
- prev.star = true;
1460
- prev.value += value;
1461
- prev.output = star;
1462
- state.backtrack = true;
1463
- state.globstar = true;
1464
- consume(value);
1465
- continue;
1466
- }
1467
-
1468
- let rest = remaining();
1469
- if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
1470
- extglobOpen('star', value);
1471
- continue;
1472
- }
1473
-
1474
- if (prev.type === 'star') {
1475
- if (opts.noglobstar === true) {
1476
- consume(value);
1477
- continue;
1478
- }
1479
-
1480
- const prior = prev.prev;
1481
- const before = prior.prev;
1482
- const isStart = prior.type === 'slash' || prior.type === 'bos';
1483
- const afterStar = before && (before.type === 'star' || before.type === 'globstar');
1484
-
1485
- if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
1486
- push({ type: 'star', value, output: '' });
1487
- continue;
1488
- }
1489
-
1490
- const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
1491
- const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
1492
- if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
1493
- push({ type: 'star', value, output: '' });
1494
- continue;
1495
- }
1496
-
1497
- // strip consecutive `/**/`
1498
- while (rest.slice(0, 3) === '/**') {
1499
- const after = input[state.index + 4];
1500
- if (after && after !== '/') {
1501
- break;
1502
- }
1503
- rest = rest.slice(3);
1504
- consume('/**', 3);
1505
- }
1506
-
1507
- if (prior.type === 'bos' && eos()) {
1508
- prev.type = 'globstar';
1509
- prev.value += value;
1510
- prev.output = globstar(opts);
1511
- state.output = prev.output;
1512
- state.globstar = true;
1513
- consume(value);
1514
- continue;
1515
- }
1516
-
1517
- if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
1518
- state.output = state.output.slice(0, -(prior.output + prev.output).length);
1519
- prior.output = `(?:${prior.output}`;
1520
-
1521
- prev.type = 'globstar';
1522
- prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
1523
- prev.value += value;
1524
- state.globstar = true;
1525
- state.output += prior.output + prev.output;
1526
- consume(value);
1527
- continue;
1528
- }
1529
-
1530
- if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
1531
- const end = rest[1] !== void 0 ? '|$' : '';
1532
-
1533
- state.output = state.output.slice(0, -(prior.output + prev.output).length);
1534
- prior.output = `(?:${prior.output}`;
1535
-
1536
- prev.type = 'globstar';
1537
- prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
1538
- prev.value += value;
1539
-
1540
- state.output += prior.output + prev.output;
1541
- state.globstar = true;
1542
-
1543
- consume(value + advance());
1544
-
1545
- push({ type: 'slash', value: '/', output: '' });
1546
- continue;
1547
- }
1548
-
1549
- if (prior.type === 'bos' && rest[0] === '/') {
1550
- prev.type = 'globstar';
1551
- prev.value += value;
1552
- prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
1553
- state.output = prev.output;
1554
- state.globstar = true;
1555
- consume(value + advance());
1556
- push({ type: 'slash', value: '/', output: '' });
1557
- continue;
1558
- }
1559
-
1560
- // remove single star from output
1561
- state.output = state.output.slice(0, -prev.output.length);
1562
-
1563
- // reset previous token to globstar
1564
- prev.type = 'globstar';
1565
- prev.output = globstar(opts);
1566
- prev.value += value;
1567
-
1568
- // reset output with globstar
1569
- state.output += prev.output;
1570
- state.globstar = true;
1571
- consume(value);
1572
- continue;
1573
- }
1574
-
1575
- const token = { type: 'star', value, output: star };
1576
-
1577
- if (opts.bash === true) {
1578
- token.output = '.*?';
1579
- if (prev.type === 'bos' || prev.type === 'slash') {
1580
- token.output = nodot + token.output;
1581
- }
1582
- push(token);
1583
- continue;
1584
- }
1585
-
1586
- if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
1587
- token.output = value;
1588
- push(token);
1589
- continue;
1590
- }
1591
-
1592
- if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
1593
- if (prev.type === 'dot') {
1594
- state.output += NO_DOT_SLASH;
1595
- prev.output += NO_DOT_SLASH;
1596
-
1597
- } else if (opts.dot === true) {
1598
- state.output += NO_DOTS_SLASH;
1599
- prev.output += NO_DOTS_SLASH;
1600
-
1601
- } else {
1602
- state.output += nodot;
1603
- prev.output += nodot;
1604
- }
1605
-
1606
- if (peek() !== '*') {
1607
- state.output += ONE_CHAR;
1608
- prev.output += ONE_CHAR;
1609
- }
1610
- }
1611
-
1612
- push(token);
1613
- }
1614
-
1615
- while (state.brackets > 0) {
1616
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
1617
- state.output = utils$1.escapeLast(state.output, '[');
1618
- decrement('brackets');
1619
- }
1620
-
1621
- while (state.parens > 0) {
1622
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
1623
- state.output = utils$1.escapeLast(state.output, '(');
1624
- decrement('parens');
1625
- }
1626
-
1627
- while (state.braces > 0) {
1628
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
1629
- state.output = utils$1.escapeLast(state.output, '{');
1630
- decrement('braces');
1631
- }
1632
-
1633
- if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
1634
- push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
1635
- }
1636
-
1637
- // rebuild the output if we had to backtrack at any point
1638
- if (state.backtrack === true) {
1639
- state.output = '';
1640
-
1641
- for (const token of state.tokens) {
1642
- state.output += token.output != null ? token.output : token.value;
1643
-
1644
- if (token.suffix) {
1645
- state.output += token.suffix;
1646
- }
1647
- }
1648
- }
1649
-
1650
- return state;
1651
- };
1652
-
1653
- /**
1654
- * Fast paths for creating regular expressions for common glob patterns.
1655
- * This can significantly speed up processing and has very little downside
1656
- * impact when none of the fast paths match.
1657
- */
1658
-
1659
- parse$1.fastpaths = (input, options) => {
1660
- const opts = { ...options };
1661
- const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
1662
- const len = input.length;
1663
- if (len > max) {
1664
- throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
1665
- }
1666
-
1667
- input = REPLACEMENTS[input] || input;
1668
- const win32 = utils$1.isWindows(options);
1669
-
1670
- // create constants based on platform, for windows or posix
1671
- const {
1672
- DOT_LITERAL,
1673
- SLASH_LITERAL,
1674
- ONE_CHAR,
1675
- DOTS_SLASH,
1676
- NO_DOT,
1677
- NO_DOTS,
1678
- NO_DOTS_SLASH,
1679
- STAR,
1680
- START_ANCHOR
1681
- } = constants$1.globChars(win32);
1682
-
1683
- const nodot = opts.dot ? NO_DOTS : NO_DOT;
1684
- const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
1685
- const capture = opts.capture ? '' : '?:';
1686
- const state = { negated: false, prefix: '' };
1687
- let star = opts.bash === true ? '.*?' : STAR;
1688
-
1689
- if (opts.capture) {
1690
- star = `(${star})`;
1691
- }
1692
-
1693
- const globstar = opts => {
1694
- if (opts.noglobstar === true) return star;
1695
- return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
1696
- };
1697
-
1698
- const create = str => {
1699
- switch (str) {
1700
- case '*':
1701
- return `${nodot}${ONE_CHAR}${star}`;
1702
-
1703
- case '.*':
1704
- return `${DOT_LITERAL}${ONE_CHAR}${star}`;
1705
-
1706
- case '*.*':
1707
- return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
1708
-
1709
- case '*/*':
1710
- return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
1711
-
1712
- case '**':
1713
- return nodot + globstar(opts);
1714
-
1715
- case '**/*':
1716
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
1717
-
1718
- case '**/*.*':
1719
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
1720
-
1721
- case '**/.*':
1722
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
1723
-
1724
- default: {
1725
- const match = /^(.*?)\.(\w+)$/.exec(str);
1726
- if (!match) return;
1727
-
1728
- const source = create(match[1]);
1729
- if (!source) return;
1730
-
1731
- return source + DOT_LITERAL + match[2];
1732
- }
1733
- }
1734
- };
1735
-
1736
- const output = utils$1.removePrefix(input, state);
1737
- let source = create(output);
1738
-
1739
- if (source && opts.strictSlashes !== true) {
1740
- source += `${SLASH_LITERAL}?`;
1741
- }
1742
-
1743
- return source;
1744
- };
1745
-
1746
- var parse_1 = parse$1;
1747
-
1748
- const path = path$2;
1749
- const scan = scan_1;
1750
- const parse = parse_1;
1751
- const utils = utils$3;
1752
- const constants = constants$2;
1753
- const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
1754
-
1755
- /**
1756
- * Creates a matcher function from one or more glob patterns. The
1757
- * returned function takes a string to match as its first argument,
1758
- * and returns true if the string is a match. The returned matcher
1759
- * function also takes a boolean as the second argument that, when true,
1760
- * returns an object with additional information.
1761
- *
1762
- * ```js
1763
- * const picomatch = require('picomatch');
1764
- * // picomatch(glob[, options]);
1765
- *
1766
- * const isMatch = picomatch('*.!(*a)');
1767
- * console.log(isMatch('a.a')); //=> false
1768
- * console.log(isMatch('a.b')); //=> true
1769
- * ```
1770
- * @name picomatch
1771
- * @param {String|Array} `globs` One or more glob patterns.
1772
- * @param {Object=} `options`
1773
- * @return {Function=} Returns a matcher function.
1774
- * @api public
1775
- */
1776
-
1777
- const picomatch$1 = (glob, options, returnState = false) => {
1778
- if (Array.isArray(glob)) {
1779
- const fns = glob.map(input => picomatch$1(input, options, returnState));
1780
- const arrayMatcher = str => {
1781
- for (const isMatch of fns) {
1782
- const state = isMatch(str);
1783
- if (state) return state;
1784
- }
1785
- return false;
1786
- };
1787
- return arrayMatcher;
1788
- }
1789
-
1790
- const isState = isObject(glob) && glob.tokens && glob.input;
1791
-
1792
- if (glob === '' || (typeof glob !== 'string' && !isState)) {
1793
- throw new TypeError('Expected pattern to be a non-empty string');
1794
- }
1795
-
1796
- const opts = options || {};
1797
- const posix = utils.isWindows(options);
1798
- const regex = isState
1799
- ? picomatch$1.compileRe(glob, options)
1800
- : picomatch$1.makeRe(glob, options, false, true);
1801
-
1802
- const state = regex.state;
1803
- delete regex.state;
1804
-
1805
- let isIgnored = () => false;
1806
- if (opts.ignore) {
1807
- const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
1808
- isIgnored = picomatch$1(opts.ignore, ignoreOpts, returnState);
1809
- }
1810
-
1811
- const matcher = (input, returnObject = false) => {
1812
- const { isMatch, match, output } = picomatch$1.test(input, regex, options, { glob, posix });
1813
- const result = { glob, state, regex, posix, input, output, match, isMatch };
1814
-
1815
- if (typeof opts.onResult === 'function') {
1816
- opts.onResult(result);
1817
- }
1818
-
1819
- if (isMatch === false) {
1820
- result.isMatch = false;
1821
- return returnObject ? result : false;
1822
- }
1823
-
1824
- if (isIgnored(input)) {
1825
- if (typeof opts.onIgnore === 'function') {
1826
- opts.onIgnore(result);
1827
- }
1828
- result.isMatch = false;
1829
- return returnObject ? result : false;
1830
- }
1831
-
1832
- if (typeof opts.onMatch === 'function') {
1833
- opts.onMatch(result);
1834
- }
1835
- return returnObject ? result : true;
1836
- };
1837
-
1838
- if (returnState) {
1839
- matcher.state = state;
1840
- }
1841
-
1842
- return matcher;
1843
- };
1844
-
1845
- /**
1846
- * Test `input` with the given `regex`. This is used by the main
1847
- * `picomatch()` function to test the input string.
1848
- *
1849
- * ```js
1850
- * const picomatch = require('picomatch');
1851
- * // picomatch.test(input, regex[, options]);
1852
- *
1853
- * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
1854
- * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
1855
- * ```
1856
- * @param {String} `input` String to test.
1857
- * @param {RegExp} `regex`
1858
- * @return {Object} Returns an object with matching info.
1859
- * @api public
1860
- */
1861
-
1862
- picomatch$1.test = (input, regex, options, { glob, posix } = {}) => {
1863
- if (typeof input !== 'string') {
1864
- throw new TypeError('Expected input to be a string');
1865
- }
1866
-
1867
- if (input === '') {
1868
- return { isMatch: false, output: '' };
1869
- }
1870
-
1871
- const opts = options || {};
1872
- const format = opts.format || (posix ? utils.toPosixSlashes : null);
1873
- let match = input === glob;
1874
- let output = (match && format) ? format(input) : input;
1875
-
1876
- if (match === false) {
1877
- output = format ? format(input) : input;
1878
- match = output === glob;
1879
- }
1880
-
1881
- if (match === false || opts.capture === true) {
1882
- if (opts.matchBase === true || opts.basename === true) {
1883
- match = picomatch$1.matchBase(input, regex, options, posix);
1884
- } else {
1885
- match = regex.exec(output);
1886
- }
1887
- }
1888
-
1889
- return { isMatch: Boolean(match), match, output };
1890
- };
1891
-
1892
- /**
1893
- * Match the basename of a filepath.
1894
- *
1895
- * ```js
1896
- * const picomatch = require('picomatch');
1897
- * // picomatch.matchBase(input, glob[, options]);
1898
- * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
1899
- * ```
1900
- * @param {String} `input` String to test.
1901
- * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
1902
- * @return {Boolean}
1903
- * @api public
1904
- */
1905
-
1906
- picomatch$1.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
1907
- const regex = glob instanceof RegExp ? glob : picomatch$1.makeRe(glob, options);
1908
- return regex.test(path.basename(input));
1909
- };
1910
-
1911
- /**
1912
- * Returns true if **any** of the given glob `patterns` match the specified `string`.
1913
- *
1914
- * ```js
1915
- * const picomatch = require('picomatch');
1916
- * // picomatch.isMatch(string, patterns[, options]);
1917
- *
1918
- * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
1919
- * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
1920
- * ```
1921
- * @param {String|Array} str The string to test.
1922
- * @param {String|Array} patterns One or more glob patterns to use for matching.
1923
- * @param {Object} [options] See available [options](#options).
1924
- * @return {Boolean} Returns true if any patterns match `str`
1925
- * @api public
1926
- */
1927
-
1928
- picomatch$1.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
1929
-
1930
- /**
1931
- * Parse a glob pattern to create the source string for a regular
1932
- * expression.
1933
- *
1934
- * ```js
1935
- * const picomatch = require('picomatch');
1936
- * const result = picomatch.parse(pattern[, options]);
1937
- * ```
1938
- * @param {String} `pattern`
1939
- * @param {Object} `options`
1940
- * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
1941
- * @api public
1942
- */
1943
-
1944
- picomatch$1.parse = (pattern, options) => {
1945
- if (Array.isArray(pattern)) return pattern.map(p => picomatch$1.parse(p, options));
1946
- return parse(pattern, { ...options, fastpaths: false });
1947
- };
1948
-
1949
- /**
1950
- * Scan a glob pattern to separate the pattern into segments.
1951
- *
1952
- * ```js
1953
- * const picomatch = require('picomatch');
1954
- * // picomatch.scan(input[, options]);
1955
- *
1956
- * const result = picomatch.scan('!./foo/*.js');
1957
- * console.log(result);
1958
- * { prefix: '!./',
1959
- * input: '!./foo/*.js',
1960
- * start: 3,
1961
- * base: 'foo',
1962
- * glob: '*.js',
1963
- * isBrace: false,
1964
- * isBracket: false,
1965
- * isGlob: true,
1966
- * isExtglob: false,
1967
- * isGlobstar: false,
1968
- * negated: true }
1969
- * ```
1970
- * @param {String} `input` Glob pattern to scan.
1971
- * @param {Object} `options`
1972
- * @return {Object} Returns an object with
1973
- * @api public
1974
- */
1975
-
1976
- picomatch$1.scan = (input, options) => scan(input, options);
1977
-
1978
- /**
1979
- * Compile a regular expression from the `state` object returned by the
1980
- * [parse()](#parse) method.
1981
- *
1982
- * @param {Object} `state`
1983
- * @param {Object} `options`
1984
- * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
1985
- * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
1986
- * @return {RegExp}
1987
- * @api public
1988
- */
1989
-
1990
- picomatch$1.compileRe = (state, options, returnOutput = false, returnState = false) => {
1991
- if (returnOutput === true) {
1992
- return state.output;
1993
- }
1994
-
1995
- const opts = options || {};
1996
- const prepend = opts.contains ? '' : '^';
1997
- const append = opts.contains ? '' : '$';
1998
-
1999
- let source = `${prepend}(?:${state.output})${append}`;
2000
- if (state && state.negated === true) {
2001
- source = `^(?!${source}).*$`;
2002
- }
2003
-
2004
- const regex = picomatch$1.toRegex(source, options);
2005
- if (returnState === true) {
2006
- regex.state = state;
2007
- }
2008
-
2009
- return regex;
2010
- };
2011
-
2012
- /**
2013
- * Create a regular expression from a parsed glob pattern.
2014
- *
2015
- * ```js
2016
- * const picomatch = require('picomatch');
2017
- * const state = picomatch.parse('*.js');
2018
- * // picomatch.compileRe(state[, options]);
2019
- *
2020
- * console.log(picomatch.compileRe(state));
2021
- * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
2022
- * ```
2023
- * @param {String} `state` The object returned from the `.parse` method.
2024
- * @param {Object} `options`
2025
- * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
2026
- * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
2027
- * @return {RegExp} Returns a regex created from the given pattern.
2028
- * @api public
2029
- */
2030
-
2031
- picomatch$1.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
2032
- if (!input || typeof input !== 'string') {
2033
- throw new TypeError('Expected a non-empty string');
2034
- }
2035
-
2036
- let parsed = { negated: false, fastpaths: true };
2037
-
2038
- if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
2039
- parsed.output = parse.fastpaths(input, options);
2040
- }
2041
-
2042
- if (!parsed.output) {
2043
- parsed = parse(input, options);
2044
- }
2045
-
2046
- return picomatch$1.compileRe(parsed, options, returnOutput, returnState);
2047
- };
2048
-
2049
- /**
2050
- * Create a regular expression from the given regex source string.
2051
- *
2052
- * ```js
2053
- * const picomatch = require('picomatch');
2054
- * // picomatch.toRegex(source[, options]);
2055
- *
2056
- * const { output } = picomatch.parse('*.js');
2057
- * console.log(picomatch.toRegex(output));
2058
- * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
2059
- * ```
2060
- * @param {String} `source` Regular expression source string.
2061
- * @param {Object} `options`
2062
- * @return {RegExp}
2063
- * @api public
2064
- */
2065
-
2066
- picomatch$1.toRegex = (source, options) => {
2067
- try {
2068
- const opts = options || {};
2069
- return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
2070
- } catch (err) {
2071
- if (options && options.debug === true) throw err;
2072
- return /$^/;
2073
- }
2074
- };
2075
-
2076
- /**
2077
- * Picomatch constants.
2078
- * @return {Object}
2079
- */
2080
-
2081
- picomatch$1.constants = constants;
2082
-
2083
- /**
2084
- * Expose "picomatch"
2085
- */
2086
-
2087
- var picomatch_1 = picomatch$1;
2088
-
2089
- var picomatch = picomatch_1;
2090
-
2091
- // Helper since Typescript can't detect readonly arrays with Array.isArray
2092
- function isArray(arg) {
2093
- return Array.isArray(arg);
2094
- }
2095
- function ensureArray(thing) {
2096
- if (isArray(thing))
2097
- return thing;
2098
- if (thing == null)
2099
- return [];
2100
- return [thing];
2101
- }
2102
-
2103
- const normalizePath = function normalizePath(filename) {
2104
- return filename.split(win32.sep).join(posix.sep);
2105
- };
2106
-
2107
- function getMatcherString(id, resolutionBase) {
2108
- if (resolutionBase === false || isAbsolute(id) || id.startsWith('*')) {
2109
- return normalizePath(id);
2110
- }
2111
- // resolve('') is valid and will default to process.cwd()
2112
- const basePath = normalizePath(resolve(resolutionBase || ''))
2113
- // escape all possible (posix + win) path characters that might interfere with regex
2114
- .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
2115
- // Note that we use posix.join because:
2116
- // 1. the basePath has been normalized to use /
2117
- // 2. the incoming glob (id) matcher, also uses /
2118
- // otherwise Node will force backslash (\) on windows
2119
- return posix.join(basePath, normalizePath(id));
2120
- }
2121
- const createFilter = function createFilter(include, exclude, options) {
2122
- const resolutionBase = options && options.resolve;
2123
- const getMatcher = (id) => id instanceof RegExp
2124
- ? id
2125
- : {
2126
- test: (what) => {
2127
- // this refactor is a tad overly verbose but makes for easy debugging
2128
- const pattern = getMatcherString(id, resolutionBase);
2129
- const fn = picomatch(pattern, { dot: true });
2130
- const result = fn(what);
2131
- return result;
2132
- }
2133
- };
2134
- const includeMatchers = ensureArray(include).map(getMatcher);
2135
- const excludeMatchers = ensureArray(exclude).map(getMatcher);
2136
- return function result(id) {
2137
- if (typeof id !== 'string')
2138
- return false;
2139
- if (/\0/.test(id))
2140
- return false;
2141
- const pathId = normalizePath(id);
2142
- for (let i = 0; i < excludeMatchers.length; ++i) {
2143
- const matcher = excludeMatchers[i];
2144
- if (matcher.test(pathId))
2145
- return false;
2146
- }
2147
- for (let i = 0; i < includeMatchers.length; ++i) {
2148
- const matcher = includeMatchers[i];
2149
- if (matcher.test(pathId))
2150
- return true;
2151
- }
2152
- return !includeMatchers.length;
2153
- };
2154
- };
2155
-
2156
- const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
2157
- const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
2158
- const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
2159
- forbiddenIdentifiers.add('');
2160
-
2161
- function resolveCompiler(root) {
2162
- const compiler = tryRequire("vue/compiler-sfc", root);
2163
- if (!compiler) {
2164
- throw new Error(`Failed to resolve vue/compiler-sfc.
2165
- @vitejs/plugin-vue2 requires vue (>=2.7.0) to be present in the dependency tree.`);
2166
- }
2167
- return compiler;
2168
- }
2169
- const _require = createRequire(import.meta.url);
2170
- function tryRequire(id, from) {
2171
- try {
2172
- return from ? _require(_require.resolve(id, { paths: [from] })) : _require(id);
2173
- } catch (e) {
2174
- }
2175
- }
2176
-
2177
- function parseVueRequest(id) {
2178
- const [filename, rawQuery] = id.split(`?`, 2);
2179
- const query = Object.fromEntries(new URLSearchParams(rawQuery));
2180
- if (query.vue != null) {
2181
- query.vue = true;
2182
- }
2183
- if (query.index != null) {
2184
- query.index = Number(query.index);
2185
- }
2186
- if (query.raw != null) {
2187
- query.raw = true;
2188
- }
2189
- if (query.scoped != null) {
2190
- query.scoped = true;
2191
- }
2192
- return {
2193
- filename,
2194
- query
2195
- };
2196
- }
2197
-
2198
- var slash = path => {
2199
- const isExtendedLengthPath = /^\\\\\?\\/.test(path);
2200
- const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex
2201
-
2202
- if (isExtendedLengthPath || hasNonAscii) {
2203
- return path;
2204
- }
2205
-
2206
- return path.replace(/\\/g, '/');
2207
- };
2208
-
2209
- const cache = /* @__PURE__ */ new Map();
2210
- const prevCache = /* @__PURE__ */ new Map();
2211
- function createDescriptor(filename, source, { root, isProduction, sourceMap, compiler }) {
2212
- let descriptor;
2213
- let errors = [];
2214
- try {
2215
- descriptor = compiler.parse({
2216
- source,
2217
- filename,
2218
- sourceMap
2219
- });
2220
- } catch (e) {
2221
- errors = [e];
2222
- descriptor = compiler.parse({ source: ``, filename });
2223
- }
2224
- const normalizedPath = slash(path$2.normalize(path$2.relative(root, filename)));
2225
- descriptor.id = getHash(normalizedPath + (isProduction ? source : ""));
2226
- cache.set(filename, descriptor);
2227
- return { descriptor, errors };
2228
- }
2229
- function getPrevDescriptor(filename) {
2230
- return prevCache.get(filename);
2231
- }
2232
- function setPrevDescriptor(filename, entry) {
2233
- prevCache.set(filename, entry);
2234
- }
2235
- function getDescriptor(filename, options, createIfNotFound = true) {
2236
- if (cache.has(filename)) {
2237
- return cache.get(filename);
2238
- }
2239
- if (createIfNotFound) {
2240
- const { descriptor, errors } = createDescriptor(filename, fs.readFileSync(filename, "utf-8"), options);
2241
- if (errors.length) {
2242
- throw errors[0];
2243
- }
2244
- return descriptor;
2245
- }
2246
- }
2247
- function getSrcDescriptor(filename, query) {
2248
- if (query.scoped) {
2249
- return cache.get(`${filename}?src=${query.src}`);
2250
- }
2251
- return cache.get(filename);
2252
- }
2253
- function setSrcDescriptor(filename, entry, scoped) {
2254
- if (scoped) {
2255
- cache.set(`${filename}?src=${entry.id}`, entry);
2256
- return;
2257
- }
2258
- cache.set(filename, entry);
2259
- }
2260
- function getHash(text) {
2261
- return createHash("sha256").update(text).digest("hex").substring(0, 8);
2262
- }
2263
-
2264
- const clientCache = /* @__PURE__ */ new WeakMap();
2265
- const ssrCache = /* @__PURE__ */ new WeakMap();
2266
- function getResolvedScript(descriptor, ssr) {
2267
- return (ssr ? ssrCache : clientCache).get(descriptor);
2268
- }
2269
- function setResolvedScript(descriptor, script, ssr) {
2270
- (ssr ? ssrCache : clientCache).set(descriptor, script);
2271
- }
2272
- function resolveScript(descriptor, options, ssr) {
2273
- if (!descriptor.script && !descriptor.scriptSetup) {
2274
- return null;
2275
- }
2276
- const cacheToUse = ssr ? ssrCache : clientCache;
2277
- const cached = cacheToUse.get(descriptor);
2278
- if (cached) {
2279
- return cached;
2280
- }
2281
- let resolved = null;
2282
- resolved = options.compiler.compileScript(descriptor, {
2283
- ...options.script,
2284
- id: descriptor.id,
2285
- isProd: options.isProduction,
2286
- sourceMap: options.sourceMap
2287
- });
2288
- cacheToUse.set(descriptor, resolved);
2289
- return resolved;
2290
- }
2291
-
2292
- function pad (hash, len) {
2293
- while (hash.length < len) {
2294
- hash = '0' + hash;
2295
- }
2296
- return hash;
2297
- }
2298
-
2299
- function fold (hash, text) {
2300
- var i;
2301
- var chr;
2302
- var len;
2303
- if (text.length === 0) {
2304
- return hash;
2305
- }
2306
- for (i = 0, len = text.length; i < len; i++) {
2307
- chr = text.charCodeAt(i);
2308
- hash = ((hash << 5) - hash) + chr;
2309
- hash |= 0;
2310
- }
2311
- return hash < 0 ? hash * -2 : hash;
2312
- }
2313
-
2314
- function foldObject (hash, o, seen) {
2315
- return Object.keys(o).sort().reduce(foldKey, hash);
2316
- function foldKey (hash, key) {
2317
- return foldValue(hash, o[key], key, seen);
2318
- }
2319
- }
2320
-
2321
- function foldValue (input, value, key, seen) {
2322
- var hash = fold(fold(fold(input, key), toString(value)), typeof value);
2323
- if (value === null) {
2324
- return fold(hash, 'null');
2325
- }
2326
- if (value === undefined) {
2327
- return fold(hash, 'undefined');
2328
- }
2329
- if (typeof value === 'object' || typeof value === 'function') {
2330
- if (seen.indexOf(value) !== -1) {
2331
- return fold(hash, '[Circular]' + key);
2332
- }
2333
- seen.push(value);
2334
-
2335
- var objHash = foldObject(hash, value, seen);
2336
-
2337
- if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
2338
- return objHash;
2339
- }
2340
-
2341
- try {
2342
- return fold(objHash, String(value.valueOf()))
2343
- } catch (err) {
2344
- return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
2345
- }
2346
- }
2347
- return fold(hash, value.toString());
2348
- }
2349
-
2350
- function toString (o) {
2351
- return Object.prototype.toString.call(o);
2352
- }
2353
-
2354
- function sum (o) {
2355
- return pad(foldValue(0, o, '', []).toString(16), 8);
2356
- }
2357
-
2358
- var hashSum = sum;
2359
-
2360
- function createRollupError(id, error) {
2361
- if ("msg" in error) {
2362
- return {
2363
- id,
2364
- plugin: "vue",
2365
- message: error.msg,
2366
- name: "vue-compiler-error"
2367
- };
2368
- } else {
2369
- return {
2370
- id,
2371
- plugin: "vue",
2372
- message: error.message,
2373
- name: error.name,
2374
- stack: error.stack
2375
- };
2376
- }
2377
- }
2378
-
2379
- const HMR_RUNTIME_ID = "plugin-vue2:hmr-runtime";
2380
- const hmrRuntimeCode = `
2381
- var __VUE_HMR_RUNTIME__ = Object.create(null)
2382
- var map = Object.create(null)
2383
-
2384
- __VUE_HMR_RUNTIME__.createRecord = function (id, options) {
2385
- if(map[id]) { return }
2386
-
2387
- var Ctor = null
2388
- if (typeof options === 'function') {
2389
- Ctor = options
2390
- options = Ctor.options
2391
- }
2392
- makeOptionsHot(id, options)
2393
- map[id] = {
2394
- Ctor: Ctor,
2395
- options: options,
2396
- instances: []
2397
- }
2398
- }
2399
-
2400
- __VUE_HMR_RUNTIME__.isRecorded = function (id) {
2401
- return typeof map[id] !== 'undefined'
2402
- }
2403
-
2404
- function makeOptionsHot(id, options) {
2405
- if (options.functional) {
2406
- var render = options.render
2407
- options.render = function (h, ctx) {
2408
- var instances = map[id].instances
2409
- if (ctx && instances.indexOf(ctx.parent) < 0) {
2410
- instances.push(ctx.parent)
2411
- }
2412
- return render(h, ctx)
2413
- }
2414
- } else {
2415
- injectHook(options, 'beforeCreate', function() {
2416
- var record = map[id]
2417
- if (!record.Ctor) {
2418
- record.Ctor = this.constructor
2419
- }
2420
- record.instances.push(this)
2421
- })
2422
- injectHook(options, 'beforeDestroy', function() {
2423
- var instances = map[id].instances
2424
- instances.splice(instances.indexOf(this), 1)
2425
- })
2426
- }
2427
- }
2428
-
2429
- function injectHook(options, name, hook) {
2430
- var existing = options[name]
2431
- options[name] = existing
2432
- ? Array.isArray(existing) ? existing.concat(hook) : [existing, hook]
2433
- : [hook]
2434
- }
2435
-
2436
- function tryWrap(fn) {
2437
- return function (id, arg) {
2438
- try {
2439
- fn(id, arg)
2440
- } catch (e) {
2441
- console.error(e)
2442
- console.warn(
2443
- 'Something went wrong during Vue component hot-reload. Full reload required.'
2444
- )
2445
- }
2446
- }
2447
- }
2448
-
2449
- function updateOptions (oldOptions, newOptions) {
2450
- for (var key in oldOptions) {
2451
- if (!(key in newOptions)) {
2452
- delete oldOptions[key]
2453
- }
2454
- }
2455
- for (var key$1 in newOptions) {
2456
- oldOptions[key$1] = newOptions[key$1]
2457
- }
2458
- }
2459
-
2460
- __VUE_HMR_RUNTIME__.rerender = tryWrap(function (id, options) {
2461
- var record = map[id]
2462
- if (!options) {
2463
- record.instances.slice().forEach(function (instance) {
2464
- instance.$forceUpdate()
2465
- })
2466
- return
2467
- }
2468
- if (typeof options === 'function') {
2469
- options = options.options
2470
- }
2471
- if(record.functional){
2472
- record.render = options.render
2473
- record.staticRenderFns = options.staticRenderFns
2474
- __VUE_HMR_RUNTIME__.reload(id, record)
2475
- return
2476
- }
2477
- if (record.Ctor) {
2478
- record.Ctor.options.render = options.render
2479
- record.Ctor.options.staticRenderFns = options.staticRenderFns
2480
- record.instances.slice().forEach(function (instance) {
2481
- instance.$options.render = options.render
2482
- instance.$options.staticRenderFns = options.staticRenderFns
2483
- // reset static trees
2484
- // pre 2.5, all static trees are cached together on the instance
2485
- if (instance._staticTrees) {
2486
- instance._staticTrees = []
2487
- }
2488
- // 2.5.0
2489
- if (Array.isArray(record.Ctor.options.cached)) {
2490
- record.Ctor.options.cached = []
2491
- }
2492
- // 2.5.3
2493
- if (Array.isArray(instance.$options.cached)) {
2494
- instance.$options.cached = []
2495
- }
2496
-
2497
- // post 2.5.4: v-once trees are cached on instance._staticTrees.
2498
- // Pure static trees are cached on the staticRenderFns array
2499
- // (both already reset above)
2500
-
2501
- // 2.6: temporarily mark rendered scoped slots as unstable so that
2502
- // child components can be forced to update
2503
- var restore = patchScopedSlots(instance)
2504
- instance.$forceUpdate()
2505
- instance.$nextTick(restore)
2506
- })
2507
- } else {
2508
- // functional or no instance created yet
2509
- record.options.render = options.render
2510
- record.options.staticRenderFns = options.staticRenderFns
2511
-
2512
- // handle functional component re-render
2513
- if (record.options.functional) {
2514
- // rerender with full options
2515
- if (Object.keys(options).length > 2) {
2516
- updateOptions(record.options, options)
2517
- } else {
2518
- // template-only rerender.
2519
- // need to inject the style injection code for CSS modules
2520
- // to work properly.
2521
- var injectStyles = record.options._injectStyles
2522
- if (injectStyles) {
2523
- var render = options.render
2524
- record.options.render = function (h, ctx) {
2525
- injectStyles.call(ctx)
2526
- return render(h, ctx)
2527
- }
2528
- }
2529
- }
2530
- record.options._Ctor = null
2531
- // 2.5.3
2532
- if (Array.isArray(record.options.cached)) {
2533
- record.options.cached = []
2534
- }
2535
- record.instances.slice().forEach(function (instance) {
2536
- instance.$forceUpdate()
2537
- })
2538
- }
2539
- }
2540
- })
2541
-
2542
- __VUE_HMR_RUNTIME__.reload = tryWrap(function (id, options) {
2543
- var record = map[id]
2544
- if (options) {
2545
- if (typeof options === 'function') {
2546
- options = options.options
2547
- }
2548
- makeOptionsHot(id, options)
2549
- if (record.Ctor) {
2550
- var newCtor = record.Ctor.super.extend(options)
2551
- // prevent record.options._Ctor from being overwritten accidentally
2552
- newCtor.options._Ctor = record.options._Ctor
2553
- record.Ctor.options = newCtor.options
2554
- record.Ctor.cid = newCtor.cid
2555
- record.Ctor.prototype = newCtor.prototype
2556
- if (newCtor.release) {
2557
- // temporary global mixin strategy used in < 2.0.0-alpha.6
2558
- newCtor.release()
2559
- }
2560
- } else {
2561
- updateOptions(record.options, options)
2562
- }
2563
- }
2564
- record.instances.slice().forEach(function (instance) {
2565
- if (instance.$vnode && instance.$vnode.context) {
2566
- instance.$vnode.context.$forceUpdate()
2567
- } else {
2568
- console.warn(
2569
- 'Root or manually mounted instance modified. Full reload required.'
2570
- )
2571
- }
2572
- })
2573
- })
2574
-
2575
- // 2.6 optimizes template-compiled scoped slots and skips updates if child
2576
- // only uses scoped slots. We need to patch the scoped slots resolving helper
2577
- // to temporarily mark all scoped slots as unstable in order to force child
2578
- // updates.
2579
- function patchScopedSlots (instance) {
2580
- if (!instance._u) { return }
2581
- // https://github.com/vuejs/vue/blob/dev/src/core/instance/render-helpers/resolve-scoped-slots.js
2582
- var original = instance._u
2583
- instance._u = function (slots) {
2584
- try {
2585
- // 2.6.4 ~ 2.6.6
2586
- return original(slots, true)
2587
- } catch (e) {
2588
- // 2.5 / >= 2.6.7
2589
- return original(slots, null, true)
2590
- }
2591
- }
2592
- return function () {
2593
- instance._u = original
2594
- }
2595
- }
2596
- export default __VUE_HMR_RUNTIME__
2597
- `;
2598
-
2599
- async function transformTemplateAsModule(code, descriptor, options, pluginContext, ssr) {
2600
- let returnCode = compile(code, descriptor, options, pluginContext, ssr);
2601
- if (options.devServer && options.devServer.config.server.hmr !== false && !ssr && !options.isProduction) {
2602
- returnCode += `
2603
- import __VUE_HMR_RUNTIME__ from "${HMR_RUNTIME_ID}"`;
2604
- returnCode += `
2605
- import.meta.hot.accept((updated) => {
2606
- __VUE_HMR_RUNTIME__.rerender(${JSON.stringify(descriptor.id)}, updated)
2607
- })`;
2608
- }
2609
- return returnCode + `
2610
- export { render, staticRenderFns }`;
2611
- }
2612
- function transformTemplateInMain(code, descriptor, options, pluginContext, ssr) {
2613
- return compile(code, descriptor, options, pluginContext, ssr).replace(/var (render|staticRenderFns) =/g, "var _sfc_$1 =").replace(/(render._withStripped)/, "_sfc_$1");
2614
- }
2615
- function compile(code, descriptor, options, pluginContext, ssr) {
2616
- const filename = descriptor.filename;
2617
- const result = options.compiler.compileTemplate({
2618
- ...resolveTemplateCompilerOptions(descriptor, options, ssr),
2619
- source: code
2620
- });
2621
- if (result.errors.length) {
2622
- result.errors.forEach((error) => pluginContext.error(typeof error === "string" ? { id: filename, message: error } : createRollupError(filename, error)));
2623
- }
2624
- if (result.tips.length) {
2625
- result.tips.forEach((tip) => pluginContext.warn({
2626
- id: filename,
2627
- message: typeof tip === "string" ? tip : tip.msg
2628
- }));
2629
- }
2630
- return transformRequireToImport(result.code);
2631
- }
2632
- function resolveTemplateCompilerOptions(descriptor, options, ssr) {
2633
- const block = descriptor.template;
2634
- if (!block) {
2635
- return;
2636
- }
2637
- const resolvedScript = getResolvedScript(descriptor, ssr);
2638
- const hasScoped = descriptor.styles.some((s) => s.scoped);
2639
- const { id, filename } = descriptor;
2640
- let preprocessOptions = block.lang && options.template?.preprocessOptions;
2641
- if (block.lang === "pug") {
2642
- preprocessOptions = {
2643
- doctype: "html",
2644
- ...preprocessOptions
2645
- };
2646
- }
2647
- const transformAssetUrls = options.template?.transformAssetUrls ?? true;
2648
- let assetUrlOptions;
2649
- if (options.devServer) {
2650
- if (filename.startsWith(options.root)) {
2651
- assetUrlOptions = {
2652
- base: (options.devServer.config.server?.origin ?? "") + options.devServer.config.base + slash(path$2.relative(options.root, path$2.dirname(filename)))
2653
- };
2654
- }
2655
- } else if (transformAssetUrls !== false) {
2656
- assetUrlOptions = {
2657
- includeAbsolute: true
2658
- };
2659
- }
2660
- return {
2661
- transformAssetUrls,
2662
- ...options.template,
2663
- filename,
2664
- isProduction: options.isProduction,
2665
- isFunctional: !!block.attrs.functional,
2666
- optimizeSSR: ssr,
2667
- transformAssetUrlsOptions: {
2668
- ...options.template?.transformAssetUrlsOptions,
2669
- ...assetUrlOptions
2670
- },
2671
- preprocessLang: block.lang,
2672
- preprocessOptions,
2673
- bindings: resolvedScript ? resolvedScript.bindings : void 0,
2674
- prettify: false,
2675
- compilerOptions: {
2676
- whitespace: "condense",
2677
- outputSourceRange: true,
2678
- ...options.template?.compilerOptions,
2679
- scopeId: hasScoped ? `data-v-${id}` : void 0
2680
- }
2681
- };
2682
- }
2683
- function transformRequireToImport(code) {
2684
- const imports = {};
2685
- let strImports = "";
2686
- code = code.replace(/require\(("(?:[^"\\]|\\.)+"|'(?:[^'\\]|\\.)+')\)/g, (_, name) => {
2687
- if (!(name in imports)) {
2688
- imports[name] = `__$_require_${hashSum(name)}__`;
2689
- strImports += `import ${imports[name]} from ${name}
2690
- `;
2691
- }
2692
- return imports[name];
2693
- });
2694
- return strImports + code;
2695
- }
2696
-
2697
- const directRequestRE = /(\?|&)direct\b/;
2698
- async function handleHotUpdate({ file, modules, read, server }, options) {
2699
- const prevDescriptor = getDescriptor(file, options, false);
2700
- if (!prevDescriptor) {
2701
- return;
2702
- }
2703
- setPrevDescriptor(file, prevDescriptor);
2704
- const content = await read();
2705
- const { descriptor } = createDescriptor(file, content, options);
2706
- let needRerender = false;
2707
- const affectedModules = /* @__PURE__ */ new Set();
2708
- const mainModule = modules.find((m) => !/type=/.test(m.url) || /type=script/.test(m.url));
2709
- const templateModule = modules.find((m) => /type=template/.test(m.url));
2710
- if (hasScriptChanged(prevDescriptor, descriptor)) {
2711
- let scriptModule;
2712
- if (descriptor.scriptSetup?.lang && !descriptor.scriptSetup.src || descriptor.script?.lang && !descriptor.script.src) {
2713
- const scriptModuleRE = new RegExp(`type=script.*&lang.${descriptor.scriptSetup?.lang || descriptor.script?.lang}$`);
2714
- scriptModule = modules.find((m) => scriptModuleRE.test(m.url));
2715
- }
2716
- affectedModules.add(scriptModule || mainModule);
2717
- }
2718
- if (!isEqualBlock(descriptor.template, prevDescriptor.template)) {
2719
- if (mainModule && !affectedModules.has(mainModule)) {
2720
- setResolvedScript(descriptor, getResolvedScript(prevDescriptor, false), false);
2721
- }
2722
- affectedModules.add(templateModule);
2723
- needRerender = true;
2724
- }
2725
- const prevStyles = prevDescriptor.styles || [];
2726
- const nextStyles = descriptor.styles || [];
2727
- if (prevStyles.some((s) => s.scoped) !== nextStyles.some((s) => s.scoped)) {
2728
- affectedModules.add(templateModule);
2729
- affectedModules.add(mainModule);
2730
- }
2731
- for (let i = 0; i < nextStyles.length; i++) {
2732
- const prev = prevStyles[i];
2733
- const next = nextStyles[i];
2734
- if (!prev || !isEqualBlock(prev, next)) {
2735
- const mod = modules.find((m) => m.url.includes(`type=style&index=${i}`) && m.url.endsWith(`.${next.lang || "css"}`) && !directRequestRE.test(m.url));
2736
- if (mod) {
2737
- affectedModules.add(mod);
2738
- if (mod.url.includes("&inline")) {
2739
- affectedModules.add(mainModule);
2740
- }
2741
- } else {
2742
- affectedModules.add(mainModule);
2743
- }
2744
- }
2745
- }
2746
- if (prevStyles.length > nextStyles.length) {
2747
- affectedModules.add(mainModule);
2748
- }
2749
- const prevCustoms = prevDescriptor.customBlocks || [];
2750
- const nextCustoms = descriptor.customBlocks || [];
2751
- if (prevCustoms.length !== nextCustoms.length) {
2752
- affectedModules.add(mainModule);
2753
- } else {
2754
- for (let i = 0; i < nextCustoms.length; i++) {
2755
- const prev = prevCustoms[i];
2756
- const next = nextCustoms[i];
2757
- if (!prev || !isEqualBlock(prev, next)) {
2758
- const mod = modules.find((m) => m.url.includes(`type=${prev.type}&index=${i}`));
2759
- if (mod) {
2760
- affectedModules.add(mod);
2761
- } else {
2762
- affectedModules.add(mainModule);
2763
- }
2764
- }
2765
- }
2766
- }
2767
- if (needRerender) {
2768
- if (!templateModule) {
2769
- affectedModules.add(mainModule);
2770
- } else if (mainModule && !affectedModules.has(mainModule)) {
2771
- const styleImporters = [...mainModule.importers].filter((m) => /\.css($|\?)/.test(m.url));
2772
- styleImporters.forEach((m) => affectedModules.add(m));
2773
- }
2774
- }
2775
- return [...affectedModules].filter(Boolean);
2776
- }
2777
- function isEqualBlock(a, b) {
2778
- if (!a && !b)
2779
- return true;
2780
- if (!a || !b)
2781
- return false;
2782
- if (a.src && b.src && a.src === b.src)
2783
- return true;
2784
- if (a.content !== b.content)
2785
- return false;
2786
- const keysA = Object.keys(a.attrs);
2787
- const keysB = Object.keys(b.attrs);
2788
- if (keysA.length !== keysB.length) {
2789
- return false;
2790
- }
2791
- return keysA.every((key) => a.attrs[key] === b.attrs[key]);
2792
- }
2793
- function isOnlyTemplateChanged(prev, next) {
2794
- return !hasScriptChanged(prev, next) && prev.styles.length === next.styles.length && prev.styles.every((s, i) => isEqualBlock(s, next.styles[i])) && prev.customBlocks.length === next.customBlocks.length && prev.customBlocks.every((s, i) => isEqualBlock(s, next.customBlocks[i]));
2795
- }
2796
- function hasScriptChanged(prev, next) {
2797
- if (!isEqualBlock(prev.script, next.script)) {
2798
- return true;
2799
- }
2800
- if (!isEqualBlock(prev.scriptSetup, next.scriptSetup)) {
2801
- return true;
2802
- }
2803
- const prevResolvedScript = getResolvedScript(prev, false);
2804
- const prevImports = prevResolvedScript?.imports;
2805
- if (prevImports) {
2806
- return next.shouldForceReload(prevImports);
2807
- }
2808
- return false;
2809
- }
2810
-
2811
- const NORMALIZER_ID = "plugin-vue2:normalizer";
2812
- const normalizerCode = `
2813
- export default function normalizeComponent (
2814
- scriptExports,
2815
- render,
2816
- staticRenderFns,
2817
- functionalTemplate,
2818
- injectStyles,
2819
- scopeId,
2820
- moduleIdentifier, /* server only */
2821
- shadowMode /* vue-cli only */
2822
- ) {
2823
- // Vue.extend constructor export interop
2824
- var options = typeof scriptExports === 'function'
2825
- ? scriptExports.options
2826
- : scriptExports
2827
-
2828
- // render functions
2829
- if (render) {
2830
- options.render = render
2831
- options.staticRenderFns = staticRenderFns
2832
- options._compiled = true
2833
- }
2834
-
2835
- // functional template
2836
- if (functionalTemplate) {
2837
- options.functional = true
2838
- }
2839
-
2840
- // scopedId
2841
- if (scopeId) {
2842
- options._scopeId = 'data-v-' + scopeId
2843
- }
2844
-
2845
- var hook
2846
- if (moduleIdentifier) { // server build
2847
- hook = function (context) {
2848
- // 2.3 injection
2849
- context =
2850
- context || // cached call
2851
- (this.$vnode && this.$vnode.ssrContext) || // stateful
2852
- (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
2853
- // 2.2 with runInNewContext: true
2854
- if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
2855
- context = __VUE_SSR_CONTEXT__
2856
- }
2857
- // inject component styles
2858
- if (injectStyles) {
2859
- injectStyles.call(this, context)
2860
- }
2861
- // register component module identifier for async chunk inference
2862
- if (context && context._registeredComponents) {
2863
- context._registeredComponents.add(moduleIdentifier)
2864
- }
2865
- }
2866
- // used by ssr in case component is cached and beforeCreate
2867
- // never gets called
2868
- options._ssrRegister = hook
2869
- } else if (injectStyles) {
2870
- hook = shadowMode
2871
- ? function () {
2872
- injectStyles.call(
2873
- this,
2874
- (options.functional ? this.parent : this).$root.$options.shadowRoot
2875
- )
2876
- }
2877
- : injectStyles
2878
- }
2879
-
2880
- if (hook) {
2881
- if (options.functional) {
2882
- // for template-only hot-reload because in that case the render fn doesn't
2883
- // go through the normalizer
2884
- options._injectStyles = hook
2885
- // register for functional component in vue file
2886
- var originalRender = options.render
2887
- options.render = function renderWithStyleInjection (h, context) {
2888
- hook.call(context)
2889
- return originalRender(h, context)
2890
- }
2891
- } else {
2892
- // inject component registration as beforeCreate hook
2893
- var existing = options.beforeCreate
2894
- options.beforeCreate = existing
2895
- ? [].concat(existing, hook)
2896
- : [hook]
2897
- }
2898
- }
2899
-
2900
- return {
2901
- exports: scriptExports,
2902
- options: options
2903
- }
2904
- }`;
2905
-
2906
- async function transformMain(code, filename, options, pluginContext, ssr) {
2907
- const { devServer, isProduction, devToolsEnabled } = options;
2908
- const prevDescriptor = getPrevDescriptor(filename);
2909
- const { descriptor, errors } = createDescriptor(filename, code, options);
2910
- if (errors.length) {
2911
- errors.forEach((error) => pluginContext.error(createRollupError(filename, error)));
2912
- return null;
2913
- }
2914
- const hasScoped = descriptor.styles.some((s) => s.scoped);
2915
- const hasCssModules = descriptor.styles.some((s) => s.module);
2916
- const hasFunctional = descriptor.template && descriptor.template.attrs.functional;
2917
- const { code: scriptCode, map: scriptMap } = await genScriptCode(descriptor, options, pluginContext, ssr);
2918
- const templateCode = await genTemplateCode(descriptor, options, pluginContext, ssr);
2919
- const stylesCode = await genStyleCode(descriptor, pluginContext);
2920
- const customBlocksCode = await genCustomBlockCode(descriptor, pluginContext);
2921
- const output = [
2922
- scriptCode,
2923
- templateCode,
2924
- stylesCode,
2925
- customBlocksCode
2926
- ];
2927
- output.push(`/* normalize component */
2928
- import __normalizer from "${NORMALIZER_ID}"
2929
- var __component__ = /*#__PURE__*/__normalizer(
2930
- _sfc_main,
2931
- _sfc_render,
2932
- _sfc_staticRenderFns,
2933
- ${hasFunctional ? "true" : "false"},
2934
- ${hasCssModules ? `_sfc_injectStyles` : `null`},
2935
- ${hasScoped ? JSON.stringify(descriptor.id) : "null"},
2936
- null,
2937
- null
2938
- )`);
2939
- if (devToolsEnabled || devServer && !isProduction) {
2940
- output.push(`__component__.options.__file = ${JSON.stringify(isProduction ? path$2.basename(filename) : filename)}`);
2941
- }
2942
- if (devServer && devServer.config.server.hmr !== false && !ssr && !isProduction) {
2943
- const id = JSON.stringify(descriptor.id);
2944
- output.push(`import __VUE_HMR_RUNTIME__ from "${HMR_RUNTIME_ID}"`, `if (!__VUE_HMR_RUNTIME__.isRecorded(${id})) {`, ` __VUE_HMR_RUNTIME__.createRecord(${id}, __component__.options)`, `}`);
2945
- if (hasFunctional || prevDescriptor && isOnlyTemplateChanged(prevDescriptor, descriptor)) {
2946
- output.push(`export const _rerender_only = true`);
2947
- }
2948
- output.push(`import.meta.hot.accept(({ default: updated, _rerender_only }) => {`, ` if (_rerender_only) {`, ` __VUE_HMR_RUNTIME__.rerender(${id}, updated)`, ` } else {`, ` __VUE_HMR_RUNTIME__.reload(${id}, updated)`, ` }`, `})`);
2949
- }
2950
- let resolvedMap = scriptMap;
2951
- output.push(`export default __component__.exports`);
2952
- let resolvedCode = output.join("\n");
2953
- if ((descriptor.script?.lang === "ts" || descriptor.scriptSetup?.lang === "ts") && !descriptor.script?.src) {
2954
- const { code: code2, map } = await transformWithEsbuild(resolvedCode, filename, { loader: "ts", sourcemap: options.sourceMap }, resolvedMap);
2955
- resolvedCode = code2;
2956
- resolvedMap = resolvedMap ? map : resolvedMap;
2957
- }
2958
- return {
2959
- code: resolvedCode,
2960
- map: resolvedMap || {
2961
- mappings: ""
2962
- },
2963
- meta: {
2964
- vite: {
2965
- lang: descriptor.script?.lang || descriptor.scriptSetup?.lang || "js"
2966
- }
2967
- }
2968
- };
2969
- }
2970
- async function genTemplateCode(descriptor, options, pluginContext, ssr) {
2971
- const template = descriptor.template;
2972
- if (!template) {
2973
- return "const _sfc_render = null; const _sfc_staticRenderFns = null";
2974
- }
2975
- const hasScoped = descriptor.styles.some((style) => style.scoped);
2976
- if (!template.lang && !template.src) {
2977
- return transformTemplateInMain(template.content, descriptor, options, pluginContext, ssr);
2978
- } else {
2979
- if (template.src) {
2980
- await linkSrcToDescriptor(template.src, descriptor, pluginContext, hasScoped);
2981
- }
2982
- const src = template.src || descriptor.filename;
2983
- const srcQuery = template.src ? hasScoped ? `&src=${descriptor.id}` : "&src=true" : "";
2984
- const scopedQuery = hasScoped ? `&scoped=${descriptor.id}` : ``;
2985
- const attrsQuery = attrsToQuery(template.attrs, "js", true);
2986
- const query = `?vue&type=template${srcQuery}${scopedQuery}${attrsQuery}`;
2987
- const request = JSON.stringify(src + query);
2988
- return `import { render as _sfc_render, staticRenderFns as _sfc_staticRenderFns } from ${request}`;
2989
- }
2990
- }
2991
- async function genScriptCode(descriptor, options, pluginContext, ssr) {
2992
- let scriptCode = `const _sfc_main = {}`;
2993
- let map;
2994
- const script = resolveScript(descriptor, options, ssr);
2995
- if (script) {
2996
- if ((!script.lang || script.lang === "ts" && options.devServer) && !script.src) {
2997
- const userPlugins = options.script?.babelParserPlugins || [];
2998
- const defaultPlugins = script.lang === "ts" ? userPlugins.includes("decorators") ? ["typescript"] : ["typescript", "decorators-legacy"] : [];
2999
- scriptCode = options.compiler.rewriteDefault(script.content, "_sfc_main", [...defaultPlugins, ...userPlugins]);
3000
- map = script.map;
3001
- } else {
3002
- if (script.src) {
3003
- await linkSrcToDescriptor(script.src, descriptor, pluginContext, false);
3004
- }
3005
- const src = script.src || descriptor.filename;
3006
- const langFallback = script.src && path$2.extname(src).slice(1) || "js";
3007
- const attrsQuery = attrsToQuery(script.attrs, langFallback);
3008
- const srcQuery = script.src ? `&src=true` : ``;
3009
- const query = `?vue&type=script${srcQuery}${attrsQuery}`;
3010
- const request = JSON.stringify(src + query);
3011
- scriptCode = `import _sfc_main from ${request}
3012
- export * from ${request}`;
3013
- }
3014
- }
3015
- return {
3016
- code: scriptCode,
3017
- map
3018
- };
3019
- }
3020
- async function genStyleCode(descriptor, pluginContext) {
3021
- let stylesCode = ``;
3022
- let cssModulesMap;
3023
- if (descriptor.styles.length) {
3024
- for (let i = 0; i < descriptor.styles.length; i++) {
3025
- const style = descriptor.styles[i];
3026
- if (style.src) {
3027
- await linkSrcToDescriptor(style.src, descriptor, pluginContext, style.scoped);
3028
- }
3029
- const src = style.src || descriptor.filename;
3030
- const attrsQuery = attrsToQuery(style.attrs, "css");
3031
- const srcQuery = style.src ? style.scoped ? `&src=${descriptor.id}` : "&src=true" : "";
3032
- const directQuery = ``;
3033
- const scopedQuery = style.scoped ? `&scoped=${descriptor.id}` : ``;
3034
- const query = `?vue&type=style&index=${i}${srcQuery}${directQuery}${scopedQuery}`;
3035
- const styleRequest = src + query + attrsQuery;
3036
- if (style.module) {
3037
- const [importCode, nameMap] = genCSSModulesCode(i, styleRequest, style.module);
3038
- stylesCode += importCode;
3039
- Object.assign(cssModulesMap || (cssModulesMap = {}), nameMap);
3040
- } else {
3041
- stylesCode += `
3042
- import ${JSON.stringify(styleRequest)}`;
3043
- }
3044
- }
3045
- }
3046
- if (cssModulesMap) {
3047
- const mappingCode = Object.entries(cssModulesMap).reduce((code, [key, value]) => code + `"${key}":${value},
3048
- `, "{\n") + "}";
3049
- stylesCode += `
3050
- const __cssModules = ${mappingCode}`;
3051
- stylesCode += `
3052
- function _sfc_injectStyles(ctx) {
3053
- for (var key in __cssModules) {
3054
- this[key] = __cssModules[key]
3055
- }
3056
- }`;
3057
- }
3058
- return stylesCode;
3059
- }
3060
- function genCSSModulesCode(index, request, moduleName) {
3061
- const styleVar = `style${index}`;
3062
- const exposedName = typeof moduleName === "string" ? moduleName : "$style";
3063
- const moduleRequest = request.replace(/\.(\w+)$/, ".module.$1");
3064
- return [
3065
- `
3066
- import ${styleVar} from ${JSON.stringify(moduleRequest)}`,
3067
- { [exposedName]: styleVar }
3068
- ];
3069
- }
3070
- async function genCustomBlockCode(descriptor, pluginContext) {
3071
- let code = "";
3072
- for (let index = 0; index < descriptor.customBlocks.length; index++) {
3073
- const block = descriptor.customBlocks[index];
3074
- if (block.src) {
3075
- await linkSrcToDescriptor(block.src, descriptor, pluginContext, false);
3076
- }
3077
- const src = block.src || descriptor.filename;
3078
- const attrsQuery = attrsToQuery(block.attrs, block.type);
3079
- const srcQuery = block.src ? `&src=true` : ``;
3080
- const query = `?vue&type=${block.type}&index=${index}${srcQuery}${attrsQuery}`;
3081
- const request = JSON.stringify(src + query);
3082
- code += `import block${index} from ${request}
3083
- `;
3084
- code += `if (typeof block${index} === 'function') block${index}(_sfc_main)
3085
- `;
3086
- }
3087
- return code;
3088
- }
3089
- async function linkSrcToDescriptor(src, descriptor, pluginContext, scoped) {
3090
- const srcFile = (await pluginContext.resolve(src, descriptor.filename))?.id || src;
3091
- setSrcDescriptor(srcFile.replace(/\?.*$/, ""), descriptor, scoped);
3092
- }
3093
- const ignoreList = ["id", "index", "src", "type", "lang", "module", "scoped"];
3094
- function attrsToQuery(attrs, langFallback, forceLangFallback = false) {
3095
- let query = ``;
3096
- for (const name in attrs) {
3097
- const value = attrs[name];
3098
- if (!ignoreList.includes(name)) {
3099
- query += `&${encodeURIComponent(name)}${value ? `=${encodeURIComponent(value)}` : ``}`;
3100
- }
3101
- }
3102
- if (langFallback || attrs.lang) {
3103
- query += `lang` in attrs ? forceLangFallback ? `&lang.${langFallback}` : `&lang.${attrs.lang}` : `&lang.${langFallback}`;
3104
- }
3105
- return query;
3106
- }
3107
-
3108
- async function transformStyle(code, descriptor, index, options, pluginContext, filename) {
3109
- const block = descriptor.styles[index];
3110
- const result = await options.compiler.compileStyleAsync({
3111
- ...options.style,
3112
- filename: descriptor.filename,
3113
- id: `data-v-${descriptor.id}`,
3114
- isProd: options.isProduction,
3115
- source: code,
3116
- scoped: !!block.scoped,
3117
- ...options.cssDevSourcemap ? {
3118
- postcssOptions: {
3119
- map: {
3120
- from: filename,
3121
- inline: false,
3122
- annotation: false
3123
- }
3124
- }
3125
- } : {}
3126
- });
3127
- if (result.errors.length) {
3128
- result.errors.forEach((error) => {
3129
- if (error.line && error.column) {
3130
- error.loc = {
3131
- file: descriptor.filename,
3132
- line: error.line + getLine(descriptor.source, block.start),
3133
- column: error.column
3134
- };
3135
- }
3136
- pluginContext.error(error);
3137
- });
3138
- return null;
3139
- }
3140
- const map = result.map ? await formatPostcssSourceMap(result.map, filename) : { mappings: "" };
3141
- return {
3142
- code: result.code,
3143
- map
3144
- };
3145
- }
3146
- function getLine(source, start) {
3147
- const lines = source.split(/\r?\n/g);
3148
- let cur = 0;
3149
- for (let i = 0; i < lines.length; i++) {
3150
- cur += lines[i].length;
3151
- if (cur >= start) {
3152
- return i;
3153
- }
3154
- }
3155
- }
3156
-
3157
- function vuePlugin(rawOptions = {}) {
3158
- const {
3159
- include = /\.vue$/,
3160
- exclude
3161
- } = rawOptions;
3162
- const filter = createFilter(include, exclude);
3163
- let options = {
3164
- isProduction: process.env.NODE_ENV === "production",
3165
- compiler: null,
3166
- ...rawOptions,
3167
- include,
3168
- exclude,
3169
- root: process.cwd(),
3170
- sourceMap: true,
3171
- cssDevSourcemap: false,
3172
- devToolsEnabled: process.env.NODE_ENV !== "production"
3173
- };
3174
- return {
3175
- name: "vite:vue2",
3176
- handleHotUpdate(ctx) {
3177
- if (!filter(ctx.file)) {
3178
- return;
3179
- }
3180
- return handleHotUpdate(ctx, options);
3181
- },
3182
- configResolved(config) {
3183
- options = {
3184
- ...options,
3185
- root: config.root,
3186
- isProduction: config.isProduction,
3187
- sourceMap: config.command === "build" ? !!config.build.sourcemap : true,
3188
- cssDevSourcemap: config.css?.devSourcemap ?? false,
3189
- devToolsEnabled: !config.isProduction
3190
- };
3191
- if (!config.resolve.alias.some(({ find }) => find === "vue")) {
3192
- config.resolve.alias.push({
3193
- find: "vue",
3194
- replacement: "vue/dist/vue.runtime.esm.js"
3195
- });
3196
- }
3197
- },
3198
- configureServer(server) {
3199
- options.devServer = server;
3200
- },
3201
- buildStart() {
3202
- options.compiler = resolveCompiler();
3203
- },
3204
- async resolveId(id) {
3205
- if (id === NORMALIZER_ID || id === HMR_RUNTIME_ID) {
3206
- return id;
3207
- }
3208
- if (parseVueRequest(id).query.vue) {
3209
- return id;
3210
- }
3211
- },
3212
- load(id, opt) {
3213
- const ssr = opt?.ssr === true;
3214
- if (id === NORMALIZER_ID) {
3215
- return normalizerCode;
3216
- }
3217
- if (id === HMR_RUNTIME_ID) {
3218
- return hmrRuntimeCode;
3219
- }
3220
- const { filename, query } = parseVueRequest(id);
3221
- if (query.vue) {
3222
- if (query.src) {
3223
- return fs.readFileSync(filename, "utf-8");
3224
- }
3225
- const descriptor = getDescriptor(filename, options);
3226
- let block;
3227
- if (query.type === "script") {
3228
- block = getResolvedScript(descriptor, ssr);
3229
- } else if (query.type === "template") {
3230
- block = descriptor.template;
3231
- } else if (query.type === "style") {
3232
- block = descriptor.styles[query.index];
3233
- } else if (query.index != null) {
3234
- block = descriptor.customBlocks[query.index];
3235
- }
3236
- if (block) {
3237
- return {
3238
- code: block.content,
3239
- map: block.map
3240
- };
3241
- }
3242
- }
3243
- },
3244
- async transform(code, id, opt) {
3245
- const ssr = opt?.ssr === true;
3246
- const { filename, query } = parseVueRequest(id);
3247
- if (query.raw) {
3248
- return;
3249
- }
3250
- if (!filter(filename) && !query.vue) {
3251
- return;
3252
- }
3253
- if (!query.vue) {
3254
- return transformMain(code, filename, options, this, ssr);
3255
- } else {
3256
- const descriptor = query.src ? getSrcDescriptor(filename, query) : getDescriptor(filename, options);
3257
- if (query.type === "template") {
3258
- return {
3259
- code: await transformTemplateAsModule(code, descriptor, options, this, ssr),
3260
- map: {
3261
- mappings: ""
3262
- }
3263
- };
3264
- } else if (query.type === "style") {
3265
- return transformStyle(code, descriptor, Number(query.index), options, this, filename);
3266
- }
3267
- }
3268
- }
3269
- };
3270
- }
3271
-
3272
- const name = "kirbyup";
3273
- const version = "2.0.1";
3274
-
3275
- class PrettyError extends Error {
3276
- constructor(message) {
3277
- super(message);
3278
- this.name = this.constructor.name;
3279
- if (typeof Error.captureStackTrace === "function")
3280
- Error.captureStackTrace(this, this.constructor);
3281
- else
3282
- this.stack = new Error(message).stack;
3283
- }
3284
- }
3285
- function handleError(error) {
3286
- consola.error(error.message);
3287
- process.exitCode = 1;
3288
- }
3289
-
3290
- function toArray(array) {
3291
- array = array || [];
3292
- if (Array.isArray(array))
3293
- return array;
3294
- return [array];
3295
- }
3296
- const compress = promisify(gzip);
3297
- async function getCompressedSize(code) {
3298
- const size = (await compress(typeof code === "string" ? code : Buffer.from(code))).length / 1024;
3299
- return ` / gzip: ${size.toFixed(2)} KiB`;
3300
- }
3301
- async function printFileInfo(root, outDir, filePath, content, type, maxLength) {
3302
- const prettyOutDir = `${normalize(relative(root, resolve$1(root, outDir)))}/`;
3303
- const kibs = content.length / 1024;
3304
- const compressedSize = await getCompressedSize(content);
3305
- const writeColor = type === "chunk" ? colors.cyan : colors.magenta;
3306
- consola.log(
3307
- colors.white(colors.dim(prettyOutDir)) + writeColor(filePath.padEnd(maxLength + 2)) + colors.dim(`${kibs.toFixed(2)} KiB${compressedSize}`)
3308
- );
3309
- }
3310
-
3311
- async function loadConfig(cwd = process.cwd(), configOrPath = cwd, extraConfigSources = []) {
3312
- let inlineConfig = {};
3313
- if (typeof configOrPath !== "string") {
3314
- inlineConfig = configOrPath;
3315
- if (inlineConfig.configFile === false) {
3316
- return {
3317
- config: inlineConfig,
3318
- sources: []
3319
- };
3320
- } else {
3321
- configOrPath = inlineConfig.configFile || process.cwd();
3322
- }
3323
- }
3324
- const resolved = resolve$1(configOrPath);
3325
- let isFile = false;
3326
- if (existsSync(resolved) && statSync(resolved).isFile()) {
3327
- isFile = true;
3328
- cwd = dirname(resolved);
3329
- }
3330
- const loader = createConfigLoader({
3331
- sources: isFile ? [
3332
- {
3333
- files: resolved,
3334
- extensions: []
3335
- }
3336
- ] : [
3337
- {
3338
- files: ["kirbyup.config"]
3339
- },
3340
- ...extraConfigSources
3341
- ],
3342
- cwd,
3343
- defaults: inlineConfig
3344
- });
3345
- const result = await loader.load();
3346
- result.config = result.config || inlineConfig;
3347
- return result;
3348
- }
3349
-
3350
- const multilineCommentsRE = /\/\*(.|[\r\n])*?\*\//gm;
3351
- const singlelineCommentsRE = /\/\/.*/g;
3352
-
3353
- function kirbyupAutoImportPlugin() {
3354
- let config;
3355
- return {
3356
- name: "kirbyup:auto-import",
3357
- configResolved(resolvedConfig) {
3358
- config = resolvedConfig;
3359
- },
3360
- async transform(code) {
3361
- if (code.includes("kirbyup.import")) {
3362
- const kirbyupImportRE = /\bkirbyup\.import\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*\)/g;
3363
- const noCommentsCode = code.replace(multilineCommentsRE, (m) => " ".repeat(m.length)).replace(singlelineCommentsRE, (m) => " ".repeat(m.length));
3364
- let s = null;
3365
- let match;
3366
- while (match = kirbyupImportRE.exec(noCommentsCode)) {
3367
- const { 0: exp, 1: rawPath, index } = match;
3368
- if (!s)
3369
- s = new MagicString(code);
3370
- s.overwrite(
3371
- index,
3372
- index + exp.length,
3373
- `kirbyup.import(import.meta.glob(${rawPath}, { eager: true }))`
3374
- );
3375
- }
3376
- if (s) {
3377
- return {
3378
- code: s.toString(),
3379
- map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
3380
- };
3381
- }
3382
- }
3383
- return null;
3384
- }
3385
- };
3386
- }
3387
-
3388
- const __HMR_CODE__ = `
3389
- if (typeof __VUE_HMR_RUNTIME__ !== 'undefined' && import.meta.hot) {
3390
- __VUE_HMR_RUNTIME__.reload = () => import.meta.hot.invalidate();
3391
- }`.trim();
3392
- const getViteProxyModule = (entryUrl, pm) => `
3393
- try {
3394
- await import("${entryUrl}");
3395
- } catch (err) {
3396
- console.error(
3397
- "[kirbyup] Couldn't connect to the development server. Run \`${pm} run serve\` to start Vite or build the plugin with \`${pm} run build\` so Kirby uses the production version."
3398
- );
3399
- throw err;
3400
- }`.trim();
3401
- function kirbyupHmrPlugin(options) {
3402
- let config;
3403
- let entry;
3404
- let indexMjs;
3405
- return {
3406
- name: "kirbyup:hmr",
3407
- apply: "serve",
3408
- configResolved(resolvedConfig) {
3409
- config = resolvedConfig;
3410
- entry = resolve$1(config.root, options.entry);
3411
- indexMjs = resolve$1(config.root, options.outDir || "", "index.dev.mjs");
3412
- },
3413
- transform(code, id) {
3414
- const { query } = parseVueRequest(id);
3415
- if (query.raw)
3416
- return;
3417
- if ((typeof id !== "string" || /\0/.test(id)) && !query.vue)
3418
- return;
3419
- if (/\.vue$/.test(id) && !query.vue)
3420
- return `${code};${__HMR_CODE__}`;
3421
- },
3422
- configureServer(server) {
3423
- if (!server.httpServer)
3424
- return;
3425
- server.httpServer.once("listening", async () => {
3426
- const entryPath = entry.replace(`${config.root}/`, "");
3427
- const { address, family, port } = server.httpServer.address();
3428
- const hostname = family === "IPv6" ? `[${address}]` : address;
3429
- const baseUrl = `http://${hostname}:${port}${config.base}`;
3430
- const entryUrl = new URL(entryPath, baseUrl).href;
3431
- const pm = await detect().catch(() => "npm");
3432
- await writeFile(indexMjs, getViteProxyModule(entryUrl, pm));
3433
- });
3434
- },
3435
- closeBundle() {
3436
- if (existsSync$1(indexMjs))
3437
- unlinkSync(indexMjs);
3438
- }
3439
- };
3440
- }
3441
-
3442
- function kirbyupBuildCleanupPlugin(options) {
3443
- let config;
3444
- let indexMjs;
3445
- return {
3446
- name: "kirbyup:build-cleanup",
3447
- configResolved(resolvedConfig) {
3448
- config = resolvedConfig;
3449
- indexMjs = resolve$1(config.root, options.outDir, "index.dev.mjs");
3450
- },
3451
- writeBundle() {
3452
- if (existsSync$1(indexMjs))
3453
- unlinkSync(indexMjs);
3454
- }
3455
- };
3456
- }
3457
-
3458
- let resolvedKirbyupConfig;
3459
- let resolvedPostCssConfig;
3460
- function getViteConfig(command, options) {
3461
- const aliasDir = resolve$1(options.cwd, dirname(options.entry));
3462
- const { alias = {}, extendViteConfig = {} } = resolvedKirbyupConfig;
3463
- const baseConfig = {
3464
- resolve: {
3465
- alias: { "~/": `${aliasDir}/`, "@/": `${aliasDir}/`, ...alias }
3466
- },
3467
- plugins: [vuePlugin(), kirbyupAutoImportPlugin()],
3468
- css: { postcss: resolvedPostCssConfig },
3469
- envPrefix: ["VITE_", "KIRBYUP_"],
3470
- logLevel: "warn"
3471
- };
3472
- if (command === "serve") {
3473
- const { port, watch } = options;
3474
- const serveConfig = mergeConfig(baseConfig, {
3475
- plugins: [
3476
- kirbyupHmrPlugin(options),
3477
- watch && fullReloadPlugin(watch)
3478
- ],
3479
- build: { rollupOptions: { input: resolve$1(options.cwd, options.entry) } },
3480
- server: { port, strictPort: true, origin: `http://localhost:${port}` }
3481
- });
3482
- return mergeConfig(serveConfig, extendViteConfig);
3483
- }
3484
- const mode = options.watch ? "development" : "production";
3485
- const buildConfig = mergeConfig(baseConfig, {
3486
- plugins: [kirbyupBuildCleanupPlugin(options)],
3487
- mode,
3488
- build: {
3489
- lib: {
3490
- entry: resolve$1(options.cwd, options.entry),
3491
- formats: ["iife"],
3492
- name: "kirbyupExport",
3493
- fileName: () => "index.js"
3494
- },
3495
- minify: mode === "production",
3496
- outDir: options.outDir,
3497
- emptyOutDir: false,
3498
- rollupOptions: {
3499
- external: ["vue"],
3500
- output: {
3501
- assetFileNames: "index.[ext]",
3502
- globals: { vue: "Vue" }
3503
- }
3504
- }
3505
- }
3506
- });
3507
- return mergeConfig(buildConfig, extendViteConfig);
3508
- }
3509
- async function generate(options) {
3510
- const config = getViteConfig("build", options);
3511
- let result;
3512
- try {
3513
- result = await build$1(config);
3514
- } catch (error) {
3515
- consola.error("Build failed");
3516
- if (config.mode === "production")
3517
- throw error;
3518
- }
3519
- if (result && !options.watch) {
3520
- const { output } = toArray(result)[0];
3521
- let longest = 0;
3522
- for (const file in output) {
3523
- const l = output[file].fileName.length;
3524
- if (l > longest)
3525
- longest = l;
3526
- }
3527
- for (const {
3528
- fileName,
3529
- type,
3530
- code
3531
- } of output) {
3532
- await printFileInfo(
3533
- options.cwd,
3534
- options.outDir,
3535
- fileName,
3536
- code ?? await readFile(resolve$1(options.outDir, fileName), "utf8"),
3537
- type,
3538
- longest
3539
- );
3540
- }
3541
- }
3542
- return result;
3543
- }
3544
- async function build(options) {
3545
- ensureEntry(options);
3546
- const { cwd } = options;
3547
- const { config, sources: configSources } = await loadConfig(cwd);
3548
- resolvedKirbyupConfig = config;
3549
- try {
3550
- resolvedPostCssConfig = await postcssrc({});
3551
- } catch (err) {
3552
- if (!/No PostCSS Config found/.test(err.message))
3553
- throw err;
3554
- resolvedPostCssConfig = {
3555
- plugins: [postcssLogical(), postcssDirPseudoClass()]
3556
- };
3557
- }
3558
- {
3559
- consola.log(colors.green(`${name} v${version}`));
3560
- consola.start(`Building ${colors.cyan(options.entry)}`);
3561
- }
3562
- if (options.watch)
3563
- consola.info("Running in watch mode");
3564
- const debouncedBuild = debounce(async () => {
3565
- generate(options).catch(handleError);
3566
- }, 100);
3567
- const startWatcher = async () => {
3568
- if (!options.watch)
3569
- return;
3570
- const { watch } = await import('chokidar');
3571
- const ignored = [
3572
- "**/{.git,node_modules}/**",
3573
- "index.{css,js}"
3574
- ];
3575
- const watchPaths = typeof options.watch === "boolean" ? dirname(options.entry) : Array.isArray(options.watch) ? options.watch.filter(
3576
- (path) => typeof path === "string"
3577
- ) : options.watch;
3578
- consola.info(
3579
- `Watching for changes in ${toArray(watchPaths).map((i) => colors.cyan(i)).join(", ")}`
3580
- );
3581
- const watcher = watch(watchPaths, {
3582
- ignoreInitial: true,
3583
- ignorePermissionErrors: true,
3584
- ignored,
3585
- cwd
3586
- });
3587
- if (configSources.length)
3588
- watcher.add(configSources);
3589
- watcher.on("all", async (type, file) => {
3590
- if (configSources.includes(file)) {
3591
- resolvedKirbyupConfig = (await loadConfig()).config;
3592
- consola.info(
3593
- `${colors.cyan(basename(file))} changed, setting new config`
3594
- );
3595
- } else {
3596
- consola.log(`${colors.green(type)} ${colors.white(colors.dim(file))}`);
3597
- }
3598
- debouncedBuild();
3599
- });
3600
- };
3601
- await generate(options);
3602
- consola.success("Build successful");
3603
- startWatcher();
3604
- }
3605
- async function serve(options) {
3606
- ensureEntry(options);
3607
- const { cwd } = options;
3608
- const { config } = await loadConfig(cwd);
3609
- resolvedKirbyupConfig = config;
3610
- try {
3611
- resolvedPostCssConfig = await postcssrc({});
3612
- } catch (err) {
3613
- if (!/No PostCSS Config found/.test(err.message))
3614
- throw err;
3615
- resolvedPostCssConfig = {
3616
- plugins: [postcssLogical(), postcssDirPseudoClass()]
3617
- };
3618
- }
3619
- {
3620
- consola.log(colors.green(`${name} v${version}`));
3621
- consola.info("Starting development server...");
3622
- }
3623
- const server = await createServer(getViteConfig("serve", options));
3624
- await server.listen();
3625
- consola.success(`Server is listening on :${server.config.server.port}`);
3626
- return server;
3627
- }
3628
- function ensureEntry(options) {
3629
- if (!existsSync$1(resolve$1(options.cwd, options.entry)))
3630
- throw new PrettyError(`Cannot find "${options.entry}"`);
3631
- }
3632
-
3633
- export { build as b, handleError as h, name as n, serve as s, version as v };