@sanity/pkg-utils 1.7.2 → 1.8.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.
Files changed (43) hide show
  1. package/bin/{pkg-utils → pkg-utils.cjs} +0 -0
  2. package/dist/{__resolveBuildContext-9b0aa9f9.cjs → __resolveBuildContext-7cb7c9a7.cjs} +59 -8
  3. package/dist/__resolveBuildContext-7cb7c9a7.cjs.map +1 -0
  4. package/dist/{_build-6e7deb31.cjs → _build-e82a508a.cjs} +24 -17
  5. package/dist/_build-e82a508a.cjs.map +1 -0
  6. package/dist/{_buildAction-d8841b41.cjs → _buildAction-727e661a.cjs} +9 -5
  7. package/dist/{_buildAction-d8841b41.cjs.map → _buildAction-727e661a.cjs.map} +1 -1
  8. package/dist/{_check-04a1f749.cjs → _check-a2eb014d.cjs} +6 -2
  9. package/dist/{_check-04a1f749.cjs.map → _check-a2eb014d.cjs.map} +1 -1
  10. package/dist/{_checkAction-09426a13.cjs → _checkAction-7cd9dfde.cjs} +3 -3
  11. package/dist/{_checkAction-09426a13.cjs.map → _checkAction-7cd9dfde.cjs.map} +1 -1
  12. package/dist/_index-a4fddb59.cjs +4244 -0
  13. package/dist/_index-a4fddb59.cjs.map +1 -0
  14. package/dist/{_watch-cf9c717f.cjs → _watch-b0a983e3.cjs} +25 -18
  15. package/dist/_watch-b0a983e3.cjs.map +1 -0
  16. package/dist/{_watchAction-5941527f.cjs → _watchAction-c44da6cb.cjs} +9 -5
  17. package/dist/{_watchAction-5941527f.cjs.map → _watchAction-c44da6cb.cjs.map} +1 -1
  18. package/dist/cli.cjs +4 -4
  19. package/dist/index.cjs +10 -6
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.js +3823 -268
  22. package/dist/index.js.map +1 -1
  23. package/dist/{index.d.ts → types/src/node/index.d.ts} +24 -10
  24. package/package.json +13 -11
  25. package/src/node/_core/pkg/_loadPkg.ts +2 -41
  26. package/src/node/_core/pkg/_loadPkgWithReporting.ts +1 -1
  27. package/src/node/_core/pkg/_parseExports.ts +26 -3
  28. package/src/node/_core/pkg/_types.ts +8 -2
  29. package/src/node/_core/pkg/_validateExports.ts +29 -0
  30. package/src/node/_core/pkg/_validatePkg.ts +50 -0
  31. package/src/node/_resolveBuildTasks.ts +18 -14
  32. package/src/node/_resolveWatchTasks.ts +19 -15
  33. package/src/node/_tasks/dts/_buildTypes.ts +2 -25
  34. package/src/node/_tasks/dts/_doExtract.ts +59 -27
  35. package/src/node/_tasks/dts/_dtsTask.ts +4 -1
  36. package/src/node/_tasks/dts/_dtsWatchTask.ts +4 -1
  37. package/src/node/_tasks/dts/_types.ts +13 -8
  38. package/src/node/_tasks/rollup/_resolveRollupConfig.ts +30 -3
  39. package/dist/__resolveBuildContext-9b0aa9f9.cjs.map +0 -1
  40. package/dist/_build-6e7deb31.cjs.map +0 -1
  41. package/dist/_index-46cab21c.cjs +0 -736
  42. package/dist/_index-46cab21c.cjs.map +0 -1
  43. package/dist/_watch-cf9c717f.cjs.map +0 -1
package/dist/index.js CHANGED
@@ -10,18 +10,20 @@ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { va
10
10
 
11
11
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
12
12
 
13
- import path from 'path';
13
+ import path$1 from 'path';
14
14
  import { register } from 'esbuild-register/dist/node';
15
15
  import findConfig from 'find-config';
16
16
  import pkgUp from 'pkg-up';
17
- import fs, { readFile } from 'fs/promises';
17
+ import fs$1, { readFile, rename } from 'fs/promises';
18
18
  import { z, ZodError } from 'zod';
19
19
  import chalk from 'chalk';
20
20
  import ts from 'typescript';
21
- import fs$1, { statSync } from 'fs';
21
+ import fs$2, { statSync } from 'fs';
22
22
  import { Observable, switchMap } from 'rxjs';
23
23
  import { promisify } from 'util';
24
- import rimrafCallback from 'rimraf';
24
+ import cpx from 'cpx';
25
+ import require$$5 from 'assert';
26
+ import require$$3 from 'events';
25
27
  import { ExtractorConfig, Extractor } from '@microsoft/api-extractor';
26
28
  import mkdirp from 'mkdirp';
27
29
  import prettier from 'prettier';
@@ -59,7 +61,7 @@ async function _loadConfig(options) {
59
61
  cwd
60
62
  });
61
63
  if (!pkgPath) return void 0;
62
- const root = path.dirname(pkgPath);
64
+ const root = path$1.dirname(pkgPath);
63
65
 
64
66
  const configFile = _findConfigFile(root);
65
67
 
@@ -122,14 +124,15 @@ function defineConfig(configOptions) {
122
124
  }
123
125
 
124
126
  const pkgSchema = z.object({
125
- type: z.optional(z.enum(["module"])),
127
+ type: z.optional(z.enum(["commonjs", "module"])),
126
128
  name: z.string(),
127
129
  version: z.string(),
130
+ license: z.string(),
128
131
  bin: z.optional(z.record(z.string())),
129
132
  dependencies: z.optional(z.record(z.string())),
130
133
  devDependencies: z.optional(z.record(z.string())),
131
134
  peerDependencies: z.optional(z.record(z.string())),
132
- source: z.string(),
135
+ source: z.optional(z.string()),
133
136
  main: z.optional(z.string()),
134
137
  browser: z.optional(z.record(z.string())),
135
138
  module: z.optional(z.string()),
@@ -138,10 +141,12 @@ const pkgSchema = z.object({
138
141
  types: z.optional(z.string()),
139
142
  source: z.string(),
140
143
  browser: z.optional(z.object({
144
+ source: z.string(),
141
145
  require: z.optional(z.string()),
142
146
  import: z.optional(z.string())
143
147
  })),
144
148
  node: z.optional(z.object({
149
+ source: z.string(),
145
150
  require: z.optional(z.string()),
146
151
  import: z.optional(z.string())
147
152
  })),
@@ -152,6 +157,13 @@ const pkgSchema = z.object({
152
157
  browserslist: z.optional(z.array(z.string()))
153
158
  });
154
159
 
160
+ function _validatePkg(input) {
161
+ const pkg = pkgSchema.parse(input);
162
+ return _objectSpread(_objectSpread({}, pkg), {}, {
163
+ type: pkg.type || "commonjs"
164
+ });
165
+ }
166
+
155
167
  async function _loadPkg(options) {
156
168
  const {
157
169
  cwd
@@ -160,8 +172,8 @@ async function _loadPkg(options) {
160
172
  cwd
161
173
  });
162
174
  if (!pkgPath) throw new Error("no package.json found");
163
- const buf = await fs.readFile(pkgPath);
164
- return pkgSchema.parse(JSON.parse(buf.toString()));
175
+ const buf = await fs$1.readFile(pkgPath);
176
+ return _validatePkg(JSON.parse(buf.toString()));
165
177
  }
166
178
 
167
179
  async function _loadPkgWithReporting(options) {
@@ -171,221 +183,3734 @@ async function _loadPkgWithReporting(options) {
171
183
  if (err instanceof ZodError) {
172
184
  for (const issue of err.issues) {
173
185
  if (issue.code === "invalid_type") {
174
- console.log("".concat(chalk.red("invalid type"), " in ./package.json at ").concat(chalk.magenta("`".concat(issue.path.join(""), "`")), " (expected ").concat(issue.expected, ", received ").concat(issue.received, ")"));
186
+ console.log("".concat(chalk.red("invalid type"), " in ./package.json at ").concat(chalk.magenta("`".concat(issue.path.join("."), "`")), " (expected ").concat(issue.expected, ", received ").concat(issue.received, ")"));
175
187
  }
176
188
  }
177
189
  } else {
178
190
  console.error(err);
179
191
  }
180
192
 
181
- process.exit(1);
182
- }
183
- }
193
+ process.exit(1);
194
+ }
195
+ }
196
+
197
+ function _validateExports(_exports, options) {
198
+ const {
199
+ pkg
200
+ } = options;
201
+
202
+ for (const exp of _exports) {
203
+ if (pkg.type === "commonjs") {
204
+ if (exp.require && !exp.require.endsWith(".js")) {
205
+ throw new Error("package.json with `\"type\": \"commonjs\"` - `exports[\"".concat(exp._path, "\"].require` must end with \".js\""));
206
+ }
207
+ }
208
+
209
+ if (pkg.type === "module") {
210
+ if (exp.require && !exp.require.endsWith(".cjs")) {
211
+ throw new Error("package.json with `\"type\": \"module\"` - `exports[\"".concat(exp._path, "\"].require` must end with \".cjs\""));
212
+ }
213
+ }
214
+ }
215
+
216
+ return _exports;
217
+ }
218
+
219
+ function _parseExports(options) {
220
+ const {
221
+ pkg
222
+ } = options;
223
+ const rootExport = {
224
+ _exported: true,
225
+ _path: ".",
226
+ types: pkg.types,
227
+ source: pkg.source || "",
228
+ browser: pkg.browser && {
229
+ require: pkg.main && pkg.browser[pkg.main],
230
+ import: pkg.module && pkg.browser[pkg.module]
231
+ },
232
+ import: pkg.module,
233
+ require: pkg.main,
234
+ default: pkg.module || pkg.main || ""
235
+ };
236
+ const extraExports = [];
237
+
238
+ if (pkg.exports) {
239
+ for (const [exportPath, exportEntry] of Object.entries(pkg.exports)) {
240
+ if (_isRecord(exportEntry)) {
241
+ if (exportPath === ".") {
242
+ if (exportEntry.require && rootExport.require && exportEntry.require !== rootExport.require) {
243
+ throw new Error('mismatch between "main" and "require"');
244
+ }
245
+
246
+ if (exportEntry.import && rootExport.import && exportEntry.import !== rootExport.import) {
247
+ throw new Error('mismatch between "module" and "import"');
248
+ }
249
+
250
+ if (exportEntry.types && rootExport.types && exportEntry.types !== rootExport.types) {
251
+ throw new Error('mismatch between "types" and "types"');
252
+ }
253
+
254
+ if (exportEntry.source && rootExport.source && exportEntry.source !== rootExport.source) {
255
+ throw new Error('mismatch between "source" and "source"');
256
+ }
257
+
258
+ Object.assign(rootExport, exportEntry);
259
+ } else {
260
+ const extraExport = _objectSpread({
261
+ _exported: true,
262
+ _path: exportPath
263
+ }, exportEntry);
264
+
265
+ extraExports.push(extraExport);
266
+ }
267
+ } else {
268
+ throw new Error("string entries are not supported");
269
+ }
270
+ }
271
+ }
272
+
273
+ const _exports = [rootExport, ...extraExports];
274
+ return _validateExports(_exports, {
275
+ pkg
276
+ });
277
+ }
278
+
279
+ async function _loadTSConfig(options) {
280
+ const {
281
+ cwd,
282
+ tsconfigPath
283
+ } = options;
284
+ const configPath = ts.findConfigFile(cwd, ts.sys.fileExists, tsconfigPath);
285
+
286
+ if (!configPath) {
287
+ throw new Error("could not find a valid '".concat(tsconfigPath, "'"));
288
+ }
289
+
290
+ const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
291
+ return ts.parseJsonConfigFileContent(configFile.config, ts.sys, cwd);
292
+ }
293
+
294
+ function _resolveBuildTasks(ctx) {
295
+ var _a, _b, _c, _d, _e;
296
+
297
+ const {
298
+ cwd,
299
+ pkg,
300
+ target
301
+ } = ctx;
302
+ const tasks = [];
303
+ const exports = Object.entries(ctx.exports || {}).map(_ref => {
304
+ let [_path, exp] = _ref;
305
+ return _objectSpread({
306
+ _path
307
+ }, exp);
308
+ });
309
+ const dtsTask = {
310
+ type: "build:dts",
311
+ entries: []
312
+ };
313
+ const rollupTasks = {};
314
+
315
+ function _addRollupTaskEntry(format, runtime, entry) {
316
+ const buildId = "".concat(format, ":").concat(runtime);
317
+
318
+ if (rollupTasks[buildId]) {
319
+ rollupTasks[buildId].entries.push(entry);
320
+ } else {
321
+ rollupTasks[buildId] = {
322
+ type: "build:js",
323
+ buildId,
324
+ entries: [entry],
325
+ runtime,
326
+ format,
327
+ target: target[runtime]
328
+ };
329
+ }
330
+ }
331
+
332
+ for (const exp of exports) {
333
+ const importId = path$1.join(pkg.name, exp._path);
334
+
335
+ if (exp.types) {
336
+ dtsTask.entries.push({
337
+ importId,
338
+ exportPath: exp._path,
339
+ sourcePath: exp.source,
340
+ targetPath: exp.types
341
+ });
342
+ }
343
+ }
344
+
345
+ for (const exp of exports) {
346
+ const output = exp.require;
347
+ if (!output) continue;
348
+
349
+ _addRollupTaskEntry("commonjs", ctx.runtime, {
350
+ path: exp._path,
351
+ source: exp.source,
352
+ output
353
+ });
354
+ }
355
+
356
+ for (const exp of exports) {
357
+ const output = (_a = exp.browser) == null ? void 0 : _a.require;
358
+ if (!output) continue;
359
+
360
+ _addRollupTaskEntry("commonjs", "browser", {
361
+ path: exp._path,
362
+ source: ((_b = exp.browser) == null ? void 0 : _b.source) || exp.source,
363
+ output
364
+ });
365
+ }
366
+
367
+ for (const exp of exports) {
368
+ const output = exp.import;
369
+ if (!output) continue;
370
+
371
+ _addRollupTaskEntry("esm", ctx.runtime, {
372
+ path: exp._path,
373
+ source: exp.source,
374
+ output
375
+ });
376
+ }
377
+
378
+ for (const exp of exports) {
379
+ const output = (_c = exp.browser) == null ? void 0 : _c.import;
380
+ if (!output) continue;
381
+
382
+ _addRollupTaskEntry("esm", "browser", {
383
+ path: exp._path,
384
+ source: ((_d = exp.browser) == null ? void 0 : _d.source) || exp.source,
385
+ output
386
+ });
387
+ }
388
+
389
+ if (dtsTask.entries.length) {
390
+ tasks.push(dtsTask);
391
+ }
392
+
393
+ tasks.push(...Object.values(rollupTasks));
394
+
395
+ for (const exp of exports) {
396
+ if (exp._exported && exp._path !== ".") {
397
+ const relativeTargetPath = (((_e = exp.browser) == null ? void 0 : _e.import) || exp.import || "").replace(/\.[^/.]+$/, "");
398
+
399
+ if (relativeTargetPath) {
400
+ fs$2.writeFileSync(path$1.resolve(cwd, "".concat(exp._path, ".js")), ["// AUTO-GENERATED \u2013 DO NOT EDIT", "", "export * from '".concat(relativeTargetPath, "'"), ""].join("\n"));
401
+ }
402
+ }
403
+ }
404
+
405
+ return tasks;
406
+ }
407
+
408
+ function _printExtractMessages(ctx, messages) {
409
+ const {
410
+ cwd,
411
+ logger
412
+ } = ctx;
413
+ const warnings = messages.filter(msg => msg.logLevel === "warning");
414
+
415
+ if (warnings.length) {
416
+ logger.log();
417
+ }
418
+
419
+ for (const msg of warnings) {
420
+ const sourceFilePath = msg.sourceFilePath && path$1.relative(cwd, msg.sourceFilePath);
421
+
422
+ if (msg.messageId === "TS6307") {
423
+ continue;
424
+ }
425
+
426
+ logger.log(["".concat(chalk.cyan(sourceFilePath || "?")), ":".concat(chalk.yellow(msg.sourceFileLine), ":").concat(chalk.yellow(msg.sourceFileColumn)), " - ".concat(chalk.yellow("warning"), " ").concat(chalk.gray(msg.messageId), "\n"), msg.text, "\n"].join(""));
427
+ }
428
+
429
+ const errors = messages.filter(msg => msg.logLevel === "error");
430
+
431
+ if (!warnings.length && errors.length) {
432
+ logger.log("");
433
+ }
434
+
435
+ for (const msg of errors) {
436
+ const sourceFilePath = msg.sourceFilePath && path$1.relative(cwd, msg.sourceFilePath);
437
+ logger.log(["".concat(chalk.cyan(sourceFilePath || "?")), ":".concat(chalk.yellow(msg.sourceFileLine), ":").concat(chalk.yellow(msg.sourceFileColumn)), " - ".concat(chalk.red("error"), " ").concat(chalk.gray(msg.messageId), "\n"), msg.text, "\n"].join(""));
438
+ }
439
+
440
+ if (errors.length) {
441
+ process.exit(1);
442
+ }
443
+ }
444
+
445
+ var old = {};
446
+ var hasRequiredOld;
447
+
448
+ function requireOld() {
449
+ if (hasRequiredOld) return old;
450
+ hasRequiredOld = 1; // Copyright Joyent, Inc. and other Node contributors.
451
+ //
452
+ // Permission is hereby granted, free of charge, to any person obtaining a
453
+ // copy of this software and associated documentation files (the
454
+ // "Software"), to deal in the Software without restriction, including
455
+ // without limitation the rights to use, copy, modify, merge, publish,
456
+ // distribute, sublicense, and/or sell copies of the Software, and to permit
457
+ // persons to whom the Software is furnished to do so, subject to the
458
+ // following conditions:
459
+ //
460
+ // The above copyright notice and this permission notice shall be included
461
+ // in all copies or substantial portions of the Software.
462
+ //
463
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
464
+ // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
465
+ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
466
+ // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
467
+ // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
468
+ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
469
+ // USE OR OTHER DEALINGS IN THE SOFTWARE.
470
+
471
+ var pathModule = path$1;
472
+ var isWindows = process.platform === 'win32';
473
+ var fs = fs$2; // JavaScript implementation of realpath, ported from node pre-v6
474
+
475
+ var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
476
+
477
+ function rethrow() {
478
+ // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
479
+ // is fairly slow to generate.
480
+ var callback;
481
+
482
+ if (DEBUG) {
483
+ var backtrace = new Error();
484
+ callback = debugCallback;
485
+ } else callback = missingCallback;
486
+
487
+ return callback;
488
+
489
+ function debugCallback(err) {
490
+ if (err) {
491
+ backtrace.message = err.message;
492
+ err = backtrace;
493
+ missingCallback(err);
494
+ }
495
+ }
496
+
497
+ function missingCallback(err) {
498
+ if (err) {
499
+ if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
500
+ else if (!process.noDeprecation) {
501
+ var msg = 'fs: missing callback ' + (err.stack || err.message);
502
+ if (process.traceDeprecation) console.trace(msg);else console.error(msg);
503
+ }
504
+ }
505
+ }
506
+ }
507
+
508
+ function maybeCallback(cb) {
509
+ return typeof cb === 'function' ? cb : rethrow();
510
+ } // Regexp that finds the next partion of a (partial) path
511
+ // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
512
+
513
+
514
+ if (isWindows) {
515
+ var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
516
+ } else {
517
+ var nextPartRe = /(.*?)(?:[\/]+|$)/g;
518
+ } // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
519
+
520
+
521
+ if (isWindows) {
522
+ var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
523
+ } else {
524
+ var splitRootRe = /^[\/]*/;
525
+ }
526
+
527
+ old.realpathSync = function realpathSync(p, cache) {
528
+ // make p is absolute
529
+ p = pathModule.resolve(p);
530
+
531
+ if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
532
+ return cache[p];
533
+ }
534
+
535
+ var original = p,
536
+ seenLinks = {},
537
+ knownHard = {}; // current character position in p
538
+
539
+ var pos; // the partial path so far, including a trailing slash if any
540
+
541
+ var current; // the partial path without a trailing slash (except when pointing at a root)
542
+
543
+ var base; // the partial path scanned in the previous round, with slash
544
+
545
+ var previous;
546
+ start();
547
+
548
+ function start() {
549
+ // Skip over roots
550
+ var m = splitRootRe.exec(p);
551
+ pos = m[0].length;
552
+ current = m[0];
553
+ base = m[0];
554
+ previous = ''; // On windows, check that the root exists. On unix there is no need.
555
+
556
+ if (isWindows && !knownHard[base]) {
557
+ fs.lstatSync(base);
558
+ knownHard[base] = true;
559
+ }
560
+ } // walk down the path, swapping out linked pathparts for their real
561
+ // values
562
+ // NB: p.length changes.
563
+
564
+
565
+ while (pos < p.length) {
566
+ // find the next part
567
+ nextPartRe.lastIndex = pos;
568
+ var result = nextPartRe.exec(p);
569
+ previous = current;
570
+ current += result[0];
571
+ base = previous + result[1];
572
+ pos = nextPartRe.lastIndex; // continue if not a symlink
573
+
574
+ if (knownHard[base] || cache && cache[base] === base) {
575
+ continue;
576
+ }
577
+
578
+ var resolvedLink;
579
+
580
+ if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
581
+ // some known symbolic link. no need to stat again.
582
+ resolvedLink = cache[base];
583
+ } else {
584
+ var stat = fs.lstatSync(base);
585
+
586
+ if (!stat.isSymbolicLink()) {
587
+ knownHard[base] = true;
588
+ if (cache) cache[base] = base;
589
+ continue;
590
+ } // read the link if it wasn't read before
591
+ // dev/ino always return 0 on windows, so skip the check.
592
+
593
+
594
+ var linkTarget = null;
595
+
596
+ if (!isWindows) {
597
+ var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
598
+
599
+ if (seenLinks.hasOwnProperty(id)) {
600
+ linkTarget = seenLinks[id];
601
+ }
602
+ }
603
+
604
+ if (linkTarget === null) {
605
+ fs.statSync(base);
606
+ linkTarget = fs.readlinkSync(base);
607
+ }
608
+
609
+ resolvedLink = pathModule.resolve(previous, linkTarget); // track this, if given a cache.
610
+
611
+ if (cache) cache[base] = resolvedLink;
612
+ if (!isWindows) seenLinks[id] = linkTarget;
613
+ } // resolve the link, then start over
614
+
615
+
616
+ p = pathModule.resolve(resolvedLink, p.slice(pos));
617
+ start();
618
+ }
619
+
620
+ if (cache) cache[original] = p;
621
+ return p;
622
+ };
623
+
624
+ old.realpath = function realpath(p, cache, cb) {
625
+ if (typeof cb !== 'function') {
626
+ cb = maybeCallback(cache);
627
+ cache = null;
628
+ } // make p is absolute
629
+
630
+
631
+ p = pathModule.resolve(p);
632
+
633
+ if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
634
+ return process.nextTick(cb.bind(null, null, cache[p]));
635
+ }
636
+
637
+ var original = p,
638
+ seenLinks = {},
639
+ knownHard = {}; // current character position in p
640
+
641
+ var pos; // the partial path so far, including a trailing slash if any
642
+
643
+ var current; // the partial path without a trailing slash (except when pointing at a root)
644
+
645
+ var base; // the partial path scanned in the previous round, with slash
646
+
647
+ var previous;
648
+ start();
649
+
650
+ function start() {
651
+ // Skip over roots
652
+ var m = splitRootRe.exec(p);
653
+ pos = m[0].length;
654
+ current = m[0];
655
+ base = m[0];
656
+ previous = ''; // On windows, check that the root exists. On unix there is no need.
657
+
658
+ if (isWindows && !knownHard[base]) {
659
+ fs.lstat(base, function (err) {
660
+ if (err) return cb(err);
661
+ knownHard[base] = true;
662
+ LOOP();
663
+ });
664
+ } else {
665
+ process.nextTick(LOOP);
666
+ }
667
+ } // walk down the path, swapping out linked pathparts for their real
668
+ // values
669
+
670
+
671
+ function LOOP() {
672
+ // stop if scanned past end of path
673
+ if (pos >= p.length) {
674
+ if (cache) cache[original] = p;
675
+ return cb(null, p);
676
+ } // find the next part
677
+
678
+
679
+ nextPartRe.lastIndex = pos;
680
+ var result = nextPartRe.exec(p);
681
+ previous = current;
682
+ current += result[0];
683
+ base = previous + result[1];
684
+ pos = nextPartRe.lastIndex; // continue if not a symlink
685
+
686
+ if (knownHard[base] || cache && cache[base] === base) {
687
+ return process.nextTick(LOOP);
688
+ }
689
+
690
+ if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
691
+ // known symbolic link. no need to stat again.
692
+ return gotResolvedLink(cache[base]);
693
+ }
694
+
695
+ return fs.lstat(base, gotStat);
696
+ }
697
+
698
+ function gotStat(err, stat) {
699
+ if (err) return cb(err); // if not a symlink, skip to the next path part
700
+
701
+ if (!stat.isSymbolicLink()) {
702
+ knownHard[base] = true;
703
+ if (cache) cache[base] = base;
704
+ return process.nextTick(LOOP);
705
+ } // stat & read the link if not read before
706
+ // call gotTarget as soon as the link target is known
707
+ // dev/ino always return 0 on windows, so skip the check.
708
+
709
+
710
+ if (!isWindows) {
711
+ var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
712
+
713
+ if (seenLinks.hasOwnProperty(id)) {
714
+ return gotTarget(null, seenLinks[id], base);
715
+ }
716
+ }
717
+
718
+ fs.stat(base, function (err) {
719
+ if (err) return cb(err);
720
+ fs.readlink(base, function (err, target) {
721
+ if (!isWindows) seenLinks[id] = target;
722
+ gotTarget(err, target);
723
+ });
724
+ });
725
+ }
726
+
727
+ function gotTarget(err, target, base) {
728
+ if (err) return cb(err);
729
+ var resolvedLink = pathModule.resolve(previous, target);
730
+ if (cache) cache[base] = resolvedLink;
731
+ gotResolvedLink(resolvedLink);
732
+ }
733
+
734
+ function gotResolvedLink(resolvedLink) {
735
+ // resolve the link, then start over
736
+ p = pathModule.resolve(resolvedLink, p.slice(pos));
737
+ start();
738
+ }
739
+ };
740
+
741
+ return old;
742
+ }
743
+
744
+ var fs_realpath;
745
+ var hasRequiredFs_realpath;
746
+
747
+ function requireFs_realpath() {
748
+ if (hasRequiredFs_realpath) return fs_realpath;
749
+ hasRequiredFs_realpath = 1;
750
+ fs_realpath = realpath;
751
+ realpath.realpath = realpath;
752
+ realpath.sync = realpathSync;
753
+ realpath.realpathSync = realpathSync;
754
+ realpath.monkeypatch = monkeypatch;
755
+ realpath.unmonkeypatch = unmonkeypatch;
756
+ var fs = fs$2;
757
+ var origRealpath = fs.realpath;
758
+ var origRealpathSync = fs.realpathSync;
759
+ var version = process.version;
760
+ var ok = /^v[0-5]\./.test(version);
761
+ var old = requireOld();
762
+
763
+ function newError(er) {
764
+ return er && er.syscall === 'realpath' && (er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG');
765
+ }
766
+
767
+ function realpath(p, cache, cb) {
768
+ if (ok) {
769
+ return origRealpath(p, cache, cb);
770
+ }
771
+
772
+ if (typeof cache === 'function') {
773
+ cb = cache;
774
+ cache = null;
775
+ }
776
+
777
+ origRealpath(p, cache, function (er, result) {
778
+ if (newError(er)) {
779
+ old.realpath(p, cache, cb);
780
+ } else {
781
+ cb(er, result);
782
+ }
783
+ });
784
+ }
785
+
786
+ function realpathSync(p, cache) {
787
+ if (ok) {
788
+ return origRealpathSync(p, cache);
789
+ }
790
+
791
+ try {
792
+ return origRealpathSync(p, cache);
793
+ } catch (er) {
794
+ if (newError(er)) {
795
+ return old.realpathSync(p, cache);
796
+ } else {
797
+ throw er;
798
+ }
799
+ }
800
+ }
801
+
802
+ function monkeypatch() {
803
+ fs.realpath = realpath;
804
+ fs.realpathSync = realpathSync;
805
+ }
806
+
807
+ function unmonkeypatch() {
808
+ fs.realpath = origRealpath;
809
+ fs.realpathSync = origRealpathSync;
810
+ }
811
+
812
+ return fs_realpath;
813
+ }
814
+
815
+ var concatMap;
816
+ var hasRequiredConcatMap;
817
+
818
+ function requireConcatMap() {
819
+ if (hasRequiredConcatMap) return concatMap;
820
+ hasRequiredConcatMap = 1;
821
+
822
+ concatMap = function (xs, fn) {
823
+ var res = [];
824
+
825
+ for (var i = 0; i < xs.length; i++) {
826
+ var x = fn(xs[i], i);
827
+ if (isArray(x)) res.push.apply(res, x);else res.push(x);
828
+ }
829
+
830
+ return res;
831
+ };
832
+
833
+ var isArray = Array.isArray || function (xs) {
834
+ return Object.prototype.toString.call(xs) === '[object Array]';
835
+ };
836
+
837
+ return concatMap;
838
+ }
839
+
840
+ var balancedMatch;
841
+ var hasRequiredBalancedMatch;
842
+
843
+ function requireBalancedMatch() {
844
+ if (hasRequiredBalancedMatch) return balancedMatch;
845
+ hasRequiredBalancedMatch = 1;
846
+ balancedMatch = balanced;
847
+
848
+ function balanced(a, b, str) {
849
+ if (a instanceof RegExp) a = maybeMatch(a, str);
850
+ if (b instanceof RegExp) b = maybeMatch(b, str);
851
+ var r = range(a, b, str);
852
+ return r && {
853
+ start: r[0],
854
+ end: r[1],
855
+ pre: str.slice(0, r[0]),
856
+ body: str.slice(r[0] + a.length, r[1]),
857
+ post: str.slice(r[1] + b.length)
858
+ };
859
+ }
860
+
861
+ function maybeMatch(reg, str) {
862
+ var m = str.match(reg);
863
+ return m ? m[0] : null;
864
+ }
865
+
866
+ balanced.range = range;
867
+
868
+ function range(a, b, str) {
869
+ var begs, beg, left, right, result;
870
+ var ai = str.indexOf(a);
871
+ var bi = str.indexOf(b, ai + 1);
872
+ var i = ai;
873
+
874
+ if (ai >= 0 && bi > 0) {
875
+ if (a === b) {
876
+ return [ai, bi];
877
+ }
878
+
879
+ begs = [];
880
+ left = str.length;
881
+
882
+ while (i >= 0 && !result) {
883
+ if (i == ai) {
884
+ begs.push(i);
885
+ ai = str.indexOf(a, i + 1);
886
+ } else if (begs.length == 1) {
887
+ result = [begs.pop(), bi];
888
+ } else {
889
+ beg = begs.pop();
890
+
891
+ if (beg < left) {
892
+ left = beg;
893
+ right = bi;
894
+ }
895
+
896
+ bi = str.indexOf(b, i + 1);
897
+ }
898
+
899
+ i = ai < bi && ai >= 0 ? ai : bi;
900
+ }
901
+
902
+ if (begs.length) {
903
+ result = [left, right];
904
+ }
905
+ }
906
+
907
+ return result;
908
+ }
909
+
910
+ return balancedMatch;
911
+ }
912
+
913
+ var braceExpansion;
914
+ var hasRequiredBraceExpansion;
915
+
916
+ function requireBraceExpansion() {
917
+ if (hasRequiredBraceExpansion) return braceExpansion;
918
+ hasRequiredBraceExpansion = 1;
919
+ var concatMap = requireConcatMap();
920
+ var balanced = requireBalancedMatch();
921
+ braceExpansion = expandTop;
922
+ var escSlash = '\0SLASH' + Math.random() + '\0';
923
+ var escOpen = '\0OPEN' + Math.random() + '\0';
924
+ var escClose = '\0CLOSE' + Math.random() + '\0';
925
+ var escComma = '\0COMMA' + Math.random() + '\0';
926
+ var escPeriod = '\0PERIOD' + Math.random() + '\0';
927
+
928
+ function numeric(str) {
929
+ return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
930
+ }
931
+
932
+ function escapeBraces(str) {
933
+ return str.split('\\\\').join(escSlash).split('\\{').join(escOpen).split('\\}').join(escClose).split('\\,').join(escComma).split('\\.').join(escPeriod);
934
+ }
935
+
936
+ function unescapeBraces(str) {
937
+ return str.split(escSlash).join('\\').split(escOpen).join('{').split(escClose).join('}').split(escComma).join(',').split(escPeriod).join('.');
938
+ } // Basically just str.split(","), but handling cases
939
+ // where we have nested braced sections, which should be
940
+ // treated as individual members, like {a,{b,c},d}
941
+
942
+
943
+ function parseCommaParts(str) {
944
+ if (!str) return [''];
945
+ var parts = [];
946
+ var m = balanced('{', '}', str);
947
+ if (!m) return str.split(',');
948
+ var pre = m.pre;
949
+ var body = m.body;
950
+ var post = m.post;
951
+ var p = pre.split(',');
952
+ p[p.length - 1] += '{' + body + '}';
953
+ var postParts = parseCommaParts(post);
954
+
955
+ if (post.length) {
956
+ p[p.length - 1] += postParts.shift();
957
+ p.push.apply(p, postParts);
958
+ }
959
+
960
+ parts.push.apply(parts, p);
961
+ return parts;
962
+ }
963
+
964
+ function expandTop(str) {
965
+ if (!str) return []; // I don't know why Bash 4.3 does this, but it does.
966
+ // Anything starting with {} will have the first two bytes preserved
967
+ // but *only* at the top level, so {},a}b will not expand to anything,
968
+ // but a{},b}c will be expanded to [a}c,abc].
969
+ // One could argue that this is a bug in Bash, but since the goal of
970
+ // this module is to match Bash's rules, we escape a leading {}
971
+
972
+ if (str.substr(0, 2) === '{}') {
973
+ str = '\\{\\}' + str.substr(2);
974
+ }
975
+
976
+ return expand(escapeBraces(str), true).map(unescapeBraces);
977
+ }
978
+
979
+ function embrace(str) {
980
+ return '{' + str + '}';
981
+ }
982
+
983
+ function isPadded(el) {
984
+ return /^-?0\d/.test(el);
985
+ }
986
+
987
+ function lte(i, y) {
988
+ return i <= y;
989
+ }
990
+
991
+ function gte(i, y) {
992
+ return i >= y;
993
+ }
994
+
995
+ function expand(str, isTop) {
996
+ var expansions = [];
997
+ var m = balanced('{', '}', str);
998
+ if (!m || /\$$/.test(m.pre)) return [str];
999
+ var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
1000
+ var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
1001
+ var isSequence = isNumericSequence || isAlphaSequence;
1002
+ var isOptions = m.body.indexOf(',') >= 0;
1003
+
1004
+ if (!isSequence && !isOptions) {
1005
+ // {a},b}
1006
+ if (m.post.match(/,.*\}/)) {
1007
+ str = m.pre + '{' + m.body + escClose + m.post;
1008
+ return expand(str);
1009
+ }
1010
+
1011
+ return [str];
1012
+ }
1013
+
1014
+ var n;
1015
+
1016
+ if (isSequence) {
1017
+ n = m.body.split(/\.\./);
1018
+ } else {
1019
+ n = parseCommaParts(m.body);
1020
+
1021
+ if (n.length === 1) {
1022
+ // x{{a,b}}y ==> x{a}y x{b}y
1023
+ n = expand(n[0], false).map(embrace);
1024
+
1025
+ if (n.length === 1) {
1026
+ var post = m.post.length ? expand(m.post, false) : [''];
1027
+ return post.map(function (p) {
1028
+ return m.pre + n[0] + p;
1029
+ });
1030
+ }
1031
+ }
1032
+ } // at this point, n is the parts, and we know it's not a comma set
1033
+ // with a single entry.
1034
+ // no need to expand pre, since it is guaranteed to be free of brace-sets
1035
+
1036
+
1037
+ var pre = m.pre;
1038
+ var post = m.post.length ? expand(m.post, false) : [''];
1039
+ var N;
1040
+
1041
+ if (isSequence) {
1042
+ var x = numeric(n[0]);
1043
+ var y = numeric(n[1]);
1044
+ var width = Math.max(n[0].length, n[1].length);
1045
+ var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
1046
+ var test = lte;
1047
+ var reverse = y < x;
1048
+
1049
+ if (reverse) {
1050
+ incr *= -1;
1051
+ test = gte;
1052
+ }
1053
+
1054
+ var pad = n.some(isPadded);
1055
+ N = [];
1056
+
1057
+ for (var i = x; test(i, y); i += incr) {
1058
+ var c;
1059
+
1060
+ if (isAlphaSequence) {
1061
+ c = String.fromCharCode(i);
1062
+ if (c === '\\') c = '';
1063
+ } else {
1064
+ c = String(i);
1065
+
1066
+ if (pad) {
1067
+ var need = width - c.length;
1068
+
1069
+ if (need > 0) {
1070
+ var z = new Array(need + 1).join('0');
1071
+ if (i < 0) c = '-' + z + c.slice(1);else c = z + c;
1072
+ }
1073
+ }
1074
+ }
1075
+
1076
+ N.push(c);
1077
+ }
1078
+ } else {
1079
+ N = concatMap(n, function (el) {
1080
+ return expand(el, false);
1081
+ });
1082
+ }
1083
+
1084
+ for (var j = 0; j < N.length; j++) {
1085
+ for (var k = 0; k < post.length; k++) {
1086
+ var expansion = pre + N[j] + post[k];
1087
+ if (!isTop || isSequence || expansion) expansions.push(expansion);
1088
+ }
1089
+ }
1090
+
1091
+ return expansions;
1092
+ }
1093
+
1094
+ return braceExpansion;
1095
+ }
1096
+
1097
+ var minimatch_1;
1098
+ var hasRequiredMinimatch;
1099
+
1100
+ function requireMinimatch() {
1101
+ if (hasRequiredMinimatch) return minimatch_1;
1102
+ hasRequiredMinimatch = 1;
1103
+ minimatch_1 = minimatch;
1104
+ minimatch.Minimatch = Minimatch;
1105
+
1106
+ var path = function () {
1107
+ try {
1108
+ return require('path');
1109
+ } catch (e) {}
1110
+ }() || {
1111
+ sep: '/'
1112
+ };
1113
+
1114
+ minimatch.sep = path.sep;
1115
+ var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
1116
+ var expand = requireBraceExpansion();
1117
+ var plTypes = {
1118
+ '!': {
1119
+ open: '(?:(?!(?:',
1120
+ close: '))[^/]*?)'
1121
+ },
1122
+ '?': {
1123
+ open: '(?:',
1124
+ close: ')?'
1125
+ },
1126
+ '+': {
1127
+ open: '(?:',
1128
+ close: ')+'
1129
+ },
1130
+ '*': {
1131
+ open: '(?:',
1132
+ close: ')*'
1133
+ },
1134
+ '@': {
1135
+ open: '(?:',
1136
+ close: ')'
1137
+ }
1138
+ }; // any single thing other than /
1139
+ // don't need to escape / when using new RegExp()
1140
+
1141
+ var qmark = '[^/]'; // * => any number of characters
1142
+
1143
+ var star = qmark + '*?'; // ** when dots are allowed. Anything goes, except .. and .
1144
+ // not (^ or / followed by one or two dots followed by $ or /),
1145
+ // followed by anything, any number of times.
1146
+
1147
+ var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; // not a ^ or / followed by a dot,
1148
+ // followed by anything, any number of times.
1149
+
1150
+ var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; // characters that need to be escaped in RegExp.
1151
+
1152
+ var reSpecials = charSet('().*{}+?[]^$\\!'); // "abc" -> { a:true, b:true, c:true }
1153
+
1154
+ function charSet(s) {
1155
+ return s.split('').reduce(function (set, c) {
1156
+ set[c] = true;
1157
+ return set;
1158
+ }, {});
1159
+ } // normalizes slashes.
1160
+
1161
+
1162
+ var slashSplit = /\/+/;
1163
+ minimatch.filter = filter;
1164
+
1165
+ function filter(pattern, options) {
1166
+ options = options || {};
1167
+ return function (p, i, list) {
1168
+ return minimatch(p, pattern, options);
1169
+ };
1170
+ }
1171
+
1172
+ function ext(a, b) {
1173
+ b = b || {};
1174
+ var t = {};
1175
+ Object.keys(a).forEach(function (k) {
1176
+ t[k] = a[k];
1177
+ });
1178
+ Object.keys(b).forEach(function (k) {
1179
+ t[k] = b[k];
1180
+ });
1181
+ return t;
1182
+ }
1183
+
1184
+ minimatch.defaults = function (def) {
1185
+ if (!def || typeof def !== 'object' || !Object.keys(def).length) {
1186
+ return minimatch;
1187
+ }
1188
+
1189
+ var orig = minimatch;
1190
+
1191
+ var m = function minimatch(p, pattern, options) {
1192
+ return orig(p, pattern, ext(def, options));
1193
+ };
1194
+
1195
+ m.Minimatch = function Minimatch(pattern, options) {
1196
+ return new orig.Minimatch(pattern, ext(def, options));
1197
+ };
1198
+
1199
+ m.Minimatch.defaults = function defaults(options) {
1200
+ return orig.defaults(ext(def, options)).Minimatch;
1201
+ };
1202
+
1203
+ m.filter = function filter(pattern, options) {
1204
+ return orig.filter(pattern, ext(def, options));
1205
+ };
1206
+
1207
+ m.defaults = function defaults(options) {
1208
+ return orig.defaults(ext(def, options));
1209
+ };
1210
+
1211
+ m.makeRe = function makeRe(pattern, options) {
1212
+ return orig.makeRe(pattern, ext(def, options));
1213
+ };
1214
+
1215
+ m.braceExpand = function braceExpand(pattern, options) {
1216
+ return orig.braceExpand(pattern, ext(def, options));
1217
+ };
1218
+
1219
+ m.match = function (list, pattern, options) {
1220
+ return orig.match(list, pattern, ext(def, options));
1221
+ };
1222
+
1223
+ return m;
1224
+ };
1225
+
1226
+ Minimatch.defaults = function (def) {
1227
+ return minimatch.defaults(def).Minimatch;
1228
+ };
1229
+
1230
+ function minimatch(p, pattern, options) {
1231
+ assertValidPattern(pattern);
1232
+ if (!options) options = {}; // shortcut: comments match nothing.
1233
+
1234
+ if (!options.nocomment && pattern.charAt(0) === '#') {
1235
+ return false;
1236
+ }
1237
+
1238
+ return new Minimatch(pattern, options).match(p);
1239
+ }
1240
+
1241
+ function Minimatch(pattern, options) {
1242
+ if (!(this instanceof Minimatch)) {
1243
+ return new Minimatch(pattern, options);
1244
+ }
1245
+
1246
+ assertValidPattern(pattern);
1247
+ if (!options) options = {};
1248
+ pattern = pattern.trim(); // windows support: need to use /, not \
1249
+
1250
+ if (!options.allowWindowsEscape && path.sep !== '/') {
1251
+ pattern = pattern.split(path.sep).join('/');
1252
+ }
1253
+
1254
+ this.options = options;
1255
+ this.set = [];
1256
+ this.pattern = pattern;
1257
+ this.regexp = null;
1258
+ this.negate = false;
1259
+ this.comment = false;
1260
+ this.empty = false;
1261
+ this.partial = !!options.partial; // make the set of regexps etc.
1262
+
1263
+ this.make();
1264
+ }
1265
+
1266
+ Minimatch.prototype.debug = function () {};
1267
+
1268
+ Minimatch.prototype.make = make;
1269
+
1270
+ function make() {
1271
+ var pattern = this.pattern;
1272
+ var options = this.options; // empty patterns and comments match nothing.
1273
+
1274
+ if (!options.nocomment && pattern.charAt(0) === '#') {
1275
+ this.comment = true;
1276
+ return;
1277
+ }
1278
+
1279
+ if (!pattern) {
1280
+ this.empty = true;
1281
+ return;
1282
+ } // step 1: figure out negation, etc.
1283
+
1284
+
1285
+ this.parseNegate(); // step 2: expand braces
1286
+
1287
+ var set = this.globSet = this.braceExpand();
1288
+ if (options.debug) this.debug = function debug() {
1289
+ console.error.apply(console, arguments);
1290
+ };
1291
+ this.debug(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion
1292
+ // matching patterns.
1293
+ // These will be regexps, except in the case of "**", which is
1294
+ // set to the GLOBSTAR object for globstar behavior,
1295
+ // and will not contain any / characters
1296
+
1297
+ set = this.globParts = set.map(function (s) {
1298
+ return s.split(slashSplit);
1299
+ });
1300
+ this.debug(this.pattern, set); // glob --> regexps
1301
+
1302
+ set = set.map(function (s, si, set) {
1303
+ return s.map(this.parse, this);
1304
+ }, this);
1305
+ this.debug(this.pattern, set); // filter out everything that didn't compile properly.
1306
+
1307
+ set = set.filter(function (s) {
1308
+ return s.indexOf(false) === -1;
1309
+ });
1310
+ this.debug(this.pattern, set);
1311
+ this.set = set;
1312
+ }
1313
+
1314
+ Minimatch.prototype.parseNegate = parseNegate;
1315
+
1316
+ function parseNegate() {
1317
+ var pattern = this.pattern;
1318
+ var negate = false;
1319
+ var options = this.options;
1320
+ var negateOffset = 0;
1321
+ if (options.nonegate) return;
1322
+
1323
+ for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === '!'; i++) {
1324
+ negate = !negate;
1325
+ negateOffset++;
1326
+ }
1327
+
1328
+ if (negateOffset) this.pattern = pattern.substr(negateOffset);
1329
+ this.negate = negate;
1330
+ } // Brace expansion:
1331
+ // a{b,c}d -> abd acd
1332
+ // a{b,}c -> abc ac
1333
+ // a{0..3}d -> a0d a1d a2d a3d
1334
+ // a{b,c{d,e}f}g -> abg acdfg acefg
1335
+ // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
1336
+ //
1337
+ // Invalid sets are not expanded.
1338
+ // a{2..}b -> a{2..}b
1339
+ // a{b}c -> a{b}c
1340
+
1341
+
1342
+ minimatch.braceExpand = function (pattern, options) {
1343
+ return braceExpand(pattern, options);
1344
+ };
1345
+
1346
+ Minimatch.prototype.braceExpand = braceExpand;
1347
+
1348
+ function braceExpand(pattern, options) {
1349
+ if (!options) {
1350
+ if (this instanceof Minimatch) {
1351
+ options = this.options;
1352
+ } else {
1353
+ options = {};
1354
+ }
1355
+ }
1356
+
1357
+ pattern = typeof pattern === 'undefined' ? this.pattern : pattern;
1358
+ assertValidPattern(pattern); // Thanks to Yeting Li <https://github.com/yetingli> for
1359
+ // improving this regexp to avoid a ReDOS vulnerability.
1360
+
1361
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
1362
+ // shortcut. no need to expand.
1363
+ return [pattern];
1364
+ }
1365
+
1366
+ return expand(pattern);
1367
+ }
1368
+
1369
+ var MAX_PATTERN_LENGTH = 1024 * 64;
1370
+
1371
+ var assertValidPattern = function (pattern) {
1372
+ if (typeof pattern !== 'string') {
1373
+ throw new TypeError('invalid pattern');
1374
+ }
1375
+
1376
+ if (pattern.length > MAX_PATTERN_LENGTH) {
1377
+ throw new TypeError('pattern is too long');
1378
+ }
1379
+ }; // parse a component of the expanded set.
1380
+ // At this point, no pattern may contain "/" in it
1381
+ // so we're going to return a 2d array, where each entry is the full
1382
+ // pattern, split on '/', and then turned into a regular expression.
1383
+ // A regexp is made at the end which joins each array with an
1384
+ // escaped /, and another full one which joins each regexp with |.
1385
+ //
1386
+ // Following the lead of Bash 4.1, note that "**" only has special meaning
1387
+ // when it is the *only* thing in a path portion. Otherwise, any series
1388
+ // of * is equivalent to a single *. Globstar behavior is enabled by
1389
+ // default, and can be disabled by setting options.noglobstar.
1390
+
1391
+
1392
+ Minimatch.prototype.parse = parse;
1393
+ var SUBPARSE = {};
1394
+
1395
+ function parse(pattern, isSub) {
1396
+ assertValidPattern(pattern);
1397
+ var options = this.options; // shortcuts
1398
+
1399
+ if (pattern === '**') {
1400
+ if (!options.noglobstar) return GLOBSTAR;else pattern = '*';
1401
+ }
1402
+
1403
+ if (pattern === '') return '';
1404
+ var re = '';
1405
+ var hasMagic = !!options.nocase;
1406
+ var escaping = false; // ? => one single character
1407
+
1408
+ var patternListStack = [];
1409
+ var negativeLists = [];
1410
+ var stateChar;
1411
+ var inClass = false;
1412
+ var reClassStart = -1;
1413
+ var classStart = -1; // . and .. never match anything that doesn't start with .,
1414
+ // even when options.dot is set.
1415
+
1416
+ var patternStart = pattern.charAt(0) === '.' ? '' // anything
1417
+ // not (start or / followed by . or .. followed by / or end)
1418
+ : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)';
1419
+ var self = this;
1420
+
1421
+ function clearStateChar() {
1422
+ if (stateChar) {
1423
+ // we had some state-tracking character
1424
+ // that wasn't consumed by this pass.
1425
+ switch (stateChar) {
1426
+ case '*':
1427
+ re += star;
1428
+ hasMagic = true;
1429
+ break;
1430
+
1431
+ case '?':
1432
+ re += qmark;
1433
+ hasMagic = true;
1434
+ break;
1435
+
1436
+ default:
1437
+ re += '\\' + stateChar;
1438
+ break;
1439
+ }
1440
+
1441
+ self.debug('clearStateChar %j %j', stateChar, re);
1442
+ stateChar = false;
1443
+ }
1444
+ }
1445
+
1446
+ for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
1447
+ this.debug('%s\t%s %s %j', pattern, i, re, c); // skip over any that are escaped.
1448
+
1449
+ if (escaping && reSpecials[c]) {
1450
+ re += '\\' + c;
1451
+ escaping = false;
1452
+ continue;
1453
+ }
1454
+
1455
+ switch (c) {
1456
+ /* istanbul ignore next */
1457
+ case '/':
1458
+ {
1459
+ // completely not allowed, even escaped.
1460
+ // Should already be path-split by now.
1461
+ return false;
1462
+ }
1463
+
1464
+ case '\\':
1465
+ clearStateChar();
1466
+ escaping = true;
1467
+ continue;
1468
+ // the various stateChar values
1469
+ // for the "extglob" stuff.
1470
+
1471
+ case '?':
1472
+ case '*':
1473
+ case '+':
1474
+ case '@':
1475
+ case '!':
1476
+ this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); // all of those are literals inside a class, except that
1477
+ // the glob [!a] means [^a] in regexp
1478
+
1479
+ if (inClass) {
1480
+ this.debug(' in class');
1481
+ if (c === '!' && i === classStart + 1) c = '^';
1482
+ re += c;
1483
+ continue;
1484
+ } // if we already have a stateChar, then it means
1485
+ // that there was something like ** or +? in there.
1486
+ // Handle the stateChar, then proceed with this one.
1487
+
1488
+
1489
+ self.debug('call clearStateChar %j', stateChar);
1490
+ clearStateChar();
1491
+ stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
1492
+ // just clear the statechar *now*, rather than even diving into
1493
+ // the patternList stuff.
1494
+
1495
+ if (options.noext) clearStateChar();
1496
+ continue;
1497
+
1498
+ case '(':
1499
+ if (inClass) {
1500
+ re += '(';
1501
+ continue;
1502
+ }
1503
+
1504
+ if (!stateChar) {
1505
+ re += '\\(';
1506
+ continue;
1507
+ }
1508
+
1509
+ patternListStack.push({
1510
+ type: stateChar,
1511
+ start: i - 1,
1512
+ reStart: re.length,
1513
+ open: plTypes[stateChar].open,
1514
+ close: plTypes[stateChar].close
1515
+ }); // negation is (?:(?!js)[^/]*)
1516
+
1517
+ re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
1518
+ this.debug('plType %j %j', stateChar, re);
1519
+ stateChar = false;
1520
+ continue;
1521
+
1522
+ case ')':
1523
+ if (inClass || !patternListStack.length) {
1524
+ re += '\\)';
1525
+ continue;
1526
+ }
1527
+
1528
+ clearStateChar();
1529
+ hasMagic = true;
1530
+ var pl = patternListStack.pop(); // negation is (?:(?!js)[^/]*)
1531
+ // The others are (?:<pattern>)<type>
1532
+
1533
+ re += pl.close;
1534
+
1535
+ if (pl.type === '!') {
1536
+ negativeLists.push(pl);
1537
+ }
1538
+
1539
+ pl.reEnd = re.length;
1540
+ continue;
1541
+
1542
+ case '|':
1543
+ if (inClass || !patternListStack.length || escaping) {
1544
+ re += '\\|';
1545
+ escaping = false;
1546
+ continue;
1547
+ }
1548
+
1549
+ clearStateChar();
1550
+ re += '|';
1551
+ continue;
1552
+ // these are mostly the same in regexp and glob
1553
+
1554
+ case '[':
1555
+ // swallow any state-tracking char before the [
1556
+ clearStateChar();
1557
+
1558
+ if (inClass) {
1559
+ re += '\\' + c;
1560
+ continue;
1561
+ }
1562
+
1563
+ inClass = true;
1564
+ classStart = i;
1565
+ reClassStart = re.length;
1566
+ re += c;
1567
+ continue;
1568
+
1569
+ case ']':
1570
+ // a right bracket shall lose its special
1571
+ // meaning and represent itself in
1572
+ // a bracket expression if it occurs
1573
+ // first in the list. -- POSIX.2 2.8.3.2
1574
+ if (i === classStart + 1 || !inClass) {
1575
+ re += '\\' + c;
1576
+ escaping = false;
1577
+ continue;
1578
+ } // handle the case where we left a class open.
1579
+ // "[z-a]" is valid, equivalent to "\[z-a\]"
1580
+ // split where the last [ was, make sure we don't have
1581
+ // an invalid re. if so, re-walk the contents of the
1582
+ // would-be class to re-translate any characters that
1583
+ // were passed through as-is
1584
+ // TODO: It would probably be faster to determine this
1585
+ // without a try/catch and a new RegExp, but it's tricky
1586
+ // to do safely. For now, this is safe and works.
1587
+
1588
+
1589
+ var cs = pattern.substring(classStart + 1, i);
1590
+
1591
+ try {
1592
+ RegExp('[' + cs + ']');
1593
+ } catch (er) {
1594
+ // not a valid class!
1595
+ var sp = this.parse(cs, SUBPARSE);
1596
+ re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
1597
+ hasMagic = hasMagic || sp[1];
1598
+ inClass = false;
1599
+ continue;
1600
+ } // finish up the class.
1601
+
1602
+
1603
+ hasMagic = true;
1604
+ inClass = false;
1605
+ re += c;
1606
+ continue;
1607
+
1608
+ default:
1609
+ // swallow any state char that wasn't consumed
1610
+ clearStateChar();
1611
+
1612
+ if (escaping) {
1613
+ // no need
1614
+ escaping = false;
1615
+ } else if (reSpecials[c] && !(c === '^' && inClass)) {
1616
+ re += '\\';
1617
+ }
1618
+
1619
+ re += c;
1620
+ } // switch
1621
+
1622
+ } // for
1623
+ // handle the case where we left a class open.
1624
+ // "[abc" is valid, equivalent to "\[abc"
1625
+
1626
+
1627
+ if (inClass) {
1628
+ // split where the last [ was, and escape it
1629
+ // this is a huge pita. We now have to re-walk
1630
+ // the contents of the would-be class to re-translate
1631
+ // any characters that were passed through as-is
1632
+ cs = pattern.substr(classStart + 1);
1633
+ sp = this.parse(cs, SUBPARSE);
1634
+ re = re.substr(0, reClassStart) + '\\[' + sp[0];
1635
+ hasMagic = hasMagic || sp[1];
1636
+ } // handle the case where we had a +( thing at the *end*
1637
+ // of the pattern.
1638
+ // each pattern list stack adds 3 chars, and we need to go through
1639
+ // and escape any | chars that were passed through as-is for the regexp.
1640
+ // Go through and escape them, taking care not to double-escape any
1641
+ // | chars that were already escaped.
1642
+
1643
+
1644
+ for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
1645
+ var tail = re.slice(pl.reStart + pl.open.length);
1646
+ this.debug('setting tail', re, pl); // maybe some even number of \, then maybe 1 \, followed by a |
1647
+
1648
+ tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
1649
+ if (!$2) {
1650
+ // the | isn't already escaped, so escape it.
1651
+ $2 = '\\';
1652
+ } // need to escape all those slashes *again*, without escaping the
1653
+ // one that we need for escaping the | character. As it works out,
1654
+ // escaping an even number of slashes can be done by simply repeating
1655
+ // it exactly after itself. That's why this trick works.
1656
+ //
1657
+ // I am sorry that you have to see this.
1658
+
1659
+
1660
+ return $1 + $1 + $2 + '|';
1661
+ });
1662
+ this.debug('tail=%j\n %s', tail, tail, pl, re);
1663
+ var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type;
1664
+ hasMagic = true;
1665
+ re = re.slice(0, pl.reStart) + t + '\\(' + tail;
1666
+ } // handle trailing things that only matter at the very end.
1667
+
1668
+
1669
+ clearStateChar();
1670
+
1671
+ if (escaping) {
1672
+ // trailing \\
1673
+ re += '\\\\';
1674
+ } // only need to apply the nodot start if the re starts with
1675
+ // something that could conceivably capture a dot
1676
+
1677
+
1678
+ var addPatternStart = false;
1679
+
1680
+ switch (re.charAt(0)) {
1681
+ case '[':
1682
+ case '.':
1683
+ case '(':
1684
+ addPatternStart = true;
1685
+ } // Hack to work around lack of negative lookbehind in JS
1686
+ // A pattern like: *.!(x).!(y|z) needs to ensure that a name
1687
+ // like 'a.xyz.yz' doesn't match. So, the first negative
1688
+ // lookahead, has to look ALL the way ahead, to the end of
1689
+ // the pattern.
1690
+
1691
+
1692
+ for (var n = negativeLists.length - 1; n > -1; n--) {
1693
+ var nl = negativeLists[n];
1694
+ var nlBefore = re.slice(0, nl.reStart);
1695
+ var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
1696
+ var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
1697
+ var nlAfter = re.slice(nl.reEnd);
1698
+ nlLast += nlAfter; // Handle nested stuff like *(*.js|!(*.json)), where open parens
1699
+ // mean that we should *not* include the ) in the bit that is considered
1700
+ // "after" the negated section.
1701
+
1702
+ var openParensBefore = nlBefore.split('(').length - 1;
1703
+ var cleanAfter = nlAfter;
1704
+
1705
+ for (i = 0; i < openParensBefore; i++) {
1706
+ cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
1707
+ }
1708
+
1709
+ nlAfter = cleanAfter;
1710
+ var dollar = '';
1711
+
1712
+ if (nlAfter === '' && isSub !== SUBPARSE) {
1713
+ dollar = '$';
1714
+ }
1715
+
1716
+ var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
1717
+ re = newRe;
1718
+ } // if the re is not "" at this point, then we need to make sure
1719
+ // it doesn't match against an empty path part.
1720
+ // Otherwise a/* will match a/, which it should not.
1721
+
1722
+
1723
+ if (re !== '' && hasMagic) {
1724
+ re = '(?=.)' + re;
1725
+ }
1726
+
1727
+ if (addPatternStart) {
1728
+ re = patternStart + re;
1729
+ } // parsing just a piece of a larger pattern.
1730
+
1731
+
1732
+ if (isSub === SUBPARSE) {
1733
+ return [re, hasMagic];
1734
+ } // skip the regexp for non-magical patterns
1735
+ // unescape anything in it, though, so that it'll be
1736
+ // an exact match against a file etc.
1737
+
1738
+
1739
+ if (!hasMagic) {
1740
+ return globUnescape(pattern);
1741
+ }
1742
+
1743
+ var flags = options.nocase ? 'i' : '';
1744
+
1745
+ try {
1746
+ var regExp = new RegExp('^' + re + '$', flags);
1747
+ } catch (er)
1748
+ /* istanbul ignore next - should be impossible */
1749
+ {
1750
+ // If it was an invalid regular expression, then it can't match
1751
+ // anything. This trick looks for a character after the end of
1752
+ // the string, which is of course impossible, except in multi-line
1753
+ // mode, but it's not a /m regex.
1754
+ return new RegExp('$.');
1755
+ }
1756
+
1757
+ regExp._glob = pattern;
1758
+ regExp._src = re;
1759
+ return regExp;
1760
+ }
1761
+
1762
+ minimatch.makeRe = function (pattern, options) {
1763
+ return new Minimatch(pattern, options || {}).makeRe();
1764
+ };
1765
+
1766
+ Minimatch.prototype.makeRe = makeRe;
1767
+
1768
+ function makeRe() {
1769
+ if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
1770
+ // pattern strings, or "**".
1771
+ //
1772
+ // It's better to use .match(). This function shouldn't
1773
+ // be used, really, but it's pretty convenient sometimes,
1774
+ // when you just want to work with a regex.
1775
+
1776
+ var set = this.set;
1777
+
1778
+ if (!set.length) {
1779
+ this.regexp = false;
1780
+ return this.regexp;
1781
+ }
1782
+
1783
+ var options = this.options;
1784
+ var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
1785
+ var flags = options.nocase ? 'i' : '';
1786
+ var re = set.map(function (pattern) {
1787
+ return pattern.map(function (p) {
1788
+ return p === GLOBSTAR ? twoStar : typeof p === 'string' ? regExpEscape(p) : p._src;
1789
+ }).join('\\\/');
1790
+ }).join('|'); // must match entire pattern
1791
+ // ending in a * or ** will make it less strict.
1792
+
1793
+ re = '^(?:' + re + ')$'; // can match anything, as long as it's not this.
1794
+
1795
+ if (this.negate) re = '^(?!' + re + ').*$';
1796
+
1797
+ try {
1798
+ this.regexp = new RegExp(re, flags);
1799
+ } catch (ex)
1800
+ /* istanbul ignore next - should be impossible */
1801
+ {
1802
+ this.regexp = false;
1803
+ }
1804
+
1805
+ return this.regexp;
1806
+ }
1807
+
1808
+ minimatch.match = function (list, pattern, options) {
1809
+ options = options || {};
1810
+ var mm = new Minimatch(pattern, options);
1811
+ list = list.filter(function (f) {
1812
+ return mm.match(f);
1813
+ });
1814
+
1815
+ if (mm.options.nonull && !list.length) {
1816
+ list.push(pattern);
1817
+ }
1818
+
1819
+ return list;
1820
+ };
1821
+
1822
+ Minimatch.prototype.match = function match(f, partial) {
1823
+ if (typeof partial === 'undefined') partial = this.partial;
1824
+ this.debug('match', f, this.pattern); // short-circuit in the case of busted things.
1825
+ // comments, etc.
1826
+
1827
+ if (this.comment) return false;
1828
+ if (this.empty) return f === '';
1829
+ if (f === '/' && partial) return true;
1830
+ var options = this.options; // windows: need to use /, not \
1831
+
1832
+ if (path.sep !== '/') {
1833
+ f = f.split(path.sep).join('/');
1834
+ } // treat the test path as a set of pathparts.
1835
+
1836
+
1837
+ f = f.split(slashSplit);
1838
+ this.debug(this.pattern, 'split', f); // just ONE of the pattern sets in this.set needs to match
1839
+ // in order for it to be valid. If negating, then just one
1840
+ // match means that we have failed.
1841
+ // Either way, return on the first hit.
1842
+
1843
+ var set = this.set;
1844
+ this.debug(this.pattern, 'set', set); // Find the basename of the path by looking for the last non-empty segment
1845
+
1846
+ var filename;
1847
+ var i;
1848
+
1849
+ for (i = f.length - 1; i >= 0; i--) {
1850
+ filename = f[i];
1851
+ if (filename) break;
1852
+ }
1853
+
1854
+ for (i = 0; i < set.length; i++) {
1855
+ var pattern = set[i];
1856
+ var file = f;
1857
+
1858
+ if (options.matchBase && pattern.length === 1) {
1859
+ file = [filename];
1860
+ }
1861
+
1862
+ var hit = this.matchOne(file, pattern, partial);
1863
+
1864
+ if (hit) {
1865
+ if (options.flipNegate) return true;
1866
+ return !this.negate;
1867
+ }
1868
+ } // didn't get any hits. this is success if it's a negative
1869
+ // pattern, failure otherwise.
1870
+
1871
+
1872
+ if (options.flipNegate) return false;
1873
+ return this.negate;
1874
+ }; // set partial to true to test if, for example,
1875
+ // "/a/b" matches the start of "/*/b/*/d"
1876
+ // Partial means, if you run out of file before you run
1877
+ // out of pattern, then that's fine, as long as all
1878
+ // the parts match.
1879
+
1880
+
1881
+ Minimatch.prototype.matchOne = function (file, pattern, partial) {
1882
+ var options = this.options;
1883
+ this.debug('matchOne', {
1884
+ 'this': this,
1885
+ file: file,
1886
+ pattern: pattern
1887
+ });
1888
+ this.debug('matchOne', file.length, pattern.length);
1889
+
1890
+ for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
1891
+ this.debug('matchOne loop');
1892
+ var p = pattern[pi];
1893
+ var f = file[fi];
1894
+ this.debug(pattern, p, f); // should be impossible.
1895
+ // some invalid regexp stuff in the set.
1896
+
1897
+ /* istanbul ignore if */
1898
+
1899
+ if (p === false) return false;
1900
+
1901
+ if (p === GLOBSTAR) {
1902
+ this.debug('GLOBSTAR', [pattern, p, f]); // "**"
1903
+ // a/**/b/**/c would match the following:
1904
+ // a/b/x/y/z/c
1905
+ // a/x/y/z/b/c
1906
+ // a/b/x/b/x/c
1907
+ // a/b/c
1908
+ // To do this, take the rest of the pattern after
1909
+ // the **, and see if it would match the file remainder.
1910
+ // If so, return success.
1911
+ // If not, the ** "swallows" a segment, and try again.
1912
+ // This is recursively awful.
1913
+ //
1914
+ // a/**/b/**/c matching a/b/x/y/z/c
1915
+ // - a matches a
1916
+ // - doublestar
1917
+ // - matchOne(b/x/y/z/c, b/**/c)
1918
+ // - b matches b
1919
+ // - doublestar
1920
+ // - matchOne(x/y/z/c, c) -> no
1921
+ // - matchOne(y/z/c, c) -> no
1922
+ // - matchOne(z/c, c) -> no
1923
+ // - matchOne(c, c) yes, hit
1924
+
1925
+ var fr = fi;
1926
+ var pr = pi + 1;
1927
+
1928
+ if (pr === pl) {
1929
+ this.debug('** at the end'); // a ** at the end will just swallow the rest.
1930
+ // We have found a match.
1931
+ // however, it will not swallow /.x, unless
1932
+ // options.dot is set.
1933
+ // . and .. are *never* matched by **, for explosively
1934
+ // exponential reasons.
1935
+
1936
+ for (; fi < fl; fi++) {
1937
+ if (file[fi] === '.' || file[fi] === '..' || !options.dot && file[fi].charAt(0) === '.') return false;
1938
+ }
1939
+
1940
+ return true;
1941
+ } // ok, let's see if we can swallow whatever we can.
1942
+
1943
+
1944
+ while (fr < fl) {
1945
+ var swallowee = file[fr];
1946
+ this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); // XXX remove this slice. Just pass the start index.
1947
+
1948
+ if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
1949
+ this.debug('globstar found match!', fr, fl, swallowee); // found a match.
1950
+
1951
+ return true;
1952
+ } else {
1953
+ // can't swallow "." or ".." ever.
1954
+ // can only swallow ".foo" when explicitly asked.
1955
+ if (swallowee === '.' || swallowee === '..' || !options.dot && swallowee.charAt(0) === '.') {
1956
+ this.debug('dot detected!', file, fr, pattern, pr);
1957
+ break;
1958
+ } // ** swallows a segment, and continue.
1959
+
1960
+
1961
+ this.debug('globstar swallow a segment, and continue');
1962
+ fr++;
1963
+ }
1964
+ } // no match was found.
1965
+ // However, in partial mode, we can't say this is necessarily over.
1966
+ // If there's more *pattern* left, then
1967
+
1968
+ /* istanbul ignore if */
1969
+
1970
+
1971
+ if (partial) {
1972
+ // ran out of file
1973
+ this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
1974
+ if (fr === fl) return true;
1975
+ }
1976
+
1977
+ return false;
1978
+ } // something other than **
1979
+ // non-magic patterns just have to match exactly
1980
+ // patterns with magic have been turned into regexps.
1981
+
1982
+
1983
+ var hit;
1984
+
1985
+ if (typeof p === 'string') {
1986
+ hit = f === p;
1987
+ this.debug('string match', p, f, hit);
1988
+ } else {
1989
+ hit = f.match(p);
1990
+ this.debug('pattern match', p, f, hit);
1991
+ }
1992
+
1993
+ if (!hit) return false;
1994
+ } // Note: ending in / means that we'll get a final ""
1995
+ // at the end of the pattern. This can only match a
1996
+ // corresponding "" at the end of the file.
1997
+ // If the file ends in /, then it can only match a
1998
+ // a pattern that ends in /, unless the pattern just
1999
+ // doesn't have any more for it. But, a/b/ should *not*
2000
+ // match "a/b/*", even though "" matches against the
2001
+ // [^/]*? pattern, except in partial mode, where it might
2002
+ // simply not be reached yet.
2003
+ // However, a/b/ should still satisfy a/*
2004
+ // now either we fell off the end of the pattern, or we're done.
2005
+
2006
+
2007
+ if (fi === fl && pi === pl) {
2008
+ // ran out of pattern and filename at the same time.
2009
+ // an exact hit!
2010
+ return true;
2011
+ } else if (fi === fl) {
2012
+ // ran out of file, but still had pattern left.
2013
+ // this is ok if we're doing the match as part of
2014
+ // a glob fs traversal.
2015
+ return partial;
2016
+ } else
2017
+ /* istanbul ignore else */
2018
+ if (pi === pl) {
2019
+ // ran out of pattern, still have file left.
2020
+ // this is only acceptable if we're on the very last
2021
+ // empty segment of a file with a trailing slash.
2022
+ // a/* should match a/b/
2023
+ return fi === fl - 1 && file[fi] === '';
2024
+ } // should be unreachable.
2025
+
2026
+ /* istanbul ignore next */
2027
+
2028
+
2029
+ throw new Error('wtf?');
2030
+ }; // replace stuff like \* with *
2031
+
2032
+
2033
+ function globUnescape(s) {
2034
+ return s.replace(/\\(.)/g, '$1');
2035
+ }
2036
+
2037
+ function regExpEscape(s) {
2038
+ return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
2039
+ }
2040
+
2041
+ return minimatch_1;
2042
+ }
2043
+
2044
+ var inherits = {
2045
+ exports: {}
2046
+ };
2047
+ var inherits_browser = {
2048
+ exports: {}
2049
+ };
2050
+ var hasRequiredInherits_browser;
2051
+
2052
+ function requireInherits_browser() {
2053
+ if (hasRequiredInherits_browser) return inherits_browser.exports;
2054
+ hasRequiredInherits_browser = 1;
2055
+
2056
+ if (typeof Object.create === 'function') {
2057
+ // implementation from standard node.js 'util' module
2058
+ inherits_browser.exports = function inherits(ctor, superCtor) {
2059
+ if (superCtor) {
2060
+ ctor.super_ = superCtor;
2061
+ ctor.prototype = Object.create(superCtor.prototype, {
2062
+ constructor: {
2063
+ value: ctor,
2064
+ enumerable: false,
2065
+ writable: true,
2066
+ configurable: true
2067
+ }
2068
+ });
2069
+ }
2070
+ };
2071
+ } else {
2072
+ // old school shim for old browsers
2073
+ inherits_browser.exports = function inherits(ctor, superCtor) {
2074
+ if (superCtor) {
2075
+ ctor.super_ = superCtor;
2076
+
2077
+ var TempCtor = function () {};
2078
+
2079
+ TempCtor.prototype = superCtor.prototype;
2080
+ ctor.prototype = new TempCtor();
2081
+ ctor.prototype.constructor = ctor;
2082
+ }
2083
+ };
2084
+ }
2085
+
2086
+ return inherits_browser.exports;
2087
+ }
2088
+
2089
+ var hasRequiredInherits;
2090
+
2091
+ function requireInherits() {
2092
+ if (hasRequiredInherits) return inherits.exports;
2093
+ hasRequiredInherits = 1;
2094
+
2095
+ (function (module) {
2096
+ try {
2097
+ var util = require('util');
2098
+ /* istanbul ignore next */
2099
+
2100
+
2101
+ if (typeof util.inherits !== 'function') throw '';
2102
+ module.exports = util.inherits;
2103
+ } catch (e) {
2104
+ /* istanbul ignore next */
2105
+ module.exports = requireInherits_browser();
2106
+ }
2107
+ })(inherits);
2108
+
2109
+ return inherits.exports;
2110
+ }
2111
+
2112
+ var pathIsAbsolute = {
2113
+ exports: {}
2114
+ };
2115
+ var hasRequiredPathIsAbsolute;
2116
+
2117
+ function requirePathIsAbsolute() {
2118
+ if (hasRequiredPathIsAbsolute) return pathIsAbsolute.exports;
2119
+ hasRequiredPathIsAbsolute = 1;
2120
+
2121
+ function posix(path) {
2122
+ return path.charAt(0) === '/';
2123
+ }
2124
+
2125
+ function win32(path) {
2126
+ // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
2127
+ var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
2128
+ var result = splitDeviceRe.exec(path);
2129
+ var device = result[1] || '';
2130
+ var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute
2131
+
2132
+ return Boolean(result[2] || isUnc);
2133
+ }
2134
+
2135
+ pathIsAbsolute.exports = process.platform === 'win32' ? win32 : posix;
2136
+ pathIsAbsolute.exports.posix = posix;
2137
+ pathIsAbsolute.exports.win32 = win32;
2138
+ return pathIsAbsolute.exports;
2139
+ }
2140
+
2141
+ var common = {};
2142
+ var hasRequiredCommon;
2143
+
2144
+ function requireCommon() {
2145
+ if (hasRequiredCommon) return common;
2146
+ hasRequiredCommon = 1;
2147
+ common.setopts = setopts;
2148
+ common.ownProp = ownProp;
2149
+ common.makeAbs = makeAbs;
2150
+ common.finish = finish;
2151
+ common.mark = mark;
2152
+ common.isIgnored = isIgnored;
2153
+ common.childrenIgnored = childrenIgnored;
2154
+
2155
+ function ownProp(obj, field) {
2156
+ return Object.prototype.hasOwnProperty.call(obj, field);
2157
+ }
2158
+
2159
+ var fs = fs$2;
2160
+ var path = path$1;
2161
+ var minimatch = requireMinimatch();
2162
+ var isAbsolute = requirePathIsAbsolute();
2163
+ var Minimatch = minimatch.Minimatch;
2164
+
2165
+ function alphasort(a, b) {
2166
+ return a.localeCompare(b, 'en');
2167
+ }
2168
+
2169
+ function setupIgnores(self, options) {
2170
+ self.ignore = options.ignore || [];
2171
+ if (!Array.isArray(self.ignore)) self.ignore = [self.ignore];
2172
+
2173
+ if (self.ignore.length) {
2174
+ self.ignore = self.ignore.map(ignoreMap);
2175
+ }
2176
+ } // ignore patterns are always in dot:true mode.
2177
+
2178
+
2179
+ function ignoreMap(pattern) {
2180
+ var gmatcher = null;
2181
+
2182
+ if (pattern.slice(-3) === '/**') {
2183
+ var gpattern = pattern.replace(/(\/\*\*)+$/, '');
2184
+ gmatcher = new Minimatch(gpattern, {
2185
+ dot: true
2186
+ });
2187
+ }
2188
+
2189
+ return {
2190
+ matcher: new Minimatch(pattern, {
2191
+ dot: true
2192
+ }),
2193
+ gmatcher: gmatcher
2194
+ };
2195
+ }
2196
+
2197
+ function setopts(self, pattern, options) {
2198
+ if (!options) options = {}; // base-matching: just use globstar for that.
2199
+
2200
+ if (options.matchBase && -1 === pattern.indexOf("/")) {
2201
+ if (options.noglobstar) {
2202
+ throw new Error("base matching requires globstar");
2203
+ }
2204
+
2205
+ pattern = "**/" + pattern;
2206
+ }
2207
+
2208
+ self.silent = !!options.silent;
2209
+ self.pattern = pattern;
2210
+ self.strict = options.strict !== false;
2211
+ self.realpath = !!options.realpath;
2212
+ self.realpathCache = options.realpathCache || Object.create(null);
2213
+ self.follow = !!options.follow;
2214
+ self.dot = !!options.dot;
2215
+ self.mark = !!options.mark;
2216
+ self.nodir = !!options.nodir;
2217
+ if (self.nodir) self.mark = true;
2218
+ self.sync = !!options.sync;
2219
+ self.nounique = !!options.nounique;
2220
+ self.nonull = !!options.nonull;
2221
+ self.nosort = !!options.nosort;
2222
+ self.nocase = !!options.nocase;
2223
+ self.stat = !!options.stat;
2224
+ self.noprocess = !!options.noprocess;
2225
+ self.absolute = !!options.absolute;
2226
+ self.fs = options.fs || fs;
2227
+ self.maxLength = options.maxLength || Infinity;
2228
+ self.cache = options.cache || Object.create(null);
2229
+ self.statCache = options.statCache || Object.create(null);
2230
+ self.symlinks = options.symlinks || Object.create(null);
2231
+ setupIgnores(self, options);
2232
+ self.changedCwd = false;
2233
+ var cwd = process.cwd();
2234
+ if (!ownProp(options, "cwd")) self.cwd = cwd;else {
2235
+ self.cwd = path.resolve(options.cwd);
2236
+ self.changedCwd = self.cwd !== cwd;
2237
+ }
2238
+ self.root = options.root || path.resolve(self.cwd, "/");
2239
+ self.root = path.resolve(self.root);
2240
+ if (process.platform === "win32") self.root = self.root.replace(/\\/g, "/"); // TODO: is an absolute `cwd` supposed to be resolved against `root`?
2241
+ // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
2242
+
2243
+ self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
2244
+ if (process.platform === "win32") self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
2245
+ self.nomount = !!options.nomount; // disable comments and negation in Minimatch.
2246
+ // Note that they are not supported in Glob itself anyway.
2247
+
2248
+ options.nonegate = true;
2249
+ options.nocomment = true; // always treat \ in patterns as escapes, not path separators
2250
+
2251
+ options.allowWindowsEscape = false;
2252
+ self.minimatch = new Minimatch(pattern, options);
2253
+ self.options = self.minimatch.options;
2254
+ }
2255
+
2256
+ function finish(self) {
2257
+ var nou = self.nounique;
2258
+ var all = nou ? [] : Object.create(null);
2259
+
2260
+ for (var i = 0, l = self.matches.length; i < l; i++) {
2261
+ var matches = self.matches[i];
2262
+
2263
+ if (!matches || Object.keys(matches).length === 0) {
2264
+ if (self.nonull) {
2265
+ // do like the shell, and spit out the literal glob
2266
+ var literal = self.minimatch.globSet[i];
2267
+ if (nou) all.push(literal);else all[literal] = true;
2268
+ }
2269
+ } else {
2270
+ // had matches
2271
+ var m = Object.keys(matches);
2272
+ if (nou) all.push.apply(all, m);else m.forEach(function (m) {
2273
+ all[m] = true;
2274
+ });
2275
+ }
2276
+ }
2277
+
2278
+ if (!nou) all = Object.keys(all);
2279
+ if (!self.nosort) all = all.sort(alphasort); // at *some* point we statted all of these
2280
+
2281
+ if (self.mark) {
2282
+ for (var i = 0; i < all.length; i++) {
2283
+ all[i] = self._mark(all[i]);
2284
+ }
2285
+
2286
+ if (self.nodir) {
2287
+ all = all.filter(function (e) {
2288
+ var notDir = !/\/$/.test(e);
2289
+ var c = self.cache[e] || self.cache[makeAbs(self, e)];
2290
+ if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c);
2291
+ return notDir;
2292
+ });
2293
+ }
2294
+ }
2295
+
2296
+ if (self.ignore.length) all = all.filter(function (m) {
2297
+ return !isIgnored(self, m);
2298
+ });
2299
+ self.found = all;
2300
+ }
2301
+
2302
+ function mark(self, p) {
2303
+ var abs = makeAbs(self, p);
2304
+ var c = self.cache[abs];
2305
+ var m = p;
2306
+
2307
+ if (c) {
2308
+ var isDir = c === 'DIR' || Array.isArray(c);
2309
+ var slash = p.slice(-1) === '/';
2310
+ if (isDir && !slash) m += '/';else if (!isDir && slash) m = m.slice(0, -1);
2311
+
2312
+ if (m !== p) {
2313
+ var mabs = makeAbs(self, m);
2314
+ self.statCache[mabs] = self.statCache[abs];
2315
+ self.cache[mabs] = self.cache[abs];
2316
+ }
2317
+ }
2318
+
2319
+ return m;
2320
+ } // lotta situps...
2321
+
2322
+
2323
+ function makeAbs(self, f) {
2324
+ var abs = f;
2325
+
2326
+ if (f.charAt(0) === '/') {
2327
+ abs = path.join(self.root, f);
2328
+ } else if (isAbsolute(f) || f === '') {
2329
+ abs = f;
2330
+ } else if (self.changedCwd) {
2331
+ abs = path.resolve(self.cwd, f);
2332
+ } else {
2333
+ abs = path.resolve(f);
2334
+ }
2335
+
2336
+ if (process.platform === 'win32') abs = abs.replace(/\\/g, '/');
2337
+ return abs;
2338
+ } // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
2339
+ // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
2340
+
2341
+
2342
+ function isIgnored(self, path) {
2343
+ if (!self.ignore.length) return false;
2344
+ return self.ignore.some(function (item) {
2345
+ return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path));
2346
+ });
2347
+ }
2348
+
2349
+ function childrenIgnored(self, path) {
2350
+ if (!self.ignore.length) return false;
2351
+ return self.ignore.some(function (item) {
2352
+ return !!(item.gmatcher && item.gmatcher.match(path));
2353
+ });
2354
+ }
2355
+
2356
+ return common;
2357
+ }
2358
+
2359
+ var sync;
2360
+ var hasRequiredSync;
2361
+
2362
+ function requireSync() {
2363
+ if (hasRequiredSync) return sync;
2364
+ hasRequiredSync = 1;
2365
+ sync = globSync;
2366
+ globSync.GlobSync = GlobSync;
2367
+ var rp = requireFs_realpath();
2368
+ var minimatch = requireMinimatch();
2369
+ requireGlob().Glob;
2370
+ var path = path$1;
2371
+ var assert = require$$5;
2372
+ var isAbsolute = requirePathIsAbsolute();
2373
+ var common = requireCommon();
2374
+ var setopts = common.setopts;
2375
+ var ownProp = common.ownProp;
2376
+ var childrenIgnored = common.childrenIgnored;
2377
+ var isIgnored = common.isIgnored;
2378
+
2379
+ function globSync(pattern, options) {
2380
+ if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n' + 'See: https://github.com/isaacs/node-glob/issues/167');
2381
+ return new GlobSync(pattern, options).found;
2382
+ }
2383
+
2384
+ function GlobSync(pattern, options) {
2385
+ if (!pattern) throw new Error('must provide pattern');
2386
+ if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n' + 'See: https://github.com/isaacs/node-glob/issues/167');
2387
+ if (!(this instanceof GlobSync)) return new GlobSync(pattern, options);
2388
+ setopts(this, pattern, options);
2389
+ if (this.noprocess) return this;
2390
+ var n = this.minimatch.set.length;
2391
+ this.matches = new Array(n);
2392
+
2393
+ for (var i = 0; i < n; i++) {
2394
+ this._process(this.minimatch.set[i], i, false);
2395
+ }
2396
+
2397
+ this._finish();
2398
+ }
2399
+
2400
+ GlobSync.prototype._finish = function () {
2401
+ assert.ok(this instanceof GlobSync);
2402
+
2403
+ if (this.realpath) {
2404
+ var self = this;
2405
+ this.matches.forEach(function (matchset, index) {
2406
+ var set = self.matches[index] = Object.create(null);
2407
+
2408
+ for (var p in matchset) {
2409
+ try {
2410
+ p = self._makeAbs(p);
2411
+ var real = rp.realpathSync(p, self.realpathCache);
2412
+ set[real] = true;
2413
+ } catch (er) {
2414
+ if (er.syscall === 'stat') set[self._makeAbs(p)] = true;else throw er;
2415
+ }
2416
+ }
2417
+ });
2418
+ }
2419
+
2420
+ common.finish(this);
2421
+ };
2422
+
2423
+ GlobSync.prototype._process = function (pattern, index, inGlobStar) {
2424
+ assert.ok(this instanceof GlobSync); // Get the first [n] parts of pattern that are all strings.
2425
+
2426
+ var n = 0;
2427
+
2428
+ while (typeof pattern[n] === 'string') {
2429
+ n++;
2430
+ } // now n is the index of the first one that is *not* a string.
2431
+ // See if there's anything else
2432
+
2433
+
2434
+ var prefix;
2435
+
2436
+ switch (n) {
2437
+ // if not, then this is rather simple
2438
+ case pattern.length:
2439
+ this._processSimple(pattern.join('/'), index);
2440
+
2441
+ return;
2442
+
2443
+ case 0:
2444
+ // pattern *starts* with some non-trivial item.
2445
+ // going to readdir(cwd), but not include the prefix in matches.
2446
+ prefix = null;
2447
+ break;
2448
+
2449
+ default:
2450
+ // pattern has some string bits in the front.
2451
+ // whatever it starts with, whether that's 'absolute' like /foo/bar,
2452
+ // or 'relative' like '../baz'
2453
+ prefix = pattern.slice(0, n).join('/');
2454
+ break;
2455
+ }
2456
+
2457
+ var remain = pattern.slice(n); // get the list of entries.
2458
+
2459
+ var read;
2460
+ if (prefix === null) read = '.';else if (isAbsolute(prefix) || isAbsolute(pattern.map(function (p) {
2461
+ return typeof p === 'string' ? p : '[*]';
2462
+ }).join('/'))) {
2463
+ if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix;
2464
+ read = prefix;
2465
+ } else read = prefix;
2466
+
2467
+ var abs = this._makeAbs(read); //if ignored, skip processing
2468
+
2469
+
2470
+ if (childrenIgnored(this, read)) return;
2471
+ var isGlobStar = remain[0] === minimatch.GLOBSTAR;
2472
+ if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);else this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
2473
+ };
2474
+
2475
+ GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
2476
+ var entries = this._readdir(abs, inGlobStar); // if the abs isn't a dir, then nothing can match!
2477
+
2478
+
2479
+ if (!entries) return; // It will only match dot entries if it starts with a dot, or if
2480
+ // dot is set. Stuff like @(.foo|.bar) isn't allowed.
2481
+
2482
+ var pn = remain[0];
2483
+ var negate = !!this.minimatch.negate;
2484
+ var rawGlob = pn._glob;
2485
+ var dotOk = this.dot || rawGlob.charAt(0) === '.';
2486
+ var matchedEntries = [];
2487
+
2488
+ for (var i = 0; i < entries.length; i++) {
2489
+ var e = entries[i];
2490
+
2491
+ if (e.charAt(0) !== '.' || dotOk) {
2492
+ var m;
2493
+
2494
+ if (negate && !prefix) {
2495
+ m = !e.match(pn);
2496
+ } else {
2497
+ m = e.match(pn);
2498
+ }
2499
+
2500
+ if (m) matchedEntries.push(e);
2501
+ }
2502
+ }
2503
+
2504
+ var len = matchedEntries.length; // If there are no matched entries, then nothing matches.
2505
+
2506
+ if (len === 0) return; // if this is the last remaining pattern bit, then no need for
2507
+ // an additional stat *unless* the user has specified mark or
2508
+ // stat explicitly. We know they exist, since readdir returned
2509
+ // them.
2510
+
2511
+ if (remain.length === 1 && !this.mark && !this.stat) {
2512
+ if (!this.matches[index]) this.matches[index] = Object.create(null);
2513
+
2514
+ for (var i = 0; i < len; i++) {
2515
+ var e = matchedEntries[i];
2516
+
2517
+ if (prefix) {
2518
+ if (prefix.slice(-1) !== '/') e = prefix + '/' + e;else e = prefix + e;
2519
+ }
2520
+
2521
+ if (e.charAt(0) === '/' && !this.nomount) {
2522
+ e = path.join(this.root, e);
2523
+ }
2524
+
2525
+ this._emitMatch(index, e);
2526
+ } // This was the last one, and no stats were needed
2527
+
2528
+
2529
+ return;
2530
+ } // now test all matched entries as stand-ins for that part
2531
+ // of the pattern.
2532
+
2533
+
2534
+ remain.shift();
2535
+
2536
+ for (var i = 0; i < len; i++) {
2537
+ var e = matchedEntries[i];
2538
+ var newPattern;
2539
+ if (prefix) newPattern = [prefix, e];else newPattern = [e];
2540
+
2541
+ this._process(newPattern.concat(remain), index, inGlobStar);
2542
+ }
2543
+ };
2544
+
2545
+ GlobSync.prototype._emitMatch = function (index, e) {
2546
+ if (isIgnored(this, e)) return;
2547
+
2548
+ var abs = this._makeAbs(e);
2549
+
2550
+ if (this.mark) e = this._mark(e);
2551
+
2552
+ if (this.absolute) {
2553
+ e = abs;
2554
+ }
2555
+
2556
+ if (this.matches[index][e]) return;
2557
+
2558
+ if (this.nodir) {
2559
+ var c = this.cache[abs];
2560
+ if (c === 'DIR' || Array.isArray(c)) return;
2561
+ }
2562
+
2563
+ this.matches[index][e] = true;
2564
+ if (this.stat) this._stat(e);
2565
+ };
2566
+
2567
+ GlobSync.prototype._readdirInGlobStar = function (abs) {
2568
+ // follow all symlinked directories forever
2569
+ // just proceed as if this is a non-globstar situation
2570
+ if (this.follow) return this._readdir(abs, false);
2571
+ var entries;
2572
+ var lstat;
2573
+
2574
+ try {
2575
+ lstat = this.fs.lstatSync(abs);
2576
+ } catch (er) {
2577
+ if (er.code === 'ENOENT') {
2578
+ // lstat failed, doesn't exist
2579
+ return null;
2580
+ }
2581
+ }
2582
+
2583
+ var isSym = lstat && lstat.isSymbolicLink();
2584
+ this.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file.
2585
+ // don't bother doing a readdir in that case.
2586
+
2587
+ if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE';else entries = this._readdir(abs, false);
2588
+ return entries;
2589
+ };
2590
+
2591
+ GlobSync.prototype._readdir = function (abs, inGlobStar) {
2592
+ if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs);
2593
+
2594
+ if (ownProp(this.cache, abs)) {
2595
+ var c = this.cache[abs];
2596
+ if (!c || c === 'FILE') return null;
2597
+ if (Array.isArray(c)) return c;
2598
+ }
2599
+
2600
+ try {
2601
+ return this._readdirEntries(abs, this.fs.readdirSync(abs));
2602
+ } catch (er) {
2603
+ this._readdirError(abs, er);
2604
+
2605
+ return null;
2606
+ }
2607
+ };
2608
+
2609
+ GlobSync.prototype._readdirEntries = function (abs, entries) {
2610
+ // if we haven't asked to stat everything, then just
2611
+ // assume that everything in there exists, so we can avoid
2612
+ // having to stat it a second time.
2613
+ if (!this.mark && !this.stat) {
2614
+ for (var i = 0; i < entries.length; i++) {
2615
+ var e = entries[i];
2616
+ if (abs === '/') e = abs + e;else e = abs + '/' + e;
2617
+ this.cache[e] = true;
2618
+ }
2619
+ }
2620
+
2621
+ this.cache[abs] = entries; // mark and cache dir-ness
2622
+
2623
+ return entries;
2624
+ };
2625
+
2626
+ GlobSync.prototype._readdirError = function (f, er) {
2627
+ // handle errors, and cache the information
2628
+ switch (er.code) {
2629
+ case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
2630
+
2631
+ case 'ENOTDIR':
2632
+ // totally normal. means it *does* exist.
2633
+ var abs = this._makeAbs(f);
2634
+
2635
+ this.cache[abs] = 'FILE';
2636
+
2637
+ if (abs === this.cwdAbs) {
2638
+ var error = new Error(er.code + ' invalid cwd ' + this.cwd);
2639
+ error.path = this.cwd;
2640
+ error.code = er.code;
2641
+ throw error;
2642
+ }
2643
+
2644
+ break;
2645
+
2646
+ case 'ENOENT': // not terribly unusual
2647
+
2648
+ case 'ELOOP':
2649
+ case 'ENAMETOOLONG':
2650
+ case 'UNKNOWN':
2651
+ this.cache[this._makeAbs(f)] = false;
2652
+ break;
2653
+
2654
+ default:
2655
+ // some unusual error. Treat as failure.
2656
+ this.cache[this._makeAbs(f)] = false;
2657
+ if (this.strict) throw er;
2658
+ if (!this.silent) console.error('glob error', er);
2659
+ break;
2660
+ }
2661
+ };
2662
+
2663
+ GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
2664
+ var entries = this._readdir(abs, inGlobStar); // no entries means not a dir, so it can never have matches
2665
+ // foo.txt/** doesn't match foo.txt
2666
+
2667
+
2668
+ if (!entries) return; // test without the globstar, and with every child both below
2669
+ // and replacing the globstar.
2670
+
2671
+ var remainWithoutGlobStar = remain.slice(1);
2672
+ var gspref = prefix ? [prefix] : [];
2673
+ var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state
2674
+
2675
+ this._process(noGlobStar, index, false);
2676
+
2677
+ var len = entries.length;
2678
+ var isSym = this.symlinks[abs]; // If it's a symlink, and we're in a globstar, then stop
2679
+
2680
+ if (isSym && inGlobStar) return;
2681
+
2682
+ for (var i = 0; i < len; i++) {
2683
+ var e = entries[i];
2684
+ if (e.charAt(0) === '.' && !this.dot) continue; // these two cases enter the inGlobStar state
2685
+
2686
+ var instead = gspref.concat(entries[i], remainWithoutGlobStar);
2687
+
2688
+ this._process(instead, index, true);
2689
+
2690
+ var below = gspref.concat(entries[i], remain);
2691
+
2692
+ this._process(below, index, true);
2693
+ }
2694
+ };
2695
+
2696
+ GlobSync.prototype._processSimple = function (prefix, index) {
2697
+ // XXX review this. Shouldn't it be doing the mounting etc
2698
+ // before doing stat? kinda weird?
2699
+ var exists = this._stat(prefix);
2700
+
2701
+ if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results
2702
+
2703
+ if (!exists) return;
2704
+
2705
+ if (prefix && isAbsolute(prefix) && !this.nomount) {
2706
+ var trail = /[\/\\]$/.test(prefix);
2707
+
2708
+ if (prefix.charAt(0) === '/') {
2709
+ prefix = path.join(this.root, prefix);
2710
+ } else {
2711
+ prefix = path.resolve(this.root, prefix);
2712
+ if (trail) prefix += '/';
2713
+ }
2714
+ }
2715
+
2716
+ if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match
2717
+
2718
+ this._emitMatch(index, prefix);
2719
+ }; // Returns either 'DIR', 'FILE', or false
2720
+
2721
+
2722
+ GlobSync.prototype._stat = function (f) {
2723
+ var abs = this._makeAbs(f);
2724
+
2725
+ var needDir = f.slice(-1) === '/';
2726
+ if (f.length > this.maxLength) return false;
2727
+
2728
+ if (!this.stat && ownProp(this.cache, abs)) {
2729
+ var c = this.cache[abs];
2730
+ if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it
2731
+
2732
+ if (!needDir || c === 'DIR') return c;
2733
+ if (needDir && c === 'FILE') return false; // otherwise we have to stat, because maybe c=true
2734
+ // if we know it exists, but not what it is.
2735
+ }
2736
+
2737
+ var stat = this.statCache[abs];
2738
+
2739
+ if (!stat) {
2740
+ var lstat;
2741
+
2742
+ try {
2743
+ lstat = this.fs.lstatSync(abs);
2744
+ } catch (er) {
2745
+ if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
2746
+ this.statCache[abs] = false;
2747
+ return false;
2748
+ }
2749
+ }
2750
+
2751
+ if (lstat && lstat.isSymbolicLink()) {
2752
+ try {
2753
+ stat = this.fs.statSync(abs);
2754
+ } catch (er) {
2755
+ stat = lstat;
2756
+ }
2757
+ } else {
2758
+ stat = lstat;
2759
+ }
2760
+ }
2761
+
2762
+ this.statCache[abs] = stat;
2763
+ var c = true;
2764
+ if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE';
2765
+ this.cache[abs] = this.cache[abs] || c;
2766
+ if (needDir && c === 'FILE') return false;
2767
+ return c;
2768
+ };
2769
+
2770
+ GlobSync.prototype._mark = function (p) {
2771
+ return common.mark(this, p);
2772
+ };
2773
+
2774
+ GlobSync.prototype._makeAbs = function (f) {
2775
+ return common.makeAbs(this, f);
2776
+ };
2777
+
2778
+ return sync;
2779
+ }
2780
+
2781
+ var wrappy_1;
2782
+ var hasRequiredWrappy;
2783
+
2784
+ function requireWrappy() {
2785
+ if (hasRequiredWrappy) return wrappy_1;
2786
+ hasRequiredWrappy = 1; // Returns a wrapper function that returns a wrapped callback
2787
+ // The wrapper function should do some stuff, and return a
2788
+ // presumably different callback function.
2789
+ // This makes sure that own properties are retained, so that
2790
+ // decorations and such are not lost along the way.
2791
+
2792
+ wrappy_1 = wrappy;
2793
+
2794
+ function wrappy(fn, cb) {
2795
+ if (fn && cb) return wrappy(fn)(cb);
2796
+ if (typeof fn !== 'function') throw new TypeError('need wrapper function');
2797
+ Object.keys(fn).forEach(function (k) {
2798
+ wrapper[k] = fn[k];
2799
+ });
2800
+ return wrapper;
2801
+
2802
+ function wrapper() {
2803
+ var args = new Array(arguments.length);
2804
+
2805
+ for (var i = 0; i < args.length; i++) {
2806
+ args[i] = arguments[i];
2807
+ }
2808
+
2809
+ var ret = fn.apply(this, args);
2810
+ var cb = args[args.length - 1];
2811
+
2812
+ if (typeof ret === 'function' && ret !== cb) {
2813
+ Object.keys(cb).forEach(function (k) {
2814
+ ret[k] = cb[k];
2815
+ });
2816
+ }
2817
+
2818
+ return ret;
2819
+ }
2820
+ }
2821
+
2822
+ return wrappy_1;
2823
+ }
2824
+
2825
+ var once = {
2826
+ exports: {}
2827
+ };
2828
+ var hasRequiredOnce;
2829
+
2830
+ function requireOnce() {
2831
+ if (hasRequiredOnce) return once.exports;
2832
+ hasRequiredOnce = 1;
2833
+ var wrappy = requireWrappy();
2834
+ once.exports = wrappy(once$1);
2835
+ once.exports.strict = wrappy(onceStrict);
2836
+ once$1.proto = once$1(function () {
2837
+ Object.defineProperty(Function.prototype, 'once', {
2838
+ value: function () {
2839
+ return once$1(this);
2840
+ },
2841
+ configurable: true
2842
+ });
2843
+ Object.defineProperty(Function.prototype, 'onceStrict', {
2844
+ value: function () {
2845
+ return onceStrict(this);
2846
+ },
2847
+ configurable: true
2848
+ });
2849
+ });
2850
+
2851
+ function once$1(fn) {
2852
+ var f = function () {
2853
+ if (f.called) return f.value;
2854
+ f.called = true;
2855
+ return f.value = fn.apply(this, arguments);
2856
+ };
2857
+
2858
+ f.called = false;
2859
+ return f;
2860
+ }
2861
+
2862
+ function onceStrict(fn) {
2863
+ var f = function () {
2864
+ if (f.called) throw new Error(f.onceError);
2865
+ f.called = true;
2866
+ return f.value = fn.apply(this, arguments);
2867
+ };
2868
+
2869
+ var name = fn.name || 'Function wrapped with `once`';
2870
+ f.onceError = name + " shouldn't be called more than once";
2871
+ f.called = false;
2872
+ return f;
2873
+ }
2874
+
2875
+ return once.exports;
2876
+ }
2877
+
2878
+ var inflight_1;
2879
+ var hasRequiredInflight;
2880
+
2881
+ function requireInflight() {
2882
+ if (hasRequiredInflight) return inflight_1;
2883
+ hasRequiredInflight = 1;
2884
+ var wrappy = requireWrappy();
2885
+ var reqs = Object.create(null);
2886
+ var once = requireOnce();
2887
+ inflight_1 = wrappy(inflight);
2888
+
2889
+ function inflight(key, cb) {
2890
+ if (reqs[key]) {
2891
+ reqs[key].push(cb);
2892
+ return null;
2893
+ } else {
2894
+ reqs[key] = [cb];
2895
+ return makeres(key);
2896
+ }
2897
+ }
2898
+
2899
+ function makeres(key) {
2900
+ return once(function RES() {
2901
+ var cbs = reqs[key];
2902
+ var len = cbs.length;
2903
+ var args = slice(arguments); // XXX It's somewhat ambiguous whether a new callback added in this
2904
+ // pass should be queued for later execution if something in the
2905
+ // list of callbacks throws, or if it should just be discarded.
2906
+ // However, it's such an edge case that it hardly matters, and either
2907
+ // choice is likely as surprising as the other.
2908
+ // As it happens, we do go ahead and schedule it for later execution.
2909
+
2910
+ try {
2911
+ for (var i = 0; i < len; i++) {
2912
+ cbs[i].apply(null, args);
2913
+ }
2914
+ } finally {
2915
+ if (cbs.length > len) {
2916
+ // added more in the interim.
2917
+ // de-zalgo, just in case, but don't call again.
2918
+ cbs.splice(0, len);
2919
+ process.nextTick(function () {
2920
+ RES.apply(null, args);
2921
+ });
2922
+ } else {
2923
+ delete reqs[key];
2924
+ }
2925
+ }
2926
+ });
2927
+ }
2928
+
2929
+ function slice(args) {
2930
+ var length = args.length;
2931
+ var array = [];
2932
+
2933
+ for (var i = 0; i < length; i++) array[i] = args[i];
2934
+
2935
+ return array;
2936
+ }
2937
+
2938
+ return inflight_1;
2939
+ }
2940
+
2941
+ var glob_1;
2942
+ var hasRequiredGlob;
2943
+
2944
+ function requireGlob() {
2945
+ if (hasRequiredGlob) return glob_1;
2946
+ hasRequiredGlob = 1; // Approach:
2947
+ //
2948
+ // 1. Get the minimatch set
2949
+ // 2. For each pattern in the set, PROCESS(pattern, false)
2950
+ // 3. Store matches per-set, then uniq them
2951
+ //
2952
+ // PROCESS(pattern, inGlobStar)
2953
+ // Get the first [n] items from pattern that are all strings
2954
+ // Join these together. This is PREFIX.
2955
+ // If there is no more remaining, then stat(PREFIX) and
2956
+ // add to matches if it succeeds. END.
2957
+ //
2958
+ // If inGlobStar and PREFIX is symlink and points to dir
2959
+ // set ENTRIES = []
2960
+ // else readdir(PREFIX) as ENTRIES
2961
+ // If fail, END
2962
+ //
2963
+ // with ENTRIES
2964
+ // If pattern[n] is GLOBSTAR
2965
+ // // handle the case where the globstar match is empty
2966
+ // // by pruning it out, and testing the resulting pattern
2967
+ // PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
2968
+ // // handle other cases.
2969
+ // for ENTRY in ENTRIES (not dotfiles)
2970
+ // // attach globstar + tail onto the entry
2971
+ // // Mark that this entry is a globstar match
2972
+ // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
2973
+ //
2974
+ // else // not globstar
2975
+ // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
2976
+ // Test ENTRY against pattern[n]
2977
+ // If fails, continue
2978
+ // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
2979
+ //
2980
+ // Caveat:
2981
+ // Cache all stats and readdirs results to minimize syscall. Since all
2982
+ // we ever care about is existence and directory-ness, we can just keep
2983
+ // `true` for files, and [children,...] for directories, or `false` for
2984
+ // things that don't exist.
2985
+
2986
+ glob_1 = glob;
2987
+ var rp = requireFs_realpath();
2988
+ var minimatch = requireMinimatch();
2989
+ var inherits = requireInherits();
2990
+ var EE = require$$3.EventEmitter;
2991
+ var path = path$1;
2992
+ var assert = require$$5;
2993
+ var isAbsolute = requirePathIsAbsolute();
2994
+ var globSync = requireSync();
2995
+ var common = requireCommon();
2996
+ var setopts = common.setopts;
2997
+ var ownProp = common.ownProp;
2998
+ var inflight = requireInflight();
2999
+ var childrenIgnored = common.childrenIgnored;
3000
+ var isIgnored = common.isIgnored;
3001
+ var once = requireOnce();
3002
+
3003
+ function glob(pattern, options, cb) {
3004
+ if (typeof options === 'function') cb = options, options = {};
3005
+ if (!options) options = {};
3006
+
3007
+ if (options.sync) {
3008
+ if (cb) throw new TypeError('callback provided to sync glob');
3009
+ return globSync(pattern, options);
3010
+ }
3011
+
3012
+ return new Glob(pattern, options, cb);
3013
+ }
3014
+
3015
+ glob.sync = globSync;
3016
+ var GlobSync = glob.GlobSync = globSync.GlobSync; // old api surface
3017
+
3018
+ glob.glob = glob;
3019
+
3020
+ function extend(origin, add) {
3021
+ if (add === null || typeof add !== 'object') {
3022
+ return origin;
3023
+ }
3024
+
3025
+ var keys = Object.keys(add);
3026
+ var i = keys.length;
3027
+
3028
+ while (i--) {
3029
+ origin[keys[i]] = add[keys[i]];
3030
+ }
3031
+
3032
+ return origin;
3033
+ }
3034
+
3035
+ glob.hasMagic = function (pattern, options_) {
3036
+ var options = extend({}, options_);
3037
+ options.noprocess = true;
3038
+ var g = new Glob(pattern, options);
3039
+ var set = g.minimatch.set;
3040
+ if (!pattern) return false;
3041
+ if (set.length > 1) return true;
3042
+
3043
+ for (var j = 0; j < set[0].length; j++) {
3044
+ if (typeof set[0][j] !== 'string') return true;
3045
+ }
3046
+
3047
+ return false;
3048
+ };
3049
+
3050
+ glob.Glob = Glob;
3051
+ inherits(Glob, EE);
3052
+
3053
+ function Glob(pattern, options, cb) {
3054
+ if (typeof options === 'function') {
3055
+ cb = options;
3056
+ options = null;
3057
+ }
3058
+
3059
+ if (options && options.sync) {
3060
+ if (cb) throw new TypeError('callback provided to sync glob');
3061
+ return new GlobSync(pattern, options);
3062
+ }
3063
+
3064
+ if (!(this instanceof Glob)) return new Glob(pattern, options, cb);
3065
+ setopts(this, pattern, options);
3066
+ this._didRealPath = false; // process each pattern in the minimatch set
3067
+
3068
+ var n = this.minimatch.set.length; // The matches are stored as {<filename>: true,...} so that
3069
+ // duplicates are automagically pruned.
3070
+ // Later, we do an Object.keys() on these.
3071
+ // Keep them as a list so we can fill in when nonull is set.
3072
+
3073
+ this.matches = new Array(n);
3074
+
3075
+ if (typeof cb === 'function') {
3076
+ cb = once(cb);
3077
+ this.on('error', cb);
3078
+ this.on('end', function (matches) {
3079
+ cb(null, matches);
3080
+ });
3081
+ }
3082
+
3083
+ var self = this;
3084
+ this._processing = 0;
3085
+ this._emitQueue = [];
3086
+ this._processQueue = [];
3087
+ this.paused = false;
3088
+ if (this.noprocess) return this;
3089
+ if (n === 0) return done();
3090
+ var sync = true;
3091
+
3092
+ for (var i = 0; i < n; i++) {
3093
+ this._process(this.minimatch.set[i], i, false, done);
3094
+ }
3095
+
3096
+ sync = false;
3097
+
3098
+ function done() {
3099
+ --self._processing;
3100
+
3101
+ if (self._processing <= 0) {
3102
+ if (sync) {
3103
+ process.nextTick(function () {
3104
+ self._finish();
3105
+ });
3106
+ } else {
3107
+ self._finish();
3108
+ }
3109
+ }
3110
+ }
3111
+ }
3112
+
3113
+ Glob.prototype._finish = function () {
3114
+ assert(this instanceof Glob);
3115
+ if (this.aborted) return;
3116
+ if (this.realpath && !this._didRealpath) return this._realpath();
3117
+ common.finish(this);
3118
+ this.emit('end', this.found);
3119
+ };
3120
+
3121
+ Glob.prototype._realpath = function () {
3122
+ if (this._didRealpath) return;
3123
+ this._didRealpath = true;
3124
+ var n = this.matches.length;
3125
+ if (n === 0) return this._finish();
3126
+ var self = this;
3127
+
3128
+ for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next);
3129
+
3130
+ function next() {
3131
+ if (--n === 0) self._finish();
3132
+ }
3133
+ };
3134
+
3135
+ Glob.prototype._realpathSet = function (index, cb) {
3136
+ var matchset = this.matches[index];
3137
+ if (!matchset) return cb();
3138
+ var found = Object.keys(matchset);
3139
+ var self = this;
3140
+ var n = found.length;
3141
+ if (n === 0) return cb();
3142
+ var set = this.matches[index] = Object.create(null);
3143
+ found.forEach(function (p, i) {
3144
+ // If there's a problem with the stat, then it means that
3145
+ // one or more of the links in the realpath couldn't be
3146
+ // resolved. just return the abs value in that case.
3147
+ p = self._makeAbs(p);
3148
+ rp.realpath(p, self.realpathCache, function (er, real) {
3149
+ if (!er) set[real] = true;else if (er.syscall === 'stat') set[p] = true;else self.emit('error', er); // srsly wtf right here
3150
+
3151
+ if (--n === 0) {
3152
+ self.matches[index] = set;
3153
+ cb();
3154
+ }
3155
+ });
3156
+ });
3157
+ };
3158
+
3159
+ Glob.prototype._mark = function (p) {
3160
+ return common.mark(this, p);
3161
+ };
3162
+
3163
+ Glob.prototype._makeAbs = function (f) {
3164
+ return common.makeAbs(this, f);
3165
+ };
3166
+
3167
+ Glob.prototype.abort = function () {
3168
+ this.aborted = true;
3169
+ this.emit('abort');
3170
+ };
3171
+
3172
+ Glob.prototype.pause = function () {
3173
+ if (!this.paused) {
3174
+ this.paused = true;
3175
+ this.emit('pause');
3176
+ }
3177
+ };
3178
+
3179
+ Glob.prototype.resume = function () {
3180
+ if (this.paused) {
3181
+ this.emit('resume');
3182
+ this.paused = false;
3183
+
3184
+ if (this._emitQueue.length) {
3185
+ var eq = this._emitQueue.slice(0);
3186
+
3187
+ this._emitQueue.length = 0;
3188
+
3189
+ for (var i = 0; i < eq.length; i++) {
3190
+ var e = eq[i];
3191
+
3192
+ this._emitMatch(e[0], e[1]);
3193
+ }
3194
+ }
3195
+
3196
+ if (this._processQueue.length) {
3197
+ var pq = this._processQueue.slice(0);
3198
+
3199
+ this._processQueue.length = 0;
3200
+
3201
+ for (var i = 0; i < pq.length; i++) {
3202
+ var p = pq[i];
3203
+ this._processing--;
3204
+
3205
+ this._process(p[0], p[1], p[2], p[3]);
3206
+ }
3207
+ }
3208
+ }
3209
+ };
3210
+
3211
+ Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
3212
+ assert(this instanceof Glob);
3213
+ assert(typeof cb === 'function');
3214
+ if (this.aborted) return;
3215
+ this._processing++;
3216
+
3217
+ if (this.paused) {
3218
+ this._processQueue.push([pattern, index, inGlobStar, cb]);
3219
+
3220
+ return;
3221
+ } //console.error('PROCESS %d', this._processing, pattern)
3222
+ // Get the first [n] parts of pattern that are all strings.
3223
+
3224
+
3225
+ var n = 0;
3226
+
3227
+ while (typeof pattern[n] === 'string') {
3228
+ n++;
3229
+ } // now n is the index of the first one that is *not* a string.
3230
+ // see if there's anything else
3231
+
3232
+
3233
+ var prefix;
3234
+
3235
+ switch (n) {
3236
+ // if not, then this is rather simple
3237
+ case pattern.length:
3238
+ this._processSimple(pattern.join('/'), index, cb);
3239
+
3240
+ return;
3241
+
3242
+ case 0:
3243
+ // pattern *starts* with some non-trivial item.
3244
+ // going to readdir(cwd), but not include the prefix in matches.
3245
+ prefix = null;
3246
+ break;
3247
+
3248
+ default:
3249
+ // pattern has some string bits in the front.
3250
+ // whatever it starts with, whether that's 'absolute' like /foo/bar,
3251
+ // or 'relative' like '../baz'
3252
+ prefix = pattern.slice(0, n).join('/');
3253
+ break;
3254
+ }
3255
+
3256
+ var remain = pattern.slice(n); // get the list of entries.
3257
+
3258
+ var read;
3259
+ if (prefix === null) read = '.';else if (isAbsolute(prefix) || isAbsolute(pattern.map(function (p) {
3260
+ return typeof p === 'string' ? p : '[*]';
3261
+ }).join('/'))) {
3262
+ if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix;
3263
+ read = prefix;
3264
+ } else read = prefix;
3265
+
3266
+ var abs = this._makeAbs(read); //if ignored, skip _processing
3267
+
3268
+
3269
+ if (childrenIgnored(this, read)) return cb();
3270
+ var isGlobStar = remain[0] === minimatch.GLOBSTAR;
3271
+ if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
3272
+ };
3273
+
3274
+ Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
3275
+ var self = this;
3276
+
3277
+ this._readdir(abs, inGlobStar, function (er, entries) {
3278
+ return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
3279
+ });
3280
+ };
3281
+
3282
+ Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
3283
+ // if the abs isn't a dir, then nothing can match!
3284
+ if (!entries) return cb(); // It will only match dot entries if it starts with a dot, or if
3285
+ // dot is set. Stuff like @(.foo|.bar) isn't allowed.
3286
+
3287
+ var pn = remain[0];
3288
+ var negate = !!this.minimatch.negate;
3289
+ var rawGlob = pn._glob;
3290
+ var dotOk = this.dot || rawGlob.charAt(0) === '.';
3291
+ var matchedEntries = [];
3292
+
3293
+ for (var i = 0; i < entries.length; i++) {
3294
+ var e = entries[i];
3295
+
3296
+ if (e.charAt(0) !== '.' || dotOk) {
3297
+ var m;
3298
+
3299
+ if (negate && !prefix) {
3300
+ m = !e.match(pn);
3301
+ } else {
3302
+ m = e.match(pn);
3303
+ }
3304
+
3305
+ if (m) matchedEntries.push(e);
3306
+ }
3307
+ } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
3308
+
3309
+
3310
+ var len = matchedEntries.length; // If there are no matched entries, then nothing matches.
3311
+
3312
+ if (len === 0) return cb(); // if this is the last remaining pattern bit, then no need for
3313
+ // an additional stat *unless* the user has specified mark or
3314
+ // stat explicitly. We know they exist, since readdir returned
3315
+ // them.
3316
+
3317
+ if (remain.length === 1 && !this.mark && !this.stat) {
3318
+ if (!this.matches[index]) this.matches[index] = Object.create(null);
3319
+
3320
+ for (var i = 0; i < len; i++) {
3321
+ var e = matchedEntries[i];
3322
+
3323
+ if (prefix) {
3324
+ if (prefix !== '/') e = prefix + '/' + e;else e = prefix + e;
3325
+ }
3326
+
3327
+ if (e.charAt(0) === '/' && !this.nomount) {
3328
+ e = path.join(this.root, e);
3329
+ }
3330
+
3331
+ this._emitMatch(index, e);
3332
+ } // This was the last one, and no stats were needed
3333
+
3334
+
3335
+ return cb();
3336
+ } // now test all matched entries as stand-ins for that part
3337
+ // of the pattern.
3338
+
3339
+
3340
+ remain.shift();
3341
+
3342
+ for (var i = 0; i < len; i++) {
3343
+ var e = matchedEntries[i];
3344
+
3345
+ if (prefix) {
3346
+ if (prefix !== '/') e = prefix + '/' + e;else e = prefix + e;
3347
+ }
3348
+
3349
+ this._process([e].concat(remain), index, inGlobStar, cb);
3350
+ }
3351
+
3352
+ cb();
3353
+ };
3354
+
3355
+ Glob.prototype._emitMatch = function (index, e) {
3356
+ if (this.aborted) return;
3357
+ if (isIgnored(this, e)) return;
3358
+
3359
+ if (this.paused) {
3360
+ this._emitQueue.push([index, e]);
3361
+
3362
+ return;
3363
+ }
3364
+
3365
+ var abs = isAbsolute(e) ? e : this._makeAbs(e);
3366
+ if (this.mark) e = this._mark(e);
3367
+ if (this.absolute) e = abs;
3368
+ if (this.matches[index][e]) return;
3369
+
3370
+ if (this.nodir) {
3371
+ var c = this.cache[abs];
3372
+ if (c === 'DIR' || Array.isArray(c)) return;
3373
+ }
3374
+
3375
+ this.matches[index][e] = true;
3376
+ var st = this.statCache[abs];
3377
+ if (st) this.emit('stat', e, st);
3378
+ this.emit('match', e);
3379
+ };
3380
+
3381
+ Glob.prototype._readdirInGlobStar = function (abs, cb) {
3382
+ if (this.aborted) return; // follow all symlinked directories forever
3383
+ // just proceed as if this is a non-globstar situation
3384
+
3385
+ if (this.follow) return this._readdir(abs, false, cb);
3386
+ var lstatkey = 'lstat\0' + abs;
3387
+ var self = this;
3388
+ var lstatcb = inflight(lstatkey, lstatcb_);
3389
+ if (lstatcb) self.fs.lstat(abs, lstatcb);
3390
+
3391
+ function lstatcb_(er, lstat) {
3392
+ if (er && er.code === 'ENOENT') return cb();
3393
+ var isSym = lstat && lstat.isSymbolicLink();
3394
+ self.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file.
3395
+ // don't bother doing a readdir in that case.
3396
+
3397
+ if (!isSym && lstat && !lstat.isDirectory()) {
3398
+ self.cache[abs] = 'FILE';
3399
+ cb();
3400
+ } else self._readdir(abs, false, cb);
3401
+ }
3402
+ };
3403
+
3404
+ Glob.prototype._readdir = function (abs, inGlobStar, cb) {
3405
+ if (this.aborted) return;
3406
+ cb = inflight('readdir\0' + abs + '\0' + inGlobStar, cb);
3407
+ if (!cb) return; //console.error('RD %j %j', +inGlobStar, abs)
3408
+
3409
+ if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb);
3410
+
3411
+ if (ownProp(this.cache, abs)) {
3412
+ var c = this.cache[abs];
3413
+ if (!c || c === 'FILE') return cb();
3414
+ if (Array.isArray(c)) return cb(null, c);
3415
+ }
3416
+
3417
+ var self = this;
3418
+ self.fs.readdir(abs, readdirCb(this, abs, cb));
3419
+ };
3420
+
3421
+ function readdirCb(self, abs, cb) {
3422
+ return function (er, entries) {
3423
+ if (er) self._readdirError(abs, er, cb);else self._readdirEntries(abs, entries, cb);
3424
+ };
3425
+ }
3426
+
3427
+ Glob.prototype._readdirEntries = function (abs, entries, cb) {
3428
+ if (this.aborted) return; // if we haven't asked to stat everything, then just
3429
+ // assume that everything in there exists, so we can avoid
3430
+ // having to stat it a second time.
3431
+
3432
+ if (!this.mark && !this.stat) {
3433
+ for (var i = 0; i < entries.length; i++) {
3434
+ var e = entries[i];
3435
+ if (abs === '/') e = abs + e;else e = abs + '/' + e;
3436
+ this.cache[e] = true;
3437
+ }
3438
+ }
3439
+
3440
+ this.cache[abs] = entries;
3441
+ return cb(null, entries);
3442
+ };
3443
+
3444
+ Glob.prototype._readdirError = function (f, er, cb) {
3445
+ if (this.aborted) return; // handle errors, and cache the information
3446
+
3447
+ switch (er.code) {
3448
+ case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
3449
+
3450
+ case 'ENOTDIR':
3451
+ // totally normal. means it *does* exist.
3452
+ var abs = this._makeAbs(f);
3453
+
3454
+ this.cache[abs] = 'FILE';
3455
+
3456
+ if (abs === this.cwdAbs) {
3457
+ var error = new Error(er.code + ' invalid cwd ' + this.cwd);
3458
+ error.path = this.cwd;
3459
+ error.code = er.code;
3460
+ this.emit('error', error);
3461
+ this.abort();
3462
+ }
3463
+
3464
+ break;
3465
+
3466
+ case 'ENOENT': // not terribly unusual
3467
+
3468
+ case 'ELOOP':
3469
+ case 'ENAMETOOLONG':
3470
+ case 'UNKNOWN':
3471
+ this.cache[this._makeAbs(f)] = false;
3472
+ break;
3473
+
3474
+ default:
3475
+ // some unusual error. Treat as failure.
3476
+ this.cache[this._makeAbs(f)] = false;
3477
+
3478
+ if (this.strict) {
3479
+ this.emit('error', er); // If the error is handled, then we abort
3480
+ // if not, we threw out of here
3481
+
3482
+ this.abort();
3483
+ }
3484
+
3485
+ if (!this.silent) console.error('glob error', er);
3486
+ break;
3487
+ }
3488
+
3489
+ return cb();
3490
+ };
3491
+
3492
+ Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
3493
+ var self = this;
3494
+
3495
+ this._readdir(abs, inGlobStar, function (er, entries) {
3496
+ self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
3497
+ });
3498
+ };
3499
+
3500
+ Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
3501
+ //console.error('pgs2', prefix, remain[0], entries)
3502
+ // no entries means not a dir, so it can never have matches
3503
+ // foo.txt/** doesn't match foo.txt
3504
+ if (!entries) return cb(); // test without the globstar, and with every child both below
3505
+ // and replacing the globstar.
3506
+
3507
+ var remainWithoutGlobStar = remain.slice(1);
3508
+ var gspref = prefix ? [prefix] : [];
3509
+ var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state
3510
+
3511
+ this._process(noGlobStar, index, false, cb);
3512
+
3513
+ var isSym = this.symlinks[abs];
3514
+ var len = entries.length; // If it's a symlink, and we're in a globstar, then stop
3515
+
3516
+ if (isSym && inGlobStar) return cb();
3517
+
3518
+ for (var i = 0; i < len; i++) {
3519
+ var e = entries[i];
3520
+ if (e.charAt(0) === '.' && !this.dot) continue; // these two cases enter the inGlobStar state
3521
+
3522
+ var instead = gspref.concat(entries[i], remainWithoutGlobStar);
3523
+
3524
+ this._process(instead, index, true, cb);
3525
+
3526
+ var below = gspref.concat(entries[i], remain);
3527
+
3528
+ this._process(below, index, true, cb);
3529
+ }
3530
+
3531
+ cb();
3532
+ };
3533
+
3534
+ Glob.prototype._processSimple = function (prefix, index, cb) {
3535
+ // XXX review this. Shouldn't it be doing the mounting etc
3536
+ // before doing stat? kinda weird?
3537
+ var self = this;
3538
+
3539
+ this._stat(prefix, function (er, exists) {
3540
+ self._processSimple2(prefix, index, er, exists, cb);
3541
+ });
3542
+ };
3543
+
3544
+ Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
3545
+ //console.error('ps2', prefix, exists)
3546
+ if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results
3547
+
3548
+ if (!exists) return cb();
3549
+
3550
+ if (prefix && isAbsolute(prefix) && !this.nomount) {
3551
+ var trail = /[\/\\]$/.test(prefix);
3552
+
3553
+ if (prefix.charAt(0) === '/') {
3554
+ prefix = path.join(this.root, prefix);
3555
+ } else {
3556
+ prefix = path.resolve(this.root, prefix);
3557
+ if (trail) prefix += '/';
3558
+ }
3559
+ }
3560
+
3561
+ if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match
3562
+
3563
+ this._emitMatch(index, prefix);
3564
+
3565
+ cb();
3566
+ }; // Returns either 'DIR', 'FILE', or false
3567
+
3568
+
3569
+ Glob.prototype._stat = function (f, cb) {
3570
+ var abs = this._makeAbs(f);
3571
+
3572
+ var needDir = f.slice(-1) === '/';
3573
+ if (f.length > this.maxLength) return cb();
3574
+
3575
+ if (!this.stat && ownProp(this.cache, abs)) {
3576
+ var c = this.cache[abs];
3577
+ if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it
3578
+
3579
+ if (!needDir || c === 'DIR') return cb(null, c);
3580
+ if (needDir && c === 'FILE') return cb(); // otherwise we have to stat, because maybe c=true
3581
+ // if we know it exists, but not what it is.
3582
+ }
3583
+
3584
+ var stat = this.statCache[abs];
184
3585
 
185
- function _parseExports(options) {
186
- const {
187
- pkg
188
- } = options;
189
- const rootExport = {
190
- _exported: true,
191
- _path: ".",
192
- types: pkg.types,
193
- source: pkg.source || "index.js",
194
- browser: pkg.browser && {
195
- require: pkg.main && pkg.browser[pkg.main],
196
- import: pkg.module && pkg.browser[pkg.module]
197
- },
198
- import: pkg.module,
199
- require: pkg.main,
200
- default: pkg.module || pkg.main || "./index.js"
201
- };
202
- const extraExports = [];
3586
+ if (stat !== undefined) {
3587
+ if (stat === false) return cb(null, stat);else {
3588
+ var type = stat.isDirectory() ? 'DIR' : 'FILE';
3589
+ if (needDir && type === 'FILE') return cb();else return cb(null, type, stat);
3590
+ }
3591
+ }
203
3592
 
204
- if (pkg.exports) {
205
- for (const [exportPath, exportEntry] of Object.entries(pkg.exports)) {
206
- if (_isRecord(exportEntry)) {
207
- if (exportPath === ".") {
208
- Object.assign(rootExport, exportEntry);
209
- } else {
210
- const extraExport = _objectSpread({
211
- _exported: true,
212
- _path: exportPath
213
- }, exportEntry);
3593
+ var self = this;
3594
+ var statcb = inflight('stat\0' + abs, lstatcb_);
3595
+ if (statcb) self.fs.lstat(abs, statcb);
214
3596
 
215
- extraExports.push(extraExport);
216
- }
3597
+ function lstatcb_(er, lstat) {
3598
+ if (lstat && lstat.isSymbolicLink()) {
3599
+ // If it's a symlink, then treat it as the target, unless
3600
+ // the target does not exist, then treat it as a file.
3601
+ return self.fs.stat(abs, function (er, stat) {
3602
+ if (er) self._stat2(f, abs, null, lstat, cb);else self._stat2(f, abs, er, stat, cb);
3603
+ });
217
3604
  } else {
218
- throw new Error("string entries are not supported");
3605
+ self._stat2(f, abs, er, lstat, cb);
219
3606
  }
220
3607
  }
221
- }
3608
+ };
222
3609
 
223
- return [rootExport, ...extraExports];
224
- }
3610
+ Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
3611
+ if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
3612
+ this.statCache[abs] = false;
3613
+ return cb();
3614
+ }
225
3615
 
226
- async function _loadTSConfig(options) {
227
- const {
228
- cwd,
229
- tsconfigPath
230
- } = options;
231
- const configPath = ts.findConfigFile(cwd, ts.sys.fileExists, tsconfigPath);
3616
+ var needDir = f.slice(-1) === '/';
3617
+ this.statCache[abs] = stat;
3618
+ if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat);
3619
+ var c = true;
3620
+ if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE';
3621
+ this.cache[abs] = this.cache[abs] || c;
3622
+ if (needDir && c === 'FILE') return cb();
3623
+ return cb(null, c, stat);
3624
+ };
232
3625
 
233
- if (!configPath) {
234
- throw new Error("could not find a valid '".concat(tsconfigPath, "'"));
235
- }
3626
+ return glob_1;
3627
+ }
236
3628
 
237
- const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
238
- return ts.parseJsonConfigFileContent(configFile.config, ts.sys, cwd);
3629
+ const assert = require$$5;
3630
+ const path = path$1;
3631
+ const fs = fs$2;
3632
+ let glob = undefined;
3633
+
3634
+ try {
3635
+ glob = requireGlob();
3636
+ } catch (_err) {// treat glob as optional.
239
3637
  }
240
3638
 
241
- function _resolveBuildTasks(ctx) {
242
- var _a, _b, _c, _d, _e;
3639
+ const defaultGlobOpts = {
3640
+ nosort: true,
3641
+ silent: true
3642
+ }; // for EMFILE handling
243
3643
 
244
- const {
245
- cwd,
246
- pkg,
247
- target
248
- } = ctx;
249
- const tasks = [];
250
- const exports = Object.entries(ctx.exports || {}).map(_ref => {
251
- let [_path, exp] = _ref;
252
- return _objectSpread({
253
- _path
254
- }, exp);
3644
+ let timeout = 0;
3645
+ const isWindows = process.platform === "win32";
3646
+
3647
+ const defaults = options => {
3648
+ const methods = ['unlink', 'chmod', 'stat', 'lstat', 'rmdir', 'readdir'];
3649
+ methods.forEach(m => {
3650
+ options[m] = options[m] || fs[m];
3651
+ m = m + 'Sync';
3652
+ options[m] = options[m] || fs[m];
255
3653
  });
256
- const dtsTasks = {};
257
- const rollupTasks = {};
3654
+ options.maxBusyTries = options.maxBusyTries || 3;
3655
+ options.emfileWait = options.emfileWait || 1000;
258
3656
 
259
- function _addRollupTaskEntry(format, runtime, entry) {
260
- const buildId = "".concat(format, ":").concat(runtime);
3657
+ if (options.glob === false) {
3658
+ options.disableGlob = true;
3659
+ }
261
3660
 
262
- if (!rollupTasks[buildId]) {
263
- rollupTasks[buildId] = {
264
- type: "build:js",
265
- buildId,
266
- entries: [entry],
267
- runtime,
268
- format,
269
- target: target[runtime]
270
- };
271
- } else {
272
- rollupTasks[buildId].entries.push(entry);
273
- }
3661
+ if (options.disableGlob !== true && glob === undefined) {
3662
+ throw Error('glob dependency not found, set `options.disableGlob = true` if intentional');
274
3663
  }
275
3664
 
276
- for (const exp of exports) {
277
- const importId = path.join(pkg.name, exp._path);
3665
+ options.disableGlob = options.disableGlob || false;
3666
+ options.glob = options.glob || defaultGlobOpts;
3667
+ };
278
3668
 
279
- if (exp.types) {
280
- if (!dtsTasks[importId]) {
281
- dtsTasks[importId] = {
282
- type: "build:dts",
283
- importId,
284
- exportPath: exp._path,
285
- sourcePath: exp.source,
286
- targetPath: exp.types
287
- };
288
- }
289
- }
3669
+ const rimraf$1 = (p, options, cb) => {
3670
+ if (typeof options === 'function') {
3671
+ cb = options;
3672
+ options = {};
290
3673
  }
291
3674
 
292
- for (const exp of exports) {
293
- const output = exp.require;
294
- if (!output) continue;
3675
+ assert(p, 'rimraf: missing path');
3676
+ assert.equal(typeof p, 'string', 'rimraf: path should be a string');
3677
+ assert.equal(typeof cb, 'function', 'rimraf: callback function required');
3678
+ assert(options, 'rimraf: invalid options argument provided');
3679
+ assert.equal(typeof options, 'object', 'rimraf: options should be object');
3680
+ defaults(options);
3681
+ let busyTries = 0;
3682
+ let errState = null;
3683
+ let n = 0;
3684
+
3685
+ const next = er => {
3686
+ errState = errState || er;
3687
+ if (--n === 0) cb(errState);
3688
+ };
295
3689
 
296
- _addRollupTaskEntry("commonjs", ctx.runtime, {
297
- path: exp._path,
298
- source: exp.source,
299
- output
300
- });
301
- }
3690
+ const afterGlob = (er, results) => {
3691
+ if (er) return cb(er);
3692
+ n = results.length;
3693
+ if (n === 0) return cb();
3694
+ results.forEach(p => {
3695
+ const CB = er => {
3696
+ if (er) {
3697
+ if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) {
3698
+ busyTries++; // try again, with the same exact callback as this one.
302
3699
 
303
- for (const exp of exports) {
304
- const output = (_a = exp.browser) == null ? void 0 : _a.require;
305
- if (!output) continue;
3700
+ return setTimeout(() => rimraf_(p, options, CB), busyTries * 100);
3701
+ } // this one won't happen if graceful-fs is used.
306
3702
 
307
- _addRollupTaskEntry("commonjs", "browser", {
308
- path: exp._path,
309
- source: ((_b = exp.browser) == null ? void 0 : _b.source) || exp.source,
310
- output
3703
+
3704
+ if (er.code === "EMFILE" && timeout < options.emfileWait) {
3705
+ return setTimeout(() => rimraf_(p, options, CB), timeout++);
3706
+ } // already gone
3707
+
3708
+
3709
+ if (er.code === "ENOENT") er = null;
3710
+ }
3711
+
3712
+ timeout = 0;
3713
+ next(er);
3714
+ };
3715
+
3716
+ rimraf_(p, options, CB);
311
3717
  });
312
- }
3718
+ };
313
3719
 
314
- for (const exp of exports) {
315
- const output = exp.import;
316
- if (!output) continue;
3720
+ if (options.disableGlob || !glob.hasMagic(p)) return afterGlob(null, [p]);
3721
+ options.lstat(p, (er, stat) => {
3722
+ if (!er) return afterGlob(null, [p]);
3723
+ glob(p, options.glob, afterGlob);
3724
+ });
3725
+ }; // Two possible strategies.
3726
+ // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR
3727
+ // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR
3728
+ //
3729
+ // Both result in an extra syscall when you guess wrong. However, there
3730
+ // are likely far more normal files in the world than directories. This
3731
+ // is based on the assumption that a the average number of files per
3732
+ // directory is >= 1.
3733
+ //
3734
+ // If anyone ever complains about this, then I guess the strategy could
3735
+ // be made configurable somehow. But until then, YAGNI.
3736
+
3737
+
3738
+ const rimraf_ = (p, options, cb) => {
3739
+ assert(p);
3740
+ assert(options);
3741
+ assert(typeof cb === 'function'); // sunos lets the root user unlink directories, which is... weird.
3742
+ // so we have to lstat here and make sure it's not a dir.
3743
+
3744
+ options.lstat(p, (er, st) => {
3745
+ if (er && er.code === "ENOENT") return cb(null); // Windows can EPERM on stat. Life is suffering.
3746
+
3747
+ if (er && er.code === "EPERM" && isWindows) fixWinEPERM(p, options, er, cb);
3748
+ if (st && st.isDirectory()) return rmdir(p, options, er, cb);
3749
+ options.unlink(p, er => {
3750
+ if (er) {
3751
+ if (er.code === "ENOENT") return cb(null);
3752
+ if (er.code === "EPERM") return isWindows ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb);
3753
+ if (er.code === "EISDIR") return rmdir(p, options, er, cb);
3754
+ }
317
3755
 
318
- _addRollupTaskEntry("esm", ctx.runtime, {
319
- path: exp._path,
320
- source: exp.source,
321
- output
3756
+ return cb(er);
3757
+ });
3758
+ });
3759
+ };
3760
+
3761
+ const fixWinEPERM = (p, options, er, cb) => {
3762
+ assert(p);
3763
+ assert(options);
3764
+ assert(typeof cb === 'function');
3765
+ options.chmod(p, 0o666, er2 => {
3766
+ if (er2) cb(er2.code === "ENOENT" ? null : er);else options.stat(p, (er3, stats) => {
3767
+ if (er3) cb(er3.code === "ENOENT" ? null : er);else if (stats.isDirectory()) rmdir(p, options, er, cb);else options.unlink(p, cb);
322
3768
  });
3769
+ });
3770
+ };
3771
+
3772
+ const fixWinEPERMSync = (p, options, er) => {
3773
+ assert(p);
3774
+ assert(options);
3775
+
3776
+ try {
3777
+ options.chmodSync(p, 0o666);
3778
+ } catch (er2) {
3779
+ if (er2.code === "ENOENT") return;else throw er;
323
3780
  }
324
3781
 
325
- for (const exp of exports) {
326
- const output = (_c = exp.browser) == null ? void 0 : _c.import;
327
- if (!output) continue;
3782
+ let stats;
328
3783
 
329
- _addRollupTaskEntry("esm", "browser", {
330
- path: exp._path,
331
- source: ((_d = exp.browser) == null ? void 0 : _d.source) || exp.source,
332
- output
333
- });
3784
+ try {
3785
+ stats = options.statSync(p);
3786
+ } catch (er3) {
3787
+ if (er3.code === "ENOENT") return;else throw er;
334
3788
  }
335
3789
 
336
- tasks.push(...Object.values(dtsTasks));
337
- tasks.push(...Object.values(rollupTasks));
3790
+ if (stats.isDirectory()) rmdirSync(p, options, er);else options.unlinkSync(p);
3791
+ };
338
3792
 
339
- for (const exp of exports) {
340
- if (exp._exported && exp._path !== ".") {
341
- const relativeTargetPath = (((_e = exp.browser) == null ? void 0 : _e.import) || exp.import || "").replace(/\.[^/.]+$/, "");
3793
+ const rmdir = (p, options, originalEr, cb) => {
3794
+ assert(p);
3795
+ assert(options);
3796
+ assert(typeof cb === 'function'); // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
3797
+ // if we guessed wrong, and it's not a directory, then
3798
+ // raise the original error.
342
3799
 
343
- if (relativeTargetPath) {
344
- fs$1.writeFileSync(path.resolve(cwd, "".concat(exp._path, ".js")), ["// AUTO-GENERATED \u2013 DO NOT EDIT", "", "export * from '".concat(relativeTargetPath, "'"), ""].join("\n"));
345
- }
3800
+ options.rmdir(p, er => {
3801
+ if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) rmkids(p, options, cb);else if (er && er.code === "ENOTDIR") cb(originalEr);else cb(er);
3802
+ });
3803
+ };
3804
+
3805
+ const rmkids = (p, options, cb) => {
3806
+ assert(p);
3807
+ assert(options);
3808
+ assert(typeof cb === 'function');
3809
+ options.readdir(p, (er, files) => {
3810
+ if (er) return cb(er);
3811
+ let n = files.length;
3812
+ if (n === 0) return options.rmdir(p, cb);
3813
+ let errState;
3814
+ files.forEach(f => {
3815
+ rimraf$1(path.join(p, f), options, er => {
3816
+ if (errState) return;
3817
+ if (er) return cb(errState = er);
3818
+ if (--n === 0) options.rmdir(p, cb);
3819
+ });
3820
+ });
3821
+ });
3822
+ }; // this looks simpler, and is strictly *faster*, but will
3823
+ // tie up the JavaScript thread and fail on excessively
3824
+ // deep directory trees.
3825
+
3826
+
3827
+ const rimrafSync = (p, options) => {
3828
+ options = options || {};
3829
+ defaults(options);
3830
+ assert(p, 'rimraf: missing path');
3831
+ assert.equal(typeof p, 'string', 'rimraf: path should be a string');
3832
+ assert(options, 'rimraf: missing options');
3833
+ assert.equal(typeof options, 'object', 'rimraf: options should be object');
3834
+ let results;
3835
+
3836
+ if (options.disableGlob || !glob.hasMagic(p)) {
3837
+ results = [p];
3838
+ } else {
3839
+ try {
3840
+ options.lstatSync(p);
3841
+ results = [p];
3842
+ } catch (er) {
3843
+ results = glob.sync(p, options.glob);
346
3844
  }
347
3845
  }
348
3846
 
349
- return tasks;
350
- }
351
-
352
- function _printExtractMessages(ctx, messages) {
353
- const {
354
- cwd,
355
- logger
356
- } = ctx;
357
- const warnings = messages.filter(msg => msg.logLevel === "warning");
3847
+ if (!results.length) return;
358
3848
 
359
- if (warnings.length) {
360
- logger.log();
361
- }
3849
+ for (let i = 0; i < results.length; i++) {
3850
+ const p = results[i];
3851
+ let st;
362
3852
 
363
- for (const msg of warnings) {
364
- const sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath);
3853
+ try {
3854
+ st = options.lstatSync(p);
3855
+ } catch (er) {
3856
+ if (er.code === "ENOENT") return; // Windows can EPERM on stat. Life is suffering.
365
3857
 
366
- if (msg.messageId === "TS6307") {
367
- continue;
3858
+ if (er.code === "EPERM" && isWindows) fixWinEPERMSync(p, options, er);
368
3859
  }
369
3860
 
370
- logger.log(["".concat(chalk.cyan(sourceFilePath || "?")), ":".concat(chalk.yellow(msg.sourceFileLine), ":").concat(chalk.yellow(msg.sourceFileColumn)), " - ".concat(chalk.yellow("warning"), " ").concat(chalk.gray(msg.messageId), "\n"), msg.text, "\n"].join(""));
3861
+ try {
3862
+ // sunos lets the root user unlink directories, which is... weird.
3863
+ if (st && st.isDirectory()) rmdirSync(p, options, null);else options.unlinkSync(p);
3864
+ } catch (er) {
3865
+ if (er.code === "ENOENT") return;
3866
+ if (er.code === "EPERM") return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er);
3867
+ if (er.code !== "EISDIR") throw er;
3868
+ rmdirSync(p, options, er);
3869
+ }
371
3870
  }
3871
+ };
372
3872
 
373
- const errors = messages.filter(msg => msg.logLevel === "error");
3873
+ const rmdirSync = (p, options, originalEr) => {
3874
+ assert(p);
3875
+ assert(options);
374
3876
 
375
- if (!warnings.length && errors.length) {
376
- logger.log("");
3877
+ try {
3878
+ options.rmdirSync(p);
3879
+ } catch (er) {
3880
+ if (er.code === "ENOENT") return;
3881
+ if (er.code === "ENOTDIR") throw originalEr;
3882
+ if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") rmkidsSync(p, options);
377
3883
  }
3884
+ };
378
3885
 
379
- for (const msg of errors) {
380
- const sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath);
381
- logger.log(["".concat(chalk.cyan(sourceFilePath || "?")), ":".concat(chalk.yellow(msg.sourceFileLine), ":").concat(chalk.yellow(msg.sourceFileColumn)), " - ".concat(chalk.red("error"), " ").concat(chalk.gray(msg.messageId), "\n"), msg.text, "\n"].join(""));
382
- }
3886
+ const rmkidsSync = (p, options) => {
3887
+ assert(p);
3888
+ assert(options);
3889
+ options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)); // We only end up here once we got ENOTEMPTY at least once, and
3890
+ // at this point, we are guaranteed to have removed all the kids.
3891
+ // So, we know that it won't be ENOENT or ENOTDIR or anything else.
3892
+ // try really hard to delete stuff on windows, because it has a
3893
+ // PROFOUNDLY annoying habit of not closing handles promptly when
3894
+ // files are deleted, resulting in spurious ENOTEMPTY errors.
383
3895
 
384
- if (errors.length) {
385
- process.exit(1);
386
- }
387
- }
3896
+ const retries = isWindows ? 100 : 1;
3897
+ let i = 0;
3898
+
3899
+ do {
3900
+ let threw = true;
3901
+
3902
+ try {
3903
+ const ret = options.rmdirSync(p, options);
3904
+ threw = false;
3905
+ return ret;
3906
+ } finally {
3907
+ if (++i < retries && threw) continue;
3908
+ }
3909
+ } while (true);
3910
+ };
388
3911
 
3912
+ var rimraf_1 = rimraf$1;
3913
+ rimraf$1.sync = rimrafSync;
389
3914
  const formatHost = {
390
3915
  getCurrentDirectory: () => ts.sys.getCurrentDirectory(),
391
3916
  getNewLine: () => ts.sys.newLine,
@@ -394,9 +3919,7 @@ const formatHost = {
394
3919
 
395
3920
  async function _buildTypes(options) {
396
3921
  const {
397
- cwd,
398
3922
  outDir,
399
- sourcePath,
400
3923
  tsconfig
401
3924
  } = options;
402
3925
 
@@ -408,15 +3931,7 @@ async function _buildTypes(options) {
408
3931
  outDir
409
3932
  });
410
3933
 
411
- const rootDir = path.relative(cwd, compilerOptions.rootDir ? path.resolve(cwd, compilerOptions.rootDir) : path.dirname(path.resolve(cwd, sourcePath))) || ".";
412
3934
  const program = ts.createProgram(tsconfig.fileNames, compilerOptions);
413
- const sourceFiles = program.getSourceFiles();
414
- const sourceFile = sourceFiles.find(f => f.fileName === path.resolve(cwd, sourcePath));
415
-
416
- if (!sourceFile) {
417
- throw new Error("source file not found: ".concat(sourcePath));
418
- }
419
-
420
3935
  const emitResult = program.emit();
421
3936
  const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
422
3937
  allDiagnostics.forEach(diagnostic => {
@@ -440,11 +3955,6 @@ async function _buildTypes(options) {
440
3955
  throw new Error("failed to compile");
441
3956
  }
442
3957
  }
443
-
444
- const typesPath = path.resolve(outDir, path.relative(rootDir, path.resolve(cwd, sourcePath))).replace(/\.[jt]sx?$/, ".d.ts");
445
- return {
446
- path: typesPath
447
- };
448
3958
  }
449
3959
 
450
3960
  class _DtsError extends Error {
@@ -475,11 +3985,11 @@ function _createApiExtractorConfig(options) {
475
3985
  },
476
3986
  docModel: {
477
3987
  enabled: false,
478
- apiJsonFilePath: path.resolve(distPath, "".concat(exportPath, ".api.json"))
3988
+ apiJsonFilePath: path$1.resolve(distPath, "".concat(exportPath, ".api.json"))
479
3989
  },
480
3990
  dtsRollup: {
481
3991
  enabled: true,
482
- untrimmedFilePath: path.resolve(distPath, filePath)
3992
+ untrimmedFilePath: path$1.resolve(distPath, filePath)
483
3993
  },
484
3994
  tsdocMetadata: {
485
3995
  enabled: false
@@ -598,7 +4108,7 @@ async function _extractTypes(options) {
598
4108
  }),
599
4109
  configObjectFullPath: void 0,
600
4110
  tsdocConfigFile,
601
- packageJsonFullPath: path.resolve(projectPath, "package.json")
4111
+ packageJsonFullPath: path$1.resolve(projectPath, "package.json")
602
4112
  });
603
4113
  const messages = [];
604
4114
  const extractorResult = Extractor.invoke(extractorConfig, {
@@ -611,11 +4121,11 @@ async function _extractTypes(options) {
611
4121
  }
612
4122
 
613
4123
  });
614
- const typesPath = path.resolve(distPath, filePath);
615
- const typesBuf = await fs.readFile(typesPath);
4124
+ const typesPath = path$1.resolve(distPath, filePath);
4125
+ const typesBuf = await fs$1.readFile(typesPath);
616
4126
  const prettierConfig = await prettier.resolveConfig(typesPath);
617
- await mkdirp(path.dirname(typesPath));
618
- await fs.writeFile(typesPath, prettier.format(typesBuf.toString(), _objectSpread(_objectSpread({}, prettierConfig), {}, {
4127
+ await mkdirp(path$1.dirname(typesPath));
4128
+ await fs$1.writeFile(typesPath, prettier.format(typesBuf.toString(), _objectSpread(_objectSpread({}, prettierConfig), {}, {
619
4129
  filepath: typesPath
620
4130
  })));
621
4131
  files.push({
@@ -628,7 +4138,7 @@ async function _extractTypes(options) {
628
4138
  };
629
4139
  }
630
4140
 
631
- const rimraf = promisify(rimrafCallback);
4141
+ const rimraf = promisify(rimraf_1);
632
4142
 
633
4143
  async function _doExtract(ctx, task) {
634
4144
  var _a;
@@ -640,52 +4150,73 @@ async function _doExtract(ctx, task) {
640
4150
  files,
641
4151
  ts
642
4152
  } = ctx;
643
- if (!ts.config || !ts.configPath) return {
644
- type: "dts",
645
- messages: []
646
- };
647
- const sourcePath = task.sourcePath;
648
- const exportPath = task.exportPath === "." ? "./index" : task.exportPath;
649
- const distPath = path.resolve(cwd, dist);
650
- const filePath = path.relative(distPath, path.resolve(cwd, task.targetPath));
651
- const tmpDirPath = path.resolve(distPath, "__dts__");
652
- const tmpDir = {
653
- path: tmpDirPath,
654
- removeCallback: () => rimraf(tmpDirPath)
655
- };
656
- const types = await _buildTypes({
657
- cwd,
658
- outDir: tmpDir.path,
659
- sourcePath,
660
- tsconfig: ts.config
661
- });
4153
+
4154
+ if (!ts.config || !ts.configPath) {
4155
+ return {
4156
+ type: "dts",
4157
+ messages: [],
4158
+ results: []
4159
+ };
4160
+ }
4161
+
4162
+ const distPath = path$1.resolve(cwd, dist);
662
4163
  const {
663
- messages
664
- } = await _extractTypes({
4164
+ outDir = distPath,
4165
+ rootDir = cwd
4166
+ } = ts.config.options;
4167
+ await _buildTypes({
665
4168
  cwd,
666
- exportPath,
667
- files,
668
- filePath,
669
- projectPath: cwd,
670
- rules: (_a = config == null ? void 0 : config.extract) == null ? void 0 : _a.rules,
671
- sourcePath: types.path,
672
- tsconfigPath: path.resolve(cwd, ts.configPath),
673
- distPath
4169
+ outDir,
4170
+ tsconfig: ts.config
674
4171
  });
675
- await tmpDir.removeCallback();
4172
+ const messages = [];
4173
+ const results = [];
4174
+
4175
+ for (const entry of task.entries) {
4176
+ const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath;
4177
+ const sourcePath = path$1.resolve(outDir, path$1.relative(cwd, rootDir), entry.sourcePath.replace(/\.ts$/, ".d.ts"));
4178
+ const filePath = path$1.relative(distPath, path$1.resolve(cwd, entry.targetPath));
4179
+ const result = await _extractTypes({
4180
+ cwd,
4181
+ exportPath,
4182
+ files,
4183
+ filePath,
4184
+ projectPath: cwd,
4185
+ rules: (_a = config == null ? void 0 : config.extract) == null ? void 0 : _a.rules,
4186
+ sourcePath,
4187
+ tsconfigPath: path$1.resolve(cwd, ts.configPath),
4188
+ distPath
4189
+ });
4190
+ results.push({
4191
+ sourcePath,
4192
+ filePath
4193
+ });
4194
+ messages.push(...result.messages);
4195
+
4196
+ if (result.messages.some(msg => msg.logLevel === "error")) {
4197
+ throw new _DtsError("encountered errors when extracting types", result.messages);
4198
+ }
4199
+ }
4200
+
4201
+ const tmpPath = path$1.resolve(distPath, "__tmp__");
4202
+ await rename(outDir, tmpPath);
676
4203
 
677
- if (messages.some(msg => msg.logLevel === "error")) {
678
- throw new _DtsError("encountered errors when extracting types", messages);
4204
+ for (const result of results) {
4205
+ const fromPath = path$1.resolve(tmpPath, path$1.relative(outDir, path$1.resolve(distPath, result.filePath)));
4206
+ const toPath = path$1.resolve(distPath, result.filePath);
4207
+ cpx.copySync(fromPath, path$1.dirname(toPath));
679
4208
  }
680
4209
 
4210
+ await rimraf(tmpPath);
681
4211
  return {
682
4212
  type: "dts",
683
- messages
4213
+ messages,
4214
+ results
684
4215
  };
685
4216
  }
686
4217
 
687
4218
  const _dtsTask = {
688
- name: (_ctx, task) => ["build type definitions", " ".concat(chalk.blue(task.importId), ": ").concat(task.sourcePath, " -> ").concat(task.targetPath)].join("\n"),
4219
+ name: (_ctx, task) => ["build type definitions", ...task.entries.map(entry => " ".concat(chalk.blue(entry.importId), ": ").concat(entry.sourcePath, " -> ").concat(entry.targetPath))].join("\n"),
689
4220
  exec: (ctx, task) => {
690
4221
  return new Observable(observer => {
691
4222
  _doExtract(ctx, task).then(result => {
@@ -712,7 +4243,7 @@ const _dtsTask = {
712
4243
  }
713
4244
  };
714
4245
  const _dtsWatchTask = {
715
- name: (_ctx, task) => ["build type definitions", " ".concat(chalk.blue(task.importId), ": ").concat(task.sourcePath, " -> ").concat(task.targetPath)].join("\n"),
4246
+ name: (_ctx, task) => ["build type definitions", ...task.entries.map(entry => " ".concat(chalk.blue(entry.importId), ": ").concat(entry.sourcePath, " -> ").concat(entry.targetPath))].join("\n"),
716
4247
  exec: (ctx, task) => {
717
4248
  return new Observable(observer => {
718
4249
  _doExtract(ctx, task).then(result => {
@@ -757,29 +4288,49 @@ function _resolveRollupConfig(ctx, buildTask) {
757
4288
  const {
758
4289
  config,
759
4290
  cwd,
4291
+ exports: _exports,
760
4292
  external,
761
4293
  dist: outDir,
4294
+ logger,
762
4295
  pkg,
763
4296
  ts
764
4297
  } = ctx;
765
- const outputExt = format === "commonjs" ? ".cjs" : pkg.type === "module" ? ".mjs" : ".js";
4298
+ const outputExt = format === "commonjs" ? ".cjs" : ".js";
766
4299
  const minify = (_ref2 = config == null ? void 0 : config.minify) !== null && _ref2 !== void 0 ? _ref2 : true;
767
4300
  const pathAliases = Object.fromEntries(Object.entries(((_a = ts.config) == null ? void 0 : _a.options.paths) || {}).map(_ref3 => {
768
4301
  let [key, val] = _ref3;
769
4302
 
770
4303
  var _a2;
771
4304
 
772
- return [key, path.resolve(cwd, ((_a2 = ts.config) == null ? void 0 : _a2.options.baseUrl) || ".", val[0])];
4305
+ return [key, path$1.resolve(cwd, ((_a2 = ts.config) == null ? void 0 : _a2.options.baseUrl) || ".", val[0])];
773
4306
  }));
774
4307
  const entries = buildTask.entries.map(entry => {
775
4308
  return _objectSpread(_objectSpread({}, entry), {}, {
776
- name: path.relative(outDir, entry.output).replace(/\.[^/.]+$/, "")
4309
+ name: path$1.relative(outDir, entry.output).replace(/\.[^/.]+$/, "")
777
4310
  });
778
4311
  }, {});
4312
+
4313
+ const exportIds = _exports && Object.keys(_exports).map(exportPath => path$1.join(pkg.name, exportPath));
4314
+
4315
+ const sourcePaths = _exports && Object.values(_exports).map(e => path$1.resolve(cwd, e.source));
4316
+
779
4317
  return {
780
4318
  inputOptions: {
781
4319
  context: cwd,
782
- external: id => {
4320
+ external: (id, importer) => {
4321
+ if (exportIds == null ? void 0 : exportIds.includes(id)) {
4322
+ return true;
4323
+ }
4324
+
4325
+ if (importer && (id.startsWith(".") || id.startsWith("/"))) {
4326
+ const idPath = path$1.resolve(path$1.dirname(importer), id);
4327
+
4328
+ if (sourcePaths == null ? void 0 : sourcePaths.includes(idPath)) {
4329
+ logger.warn("detected self-referencing import \u2013 treating as external: ".concat(path$1.relative(cwd, idPath)));
4330
+ return true;
4331
+ }
4332
+ }
4333
+
783
4334
  const idParts = id.split("/");
784
4335
  const name = idParts[0].startsWith("@") ? "".concat(idParts[0], "/").concat(idParts[1]) : idParts[0];
785
4336
 
@@ -805,14 +4356,14 @@ function _resolveRollupConfig(ctx, buildTask) {
805
4356
  preventAssignment: true,
806
4357
  values: _objectSpread({}, pkg.name === "@sanity/pkg-utils" ? {} : {
807
4358
  "process.env.PKG_FILE_PATH": arg => {
808
- const sourcePath = "./" + path.relative(cwd, arg);
4359
+ const sourcePath = "./" + path$1.relative(cwd, arg);
809
4360
  const entry = entries.find(e => e.source === sourcePath);
810
4361
 
811
4362
  if (!entry) {
812
4363
  throw new Error("could not find source entry: ".concat(sourcePath));
813
4364
  }
814
4365
 
815
- return JSON.stringify(path.relative(cwd, path.resolve(outDir, entry.name + outputExt)));
4366
+ return JSON.stringify(path$1.relative(cwd, path$1.resolve(outDir, entry.name + outputExt)));
816
4367
  },
817
4368
  "process.env.PKG_FORMAT": JSON.stringify(format),
818
4369
  "process.env.PKG_RUNTIME": JSON.stringify(runtime),
@@ -835,6 +4386,7 @@ function _resolveRollupConfig(ctx, buildTask) {
835
4386
  target,
836
4387
  tsconfig: ctx.ts.configPath || "tsconfig.json"
837
4388
  }), getBabelOutputPlugin({
4389
+ babelrc: false,
838
4390
  plugins: ["@babel/plugin-proposal-object-rest-spread"],
839
4391
  presets: [["@babel/preset-env", {
840
4392
  targets: pkg.browserslist || _DEFAULTS.browserslist
@@ -869,7 +4421,7 @@ function _resolveRollupConfig(ctx, buildTask) {
869
4421
  }
870
4422
 
871
4423
  const _rollupTask = {
872
- name: (ctx, task) => "build javascript files (target ".concat(task.target.join(" + "), ", format ").concat(task.format, ")\n ").concat(task.entries.map(e => "".concat(chalk.blue(path.join(ctx.pkg.name, e.path)), ": ").concat(e.source, " -> ").concat(e.output)).join("\n ")),
4424
+ name: (ctx, task) => "build javascript files (target ".concat(task.target.join(" + "), ", format ").concat(task.format, ")\n ").concat(task.entries.map(e => "".concat(chalk.blue(path$1.join(ctx.pkg.name, e.path)), ": ").concat(e.source, " -> ").concat(e.output)).join("\n ")),
873
4425
  exec: (ctx, task) => {
874
4426
  return new Observable(observer => {
875
4427
  _execPromise(ctx, task).then(result => {
@@ -906,12 +4458,12 @@ async function _execPromise(ctx, task) {
906
4458
  if (chunkOrAsset.type === "asset") {
907
4459
  files.push({
908
4460
  type: "asset",
909
- path: path.resolve(outDir, chunkOrAsset.fileName)
4461
+ path: path$1.resolve(outDir, chunkOrAsset.fileName)
910
4462
  });
911
4463
  } else {
912
4464
  files.push({
913
4465
  type: "chunk",
914
- path: path.resolve(outDir, chunkOrAsset.fileName)
4466
+ path: path$1.resolve(outDir, chunkOrAsset.fileName)
915
4467
  });
916
4468
  }
917
4469
  }
@@ -921,7 +4473,7 @@ async function _execPromise(ctx, task) {
921
4473
  }
922
4474
 
923
4475
  const _rollupWatchTask = {
924
- name: (ctx, task) => "build javascript files (target ".concat(task.target.join(" + "), ", format ").concat(task.format, ")\n ").concat(task.entries.map(e => "".concat(chalk.blue(path.join(ctx.pkg.name, e.path)), ": ").concat(e.source, " -> ").concat(e.output)).join("\n ")),
4476
+ name: (ctx, task) => "build javascript files (target ".concat(task.target.join(" + "), ", format ").concat(task.format, ")\n ").concat(task.entries.map(e => "".concat(chalk.blue(path$1.join(ctx.pkg.name, e.path)), ": ").concat(e.source, " -> ").concat(e.output)).join("\n ")),
925
4477
  exec: (ctx, task) => {
926
4478
  const {
927
4479
  inputOptions,
@@ -948,7 +4500,7 @@ const _rollupWatchTask = {
948
4500
  } = ctx;
949
4501
 
950
4502
  if (event.code === "BUNDLE_END") {
951
- logger.success("build javascript files (target ".concat(task.target.join(" + "), ", format ").concat(task.format, ")\n ").concat(task.entries.map(e => "".concat(chalk.blue(path.join(ctx.pkg.name, e.path)), ": ").concat(e.source, " -> ").concat(e.output)).join("\n ")));
4503
+ logger.success("build javascript files (target ".concat(task.target.join(" + "), ", format ").concat(task.format, ")\n ").concat(task.entries.map(e => "".concat(chalk.blue(path$1.join(ctx.pkg.name, e.path)), ": ").concat(e.source, " -> ").concat(e.output)).join("\n ")));
952
4504
  logger.log("");
953
4505
  return;
954
4506
  }
@@ -1096,8 +4648,8 @@ async function _resolveBuildContext(options) {
1096
4648
 
1097
4649
  const targetVersions = _resolveBrowserslistVersions(pkg.browserslist || _DEFAULTS.browserslist);
1098
4650
 
1099
- const srcPath = path.resolve(cwd, (config == null ? void 0 : config.src) || "src");
1100
- const distPath = path.resolve(cwd, (config == null ? void 0 : config.dist) || "dist");
4651
+ const srcPath = path$1.resolve(cwd, (config == null ? void 0 : config.src) || "src");
4652
+ const distPath = path$1.resolve(cwd, (config == null ? void 0 : config.dist) || "dist");
1101
4653
 
1102
4654
  const nodeTarget = _resolveNodeTarget(targetVersions);
1103
4655
 
@@ -1139,7 +4691,7 @@ async function _resolveBuildContext(options) {
1139
4691
  const ctx = {
1140
4692
  config,
1141
4693
  cwd,
1142
- dist: path.relative(cwd, distPath),
4694
+ dist: path$1.relative(cwd, distPath),
1143
4695
  exports,
1144
4696
  external,
1145
4697
  files: [],
@@ -1177,7 +4729,7 @@ async function _resolveBuildContext(options) {
1177
4729
  }
1178
4730
  },
1179
4731
  pkg,
1180
- src: path.relative(cwd, srcPath),
4732
+ src: path$1.relative(cwd, srcPath),
1181
4733
  runtime: (_ref9 = config == null ? void 0 : config.runtime) !== null && _ref9 !== void 0 ? _ref9 : "*",
1182
4734
  target,
1183
4735
  ts: {
@@ -1254,7 +4806,7 @@ function _getFilesize(file) {
1254
4806
 
1255
4807
  function _fileExists(file) {
1256
4808
  try {
1257
- fs$1.accessSync(file);
4809
+ fs$2.accessSync(file);
1258
4810
  return true;
1259
4811
  } catch (_) {
1260
4812
  return false;
@@ -1262,7 +4814,7 @@ function _fileExists(file) {
1262
4814
  }
1263
4815
 
1264
4816
  function _getFileInfo(cwd, filePath) {
1265
- const p = path.resolve(cwd, filePath);
4817
+ const p = path$1.resolve(cwd, filePath);
1266
4818
 
1267
4819
  const exists = _fileExists(p);
1268
4820
 
@@ -1318,7 +4870,7 @@ function _printPackageTree(ctx) {
1318
4870
  if (entry.require) exp.require = _fileInfo(entry.require);
1319
4871
  if (entry.types) exp.types = _fileInfo(entry.types);
1320
4872
  exp.default = _fileInfo(entry.default);
1321
- return [chalk.green(path.join(pkg.name, exportPath)), exp];
4873
+ return [chalk.green(path$1.join(pkg.name, exportPath)), exp];
1322
4874
  }));
1323
4875
  logger.log(treeify.asTree(tree, true, true));
1324
4876
  }
@@ -1348,19 +4900,19 @@ async function check(options) {
1348
4900
  const missingFiles = [];
1349
4901
 
1350
4902
  for (const [, exp] of Object.entries(ctx.exports || {})) {
1351
- if (exp.source && !_fileExists(path.resolve(cwd, exp.source))) {
4903
+ if (exp.source && !_fileExists(path$1.resolve(cwd, exp.source))) {
1352
4904
  missingFiles.push(exp.source);
1353
4905
  }
1354
4906
 
1355
- if (exp.require && !_fileExists(path.resolve(cwd, exp.require))) {
4907
+ if (exp.require && !_fileExists(path$1.resolve(cwd, exp.require))) {
1356
4908
  missingFiles.push(exp.require);
1357
4909
  }
1358
4910
 
1359
- if (exp.import && !_fileExists(path.resolve(cwd, exp.import))) {
4911
+ if (exp.import && !_fileExists(path$1.resolve(cwd, exp.import))) {
1360
4912
  missingFiles.push(exp.import);
1361
4913
  }
1362
4914
 
1363
- if (exp.types && !_fileExists(path.resolve(cwd, exp.types))) {
4915
+ if (exp.types && !_fileExists(path$1.resolve(cwd, exp.types))) {
1364
4916
  missingFiles.push(exp.types);
1365
4917
  }
1366
4918
  }
@@ -1466,13 +5018,18 @@ function _resolveWatchTasks(ctx) {
1466
5018
  _path
1467
5019
  }, exp);
1468
5020
  });
1469
- const dtsTasks = {};
5021
+ const dtsTask = {
5022
+ type: "watch:dts",
5023
+ entries: []
5024
+ };
1470
5025
  const rollupTasks = {};
1471
5026
 
1472
5027
  function _addRollupTaskEntry(format, runtime, entry) {
1473
5028
  const buildId = "".concat(format, ":").concat(runtime);
1474
5029
 
1475
- if (!rollupTasks[buildId]) {
5030
+ if (rollupTasks[buildId]) {
5031
+ rollupTasks[buildId].entries.push(entry);
5032
+ } else {
1476
5033
  rollupTasks[buildId] = {
1477
5034
  type: "watch:js",
1478
5035
  buildId,
@@ -1481,24 +5038,19 @@ function _resolveWatchTasks(ctx) {
1481
5038
  format,
1482
5039
  target: target[runtime]
1483
5040
  };
1484
- } else {
1485
- rollupTasks[buildId].entries.push(entry);
1486
5041
  }
1487
5042
  }
1488
5043
 
1489
5044
  for (const exp of exports) {
1490
- const importId = path.join(pkg.name, exp._path);
5045
+ const importId = path$1.join(pkg.name, exp._path);
1491
5046
 
1492
5047
  if (exp.types) {
1493
- if (!dtsTasks[importId]) {
1494
- dtsTasks[importId] = {
1495
- type: "watch:dts",
1496
- importId,
1497
- exportPath: exp._path,
1498
- sourcePath: exp.source,
1499
- targetPath: exp.types
1500
- };
1501
- }
5048
+ dtsTask.entries.push({
5049
+ importId,
5050
+ exportPath: exp._path,
5051
+ sourcePath: exp.source,
5052
+ targetPath: exp.types
5053
+ });
1502
5054
  }
1503
5055
  }
1504
5056
 
@@ -1546,7 +5098,10 @@ function _resolveWatchTasks(ctx) {
1546
5098
  });
1547
5099
  }
1548
5100
 
1549
- tasks.push(...Object.values(dtsTasks));
5101
+ if (dtsTask.entries.length) {
5102
+ tasks.push(dtsTask);
5103
+ }
5104
+
1550
5105
  tasks.push(...Object.values(rollupTasks));
1551
5106
 
1552
5107
  for (const exp of exports) {
@@ -1554,7 +5109,7 @@ function _resolveWatchTasks(ctx) {
1554
5109
  const relativeTargetPath = (((_e = exp.browser) == null ? void 0 : _e.import) || exp.import || "").replace(/\.[^/.]+$/, "");
1555
5110
 
1556
5111
  if (relativeTargetPath) {
1557
- fs$1.writeFileSync(path.resolve(cwd, "".concat(exp._path, ".js")), ["// AUTO-GENERATED \u2013 DO NOT EDIT", "", "export {default} from '".concat(relativeTargetPath, "'"), "export * from '".concat(relativeTargetPath, "'"), ""].join("\n"));
5112
+ fs$2.writeFileSync(path$1.resolve(cwd, "".concat(exp._path, ".js")), ["// AUTO-GENERATED \u2013 DO NOT EDIT", "", "export * from '".concat(relativeTargetPath, "'"), ""].join("\n"));
1558
5113
  }
1559
5114
  }
1560
5115
  }
@@ -1591,9 +5146,9 @@ async function _watchConfigFiles(options) {
1591
5146
  const {
1592
5147
  cwd
1593
5148
  } = options;
1594
- const initialFiles = await _globFiles([path.resolve(cwd, "package.json"), path.resolve(cwd, "package.config.cjs"), path.resolve(cwd, "package.config.js"), path.resolve(cwd, "package.config.ts")]);
5149
+ const initialFiles = await _globFiles([path$1.resolve(cwd, "package.json"), path$1.resolve(cwd, "package.config.cjs"), path$1.resolve(cwd, "package.config.js"), path$1.resolve(cwd, "package.config.ts")]);
1595
5150
 
1596
- const fileEvent$ = _watchFiles([path.resolve(cwd, "package.json"), path.resolve(cwd, "package.config.cjs"), path.resolve(cwd, "package.config.js"), path.resolve(cwd, "package.config.ts")]);
5151
+ const fileEvent$ = _watchFiles([path$1.resolve(cwd, "package.json"), path$1.resolve(cwd, "package.config.cjs"), path$1.resolve(cwd, "package.config.js"), path$1.resolve(cwd, "package.config.ts")]);
1597
5152
 
1598
5153
  return fileEvent$.pipe(scan((files, fileEvent) => {
1599
5154
  if (fileEvent.type === "add") {
@@ -1606,7 +5161,7 @@ async function _watchConfigFiles(options) {
1606
5161
 
1607
5162
  if (fileEvent.type === "change") {
1608
5163
  console.log("--------------------------------------------------------------------------------");
1609
- console.log(chalk.blue("info "), path.relative(cwd, fileEvent.file), "changed");
5164
+ console.log(chalk.blue("info "), path$1.relative(cwd, fileEvent.file), "changed");
1610
5165
  console.log("");
1611
5166
  return files.slice(0);
1612
5167
  }
@@ -1624,7 +5179,7 @@ async function watch(options) {
1624
5179
  cwd
1625
5180
  });
1626
5181
  const ctx$ = configFiles$.pipe(switchMap(async configFiles => {
1627
- const _files = configFiles.map(f => path.relative(cwd, f));
5182
+ const _files = configFiles.map(f => path$1.relative(cwd, f));
1628
5183
 
1629
5184
  const packageJsonPath = _files.find(f => f === "package.json");
1630
5185