Best JavaScript code snippet using playwright-internal
compiler-core.esm-bundler.js
Source:compiler-core.esm-bundler.js
2export { generateCodeFrame } from '@vue/shared';3function defaultOnError(error) {4 throw error;5}6function defaultOnWarn(msg) {7 (process.env.NODE_ENV !== 'production') && console.warn(`[Vue warn] ${msg.message}`);8}9function createCompilerError(code, loc, messages, additionalMessage) {10 const msg = (process.env.NODE_ENV !== 'production') || !true11 ? (messages || errorMessages)[code] + (additionalMessage || ``)12 : code;13 const error = new SyntaxError(String(msg));14 error.code = code;15 error.loc = loc;16 return error;17}18const errorMessages = {19 // parse errors20 [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',...
watch.js
Source:watch.js
1/*2 @license3 Rollup.js v2.67.24 Thu, 10 Feb 2022 08:15:45 GMT - commit 60706c33073abe34cac170a92a17a1b166d348e35 https://github.com/rollup/rollup6 Released under the MIT License.7*/8import require$$0$2, { resolve } from 'path';9import process$1 from 'process';10import { defaultOnWarn, ensureArray, warnUnknownOptions, objectifyOptionWithPresets, treeshakePresets, objectifyOption, generatedCodePresets, picomatch as picomatch$2, getAugmentedNamespace, fseventsImporter, createFilter, rollupInternal } from './rollup.js';11import require$$2$1, { platform } from 'os';12import require$$0$3 from 'events';13import require$$0$1 from 'fs';14import require$$2 from 'util';15import require$$1 from 'stream';16import 'perf_hooks';17import 'crypto';18const commandAliases = {19 c: 'config',20 d: 'dir',21 e: 'external',22 f: 'format',23 g: 'globals',24 h: 'help',25 i: 'input',26 m: 'sourcemap',27 n: 'name',28 o: 'file',29 p: 'plugin',30 v: 'version',31 w: 'watch'32};33function mergeOptions(config, rawCommandOptions = { external: [], globals: undefined }, defaultOnWarnHandler = defaultOnWarn) {34 const command = getCommandOptions(rawCommandOptions);35 const inputOptions = mergeInputOptions(config, command, defaultOnWarnHandler);36 const warn = inputOptions.onwarn;37 if (command.output) {38 Object.assign(command, command.output);39 }40 const outputOptionsArray = ensureArray(config.output);41 if (outputOptionsArray.length === 0)42 outputOptionsArray.push({});43 const outputOptions = outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, warn));44 warnUnknownOptions(command, Object.keys(inputOptions).concat(Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapPathTransform'), Object.keys(commandAliases), 'config', 'environment', 'plugin', 'silent', 'failAfterWarnings', 'stdin', 'waitForBundleInput', 'configPlugin'), 'CLI flags', warn, /^_$|output$|config/);45 inputOptions.output = outputOptions;46 return inputOptions;47}48function getCommandOptions(rawCommandOptions) {49 const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'50 ? rawCommandOptions.external.split(',')51 : [];52 return {53 ...rawCommandOptions,54 external,55 globals: typeof rawCommandOptions.globals === 'string'56 ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {57 const [id, variableName] = globalDefinition.split(':');58 globals[id] = variableName;59 if (external.indexOf(id) === -1) {60 external.push(id);61 }62 return globals;63 }, Object.create(null))64 : undefined65 };66}67function mergeInputOptions(config, overrides, defaultOnWarnHandler) {68 const getOption = (name) => { var _a; return (_a = overrides[name]) !== null && _a !== void 0 ? _a : config[name]; };69 const inputOptions = {70 acorn: getOption('acorn'),71 acornInjectPlugins: config.acornInjectPlugins,72 cache: config.cache,73 context: getOption('context'),74 experimentalCacheExpiry: getOption('experimentalCacheExpiry'),75 external: getExternal(config, overrides),76 inlineDynamicImports: getOption('inlineDynamicImports'),77 input: getOption('input') || [],78 makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),79 manualChunks: getOption('manualChunks'),80 maxParallelFileReads: getOption('maxParallelFileReads'),81 moduleContext: getOption('moduleContext'),82 onwarn: getOnWarn(config, defaultOnWarnHandler),83 perf: getOption('perf'),84 plugins: ensureArray(config.plugins),85 preserveEntrySignatures: getOption('preserveEntrySignatures'),86 preserveModules: getOption('preserveModules'),87 preserveSymlinks: getOption('preserveSymlinks'),88 shimMissingExports: getOption('shimMissingExports'),89 strictDeprecations: getOption('strictDeprecations'),90 treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', 'false, true, ')),91 watch: getWatch(config, overrides)92 };93 warnUnknownOptions(config, Object.keys(inputOptions), 'input options', inputOptions.onwarn, /^output$/);94 return inputOptions;95}96const getExternal = (config, overrides) => {97 const configExternal = config.external;98 return typeof configExternal === 'function'99 ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.indexOf(source) !== -1100 : ensureArray(configExternal).concat(overrides.external);101};102const getOnWarn = (config, defaultOnWarnHandler) => config.onwarn103 ? warning => config.onwarn(warning, defaultOnWarnHandler)104 : defaultOnWarnHandler;105const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {106 const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);107 const configOption = normalizeObjectOptionValue(config[name], objectifyValue);108 if (commandOption !== undefined) {109 return commandOption && { ...configOption, ...commandOption };110 }111 return configOption;112};113const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');114const normalizeObjectOptionValue = (optionValue, objectifyValue) => {115 if (!optionValue) {116 return optionValue;117 }118 if (Array.isArray(optionValue)) {119 return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});120 }121 return objectifyValue(optionValue);122};123function mergeOutputOptions(config, overrides, warn) {124 const getOption = (name) => { var _a; return (_a = overrides[name]) !== null && _a !== void 0 ? _a : config[name]; };125 const outputOptions = {126 amd: getObjectOption(config, overrides, 'amd'),127 assetFileNames: getOption('assetFileNames'),128 banner: getOption('banner'),129 chunkFileNames: getOption('chunkFileNames'),130 compact: getOption('compact'),131 dir: getOption('dir'),132 dynamicImportFunction: getOption('dynamicImportFunction'),133 entryFileNames: getOption('entryFileNames'),134 esModule: getOption('esModule'),135 exports: getOption('exports'),136 extend: getOption('extend'),137 externalLiveBindings: getOption('externalLiveBindings'),138 file: getOption('file'),139 footer: getOption('footer'),140 format: getOption('format'),141 freeze: getOption('freeze'),142 generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', '')),143 globals: getOption('globals'),144 hoistTransitiveImports: getOption('hoistTransitiveImports'),145 indent: getOption('indent'),146 inlineDynamicImports: getOption('inlineDynamicImports'),147 interop: getOption('interop'),148 intro: getOption('intro'),149 manualChunks: getOption('manualChunks'),150 minifyInternalExports: getOption('minifyInternalExports'),151 name: getOption('name'),152 namespaceToStringTag: getOption('namespaceToStringTag'),153 noConflict: getOption('noConflict'),154 outro: getOption('outro'),155 paths: getOption('paths'),156 plugins: ensureArray(config.plugins),157 preferConst: getOption('preferConst'),158 preserveModules: getOption('preserveModules'),159 preserveModulesRoot: getOption('preserveModulesRoot'),160 sanitizeFileName: getOption('sanitizeFileName'),161 sourcemap: getOption('sourcemap'),162 sourcemapExcludeSources: getOption('sourcemapExcludeSources'),163 sourcemapFile: getOption('sourcemapFile'),164 sourcemapPathTransform: getOption('sourcemapPathTransform'),165 strict: getOption('strict'),166 systemNullSetters: getOption('systemNullSetters'),167 validate: getOption('validate')168 };169 warnUnknownOptions(config, Object.keys(outputOptions), 'output options', warn);170 return outputOptions;171}172var chokidar$1 = {};173const fs$3 = require$$0$1;174const { Readable } = require$$1;175const sysPath$3 = require$$0$2;176const { promisify: promisify$3 } = require$$2;177const picomatch$1 = picomatch$2;178const readdir$1 = promisify$3(fs$3.readdir);179const stat$3 = promisify$3(fs$3.stat);180const lstat$2 = promisify$3(fs$3.lstat);181const realpath$1 = promisify$3(fs$3.realpath);182/**183 * @typedef {Object} EntryInfo184 * @property {String} path185 * @property {String} fullPath186 * @property {fs.Stats=} stats187 * @property {fs.Dirent=} dirent188 * @property {String} basename189 */190const BANG$2 = '!';191const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';192const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);193const FILE_TYPE = 'files';194const DIR_TYPE = 'directories';195const FILE_DIR_TYPE = 'files_directories';196const EVERYTHING_TYPE = 'all';197const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];198const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);199const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10));200const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5));201const normalizeFilter = filter => {202 if (filter === undefined) return;203 if (typeof filter === 'function') return filter;204 if (typeof filter === 'string') {205 const glob = picomatch$1(filter.trim());206 return entry => glob(entry.basename);207 }208 if (Array.isArray(filter)) {209 const positive = [];210 const negative = [];211 for (const item of filter) {212 const trimmed = item.trim();213 if (trimmed.charAt(0) === BANG$2) {214 negative.push(picomatch$1(trimmed.slice(1)));215 } else {216 positive.push(picomatch$1(trimmed));217 }218 }219 if (negative.length > 0) {220 if (positive.length > 0) {221 return entry =>222 positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));223 }224 return entry => !negative.some(f => f(entry.basename));225 }226 return entry => positive.some(f => f(entry.basename));227 }228};229class ReaddirpStream extends Readable {230 static get defaultOptions() {231 return {232 root: '.',233 /* eslint-disable no-unused-vars */234 fileFilter: (path) => true,235 directoryFilter: (path) => true,236 /* eslint-enable no-unused-vars */237 type: FILE_TYPE,238 lstat: false,239 depth: 2147483648,240 alwaysStat: false241 };242 }243 constructor(options = {}) {244 super({245 objectMode: true,246 autoDestroy: true,247 highWaterMark: options.highWaterMark || 4096248 });249 const opts = { ...ReaddirpStream.defaultOptions, ...options };250 const { root, type } = opts;251 this._fileFilter = normalizeFilter(opts.fileFilter);252 this._directoryFilter = normalizeFilter(opts.directoryFilter);253 const statMethod = opts.lstat ? lstat$2 : stat$3;254 // Use bigint stats if it's windows and stat() supports options (node 10+).255 if (wantBigintFsStats) {256 this._stat = path => statMethod(path, { bigint: true });257 } else {258 this._stat = statMethod;259 }260 this._maxDepth = opts.depth;261 this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);262 this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);263 this._wantsEverything = type === EVERYTHING_TYPE;264 this._root = sysPath$3.resolve(root);265 this._isDirent = ('Dirent' in fs$3) && !opts.alwaysStat;266 this._statsProp = this._isDirent ? 'dirent' : 'stats';267 this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };268 // Launch stream with one parent, the root dir.269 this.parents = [this._exploreDir(root, 1)];270 this.reading = false;271 this.parent = undefined;272 }273 async _read(batch) {274 if (this.reading) return;275 this.reading = true;276 try {277 while (!this.destroyed && batch > 0) {278 const { path, depth, files = [] } = this.parent || {};279 if (files.length > 0) {280 const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));281 for (const entry of await Promise.all(slice)) {282 if (this.destroyed) return;283 const entryType = await this._getEntryType(entry);284 if (entryType === 'directory' && this._directoryFilter(entry)) {285 if (depth <= this._maxDepth) {286 this.parents.push(this._exploreDir(entry.fullPath, depth + 1));287 }288 if (this._wantsDir) {289 this.push(entry);290 batch--;291 }292 } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {293 if (this._wantsFile) {294 this.push(entry);295 batch--;296 }297 }298 }299 } else {300 const parent = this.parents.pop();301 if (!parent) {302 this.push(null);303 break;304 }305 this.parent = await parent;306 if (this.destroyed) return;307 }308 }309 } catch (error) {310 this.destroy(error);311 } finally {312 this.reading = false;313 }314 }315 async _exploreDir(path, depth) {316 let files;317 try {318 files = await readdir$1(path, this._rdOptions);319 } catch (error) {320 this._onError(error);321 }322 return { files, depth, path };323 }324 async _formatEntry(dirent, path) {325 let entry;326 try {327 const basename = this._isDirent ? dirent.name : dirent;328 const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));329 entry = { path: sysPath$3.relative(this._root, fullPath), fullPath, basename };330 entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);331 } catch (err) {332 this._onError(err);333 }334 return entry;335 }336 _onError(err) {337 if (isNormalFlowError(err) && !this.destroyed) {338 this.emit('warn', err);339 } else {340 this.destroy(err);341 }342 }343 async _getEntryType(entry) {344 // entry may be undefined, because a warning or an error were emitted345 // and the statsProp is undefined346 const stats = entry && entry[this._statsProp];347 if (!stats) {348 return;349 }350 if (stats.isFile()) {351 return 'file';352 }353 if (stats.isDirectory()) {354 return 'directory';355 }356 if (stats && stats.isSymbolicLink()) {357 const full = entry.fullPath;358 try {359 const entryRealPath = await realpath$1(full);360 const entryRealPathStats = await lstat$2(entryRealPath);361 if (entryRealPathStats.isFile()) {362 return 'file';363 }364 if (entryRealPathStats.isDirectory()) {365 const len = entryRealPath.length;366 if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {367 const recursiveError = new Error(368 `Circular symlink detected: "${full}" points to "${entryRealPath}"`369 );370 recursiveError.code = RECURSIVE_ERROR_CODE;371 return this._onError(recursiveError);372 }373 return 'directory';374 }375 } catch (error) {376 this._onError(error);377 }378 }379 }380 _includeAsFile(entry) {381 const stats = entry && entry[this._statsProp];382 return stats && this._wantsEverything && !stats.isDirectory();383 }384}385/**386 * @typedef {Object} ReaddirpArguments387 * @property {Function=} fileFilter388 * @property {Function=} directoryFilter389 * @property {String=} type390 * @property {Number=} depth391 * @property {String=} root392 * @property {Boolean=} lstat393 * @property {Boolean=} bigint394 */395/**396 * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.397 * @param {String} root Root directory398 * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth399 */400const readdirp$1 = (root, options = {}) => {401 let type = options.entryType || options.type;402 if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility403 if (type) options.type = type;404 if (!root) {405 throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');406 } else if (typeof root !== 'string') {407 throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');408 } else if (type && !ALL_TYPES.includes(type)) {409 throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);410 }411 options.root = root;412 return new ReaddirpStream(options);413};414const readdirpPromise = (root, options = {}) => {415 return new Promise((resolve, reject) => {416 const files = [];417 readdirp$1(root, options)418 .on('data', entry => files.push(entry))419 .on('end', () => resolve(files))420 .on('error', error => reject(error));421 });422};423readdirp$1.promise = readdirpPromise;424readdirp$1.ReaddirpStream = ReaddirpStream;425readdirp$1.default = readdirp$1;426var readdirp_1 = readdirp$1;427var anymatch$2 = {exports: {}};428/*!429 * normalize-path <https://github.com/jonschlinkert/normalize-path>430 *431 * Copyright (c) 2014-2018, Jon Schlinkert.432 * Released under the MIT License.433 */434var normalizePath$2 = function(path, stripTrailing) {435 if (typeof path !== 'string') {436 throw new TypeError('expected path to be a string');437 }438 if (path === '\\' || path === '/') return '/';439 var len = path.length;440 if (len <= 1) return path;441 // ensure that win32 namespaces has two leading slashes, so that the path is442 // handled properly by the win32 version of path.parse() after being normalized443 // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces444 var prefix = '';445 if (len > 4 && path[3] === '\\') {446 var ch = path[2];447 if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {448 path = path.slice(2);449 prefix = '//';450 }451 }452 var segs = path.split(/[/\\]+/);453 if (stripTrailing !== false && segs[segs.length - 1] === '') {454 segs.pop();455 }456 return prefix + segs.join('/');457};458Object.defineProperty(anymatch$2.exports, "__esModule", { value: true });459const picomatch = picomatch$2;460const normalizePath$1 = normalizePath$2;461/**462 * @typedef {(testString: string) => boolean} AnymatchFn463 * @typedef {string|RegExp|AnymatchFn} AnymatchPattern464 * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher465 */466const BANG$1 = '!';467const DEFAULT_OPTIONS = {returnIndex: false};468const arrify$1 = (item) => Array.isArray(item) ? item : [item];469/**470 * @param {AnymatchPattern} matcher471 * @param {object} options472 * @returns {AnymatchFn}473 */474const createPattern = (matcher, options) => {475 if (typeof matcher === 'function') {476 return matcher;477 }478 if (typeof matcher === 'string') {479 const glob = picomatch(matcher, options);480 return (string) => matcher === string || glob(string);481 }482 if (matcher instanceof RegExp) {483 return (string) => matcher.test(string);484 }485 return (string) => false;486};487/**488 * @param {Array<Function>} patterns489 * @param {Array<Function>} negPatterns490 * @param {String|Array} args491 * @param {Boolean} returnIndex492 * @returns {boolean|number}493 */494const matchPatterns = (patterns, negPatterns, args, returnIndex) => {495 const isList = Array.isArray(args);496 const _path = isList ? args[0] : args;497 if (!isList && typeof _path !== 'string') {498 throw new TypeError('anymatch: second argument must be a string: got ' +499 Object.prototype.toString.call(_path))500 }501 const path = normalizePath$1(_path);502 for (let index = 0; index < negPatterns.length; index++) {503 const nglob = negPatterns[index];504 if (nglob(path)) {505 return returnIndex ? -1 : false;506 }507 }508 const applied = isList && [path].concat(args.slice(1));509 for (let index = 0; index < patterns.length; index++) {510 const pattern = patterns[index];511 if (isList ? pattern(...applied) : pattern(path)) {512 return returnIndex ? index : true;513 }514 }515 return returnIndex ? -1 : false;516};517/**518 * @param {AnymatchMatcher} matchers519 * @param {Array|string} testString520 * @param {object} options521 * @returns {boolean|number|Function}522 */523const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => {524 if (matchers == null) {525 throw new TypeError('anymatch: specify first argument');526 }527 const opts = typeof options === 'boolean' ? {returnIndex: options} : options;528 const returnIndex = opts.returnIndex || false;529 // Early cache for matchers.530 const mtchers = arrify$1(matchers);531 const negatedGlobs = mtchers532 .filter(item => typeof item === 'string' && item.charAt(0) === BANG$1)533 .map(item => item.slice(1))534 .map(item => picomatch(item, opts));535 const patterns = mtchers536 .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG$1))537 .map(matcher => createPattern(matcher, opts));538 if (testString == null) {539 return (testString, ri = false) => {540 const returnIndex = typeof ri === 'boolean' ? ri : false;541 return matchPatterns(patterns, negatedGlobs, testString, returnIndex);542 }543 }544 return matchPatterns(patterns, negatedGlobs, testString, returnIndex);545};546anymatch$1.default = anymatch$1;547anymatch$2.exports = anymatch$1;548/*!549 * is-extglob <https://github.com/jonschlinkert/is-extglob>550 *551 * Copyright (c) 2014-2016, Jon Schlinkert.552 * Licensed under the MIT License.553 */554var isExtglob$1 = function isExtglob(str) {555 if (typeof str !== 'string' || str === '') {556 return false;557 }558 var match;559 while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {560 if (match[2]) return true;561 str = str.slice(match.index + match[0].length);562 }563 return false;564};565/*!566 * is-glob <https://github.com/jonschlinkert/is-glob>567 *568 * Copyright (c) 2014-2017, Jon Schlinkert.569 * Released under the MIT License.570 */571var isExtglob = isExtglob$1;572var chars = { '{': '}', '(': ')', '[': ']'};573var strictCheck = function(str) {574 if (str[0] === '!') {575 return true;576 }577 var index = 0;578 var pipeIndex = -2;579 var closeSquareIndex = -2;580 var closeCurlyIndex = -2;581 var closeParenIndex = -2;582 var backSlashIndex = -2;583 while (index < str.length) {584 if (str[index] === '*') {585 return true;586 }587 if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) {588 return true;589 }590 if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {591 if (closeSquareIndex < index) {592 closeSquareIndex = str.indexOf(']', index);593 }594 if (closeSquareIndex > index) {595 if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {596 return true;597 }598 backSlashIndex = str.indexOf('\\', index);599 if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {600 return true;601 }602 }603 }604 if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {605 closeCurlyIndex = str.indexOf('}', index);606 if (closeCurlyIndex > index) {607 backSlashIndex = str.indexOf('\\', index);608 if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {609 return true;610 }611 }612 }613 if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {614 closeParenIndex = str.indexOf(')', index);615 if (closeParenIndex > index) {616 backSlashIndex = str.indexOf('\\', index);617 if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {618 return true;619 }620 }621 }622 if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {623 if (pipeIndex < index) {624 pipeIndex = str.indexOf('|', index);625 }626 if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {627 closeParenIndex = str.indexOf(')', pipeIndex);628 if (closeParenIndex > pipeIndex) {629 backSlashIndex = str.indexOf('\\', pipeIndex);630 if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {631 return true;632 }633 }634 }635 }636 if (str[index] === '\\') {637 var open = str[index + 1];638 index += 2;639 var close = chars[open];640 if (close) {641 var n = str.indexOf(close, index);642 if (n !== -1) {643 index = n + 1;644 }645 }646 if (str[index] === '!') {647 return true;648 }649 } else {650 index++;651 }652 }653 return false;654};655var relaxedCheck = function(str) {656 if (str[0] === '!') {657 return true;658 }659 var index = 0;660 while (index < str.length) {661 if (/[*?{}()[\]]/.test(str[index])) {662 return true;663 }664 if (str[index] === '\\') {665 var open = str[index + 1];666 index += 2;667 var close = chars[open];668 if (close) {669 var n = str.indexOf(close, index);670 if (n !== -1) {671 index = n + 1;672 }673 }674 if (str[index] === '!') {675 return true;676 }677 } else {678 index++;679 }680 }681 return false;682};683var isGlob$2 = function isGlob(str, options) {684 if (typeof str !== 'string' || str === '') {685 return false;686 }687 if (isExtglob(str)) {688 return true;689 }690 var check = strictCheck;691 // optionally relax check692 if (options && options.strict === false) {693 check = relaxedCheck;694 }695 return check(str);696};697var isGlob$1 = isGlob$2;698var pathPosixDirname = require$$0$2.posix.dirname;699var isWin32 = require$$2$1.platform() === 'win32';700var slash = '/';701var backslash = /\\/g;702var enclosure = /[\{\[].*[\}\]]$/;703var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;704var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;705/**706 * @param {string} str707 * @param {Object} opts708 * @param {boolean} [opts.flipBackslashes=true]709 * @returns {string}710 */711var globParent$1 = function globParent(str, opts) {712 var options = Object.assign({ flipBackslashes: true }, opts);713 // flip windows path separators714 if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {715 str = str.replace(backslash, slash);716 }717 // special case for strings ending in enclosure containing path separator718 if (enclosure.test(str)) {719 str += slash;720 }721 // preserves full path in case of trailing path separator722 str += 'a';723 // remove path parts that are globby724 do {725 str = pathPosixDirname(str);726 } while (isGlob$1(str) || globby.test(str));727 // remove escape chars and return result728 return str.replace(escaped, '$1');729};730var utils$3 = {};731(function (exports) {732exports.isInteger = num => {733 if (typeof num === 'number') {734 return Number.isInteger(num);735 }736 if (typeof num === 'string' && num.trim() !== '') {737 return Number.isInteger(Number(num));738 }739 return false;740};741/**742 * Find a node of the given type743 */744exports.find = (node, type) => node.nodes.find(node => node.type === type);745/**746 * Find a node of the given type747 */748exports.exceedsLimit = (min, max, step = 1, limit) => {749 if (limit === false) return false;750 if (!exports.isInteger(min) || !exports.isInteger(max)) return false;751 return ((Number(max) - Number(min)) / Number(step)) >= limit;752};753/**754 * Escape the given node with '\\' before node.value755 */756exports.escapeNode = (block, n = 0, type) => {757 let node = block.nodes[n];758 if (!node) return;759 if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {760 if (node.escaped !== true) {761 node.value = '\\' + node.value;762 node.escaped = true;763 }764 }765};766/**767 * Returns true if the given brace node should be enclosed in literal braces768 */769exports.encloseBrace = node => {770 if (node.type !== 'brace') return false;771 if ((node.commas >> 0 + node.ranges >> 0) === 0) {772 node.invalid = true;773 return true;774 }775 return false;776};777/**778 * Returns true if a brace node is invalid.779 */780exports.isInvalidBrace = block => {781 if (block.type !== 'brace') return false;782 if (block.invalid === true || block.dollar) return true;783 if ((block.commas >> 0 + block.ranges >> 0) === 0) {784 block.invalid = true;785 return true;786 }787 if (block.open !== true || block.close !== true) {788 block.invalid = true;789 return true;790 }791 return false;792};793/**794 * Returns true if a node is an open or close node795 */796exports.isOpenOrClose = node => {797 if (node.type === 'open' || node.type === 'close') {798 return true;799 }800 return node.open === true || node.close === true;801};802/**803 * Reduce an array of text nodes.804 */805exports.reduce = nodes => nodes.reduce((acc, node) => {806 if (node.type === 'text') acc.push(node.value);807 if (node.type === 'range') node.type = 'text';808 return acc;809}, []);810/**811 * Flatten an array812 */813exports.flatten = (...args) => {814 const result = [];815 const flat = arr => {816 for (let i = 0; i < arr.length; i++) {817 let ele = arr[i];818 Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);819 }820 return result;821 };822 flat(args);823 return result;824};825}(utils$3));826const utils$2 = utils$3;827var stringify$4 = (ast, options = {}) => {828 let stringify = (node, parent = {}) => {829 let invalidBlock = options.escapeInvalid && utils$2.isInvalidBrace(parent);830 let invalidNode = node.invalid === true && options.escapeInvalid === true;831 let output = '';832 if (node.value) {833 if ((invalidBlock || invalidNode) && utils$2.isOpenOrClose(node)) {834 return '\\' + node.value;835 }836 return node.value;837 }838 if (node.value) {839 return node.value;840 }841 if (node.nodes) {842 for (let child of node.nodes) {843 output += stringify(child);844 }845 }846 return output;847 };848 return stringify(ast);849};850/*!851 * is-number <https://github.com/jonschlinkert/is-number>852 *853 * Copyright (c) 2014-present, Jon Schlinkert.854 * Released under the MIT License.855 */856var isNumber$2 = function(num) {857 if (typeof num === 'number') {858 return num - num === 0;859 }860 if (typeof num === 'string' && num.trim() !== '') {861 return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);862 }863 return false;864};865/*!866 * to-regex-range <https://github.com/micromatch/to-regex-range>867 *868 * Copyright (c) 2015-present, Jon Schlinkert.869 * Released under the MIT License.870 */871const isNumber$1 = isNumber$2;872const toRegexRange$1 = (min, max, options) => {873 if (isNumber$1(min) === false) {874 throw new TypeError('toRegexRange: expected the first argument to be a number');875 }876 if (max === void 0 || min === max) {877 return String(min);878 }879 if (isNumber$1(max) === false) {880 throw new TypeError('toRegexRange: expected the second argument to be a number.');881 }882 let opts = { relaxZeros: true, ...options };883 if (typeof opts.strictZeros === 'boolean') {884 opts.relaxZeros = opts.strictZeros === false;885 }886 let relax = String(opts.relaxZeros);887 let shorthand = String(opts.shorthand);888 let capture = String(opts.capture);889 let wrap = String(opts.wrap);890 let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;891 if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {892 return toRegexRange$1.cache[cacheKey].result;893 }894 let a = Math.min(min, max);895 let b = Math.max(min, max);896 if (Math.abs(a - b) === 1) {897 let result = min + '|' + max;898 if (opts.capture) {899 return `(${result})`;900 }901 if (opts.wrap === false) {902 return result;903 }904 return `(?:${result})`;905 }906 let isPadded = hasPadding(min) || hasPadding(max);907 let state = { min, max, a, b };908 let positives = [];909 let negatives = [];910 if (isPadded) {911 state.isPadded = isPadded;912 state.maxLen = String(state.max).length;913 }914 if (a < 0) {915 let newMin = b < 0 ? Math.abs(b) : 1;916 negatives = splitToPatterns(newMin, Math.abs(a), state, opts);917 a = state.a = 0;918 }919 if (b >= 0) {920 positives = splitToPatterns(a, b, state, opts);921 }922 state.negatives = negatives;923 state.positives = positives;924 state.result = collatePatterns(negatives, positives);925 if (opts.capture === true) {926 state.result = `(${state.result})`;927 } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {928 state.result = `(?:${state.result})`;929 }930 toRegexRange$1.cache[cacheKey] = state;931 return state.result;932};933function collatePatterns(neg, pos, options) {934 let onlyNegative = filterPatterns(neg, pos, '-', false) || [];935 let onlyPositive = filterPatterns(pos, neg, '', false) || [];936 let intersected = filterPatterns(neg, pos, '-?', true) || [];937 let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);938 return subpatterns.join('|');939}940function splitToRanges(min, max) {941 let nines = 1;942 let zeros = 1;943 let stop = countNines(min, nines);944 let stops = new Set([max]);945 while (min <= stop && stop <= max) {946 stops.add(stop);947 nines += 1;948 stop = countNines(min, nines);949 }950 stop = countZeros(max + 1, zeros) - 1;951 while (min < stop && stop <= max) {952 stops.add(stop);953 zeros += 1;954 stop = countZeros(max + 1, zeros) - 1;955 }956 stops = [...stops];957 stops.sort(compare);958 return stops;959}960/**961 * Convert a range to a regex pattern962 * @param {Number} `start`963 * @param {Number} `stop`964 * @return {String}965 */966function rangeToPattern(start, stop, options) {967 if (start === stop) {968 return { pattern: start, count: [], digits: 0 };969 }970 let zipped = zip(start, stop);971 let digits = zipped.length;972 let pattern = '';973 let count = 0;974 for (let i = 0; i < digits; i++) {975 let [startDigit, stopDigit] = zipped[i];976 if (startDigit === stopDigit) {977 pattern += startDigit;978 } else if (startDigit !== '0' || stopDigit !== '9') {979 pattern += toCharacterClass(startDigit, stopDigit);980 } else {981 count++;982 }983 }984 if (count) {985 pattern += options.shorthand === true ? '\\d' : '[0-9]';986 }987 return { pattern, count: [count], digits };988}989function splitToPatterns(min, max, tok, options) {990 let ranges = splitToRanges(min, max);991 let tokens = [];992 let start = min;993 let prev;994 for (let i = 0; i < ranges.length; i++) {995 let max = ranges[i];996 let obj = rangeToPattern(String(start), String(max), options);997 let zeros = '';998 if (!tok.isPadded && prev && prev.pattern === obj.pattern) {999 if (prev.count.length > 1) {1000 prev.count.pop();1001 }1002 prev.count.push(obj.count[0]);1003 prev.string = prev.pattern + toQuantifier(prev.count);1004 start = max + 1;1005 continue;1006 }1007 if (tok.isPadded) {1008 zeros = padZeros(max, tok, options);1009 }1010 obj.string = zeros + obj.pattern + toQuantifier(obj.count);1011 tokens.push(obj);1012 start = max + 1;1013 prev = obj;1014 }1015 return tokens;1016}1017function filterPatterns(arr, comparison, prefix, intersection, options) {1018 let result = [];1019 for (let ele of arr) {1020 let { string } = ele;1021 // only push if _both_ are negative...1022 if (!intersection && !contains(comparison, 'string', string)) {1023 result.push(prefix + string);1024 }1025 // or _both_ are positive1026 if (intersection && contains(comparison, 'string', string)) {1027 result.push(prefix + string);1028 }1029 }1030 return result;1031}1032/**1033 * Zip strings1034 */1035function zip(a, b) {1036 let arr = [];1037 for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);1038 return arr;1039}1040function compare(a, b) {1041 return a > b ? 1 : b > a ? -1 : 0;1042}1043function contains(arr, key, val) {1044 return arr.some(ele => ele[key] === val);1045}1046function countNines(min, len) {1047 return Number(String(min).slice(0, -len) + '9'.repeat(len));1048}1049function countZeros(integer, zeros) {1050 return integer - (integer % Math.pow(10, zeros));1051}1052function toQuantifier(digits) {1053 let [start = 0, stop = ''] = digits;1054 if (stop || start > 1) {1055 return `{${start + (stop ? ',' + stop : '')}}`;1056 }1057 return '';1058}1059function toCharacterClass(a, b, options) {1060 return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;1061}1062function hasPadding(str) {1063 return /^-?(0+)\d/.test(str);1064}1065function padZeros(value, tok, options) {1066 if (!tok.isPadded) {1067 return value;1068 }1069 let diff = Math.abs(tok.maxLen - String(value).length);1070 let relax = options.relaxZeros !== false;1071 switch (diff) {1072 case 0:1073 return '';1074 case 1:1075 return relax ? '0?' : '0';1076 case 2:1077 return relax ? '0{0,2}' : '00';1078 default: {1079 return relax ? `0{0,${diff}}` : `0{${diff}}`;1080 }1081 }1082}1083/**1084 * Cache1085 */1086toRegexRange$1.cache = {};1087toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {});1088/**1089 * Expose `toRegexRange`1090 */1091var toRegexRange_1 = toRegexRange$1;1092/*!1093 * fill-range <https://github.com/jonschlinkert/fill-range>1094 *1095 * Copyright (c) 2014-present, Jon Schlinkert.1096 * Licensed under the MIT License.1097 */1098const util = require$$2;1099const toRegexRange = toRegexRange_1;1100const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);1101const transform = toNumber => {1102 return value => toNumber === true ? Number(value) : String(value);1103};1104const isValidValue = value => {1105 return typeof value === 'number' || (typeof value === 'string' && value !== '');1106};1107const isNumber = num => Number.isInteger(+num);1108const zeros = input => {1109 let value = `${input}`;1110 let index = -1;1111 if (value[0] === '-') value = value.slice(1);1112 if (value === '0') return false;1113 while (value[++index] === '0');1114 return index > 0;1115};1116const stringify$3 = (start, end, options) => {1117 if (typeof start === 'string' || typeof end === 'string') {1118 return true;1119 }1120 return options.stringify === true;1121};1122const pad = (input, maxLength, toNumber) => {1123 if (maxLength > 0) {1124 let dash = input[0] === '-' ? '-' : '';1125 if (dash) input = input.slice(1);1126 input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));1127 }1128 if (toNumber === false) {1129 return String(input);1130 }1131 return input;1132};1133const toMaxLen = (input, maxLength) => {1134 let negative = input[0] === '-' ? '-' : '';1135 if (negative) {1136 input = input.slice(1);1137 maxLength--;1138 }1139 while (input.length < maxLength) input = '0' + input;1140 return negative ? ('-' + input) : input;1141};1142const toSequence = (parts, options) => {1143 parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);1144 parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);1145 let prefix = options.capture ? '' : '?:';1146 let positives = '';1147 let negatives = '';1148 let result;1149 if (parts.positives.length) {1150 positives = parts.positives.join('|');1151 }1152 if (parts.negatives.length) {1153 negatives = `-(${prefix}${parts.negatives.join('|')})`;1154 }1155 if (positives && negatives) {1156 result = `${positives}|${negatives}`;1157 } else {1158 result = positives || negatives;1159 }1160 if (options.wrap) {1161 return `(${prefix}${result})`;1162 }1163 return result;1164};1165const toRange = (a, b, isNumbers, options) => {1166 if (isNumbers) {1167 return toRegexRange(a, b, { wrap: false, ...options });1168 }1169 let start = String.fromCharCode(a);1170 if (a === b) return start;1171 let stop = String.fromCharCode(b);1172 return `[${start}-${stop}]`;1173};1174const toRegex = (start, end, options) => {1175 if (Array.isArray(start)) {1176 let wrap = options.wrap === true;1177 let prefix = options.capture ? '' : '?:';1178 return wrap ? `(${prefix}${start.join('|')})` : start.join('|');1179 }1180 return toRegexRange(start, end, options);1181};1182const rangeError = (...args) => {1183 return new RangeError('Invalid range arguments: ' + util.inspect(...args));1184};1185const invalidRange = (start, end, options) => {1186 if (options.strictRanges === true) throw rangeError([start, end]);1187 return [];1188};1189const invalidStep = (step, options) => {1190 if (options.strictRanges === true) {1191 throw new TypeError(`Expected step "${step}" to be a number`);1192 }1193 return [];1194};1195const fillNumbers = (start, end, step = 1, options = {}) => {1196 let a = Number(start);1197 let b = Number(end);1198 if (!Number.isInteger(a) || !Number.isInteger(b)) {1199 if (options.strictRanges === true) throw rangeError([start, end]);1200 return [];1201 }1202 // fix negative zero1203 if (a === 0) a = 0;1204 if (b === 0) b = 0;1205 let descending = a > b;1206 let startString = String(start);1207 let endString = String(end);1208 let stepString = String(step);1209 step = Math.max(Math.abs(step), 1);1210 let padded = zeros(startString) || zeros(endString) || zeros(stepString);1211 let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;1212 let toNumber = padded === false && stringify$3(start, end, options) === false;1213 let format = options.transform || transform(toNumber);1214 if (options.toRegex && step === 1) {1215 return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);1216 }1217 let parts = { negatives: [], positives: [] };1218 let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));1219 let range = [];1220 let index = 0;1221 while (descending ? a >= b : a <= b) {1222 if (options.toRegex === true && step > 1) {1223 push(a);1224 } else {1225 range.push(pad(format(a, index), maxLen, toNumber));1226 }1227 a = descending ? a - step : a + step;1228 index++;1229 }1230 if (options.toRegex === true) {1231 return step > 11232 ? toSequence(parts, options)1233 : toRegex(range, null, { wrap: false, ...options });1234 }1235 return range;1236};1237const fillLetters = (start, end, step = 1, options = {}) => {1238 if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {1239 return invalidRange(start, end, options);1240 }1241 let format = options.transform || (val => String.fromCharCode(val));1242 let a = `${start}`.charCodeAt(0);1243 let b = `${end}`.charCodeAt(0);1244 let descending = a > b;1245 let min = Math.min(a, b);1246 let max = Math.max(a, b);1247 if (options.toRegex && step === 1) {1248 return toRange(min, max, false, options);1249 }1250 let range = [];1251 let index = 0;1252 while (descending ? a >= b : a <= b) {1253 range.push(format(a, index));1254 a = descending ? a - step : a + step;1255 index++;1256 }1257 if (options.toRegex === true) {1258 return toRegex(range, null, { wrap: false, options });1259 }1260 return range;1261};1262const fill$2 = (start, end, step, options = {}) => {1263 if (end == null && isValidValue(start)) {1264 return [start];1265 }1266 if (!isValidValue(start) || !isValidValue(end)) {1267 return invalidRange(start, end, options);1268 }1269 if (typeof step === 'function') {1270 return fill$2(start, end, 1, { transform: step });1271 }1272 if (isObject(step)) {1273 return fill$2(start, end, 0, step);1274 }1275 let opts = { ...options };1276 if (opts.capture === true) opts.wrap = true;1277 step = step || opts.step || 1;1278 if (!isNumber(step)) {1279 if (step != null && !isObject(step)) return invalidStep(step, opts);1280 return fill$2(start, end, 1, step);1281 }1282 if (isNumber(start) && isNumber(end)) {1283 return fillNumbers(start, end, step, opts);1284 }1285 return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);1286};1287var fillRange = fill$2;1288const fill$1 = fillRange;1289const utils$1 = utils$3;1290const compile$1 = (ast, options = {}) => {1291 let walk = (node, parent = {}) => {1292 let invalidBlock = utils$1.isInvalidBrace(parent);1293 let invalidNode = node.invalid === true && options.escapeInvalid === true;1294 let invalid = invalidBlock === true || invalidNode === true;1295 let prefix = options.escapeInvalid === true ? '\\' : '';1296 let output = '';1297 if (node.isOpen === true) {1298 return prefix + node.value;1299 }1300 if (node.isClose === true) {1301 return prefix + node.value;1302 }1303 if (node.type === 'open') {1304 return invalid ? (prefix + node.value) : '(';1305 }1306 if (node.type === 'close') {1307 return invalid ? (prefix + node.value) : ')';1308 }1309 if (node.type === 'comma') {1310 return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');1311 }1312 if (node.value) {1313 return node.value;1314 }1315 if (node.nodes && node.ranges > 0) {1316 let args = utils$1.reduce(node.nodes);1317 let range = fill$1(...args, { ...options, wrap: false, toRegex: true });1318 if (range.length !== 0) {1319 return args.length > 1 && range.length > 1 ? `(${range})` : range;1320 }1321 }1322 if (node.nodes) {1323 for (let child of node.nodes) {1324 output += walk(child, node);1325 }1326 }1327 return output;1328 };1329 return walk(ast);1330};1331var compile_1 = compile$1;1332const fill = fillRange;1333const stringify$2 = stringify$4;1334const utils = utils$3;1335const append = (queue = '', stash = '', enclose = false) => {1336 let result = [];1337 queue = [].concat(queue);1338 stash = [].concat(stash);1339 if (!stash.length) return queue;1340 if (!queue.length) {1341 return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;1342 }1343 for (let item of queue) {1344 if (Array.isArray(item)) {1345 for (let value of item) {1346 result.push(append(value, stash, enclose));1347 }1348 } else {1349 for (let ele of stash) {1350 if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;1351 result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));1352 }1353 }1354 }1355 return utils.flatten(result);1356};1357const expand$1 = (ast, options = {}) => {1358 let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;1359 let walk = (node, parent = {}) => {1360 node.queue = [];1361 let p = parent;1362 let q = parent.queue;1363 while (p.type !== 'brace' && p.type !== 'root' && p.parent) {1364 p = p.parent;1365 q = p.queue;1366 }1367 if (node.invalid || node.dollar) {1368 q.push(append(q.pop(), stringify$2(node, options)));1369 return;1370 }1371 if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {1372 q.push(append(q.pop(), ['{}']));1373 return;1374 }1375 if (node.nodes && node.ranges > 0) {1376 let args = utils.reduce(node.nodes);1377 if (utils.exceedsLimit(...args, options.step, rangeLimit)) {1378 throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');1379 }1380 let range = fill(...args, options);1381 if (range.length === 0) {1382 range = stringify$2(node, options);1383 }1384 q.push(append(q.pop(), range));1385 node.nodes = [];1386 return;1387 }1388 let enclose = utils.encloseBrace(node);1389 let queue = node.queue;1390 let block = node;1391 while (block.type !== 'brace' && block.type !== 'root' && block.parent) {1392 block = block.parent;1393 queue = block.queue;1394 }1395 for (let i = 0; i < node.nodes.length; i++) {1396 let child = node.nodes[i];1397 if (child.type === 'comma' && node.type === 'brace') {1398 if (i === 1) queue.push('');1399 queue.push('');1400 continue;1401 }1402 if (child.type === 'close') {1403 q.push(append(q.pop(), queue, enclose));1404 continue;1405 }1406 if (child.value && child.type !== 'open') {1407 queue.push(append(queue.pop(), child.value));1408 continue;1409 }1410 if (child.nodes) {1411 walk(child, node);1412 }1413 }1414 return queue;1415 };1416 return utils.flatten(walk(ast));1417};1418var expand_1 = expand$1;1419var constants$1 = {1420 MAX_LENGTH: 1024 * 64,1421 // Digits1422 CHAR_0: '0', /* 0 */1423 CHAR_9: '9', /* 9 */1424 // Alphabet chars.1425 CHAR_UPPERCASE_A: 'A', /* A */1426 CHAR_LOWERCASE_A: 'a', /* a */1427 CHAR_UPPERCASE_Z: 'Z', /* Z */1428 CHAR_LOWERCASE_Z: 'z', /* z */1429 CHAR_LEFT_PARENTHESES: '(', /* ( */1430 CHAR_RIGHT_PARENTHESES: ')', /* ) */1431 CHAR_ASTERISK: '*', /* * */1432 // Non-alphabetic chars.1433 CHAR_AMPERSAND: '&', /* & */1434 CHAR_AT: '@', /* @ */1435 CHAR_BACKSLASH: '\\', /* \ */1436 CHAR_BACKTICK: '`', /* ` */1437 CHAR_CARRIAGE_RETURN: '\r', /* \r */1438 CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */1439 CHAR_COLON: ':', /* : */1440 CHAR_COMMA: ',', /* , */1441 CHAR_DOLLAR: '$', /* . */1442 CHAR_DOT: '.', /* . */1443 CHAR_DOUBLE_QUOTE: '"', /* " */1444 CHAR_EQUAL: '=', /* = */1445 CHAR_EXCLAMATION_MARK: '!', /* ! */1446 CHAR_FORM_FEED: '\f', /* \f */1447 CHAR_FORWARD_SLASH: '/', /* / */1448 CHAR_HASH: '#', /* # */1449 CHAR_HYPHEN_MINUS: '-', /* - */1450 CHAR_LEFT_ANGLE_BRACKET: '<', /* < */1451 CHAR_LEFT_CURLY_BRACE: '{', /* { */1452 CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */1453 CHAR_LINE_FEED: '\n', /* \n */1454 CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */1455 CHAR_PERCENT: '%', /* % */1456 CHAR_PLUS: '+', /* + */1457 CHAR_QUESTION_MARK: '?', /* ? */1458 CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */1459 CHAR_RIGHT_CURLY_BRACE: '}', /* } */1460 CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */1461 CHAR_SEMICOLON: ';', /* ; */1462 CHAR_SINGLE_QUOTE: '\'', /* ' */1463 CHAR_SPACE: ' ', /* */1464 CHAR_TAB: '\t', /* \t */1465 CHAR_UNDERSCORE: '_', /* _ */1466 CHAR_VERTICAL_LINE: '|', /* | */1467 CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */1468};1469const stringify$1 = stringify$4;1470/**1471 * Constants1472 */1473const {1474 MAX_LENGTH,1475 CHAR_BACKSLASH, /* \ */1476 CHAR_BACKTICK, /* ` */1477 CHAR_COMMA, /* , */1478 CHAR_DOT, /* . */1479 CHAR_LEFT_PARENTHESES, /* ( */1480 CHAR_RIGHT_PARENTHESES, /* ) */1481 CHAR_LEFT_CURLY_BRACE, /* { */1482 CHAR_RIGHT_CURLY_BRACE, /* } */1483 CHAR_LEFT_SQUARE_BRACKET, /* [ */1484 CHAR_RIGHT_SQUARE_BRACKET, /* ] */1485 CHAR_DOUBLE_QUOTE, /* " */1486 CHAR_SINGLE_QUOTE, /* ' */1487 CHAR_NO_BREAK_SPACE,1488 CHAR_ZERO_WIDTH_NOBREAK_SPACE1489} = constants$1;1490/**1491 * parse1492 */1493const parse$1 = (input, options = {}) => {1494 if (typeof input !== 'string') {1495 throw new TypeError('Expected a string');1496 }1497 let opts = options || {};1498 let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;1499 if (input.length > max) {1500 throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);1501 }1502 let ast = { type: 'root', input, nodes: [] };1503 let stack = [ast];1504 let block = ast;1505 let prev = ast;1506 let brackets = 0;1507 let length = input.length;1508 let index = 0;1509 let depth = 0;1510 let value;1511 /**1512 * Helpers1513 */1514 const advance = () => input[index++];1515 const push = node => {1516 if (node.type === 'text' && prev.type === 'dot') {1517 prev.type = 'text';1518 }1519 if (prev && prev.type === 'text' && node.type === 'text') {1520 prev.value += node.value;1521 return;1522 }1523 block.nodes.push(node);1524 node.parent = block;1525 node.prev = prev;1526 prev = node;1527 return node;1528 };1529 push({ type: 'bos' });1530 while (index < length) {1531 block = stack[stack.length - 1];1532 value = advance();1533 /**1534 * Invalid chars1535 */1536 if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {1537 continue;1538 }1539 /**1540 * Escaped chars1541 */1542 if (value === CHAR_BACKSLASH) {1543 push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });1544 continue;1545 }1546 /**1547 * Right square bracket (literal): ']'1548 */1549 if (value === CHAR_RIGHT_SQUARE_BRACKET) {1550 push({ type: 'text', value: '\\' + value });1551 continue;1552 }1553 /**1554 * Left square bracket: '['1555 */1556 if (value === CHAR_LEFT_SQUARE_BRACKET) {1557 brackets++;1558 let next;1559 while (index < length && (next = advance())) {1560 value += next;1561 if (next === CHAR_LEFT_SQUARE_BRACKET) {1562 brackets++;1563 continue;1564 }1565 if (next === CHAR_BACKSLASH) {1566 value += advance();1567 continue;1568 }1569 if (next === CHAR_RIGHT_SQUARE_BRACKET) {1570 brackets--;1571 if (brackets === 0) {1572 break;1573 }1574 }1575 }1576 push({ type: 'text', value });1577 continue;1578 }1579 /**1580 * Parentheses1581 */1582 if (value === CHAR_LEFT_PARENTHESES) {1583 block = push({ type: 'paren', nodes: [] });1584 stack.push(block);1585 push({ type: 'text', value });1586 continue;1587 }1588 if (value === CHAR_RIGHT_PARENTHESES) {1589 if (block.type !== 'paren') {1590 push({ type: 'text', value });1591 continue;1592 }1593 block = stack.pop();1594 push({ type: 'text', value });1595 block = stack[stack.length - 1];1596 continue;1597 }1598 /**1599 * Quotes: '|"|`1600 */1601 if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {1602 let open = value;1603 let next;1604 if (options.keepQuotes !== true) {1605 value = '';1606 }1607 while (index < length && (next = advance())) {1608 if (next === CHAR_BACKSLASH) {1609 value += next + advance();1610 continue;1611 }1612 if (next === open) {1613 if (options.keepQuotes === true) value += next;1614 break;1615 }1616 value += next;1617 }1618 push({ type: 'text', value });1619 continue;1620 }1621 /**1622 * Left curly brace: '{'1623 */1624 if (value === CHAR_LEFT_CURLY_BRACE) {1625 depth++;1626 let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;1627 let brace = {1628 type: 'brace',1629 open: true,1630 close: false,1631 dollar,1632 depth,1633 commas: 0,1634 ranges: 0,1635 nodes: []1636 };1637 block = push(brace);1638 stack.push(block);1639 push({ type: 'open', value });1640 continue;1641 }1642 /**1643 * Right curly brace: '}'1644 */1645 if (value === CHAR_RIGHT_CURLY_BRACE) {1646 if (block.type !== 'brace') {1647 push({ type: 'text', value });1648 continue;1649 }1650 let type = 'close';1651 block = stack.pop();1652 block.close = true;1653 push({ type, value });1654 depth--;1655 block = stack[stack.length - 1];1656 continue;1657 }1658 /**1659 * Comma: ','1660 */1661 if (value === CHAR_COMMA && depth > 0) {1662 if (block.ranges > 0) {1663 block.ranges = 0;1664 let open = block.nodes.shift();1665 block.nodes = [open, { type: 'text', value: stringify$1(block) }];1666 }1667 push({ type: 'comma', value });1668 block.commas++;1669 continue;1670 }1671 /**1672 * Dot: '.'1673 */1674 if (value === CHAR_DOT && depth > 0 && block.commas === 0) {1675 let siblings = block.nodes;1676 if (depth === 0 || siblings.length === 0) {1677 push({ type: 'text', value });1678 continue;1679 }1680 if (prev.type === 'dot') {1681 block.range = [];1682 prev.value += value;1683 prev.type = 'range';1684 if (block.nodes.length !== 3 && block.nodes.length !== 5) {1685 block.invalid = true;1686 block.ranges = 0;1687 prev.type = 'text';1688 continue;1689 }1690 block.ranges++;1691 block.args = [];1692 continue;1693 }1694 if (prev.type === 'range') {1695 siblings.pop();1696 let before = siblings[siblings.length - 1];1697 before.value += prev.value + value;1698 prev = before;1699 block.ranges--;1700 continue;1701 }1702 push({ type: 'dot', value });1703 continue;1704 }1705 /**1706 * Text1707 */1708 push({ type: 'text', value });1709 }1710 // Mark imbalanced braces and brackets as invalid1711 do {1712 block = stack.pop();1713 if (block.type !== 'root') {1714 block.nodes.forEach(node => {1715 if (!node.nodes) {1716 if (node.type === 'open') node.isOpen = true;1717 if (node.type === 'close') node.isClose = true;1718 if (!node.nodes) node.type = 'text';1719 node.invalid = true;1720 }1721 });1722 // get the location of the block on parent.nodes (block's siblings)1723 let parent = stack[stack.length - 1];1724 let index = parent.nodes.indexOf(block);1725 // replace the (invalid) block with it's nodes1726 parent.nodes.splice(index, 1, ...block.nodes);1727 }1728 } while (stack.length > 0);1729 push({ type: 'eos' });1730 return ast;1731};1732var parse_1 = parse$1;1733const stringify = stringify$4;1734const compile = compile_1;1735const expand = expand_1;1736const parse = parse_1;1737/**1738 * Expand the given pattern or create a regex-compatible string.1739 *1740 * ```js1741 * const braces = require('braces');1742 * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']1743 * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']1744 * ```1745 * @param {String} `str`1746 * @param {Object} `options`1747 * @return {String}1748 * @api public1749 */1750const braces$1 = (input, options = {}) => {1751 let output = [];1752 if (Array.isArray(input)) {1753 for (let pattern of input) {1754 let result = braces$1.create(pattern, options);1755 if (Array.isArray(result)) {1756 output.push(...result);1757 } else {1758 output.push(result);1759 }1760 }1761 } else {1762 output = [].concat(braces$1.create(input, options));1763 }1764 if (options && options.expand === true && options.nodupes === true) {1765 output = [...new Set(output)];1766 }1767 return output;1768};1769/**1770 * Parse the given `str` with the given `options`.1771 *1772 * ```js1773 * // braces.parse(pattern, [, options]);1774 * const ast = braces.parse('a/{b,c}/d');1775 * console.log(ast);1776 * ```1777 * @param {String} pattern Brace pattern to parse1778 * @param {Object} options1779 * @return {Object} Returns an AST1780 * @api public1781 */1782braces$1.parse = (input, options = {}) => parse(input, options);1783/**1784 * Creates a braces string from an AST, or an AST node.1785 *1786 * ```js1787 * const braces = require('braces');1788 * let ast = braces.parse('foo/{a,b}/bar');1789 * console.log(stringify(ast.nodes[2])); //=> '{a,b}'1790 * ```1791 * @param {String} `input` Brace pattern or AST.1792 * @param {Object} `options`1793 * @return {Array} Returns an array of expanded values.1794 * @api public1795 */1796braces$1.stringify = (input, options = {}) => {1797 if (typeof input === 'string') {1798 return stringify(braces$1.parse(input, options), options);1799 }1800 return stringify(input, options);1801};1802/**1803 * Compiles a brace pattern into a regex-compatible, optimized string.1804 * This method is called by the main [braces](#braces) function by default.1805 *1806 * ```js1807 * const braces = require('braces');1808 * console.log(braces.compile('a/{b,c}/d'));1809 * //=> ['a/(b|c)/d']1810 * ```1811 * @param {String} `input` Brace pattern or AST.1812 * @param {Object} `options`1813 * @return {Array} Returns an array of expanded values.1814 * @api public1815 */1816braces$1.compile = (input, options = {}) => {1817 if (typeof input === 'string') {1818 input = braces$1.parse(input, options);1819 }1820 return compile(input, options);1821};1822/**1823 * Expands a brace pattern into an array. This method is called by the1824 * main [braces](#braces) function when `options.expand` is true. Before1825 * using this method it's recommended that you read the [performance notes](#performance))1826 * and advantages of using [.compile](#compile) instead.1827 *1828 * ```js1829 * const braces = require('braces');1830 * console.log(braces.expand('a/{b,c}/d'));1831 * //=> ['a/b/d', 'a/c/d'];1832 * ```1833 * @param {String} `pattern` Brace pattern1834 * @param {Object} `options`1835 * @return {Array} Returns an array of expanded values.1836 * @api public1837 */1838braces$1.expand = (input, options = {}) => {1839 if (typeof input === 'string') {1840 input = braces$1.parse(input, options);1841 }1842 let result = expand(input, options);1843 // filter out empty strings if specified1844 if (options.noempty === true) {1845 result = result.filter(Boolean);1846 }1847 // filter out duplicates if specified1848 if (options.nodupes === true) {1849 result = [...new Set(result)];1850 }1851 return result;1852};1853/**1854 * Processes a brace pattern and returns either an expanded array1855 * (if `options.expand` is true), a highly optimized regex-compatible string.1856 * This method is called by the main [braces](#braces) function.1857 *1858 * ```js1859 * const braces = require('braces');1860 * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))1861 * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'1862 * ```1863 * @param {String} `pattern` Brace pattern1864 * @param {Object} `options`1865 * @return {Array} Returns an array of expanded values.1866 * @api public1867 */1868braces$1.create = (input, options = {}) => {1869 if (input === '' || input.length < 3) {1870 return [input];1871 }1872 return options.expand !== true1873 ? braces$1.compile(input, options)1874 : braces$1.expand(input, options);1875};1876/**1877 * Expose "braces"1878 */1879var braces_1 = braces$1;1880const require$$0 = [1881 "3dm",1882 "3ds",1883 "3g2",1884 "3gp",1885 "7z",1886 "a",1887 "aac",1888 "adp",1889 "ai",1890 "aif",1891 "aiff",1892 "alz",1893 "ape",1894 "apk",1895 "appimage",1896 "ar",1897 "arj",1898 "asf",1899 "au",1900 "avi",1901 "bak",1902 "baml",1903 "bh",1904 "bin",1905 "bk",1906 "bmp",1907 "btif",1908 "bz2",1909 "bzip2",1910 "cab",1911 "caf",1912 "cgm",1913 "class",1914 "cmx",1915 "cpio",1916 "cr2",1917 "cur",1918 "dat",1919 "dcm",1920 "deb",1921 "dex",1922 "djvu",1923 "dll",1924 "dmg",1925 "dng",1926 "doc",1927 "docm",1928 "docx",1929 "dot",1930 "dotm",1931 "dra",1932 "DS_Store",1933 "dsk",1934 "dts",1935 "dtshd",1936 "dvb",1937 "dwg",1938 "dxf",1939 "ecelp4800",1940 "ecelp7470",1941 "ecelp9600",1942 "egg",1943 "eol",1944 "eot",1945 "epub",1946 "exe",1947 "f4v",1948 "fbs",1949 "fh",1950 "fla",1951 "flac",1952 "flatpak",1953 "fli",1954 "flv",1955 "fpx",1956 "fst",1957 "fvt",1958 "g3",1959 "gh",1960 "gif",1961 "graffle",1962 "gz",1963 "gzip",1964 "h261",1965 "h263",1966 "h264",1967 "icns",1968 "ico",1969 "ief",1970 "img",1971 "ipa",1972 "iso",1973 "jar",1974 "jpeg",1975 "jpg",1976 "jpgv",1977 "jpm",1978 "jxr",1979 "key",1980 "ktx",1981 "lha",1982 "lib",1983 "lvp",1984 "lz",1985 "lzh",1986 "lzma",1987 "lzo",1988 "m3u",1989 "m4a",1990 "m4v",1991 "mar",1992 "mdi",1993 "mht",1994 "mid",1995 "midi",1996 "mj2",1997 "mka",1998 "mkv",1999 "mmr",2000 "mng",2001 "mobi",2002 "mov",2003 "movie",2004 "mp3",2005 "mp4",2006 "mp4a",2007 "mpeg",2008 "mpg",2009 "mpga",2010 "mxu",2011 "nef",2012 "npx",2013 "numbers",2014 "nupkg",2015 "o",2016 "odp",2017 "ods",2018 "odt",2019 "oga",2020 "ogg",2021 "ogv",2022 "otf",2023 "ott",2024 "pages",2025 "pbm",2026 "pcx",2027 "pdb",2028 "pdf",2029 "pea",2030 "pgm",2031 "pic",2032 "png",2033 "pnm",2034 "pot",2035 "potm",2036 "potx",2037 "ppa",2038 "ppam",2039 "ppm",2040 "pps",2041 "ppsm",2042 "ppsx",2043 "ppt",2044 "pptm",2045 "pptx",2046 "psd",2047 "pya",2048 "pyc",2049 "pyo",2050 "pyv",2051 "qt",2052 "rar",2053 "ras",2054 "raw",2055 "resources",2056 "rgb",2057 "rip",2058 "rlc",2059 "rmf",2060 "rmvb",2061 "rpm",2062 "rtf",2063 "rz",2064 "s3m",2065 "s7z",2066 "scpt",2067 "sgi",2068 "shar",2069 "snap",2070 "sil",2071 "sketch",2072 "slk",2073 "smv",2074 "snk",2075 "so",2076 "stl",2077 "suo",2078 "sub",2079 "swf",2080 "tar",2081 "tbz",2082 "tbz2",2083 "tga",2084 "tgz",2085 "thmx",2086 "tif",2087 "tiff",2088 "tlz",2089 "ttc",2090 "ttf",2091 "txz",2092 "udf",2093 "uvh",2094 "uvi",2095 "uvm",2096 "uvp",2097 "uvs",2098 "uvu",2099 "viv",2100 "vob",2101 "war",2102 "wav",2103 "wax",2104 "wbmp",2105 "wdp",2106 "weba",2107 "webm",2108 "webp",2109 "whl",2110 "wim",2111 "wm",2112 "wma",2113 "wmv",2114 "wmx",2115 "woff",2116 "woff2",2117 "wrm",2118 "wvx",2119 "xbm",2120 "xif",2121 "xla",2122 "xlam",2123 "xls",2124 "xlsb",2125 "xlsm",2126 "xlsx",2127 "xlt",2128 "xltm",2129 "xltx",2130 "xm",2131 "xmind",2132 "xpi",2133 "xpm",2134 "xwd",2135 "xz",2136 "z",2137 "zip",2138 "zipx"2139];2140var binaryExtensions$1 = require$$0;2141const path = require$$0$2;2142const binaryExtensions = binaryExtensions$1;2143const extensions = new Set(binaryExtensions);2144var isBinaryPath$1 = filePath => extensions.has(path.extname(filePath).slice(1).toLowerCase());2145var constants = {};2146(function (exports) {2147const {sep} = require$$0$2;2148const {platform} = process;2149const os = require$$2$1;2150exports.EV_ALL = 'all';2151exports.EV_READY = 'ready';2152exports.EV_ADD = 'add';2153exports.EV_CHANGE = 'change';2154exports.EV_ADD_DIR = 'addDir';2155exports.EV_UNLINK = 'unlink';2156exports.EV_UNLINK_DIR = 'unlinkDir';2157exports.EV_RAW = 'raw';2158exports.EV_ERROR = 'error';2159exports.STR_DATA = 'data';2160exports.STR_END = 'end';2161exports.STR_CLOSE = 'close';2162exports.FSEVENT_CREATED = 'created';2163exports.FSEVENT_MODIFIED = 'modified';2164exports.FSEVENT_DELETED = 'deleted';2165exports.FSEVENT_MOVED = 'moved';2166exports.FSEVENT_CLONED = 'cloned';2167exports.FSEVENT_UNKNOWN = 'unknown';2168exports.FSEVENT_TYPE_FILE = 'file';2169exports.FSEVENT_TYPE_DIRECTORY = 'directory';2170exports.FSEVENT_TYPE_SYMLINK = 'symlink';2171exports.KEY_LISTENERS = 'listeners';2172exports.KEY_ERR = 'errHandlers';2173exports.KEY_RAW = 'rawEmitters';2174exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];2175exports.DOT_SLASH = `.${sep}`;2176exports.BACK_SLASH_RE = /\\/g;2177exports.DOUBLE_SLASH_RE = /\/\//;2178exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;2179exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;2180exports.REPLACER_RE = /^\.[/\\]/;2181exports.SLASH = '/';2182exports.SLASH_SLASH = '//';2183exports.BRACE_START = '{';2184exports.BANG = '!';2185exports.ONE_DOT = '.';2186exports.TWO_DOTS = '..';2187exports.STAR = '*';2188exports.GLOBSTAR = '**';2189exports.ROOT_GLOBSTAR = '/**/*';2190exports.SLASH_GLOBSTAR = '/**';2191exports.DIR_SUFFIX = 'Dir';2192exports.ANYMATCH_OPTS = {dot: true};2193exports.STRING_TYPE = 'string';2194exports.FUNCTION_TYPE = 'function';2195exports.EMPTY_STR = '';2196exports.EMPTY_FN = () => {};2197exports.IDENTITY_FN = val => val;2198exports.isWindows = platform === 'win32';2199exports.isMacos = platform === 'darwin';2200exports.isLinux = platform === 'linux';2201exports.isIBMi = os.type() === 'OS400';2202}(constants));2203const fs$2 = require$$0$1;2204const sysPath$2 = require$$0$2;2205const { promisify: promisify$2 } = require$$2;2206const isBinaryPath = isBinaryPath$1;2207const {2208 isWindows: isWindows$1,2209 isLinux,2210 EMPTY_FN: EMPTY_FN$2,2211 EMPTY_STR: EMPTY_STR$1,2212 KEY_LISTENERS,2213 KEY_ERR,2214 KEY_RAW,2215 HANDLER_KEYS,2216 EV_CHANGE: EV_CHANGE$2,2217 EV_ADD: EV_ADD$2,2218 EV_ADD_DIR: EV_ADD_DIR$2,2219 EV_ERROR: EV_ERROR$2,2220 STR_DATA: STR_DATA$1,2221 STR_END: STR_END$2,2222 BRACE_START: BRACE_START$1,2223 STAR2224} = constants;2225const THROTTLE_MODE_WATCH = 'watch';2226const open = promisify$2(fs$2.open);2227const stat$2 = promisify$2(fs$2.stat);2228const lstat$1 = promisify$2(fs$2.lstat);2229const close = promisify$2(fs$2.close);2230const fsrealpath = promisify$2(fs$2.realpath);2231const statMethods$1 = { lstat: lstat$1, stat: stat$2 };2232// TODO: emit errors properly. Example: EMFILE on Macos.2233const foreach = (val, fn) => {2234 if (val instanceof Set) {2235 val.forEach(fn);2236 } else {2237 fn(val);2238 }2239};2240const addAndConvert = (main, prop, item) => {2241 let container = main[prop];2242 if (!(container instanceof Set)) {2243 main[prop] = container = new Set([container]);2244 }2245 container.add(item);2246};2247const clearItem = cont => key => {2248 const set = cont[key];2249 if (set instanceof Set) {2250 set.clear();2251 } else {2252 delete cont[key];2253 }2254};2255const delFromSet = (main, prop, item) => {2256 const container = main[prop];2257 if (container instanceof Set) {2258 container.delete(item);2259 } else if (container === item) {2260 delete main[prop];2261 }2262};2263const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;2264/**2265 * @typedef {String} Path2266 */2267// fs_watch helpers2268// object to hold per-process fs_watch instances2269// (may be shared across chokidar FSWatcher instances)2270/**2271 * @typedef {Object} FsWatchContainer2272 * @property {Set} listeners2273 * @property {Set} errHandlers2274 * @property {Set} rawEmitters2275 * @property {fs.FSWatcher=} watcher2276 * @property {Boolean=} watcherUnusable2277 */2278/**2279 * @type {Map<String,FsWatchContainer>}2280 */2281const FsWatchInstances = new Map();2282/**2283 * Instantiates the fs_watch interface2284 * @param {String} path to be watched2285 * @param {Object} options to be passed to fs_watch2286 * @param {Function} listener main event handler2287 * @param {Function} errHandler emits info about errors2288 * @param {Function} emitRaw emits raw event data2289 * @returns {fs.FSWatcher} new fsevents instance2290 */2291function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {2292 const handleEvent = (rawEvent, evPath) => {2293 listener(path);2294 emitRaw(rawEvent, evPath, {watchedPath: path});2295 // emit based on events occurring for files from a directory's watcher in2296 // case the file's watcher misses it (and rely on throttling to de-dupe)2297 if (evPath && path !== evPath) {2298 fsWatchBroadcast(2299 sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath)2300 );2301 }2302 };2303 try {2304 return fs$2.watch(path, options, handleEvent);2305 } catch (error) {2306 errHandler(error);2307 }2308}2309/**2310 * Helper for passing fs_watch event data to a collection of listeners2311 * @param {Path} fullPath absolute path bound to fs_watch instance2312 * @param {String} type listener type2313 * @param {*=} val1 arguments to be passed to listeners2314 * @param {*=} val22315 * @param {*=} val32316 */2317const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {2318 const cont = FsWatchInstances.get(fullPath);2319 if (!cont) return;2320 foreach(cont[type], (listener) => {2321 listener(val1, val2, val3);2322 });2323};2324/**2325 * Instantiates the fs_watch interface or binds listeners2326 * to an existing one covering the same file system entry2327 * @param {String} path2328 * @param {String} fullPath absolute path2329 * @param {Object} options to be passed to fs_watch2330 * @param {Object} handlers container for event listener functions2331 */2332const setFsWatchListener = (path, fullPath, options, handlers) => {2333 const {listener, errHandler, rawEmitter} = handlers;2334 let cont = FsWatchInstances.get(fullPath);2335 /** @type {fs.FSWatcher=} */2336 let watcher;2337 if (!options.persistent) {2338 watcher = createFsWatchInstance(2339 path, options, listener, errHandler, rawEmitter2340 );2341 return watcher.close.bind(watcher);2342 }2343 if (cont) {2344 addAndConvert(cont, KEY_LISTENERS, listener);2345 addAndConvert(cont, KEY_ERR, errHandler);2346 addAndConvert(cont, KEY_RAW, rawEmitter);2347 } else {2348 watcher = createFsWatchInstance(2349 path,2350 options,2351 fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),2352 errHandler, // no need to use broadcast here2353 fsWatchBroadcast.bind(null, fullPath, KEY_RAW)2354 );2355 if (!watcher) return;2356 watcher.on(EV_ERROR$2, async (error) => {2357 const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);2358 cont.watcherUnusable = true; // documented since Node 10.4.12359 // Workaround for https://github.com/joyent/node/issues/43372360 if (isWindows$1 && error.code === 'EPERM') {2361 try {2362 const fd = await open(path, 'r');2363 await close(fd);2364 broadcastErr(error);2365 } catch (err) {}2366 } else {2367 broadcastErr(error);2368 }2369 });2370 cont = {2371 listeners: listener,2372 errHandlers: errHandler,2373 rawEmitters: rawEmitter,2374 watcher2375 };2376 FsWatchInstances.set(fullPath, cont);2377 }2378 // const index = cont.listeners.indexOf(listener);2379 // removes this instance's listeners and closes the underlying fs_watch2380 // instance if there are no more listeners left2381 return () => {2382 delFromSet(cont, KEY_LISTENERS, listener);2383 delFromSet(cont, KEY_ERR, errHandler);2384 delFromSet(cont, KEY_RAW, rawEmitter);2385 if (isEmptySet(cont.listeners)) {2386 // Check to protect against issue gh-730.2387 // if (cont.watcherUnusable) {2388 cont.watcher.close();2389 // }2390 FsWatchInstances.delete(fullPath);2391 HANDLER_KEYS.forEach(clearItem(cont));2392 cont.watcher = undefined;2393 Object.freeze(cont);2394 }2395 };2396};2397// fs_watchFile helpers2398// object to hold per-process fs_watchFile instances2399// (may be shared across chokidar FSWatcher instances)2400const FsWatchFileInstances = new Map();2401/**2402 * Instantiates the fs_watchFile interface or binds listeners2403 * to an existing one covering the same file system entry2404 * @param {String} path to be watched2405 * @param {String} fullPath absolute path2406 * @param {Object} options options to be passed to fs_watchFile2407 * @param {Object} handlers container for event listener functions2408 * @returns {Function} closer2409 */2410const setFsWatchFileListener = (path, fullPath, options, handlers) => {2411 const {listener, rawEmitter} = handlers;2412 let cont = FsWatchFileInstances.get(fullPath);2413 const copts = cont && cont.options;2414 if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {2415 fs$2.unwatchFile(fullPath);2416 cont = undefined;2417 }2418 /* eslint-enable no-unused-vars, prefer-destructuring */2419 if (cont) {2420 addAndConvert(cont, KEY_LISTENERS, listener);2421 addAndConvert(cont, KEY_RAW, rawEmitter);2422 } else {2423 // TODO2424 // listeners.add(listener);2425 // rawEmitters.add(rawEmitter);2426 cont = {2427 listeners: listener,2428 rawEmitters: rawEmitter,2429 options,2430 watcher: fs$2.watchFile(fullPath, options, (curr, prev) => {2431 foreach(cont.rawEmitters, (rawEmitter) => {2432 rawEmitter(EV_CHANGE$2, fullPath, {curr, prev});2433 });2434 const currmtime = curr.mtimeMs;2435 if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {2436 foreach(cont.listeners, (listener) => listener(path, curr));2437 }2438 })2439 };2440 FsWatchFileInstances.set(fullPath, cont);2441 }2442 // const index = cont.listeners.indexOf(listener);2443 // Removes this instance's listeners and closes the underlying fs_watchFile2444 // instance if there are no more listeners left.2445 return () => {2446 delFromSet(cont, KEY_LISTENERS, listener);2447 delFromSet(cont, KEY_RAW, rawEmitter);2448 if (isEmptySet(cont.listeners)) {2449 FsWatchFileInstances.delete(fullPath);2450 fs$2.unwatchFile(fullPath);2451 cont.options = cont.watcher = undefined;2452 Object.freeze(cont);2453 }2454 };2455};2456/**2457 * @mixin2458 */2459class NodeFsHandler$1 {2460/**2461 * @param {import("../index").FSWatcher} fsW2462 */2463constructor(fsW) {2464 this.fsw = fsW;2465 this._boundHandleError = (error) => fsW._handleError(error);2466}2467/**2468 * Watch file for changes with fs_watchFile or fs_watch.2469 * @param {String} path to file or dir2470 * @param {Function} listener on fs change2471 * @returns {Function} closer for the watcher instance2472 */2473_watchWithNodeFs(path, listener) {2474 const opts = this.fsw.options;2475 const directory = sysPath$2.dirname(path);2476 const basename = sysPath$2.basename(path);2477 const parent = this.fsw._getWatchedDir(directory);2478 parent.add(basename);2479 const absolutePath = sysPath$2.resolve(path);2480 const options = {persistent: opts.persistent};2481 if (!listener) listener = EMPTY_FN$2;2482 let closer;2483 if (opts.usePolling) {2484 options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?2485 opts.binaryInterval : opts.interval;2486 closer = setFsWatchFileListener(path, absolutePath, options, {2487 listener,2488 rawEmitter: this.fsw._emitRaw2489 });2490 } else {2491 closer = setFsWatchListener(path, absolutePath, options, {2492 listener,2493 errHandler: this._boundHandleError,2494 rawEmitter: this.fsw._emitRaw2495 });2496 }2497 return closer;2498}2499/**2500 * Watch a file and emit add event if warranted.2501 * @param {Path} file Path2502 * @param {fs.Stats} stats result of fs_stat2503 * @param {Boolean} initialAdd was the file added at watch instantiation?2504 * @returns {Function} closer for the watcher instance2505 */2506_handleFile(file, stats, initialAdd) {2507 if (this.fsw.closed) {2508 return;2509 }2510 const dirname = sysPath$2.dirname(file);2511 const basename = sysPath$2.basename(file);2512 const parent = this.fsw._getWatchedDir(dirname);2513 // stats is always present2514 let prevStats = stats;2515 // if the file is already being watched, do nothing2516 if (parent.has(basename)) return;2517 const listener = async (path, newStats) => {2518 if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;2519 if (!newStats || newStats.mtimeMs === 0) {2520 try {2521 const newStats = await stat$2(file);2522 if (this.fsw.closed) return;2523 // Check that change event was not fired because of changed only accessTime.2524 const at = newStats.atimeMs;2525 const mt = newStats.mtimeMs;2526 if (!at || at <= mt || mt !== prevStats.mtimeMs) {2527 this.fsw._emit(EV_CHANGE$2, file, newStats);2528 }2529 if (isLinux && prevStats.ino !== newStats.ino) {2530 this.fsw._closeFile(path);2531 prevStats = newStats;2532 this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));2533 } else {2534 prevStats = newStats;2535 }2536 } catch (error) {2537 // Fix issues where mtime is null but file is still present2538 this.fsw._remove(dirname, basename);2539 }2540 // add is about to be emitted if file not already tracked in parent2541 } else if (parent.has(basename)) {2542 // Check that change event was not fired because of changed only accessTime.2543 const at = newStats.atimeMs;2544 const mt = newStats.mtimeMs;2545 if (!at || at <= mt || mt !== prevStats.mtimeMs) {2546 this.fsw._emit(EV_CHANGE$2, file, newStats);2547 }2548 prevStats = newStats;2549 }2550 };2551 // kick off the watcher2552 const closer = this._watchWithNodeFs(file, listener);2553 // emit an add event if we're supposed to2554 if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {2555 if (!this.fsw._throttle(EV_ADD$2, file, 0)) return;2556 this.fsw._emit(EV_ADD$2, file, stats);2557 }2558 return closer;2559}2560/**2561 * Handle symlinks encountered while reading a dir.2562 * @param {Object} entry returned by readdirp2563 * @param {String} directory path of dir being read2564 * @param {String} path of this item2565 * @param {String} item basename of this item2566 * @returns {Promise<Boolean>} true if no more processing is needed for this entry.2567 */2568async _handleSymlink(entry, directory, path, item) {2569 if (this.fsw.closed) {2570 return;2571 }2572 const full = entry.fullPath;2573 const dir = this.fsw._getWatchedDir(directory);2574 if (!this.fsw.options.followSymlinks) {2575 // watch symlink directly (don't follow) and detect changes2576 this.fsw._incrReadyCount();2577 let linkPath;2578 try {2579 linkPath = await fsrealpath(path);2580 } catch (e) {2581 this.fsw._emitReady();2582 return true;2583 }2584 if (this.fsw.closed) return;2585 if (dir.has(item)) {2586 if (this.fsw._symlinkPaths.get(full) !== linkPath) {2587 this.fsw._symlinkPaths.set(full, linkPath);2588 this.fsw._emit(EV_CHANGE$2, path, entry.stats);2589 }2590 } else {2591 dir.add(item);2592 this.fsw._symlinkPaths.set(full, linkPath);2593 this.fsw._emit(EV_ADD$2, path, entry.stats);2594 }2595 this.fsw._emitReady();2596 return true;2597 }2598 // don't follow the same symlink more than once2599 if (this.fsw._symlinkPaths.has(full)) {2600 return true;2601 }2602 this.fsw._symlinkPaths.set(full, true);2603}2604_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {2605 // Normalize the directory name on Windows2606 directory = sysPath$2.join(directory, EMPTY_STR$1);2607 if (!wh.hasGlob) {2608 throttler = this.fsw._throttle('readdir', directory, 1000);2609 if (!throttler) return;2610 }2611 const previous = this.fsw._getWatchedDir(wh.path);2612 const current = new Set();2613 let stream = this.fsw._readdirp(directory, {2614 fileFilter: entry => wh.filterPath(entry),2615 directoryFilter: entry => wh.filterDir(entry),2616 depth: 02617 }).on(STR_DATA$1, async (entry) => {2618 if (this.fsw.closed) {2619 stream = undefined;2620 return;2621 }2622 const item = entry.path;2623 let path = sysPath$2.join(directory, item);2624 current.add(item);2625 if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {2626 return;2627 }2628 if (this.fsw.closed) {2629 stream = undefined;2630 return;2631 }2632 // Files that present in current directory snapshot2633 // but absent in previous are added to watch list and2634 // emit `add` event.2635 if (item === target || !target && !previous.has(item)) {2636 this.fsw._incrReadyCount();2637 // ensure relativeness of path is preserved in case of watcher reuse2638 path = sysPath$2.join(dir, sysPath$2.relative(dir, path));2639 this._addToNodeFs(path, initialAdd, wh, depth + 1);2640 }2641 }).on(EV_ERROR$2, this._boundHandleError);2642 return new Promise(resolve =>2643 stream.once(STR_END$2, () => {2644 if (this.fsw.closed) {2645 stream = undefined;2646 return;2647 }2648 const wasThrottled = throttler ? throttler.clear() : false;2649 resolve();2650 // Files that absent in current directory snapshot2651 // but present in previous emit `remove` event2652 // and are removed from @watched[directory].2653 previous.getChildren().filter((item) => {2654 return item !== directory &&2655 !current.has(item) &&2656 // in case of intersecting globs;2657 // a path may have been filtered out of this readdir, but2658 // shouldn't be removed because it matches a different glob2659 (!wh.hasGlob || wh.filterPath({2660 fullPath: sysPath$2.resolve(directory, item)2661 }));2662 }).forEach((item) => {2663 this.fsw._remove(directory, item);2664 });2665 stream = undefined;2666 // one more time for any missed in case changes came in extremely quickly2667 if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);2668 })2669 );2670}2671/**2672 * Read directory to add / remove files from `@watched` list and re-read it on change.2673 * @param {String} dir fs path2674 * @param {fs.Stats} stats2675 * @param {Boolean} initialAdd2676 * @param {Number} depth relative to user-supplied path2677 * @param {String} target child path targeted for watch2678 * @param {Object} wh Common watch helpers for this path2679 * @param {String} realpath2680 * @returns {Promise<Function>} closer for the watcher instance.2681 */2682async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {2683 const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));2684 const tracked = parentDir.has(sysPath$2.basename(dir));2685 if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {2686 if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats);2687 }2688 // ensure dir is tracked (harmless if redundant)2689 parentDir.add(sysPath$2.basename(dir));2690 this.fsw._getWatchedDir(dir);2691 let throttler;2692 let closer;2693 const oDepth = this.fsw.options.depth;2694 if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {2695 if (!target) {2696 await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);2697 if (this.fsw.closed) return;2698 }2699 closer = this._watchWithNodeFs(dir, (dirPath, stats) => {2700 // if current directory is removed, do nothing2701 if (stats && stats.mtimeMs === 0) return;2702 this._handleRead(dirPath, false, wh, target, dir, depth, throttler);2703 });2704 }2705 return closer;2706}2707/**2708 * Handle added file, directory, or glob pattern.2709 * Delegates call to _handleFile / _handleDir after checks.2710 * @param {String} path to file or ir2711 * @param {Boolean} initialAdd was the file added at watch instantiation?2712 * @param {Object} priorWh depth relative to user-supplied path2713 * @param {Number} depth Child path actually targeted for watch2714 * @param {String=} target Child path actually targeted for watch2715 * @returns {Promise}2716 */2717async _addToNodeFs(path, initialAdd, priorWh, depth, target) {2718 const ready = this.fsw._emitReady;2719 if (this.fsw._isIgnored(path) || this.fsw.closed) {2720 ready();2721 return false;2722 }2723 const wh = this.fsw._getWatchHelpers(path, depth);2724 if (!wh.hasGlob && priorWh) {2725 wh.hasGlob = priorWh.hasGlob;2726 wh.globFilter = priorWh.globFilter;2727 wh.filterPath = entry => priorWh.filterPath(entry);2728 wh.filterDir = entry => priorWh.filterDir(entry);2729 }2730 // evaluate what is at the path we're being asked to watch2731 try {2732 const stats = await statMethods$1[wh.statMethod](wh.watchPath);2733 if (this.fsw.closed) return;2734 if (this.fsw._isIgnored(wh.watchPath, stats)) {2735 ready();2736 return false;2737 }2738 const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START$1);2739 let closer;2740 if (stats.isDirectory()) {2741 const absPath = sysPath$2.resolve(path);2742 const targetPath = follow ? await fsrealpath(path) : path;2743 if (this.fsw.closed) return;2744 closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);2745 if (this.fsw.closed) return;2746 // preserve this symlink's target path2747 if (absPath !== targetPath && targetPath !== undefined) {2748 this.fsw._symlinkPaths.set(absPath, targetPath);2749 }2750 } else if (stats.isSymbolicLink()) {2751 const targetPath = follow ? await fsrealpath(path) : path;2752 if (this.fsw.closed) return;2753 const parent = sysPath$2.dirname(wh.watchPath);2754 this.fsw._getWatchedDir(parent).add(wh.watchPath);2755 this.fsw._emit(EV_ADD$2, wh.watchPath, stats);2756 closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);2757 if (this.fsw.closed) return;2758 // preserve this symlink's target path2759 if (targetPath !== undefined) {2760 this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);2761 }2762 } else {2763 closer = this._handleFile(wh.watchPath, stats, initialAdd);2764 }2765 ready();2766 this.fsw._addPathCloser(path, closer);2767 return false;2768 } catch (error) {2769 if (this.fsw._handleError(error)) {2770 ready();2771 return path;2772 }2773 }2774}2775}2776var nodefsHandler = NodeFsHandler$1;2777var fseventsHandler = {exports: {}};2778const require$$3 = /*@__PURE__*/getAugmentedNamespace(fseventsImporter);2779const fs$1 = require$$0$1;2780const sysPath$1 = require$$0$2;2781const { promisify: promisify$1 } = require$$2;2782let fsevents;2783try {2784 fsevents = require$$3.getFsEvents();2785} catch (error) {2786 if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);2787}2788if (fsevents) {2789 // TODO: real check2790 const mtch = process.version.match(/v(\d+)\.(\d+)/);2791 if (mtch && mtch[1] && mtch[2]) {2792 const maj = Number.parseInt(mtch[1], 10);2793 const min = Number.parseInt(mtch[2], 10);2794 if (maj === 8 && min < 16) {2795 fsevents = undefined;2796 }2797 }2798}2799const {2800 EV_ADD: EV_ADD$1,2801 EV_CHANGE: EV_CHANGE$1,2802 EV_ADD_DIR: EV_ADD_DIR$1,2803 EV_UNLINK: EV_UNLINK$1,2804 EV_ERROR: EV_ERROR$1,2805 STR_DATA,2806 STR_END: STR_END$1,2807 FSEVENT_CREATED,2808 FSEVENT_MODIFIED,2809 FSEVENT_DELETED,2810 FSEVENT_MOVED,2811 // FSEVENT_CLONED,2812 FSEVENT_UNKNOWN,2813 FSEVENT_TYPE_FILE,2814 FSEVENT_TYPE_DIRECTORY,2815 FSEVENT_TYPE_SYMLINK,2816 ROOT_GLOBSTAR,2817 DIR_SUFFIX,2818 DOT_SLASH,2819 FUNCTION_TYPE: FUNCTION_TYPE$1,2820 EMPTY_FN: EMPTY_FN$1,2821 IDENTITY_FN2822} = constants;2823const Depth = (value) => isNaN(value) ? {} : {depth: value};2824const stat$1 = promisify$1(fs$1.stat);2825const lstat = promisify$1(fs$1.lstat);2826const realpath = promisify$1(fs$1.realpath);2827const statMethods = { stat: stat$1, lstat };2828/**2829 * @typedef {String} Path2830 */2831/**2832 * @typedef {Object} FsEventsWatchContainer2833 * @property {Set<Function>} listeners2834 * @property {Function} rawEmitter2835 * @property {{stop: Function}} watcher2836 */2837// fsevents instance helper functions2838/**2839 * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)2840 * @type {Map<Path,FsEventsWatchContainer>}2841 */2842const FSEventsWatchers = new Map();2843// Threshold of duplicate path prefixes at which to start2844// consolidating going forward2845const consolidateThreshhold = 10;2846const wrongEventFlags = new Set([2847 69888, 70400, 71424, 72704, 73472, 131328, 131840, 2629122848]);2849/**2850 * Instantiates the fsevents interface2851 * @param {Path} path path to be watched2852 * @param {Function} callback called when fsevents is bound and ready2853 * @returns {{stop: Function}} new fsevents instance2854 */2855const createFSEventsInstance = (path, callback) => {2856 const stop = fsevents.watch(path, callback);2857 return {stop};2858};2859/**2860 * Instantiates the fsevents interface or binds listeners to an existing one covering2861 * the same file tree.2862 * @param {Path} path - to be watched2863 * @param {Path} realPath - real path for symlinks2864 * @param {Function} listener - called when fsevents emits events2865 * @param {Function} rawEmitter - passes data to listeners of the 'raw' event2866 * @returns {Function} closer2867 */2868function setFSEventsListener(path, realPath, listener, rawEmitter) {2869 let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath;2870 const parentPath = sysPath$1.dirname(watchPath);2871 let cont = FSEventsWatchers.get(watchPath);2872 // If we've accumulated a substantial number of paths that2873 // could have been consolidated by watching one directory2874 // above the current one, create a watcher on the parent2875 // path instead, so that we do consolidate going forward.2876 if (couldConsolidate(parentPath)) {2877 watchPath = parentPath;2878 }2879 const resolvedPath = sysPath$1.resolve(path);2880 const hasSymlink = resolvedPath !== realPath;2881 const filteredListener = (fullPath, flags, info) => {2882 if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);2883 if (2884 fullPath === resolvedPath ||2885 !fullPath.indexOf(resolvedPath + sysPath$1.sep)2886 ) listener(fullPath, flags, info);2887 };2888 // check if there is already a watcher on a parent path2889 // modifies `watchPath` to the parent path when it finds a match2890 let watchedParent = false;2891 for (const watchedPath of FSEventsWatchers.keys()) {2892 if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {2893 watchPath = watchedPath;2894 cont = FSEventsWatchers.get(watchPath);2895 watchedParent = true;2896 break;2897 }2898 }2899 if (cont || watchedParent) {2900 cont.listeners.add(filteredListener);2901 } else {2902 cont = {2903 listeners: new Set([filteredListener]),2904 rawEmitter,2905 watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {2906 if (!cont.listeners.size) return;2907 const info = fsevents.getInfo(fullPath, flags);2908 cont.listeners.forEach(list => {2909 list(fullPath, flags, info);2910 });2911 cont.rawEmitter(info.event, fullPath, info);2912 })2913 };2914 FSEventsWatchers.set(watchPath, cont);2915 }2916 // removes this instance's listeners and closes the underlying fsevents2917 // instance if there are no more listeners left2918 return () => {2919 const lst = cont.listeners;2920 lst.delete(filteredListener);2921 if (!lst.size) {2922 FSEventsWatchers.delete(watchPath);2923 if (cont.watcher) return cont.watcher.stop().then(() => {2924 cont.rawEmitter = cont.watcher = undefined;2925 Object.freeze(cont);2926 });2927 }2928 };2929}2930// Decide whether or not we should start a new higher-level2931// parent watcher2932const couldConsolidate = (path) => {2933 let count = 0;2934 for (const watchPath of FSEventsWatchers.keys()) {2935 if (watchPath.indexOf(path) === 0) {2936 count++;2937 if (count >= consolidateThreshhold) {2938 return true;2939 }2940 }2941 }2942 return false;2943};2944// returns boolean indicating whether fsevents can be used2945const canUse = () => fsevents && FSEventsWatchers.size < 128;2946// determines subdirectory traversal levels from root to path2947const calcDepth = (path, root) => {2948 let i = 0;2949 while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;2950 return i;2951};2952// returns boolean indicating whether the fsevents' event info has the same type2953// as the one returned by fs.stat2954const sameTypes = (info, stats) => (2955 info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||2956 info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||2957 info.type === FSEVENT_TYPE_FILE && stats.isFile()2958);2959/**2960 * @mixin2961 */2962class FsEventsHandler$1 {2963/**2964 * @param {import('../index').FSWatcher} fsw2965 */2966constructor(fsw) {2967 this.fsw = fsw;2968}2969checkIgnored(path, stats) {2970 const ipaths = this.fsw._ignoredPaths;2971 if (this.fsw._isIgnored(path, stats)) {2972 ipaths.add(path);2973 if (stats && stats.isDirectory()) {2974 ipaths.add(path + ROOT_GLOBSTAR);2975 }2976 return true;2977 }2978 ipaths.delete(path);2979 ipaths.delete(path + ROOT_GLOBSTAR);2980}2981addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {2982 const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;2983 this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);2984}2985async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {2986 try {2987 const stats = await stat$1(path);2988 if (this.fsw.closed) return;2989 if (sameTypes(info, stats)) {2990 this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);2991 } else {2992 this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);2993 }2994 } catch (error) {2995 if (error.code === 'EACCES') {2996 this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);2997 } else {2998 this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);2999 }3000 }3001}3002handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {3003 if (this.fsw.closed || this.checkIgnored(path)) return;3004 if (event === EV_UNLINK$1) {3005 const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;3006 // suppress unlink events on never before seen files3007 if (isDirectory || watchedDir.has(item)) {3008 this.fsw._remove(parent, item, isDirectory);3009 }3010 } else {3011 if (event === EV_ADD$1) {3012 // track new directories3013 if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);3014 if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {3015 // push symlinks back to the top of the stack to get handled3016 const curDepth = opts.depth === undefined ?3017 undefined : calcDepth(fullPath, realPath) + 1;3018 return this._addToFsEvents(path, false, true, curDepth);3019 }3020 // track new paths3021 // (other than symlinks being followed, which will be tracked soon)3022 this.fsw._getWatchedDir(parent).add(item);3023 }3024 /**3025 * @type {'add'|'addDir'|'unlink'|'unlinkDir'}3026 */3027 const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;3028 this.fsw._emit(eventName, path);3029 if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true);3030 }3031}3032/**3033 * Handle symlinks encountered during directory scan3034 * @param {String} watchPath - file/dir path to be watched with fsevents3035 * @param {String} realPath - real path (in case of symlinks)3036 * @param {Function} transform - path transformer3037 * @param {Function} globFilter - path filter in case a glob pattern was provided3038 * @returns {Function} closer for the watcher instance3039*/3040_watchWithFsEvents(watchPath, realPath, transform, globFilter) {3041 if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;3042 const opts = this.fsw.options;3043 const watchCallback = async (fullPath, flags, info) => {3044 if (this.fsw.closed) return;3045 if (3046 opts.depth !== undefined &&3047 calcDepth(fullPath, realPath) > opts.depth3048 ) return;3049 const path = transform(sysPath$1.join(3050 watchPath, sysPath$1.relative(watchPath, fullPath)3051 ));3052 if (globFilter && !globFilter(path)) return;3053 // ensure directories are tracked3054 const parent = sysPath$1.dirname(path);3055 const item = sysPath$1.basename(path);3056 const watchedDir = this.fsw._getWatchedDir(3057 info.type === FSEVENT_TYPE_DIRECTORY ? path : parent3058 );3059 // correct for wrong events emitted3060 if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {3061 if (typeof opts.ignored === FUNCTION_TYPE$1) {3062 let stats;3063 try {3064 stats = await stat$1(path);3065 } catch (error) {}3066 if (this.fsw.closed) return;3067 if (this.checkIgnored(path, stats)) return;3068 if (sameTypes(info, stats)) {3069 this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);3070 } else {3071 this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);3072 }3073 } else {3074 this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);3075 }3076 } else {3077 switch (info.event) {3078 case FSEVENT_CREATED:3079 case FSEVENT_MODIFIED:3080 return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);3081 case FSEVENT_DELETED:3082 case FSEVENT_MOVED:3083 return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);3084 }3085 }3086 };3087 const closer = setFSEventsListener(3088 watchPath,3089 realPath,3090 watchCallback,3091 this.fsw._emitRaw3092 );3093 this.fsw._emitReady();3094 return closer;3095}3096/**3097 * Handle symlinks encountered during directory scan3098 * @param {String} linkPath path to symlink3099 * @param {String} fullPath absolute path to the symlink3100 * @param {Function} transform pre-existing path transformer3101 * @param {Number} curDepth level of subdirectories traversed to where symlink is3102 * @returns {Promise<void>}3103 */3104async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {3105 // don't follow the same symlink more than once3106 if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;3107 this.fsw._symlinkPaths.set(fullPath, true);3108 this.fsw._incrReadyCount();3109 try {3110 const linkTarget = await realpath(linkPath);3111 if (this.fsw.closed) return;3112 if (this.fsw._isIgnored(linkTarget)) {3113 return this.fsw._emitReady();3114 }3115 this.fsw._incrReadyCount();3116 // add the linkTarget for watching with a wrapper for transform3117 // that causes emitted paths to incorporate the link's path3118 this._addToFsEvents(linkTarget || linkPath, (path) => {3119 let aliasedPath = linkPath;3120 if (linkTarget && linkTarget !== DOT_SLASH) {3121 aliasedPath = path.replace(linkTarget, linkPath);3122 } else if (path !== DOT_SLASH) {3123 aliasedPath = sysPath$1.join(linkPath, path);3124 }3125 return transform(aliasedPath);3126 }, false, curDepth);3127 } catch(error) {3128 if (this.fsw._handleError(error)) {3129 return this.fsw._emitReady();3130 }3131 }3132}3133/**3134 *3135 * @param {Path} newPath3136 * @param {fs.Stats} stats3137 */3138emitAdd(newPath, stats, processPath, opts, forceAdd) {3139 const pp = processPath(newPath);3140 const isDir = stats.isDirectory();3141 const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));3142 const base = sysPath$1.basename(pp);3143 // ensure empty dirs get tracked3144 if (isDir) this.fsw._getWatchedDir(pp);3145 if (dirObj.has(base)) return;3146 dirObj.add(base);3147 if (!opts.ignoreInitial || forceAdd === true) {3148 this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);3149 }3150}3151initWatch(realPath, path, wh, processPath) {3152 if (this.fsw.closed) return;3153 const closer = this._watchWithFsEvents(3154 wh.watchPath,3155 sysPath$1.resolve(realPath || wh.watchPath),3156 processPath,3157 wh.globFilter3158 );3159 this.fsw._addPathCloser(path, closer);3160}3161/**3162 * Handle added path with fsevents3163 * @param {String} path file/dir path or glob pattern3164 * @param {Function|Boolean=} transform converts working path to what the user expects3165 * @param {Boolean=} forceAdd ensure add is emitted3166 * @param {Number=} priorDepth Level of subdirectories already traversed.3167 * @returns {Promise<void>}3168 */3169async _addToFsEvents(path, transform, forceAdd, priorDepth) {3170 if (this.fsw.closed) {3171 return;3172 }3173 const opts = this.fsw.options;3174 const processPath = typeof transform === FUNCTION_TYPE$1 ? transform : IDENTITY_FN;3175 const wh = this.fsw._getWatchHelpers(path);3176 // evaluate what is at the path we're being asked to watch3177 try {3178 const stats = await statMethods[wh.statMethod](wh.watchPath);3179 if (this.fsw.closed) return;3180 if (this.fsw._isIgnored(wh.watchPath, stats)) {3181 throw null;3182 }3183 if (stats.isDirectory()) {3184 // emit addDir unless this is a glob parent3185 if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);3186 // don't recurse further if it would exceed depth setting3187 if (priorDepth && priorDepth > opts.depth) return;3188 // scan the contents of the dir3189 this.fsw._readdirp(wh.watchPath, {3190 fileFilter: entry => wh.filterPath(entry),3191 directoryFilter: entry => wh.filterDir(entry),3192 ...Depth(opts.depth - (priorDepth || 0))3193 }).on(STR_DATA, (entry) => {3194 // need to check filterPath on dirs b/c filterDir is less restrictive3195 if (this.fsw.closed) {3196 return;3197 }3198 if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;3199 const joinedPath = sysPath$1.join(wh.watchPath, entry.path);3200 const {fullPath} = entry;3201 if (wh.followSymlinks && entry.stats.isSymbolicLink()) {3202 // preserve the current depth here since it can't be derived from3203 // real paths past the symlink3204 const curDepth = opts.depth === undefined ?3205 undefined : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;3206 this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);3207 } else {3208 this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);3209 }3210 }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {3211 this.fsw._emitReady();3212 });3213 } else {3214 this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);3215 this.fsw._emitReady();3216 }3217 } catch (error) {3218 if (!error || this.fsw._handleError(error)) {3219 // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-3220 this.fsw._emitReady();3221 this.fsw._emitReady();3222 }3223 }3224 if (opts.persistent && forceAdd !== true) {3225 if (typeof transform === FUNCTION_TYPE$1) {3226 // realpath has already been resolved3227 this.initWatch(undefined, path, wh, processPath);3228 } else {3229 let realPath;3230 try {3231 realPath = await realpath(wh.watchPath);3232 } catch (e) {}3233 this.initWatch(realPath, path, wh, processPath);3234 }3235 }3236}3237}3238fseventsHandler.exports = FsEventsHandler$1;3239fseventsHandler.exports.canUse = canUse;3240const { EventEmitter } = require$$0$3;3241const fs = require$$0$1;3242const sysPath = require$$0$2;3243const { promisify } = require$$2;3244const readdirp = readdirp_1;3245const anymatch = anymatch$2.exports.default;3246const globParent = globParent$1;3247const isGlob = isGlob$2;3248const braces = braces_1;3249const normalizePath = normalizePath$2;3250const NodeFsHandler = nodefsHandler;3251const FsEventsHandler = fseventsHandler.exports;3252const {3253 EV_ALL,3254 EV_READY,3255 EV_ADD,3256 EV_CHANGE,3257 EV_UNLINK,3258 EV_ADD_DIR,3259 EV_UNLINK_DIR,3260 EV_RAW,3261 EV_ERROR,3262 STR_CLOSE,3263 STR_END,3264 BACK_SLASH_RE,3265 DOUBLE_SLASH_RE,3266 SLASH_OR_BACK_SLASH_RE,3267 DOT_RE,3268 REPLACER_RE,3269 SLASH,3270 SLASH_SLASH,3271 BRACE_START,3272 BANG,3273 ONE_DOT,3274 TWO_DOTS,3275 GLOBSTAR,3276 SLASH_GLOBSTAR,3277 ANYMATCH_OPTS,3278 STRING_TYPE,3279 FUNCTION_TYPE,3280 EMPTY_STR,3281 EMPTY_FN,3282 isWindows,3283 isMacos,3284 isIBMi3285} = constants;3286const stat = promisify(fs.stat);3287const readdir = promisify(fs.readdir);3288/**3289 * @typedef {String} Path3290 * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName3291 * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType3292 */3293/**3294 *3295 * @typedef {Object} WatchHelpers3296 * @property {Boolean} followSymlinks3297 * @property {'stat'|'lstat'} statMethod3298 * @property {Path} path3299 * @property {Path} watchPath3300 * @property {Function} entryPath3301 * @property {Boolean} hasGlob3302 * @property {Object} globFilter3303 * @property {Function} filterPath3304 * @property {Function} filterDir3305 */3306const arrify = (value = []) => Array.isArray(value) ? value : [value];3307const flatten = (list, result = []) => {3308 list.forEach(item => {3309 if (Array.isArray(item)) {3310 flatten(item, result);3311 } else {3312 result.push(item);3313 }3314 });3315 return result;3316};3317const unifyPaths = (paths_) => {3318 /**3319 * @type {Array<String>}3320 */3321 const paths = flatten(arrify(paths_));3322 if (!paths.every(p => typeof p === STRING_TYPE)) {3323 throw new TypeError(`Non-string provided as watch path: ${paths}`);3324 }3325 return paths.map(normalizePathToUnix);3326};3327// If SLASH_SLASH occurs at the beginning of path, it is not replaced3328// because "//StoragePC/DrivePool/Movies" is a valid network path3329const toUnix = (string) => {3330 let str = string.replace(BACK_SLASH_RE, SLASH);3331 let prepend = false;3332 if (str.startsWith(SLASH_SLASH)) {3333 prepend = true;3334 }3335 while (str.match(DOUBLE_SLASH_RE)) {3336 str = str.replace(DOUBLE_SLASH_RE, SLASH);3337 }3338 if (prepend) {3339 str = SLASH + str;3340 }3341 return str;3342};3343// Our version of upath.normalize3344// TODO: this is not equal to path-normalize module - investigate why3345const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));3346const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {3347 if (typeof path !== STRING_TYPE) return path;3348 return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));3349};3350const getAbsolutePath = (path, cwd) => {3351 if (sysPath.isAbsolute(path)) {3352 return path;3353 }3354 if (path.startsWith(BANG)) {3355 return BANG + sysPath.join(cwd, path.slice(1));3356 }3357 return sysPath.join(cwd, path);3358};3359const undef = (opts, key) => opts[key] === undefined;3360/**3361 * Directory entry.3362 * @property {Path} path3363 * @property {Set<Path>} items3364 */3365class DirEntry {3366 /**3367 * @param {Path} dir3368 * @param {Function} removeWatcher3369 */3370 constructor(dir, removeWatcher) {3371 this.path = dir;3372 this._removeWatcher = removeWatcher;3373 /** @type {Set<Path>} */3374 this.items = new Set();3375 }3376 add(item) {3377 const {items} = this;3378 if (!items) return;3379 if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);3380 }3381 async remove(item) {3382 const {items} = this;3383 if (!items) return;3384 items.delete(item);3385 if (items.size > 0) return;3386 const dir = this.path;3387 try {3388 await readdir(dir);3389 } catch (err) {3390 if (this._removeWatcher) {3391 this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));3392 }3393 }3394 }3395 has(item) {3396 const {items} = this;3397 if (!items) return;3398 return items.has(item);3399 }3400 /**3401 * @returns {Array<String>}3402 */3403 getChildren() {3404 const {items} = this;3405 if (!items) return;3406 return [...items.values()];3407 }3408 dispose() {3409 this.items.clear();3410 delete this.path;3411 delete this._removeWatcher;3412 delete this.items;3413 Object.freeze(this);3414 }3415}3416const STAT_METHOD_F = 'stat';3417const STAT_METHOD_L = 'lstat';3418class WatchHelper {3419 constructor(path, watchPath, follow, fsw) {3420 this.fsw = fsw;3421 this.path = path = path.replace(REPLACER_RE, EMPTY_STR);3422 this.watchPath = watchPath;3423 this.fullWatchPath = sysPath.resolve(watchPath);3424 this.hasGlob = watchPath !== path;3425 /** @type {object|boolean} */3426 if (path === EMPTY_STR) this.hasGlob = false;3427 this.globSymlink = this.hasGlob && follow ? undefined : false;3428 this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;3429 this.dirParts = this.getDirParts(path);3430 this.dirParts.forEach((parts) => {3431 if (parts.length > 1) parts.pop();3432 });3433 this.followSymlinks = follow;3434 this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;3435 }3436 checkGlobSymlink(entry) {3437 // only need to resolve once3438 // first entry should always have entry.parentDir === EMPTY_STR3439 if (this.globSymlink === undefined) {3440 this.globSymlink = entry.fullParentDir === this.fullWatchPath ?3441 false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};3442 }3443 if (this.globSymlink) {3444 return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);3445 }3446 return entry.fullPath;3447 }3448 entryPath(entry) {3449 return sysPath.join(this.watchPath,3450 sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))3451 );3452 }3453 filterPath(entry) {3454 const {stats} = entry;3455 if (stats && stats.isSymbolicLink()) return this.filterDir(entry);3456 const resolvedPath = this.entryPath(entry);3457 const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?3458 this.globFilter(resolvedPath) : true;3459 return matchesGlob &&3460 this.fsw._isntIgnored(resolvedPath, stats) &&3461 this.fsw._hasReadPermissions(stats);3462 }3463 getDirParts(path) {3464 if (!this.hasGlob) return [];3465 const parts = [];3466 const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];3467 expandedPath.forEach((path) => {3468 parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));3469 });3470 return parts;3471 }3472 filterDir(entry) {3473 if (this.hasGlob) {3474 const entryParts = this.getDirParts(this.checkGlobSymlink(entry));3475 let globstar = false;3476 this.unmatchedGlob = !this.dirParts.some((parts) => {3477 return parts.every((part, i) => {3478 if (part === GLOBSTAR) globstar = true;3479 return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);3480 });3481 });3482 }3483 return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);3484 }3485}3486/**3487 * Watches files & directories for changes. Emitted events:3488 * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`3489 *3490 * new FSWatcher()3491 * .add(directories)3492 * .on('add', path => log('File', path, 'was added'))3493 */3494class FSWatcher extends EventEmitter {3495// Not indenting methods for history sake; for now.3496constructor(_opts) {3497 super();3498 const opts = {};3499 if (_opts) Object.assign(opts, _opts); // for frozen objects3500 /** @type {Map<String, DirEntry>} */3501 this._watched = new Map();3502 /** @type {Map<String, Array>} */3503 this._closers = new Map();3504 /** @type {Set<String>} */3505 this._ignoredPaths = new Set();3506 /** @type {Map<ThrottleType, Map>} */3507 this._throttled = new Map();3508 /** @type {Map<Path, String|Boolean>} */3509 this._symlinkPaths = new Map();3510 this._streams = new Set();3511 this.closed = false;3512 // Set up default options.3513 if (undef(opts, 'persistent')) opts.persistent = true;3514 if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;3515 if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;3516 if (undef(opts, 'interval')) opts.interval = 100;3517 if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;3518 if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;3519 opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;3520 // Enable fsevents on OS X when polling isn't explicitly enabled.3521 if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;3522 // If we can't use fsevents, ensure the options reflect it's disabled.3523 const canUseFsEvents = FsEventsHandler.canUse();3524 if (!canUseFsEvents) opts.useFsEvents = false;3525 // Use polling on Mac if not using fsevents.3526 // Other platforms use non-polling fs_watch.3527 if (undef(opts, 'usePolling') && !opts.useFsEvents) {3528 opts.usePolling = isMacos;3529 }3530 // Always default to polling on IBM i because fs.watch() is not available on IBM i.3531 if(isIBMi) {3532 opts.usePolling = true;3533 }3534 // Global override (useful for end-developers that need to force polling for all3535 // instances of chokidar, regardless of usage/dependency depth)3536 const envPoll = process.env.CHOKIDAR_USEPOLLING;3537 if (envPoll !== undefined) {3538 const envLower = envPoll.toLowerCase();3539 if (envLower === 'false' || envLower === '0') {3540 opts.usePolling = false;3541 } else if (envLower === 'true' || envLower === '1') {3542 opts.usePolling = true;3543 } else {3544 opts.usePolling = !!envLower;3545 }3546 }3547 const envInterval = process.env.CHOKIDAR_INTERVAL;3548 if (envInterval) {3549 opts.interval = Number.parseInt(envInterval, 10);3550 }3551 // Editor atomic write normalization enabled by default with fs.watch3552 if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;3553 if (opts.atomic) this._pendingUnlinks = new Map();3554 if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;3555 if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;3556 if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};3557 const awf = opts.awaitWriteFinish;3558 if (awf) {3559 if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;3560 if (!awf.pollInterval) awf.pollInterval = 100;3561 this._pendingWrites = new Map();3562 }3563 if (opts.ignored) opts.ignored = arrify(opts.ignored);3564 let readyCalls = 0;3565 this._emitReady = () => {3566 readyCalls++;3567 if (readyCalls >= this._readyCount) {3568 this._emitReady = EMPTY_FN;3569 this._readyEmitted = true;3570 // use process.nextTick to allow time for listener to be bound3571 process.nextTick(() => this.emit(EV_READY));3572 }3573 };3574 this._emitRaw = (...args) => this.emit(EV_RAW, ...args);3575 this._readyEmitted = false;3576 this.options = opts;3577 // Initialize with proper watcher.3578 if (opts.useFsEvents) {3579 this._fsEventsHandler = new FsEventsHandler(this);3580 } else {3581 this._nodeFsHandler = new NodeFsHandler(this);3582 }3583 // Youâre frozen when your heartâs not open.3584 Object.freeze(opts);3585}3586// Public methods3587/**3588 * Adds paths to be watched on an existing FSWatcher instance3589 * @param {Path|Array<Path>} paths_3590 * @param {String=} _origAdd private; for handling non-existent paths to be watched3591 * @param {Boolean=} _internal private; indicates a non-user add3592 * @returns {FSWatcher} for chaining3593 */3594add(paths_, _origAdd, _internal) {3595 const {cwd, disableGlobbing} = this.options;3596 this.closed = false;3597 let paths = unifyPaths(paths_);3598 if (cwd) {3599 paths = paths.map((path) => {3600 const absPath = getAbsolutePath(path, cwd);3601 // Check `path` instead of `absPath` because the cwd portion can't be a glob3602 if (disableGlobbing || !isGlob(path)) {3603 return absPath;3604 }3605 return normalizePath(absPath);3606 });3607 }3608 // set aside negated glob strings3609 paths = paths.filter((path) => {3610 if (path.startsWith(BANG)) {3611 this._ignoredPaths.add(path.slice(1));3612 return false;3613 }3614 // if a path is being added that was previously ignored, stop ignoring it3615 this._ignoredPaths.delete(path);3616 this._ignoredPaths.delete(path + SLASH_GLOBSTAR);3617 // reset the cached userIgnored anymatch fn3618 // to make ignoredPaths changes effective3619 this._userIgnored = undefined;3620 return true;3621 });3622 if (this.options.useFsEvents && this._fsEventsHandler) {3623 if (!this._readyCount) this._readyCount = paths.length;3624 if (this.options.persistent) this._readyCount *= 2;3625 paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));3626 } else {3627 if (!this._readyCount) this._readyCount = 0;3628 this._readyCount += paths.length;3629 Promise.all(3630 paths.map(async path => {3631 const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);3632 if (res) this._emitReady();3633 return res;3634 })3635 ).then(results => {3636 if (this.closed) return;3637 results.filter(item => item).forEach(item => {3638 this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));3639 });3640 });3641 }3642 return this;3643}3644/**3645 * Close watchers or start ignoring events from specified paths.3646 * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs3647 * @returns {FSWatcher} for chaining3648*/3649unwatch(paths_) {3650 if (this.closed) return this;3651 const paths = unifyPaths(paths_);3652 const {cwd} = this.options;3653 paths.forEach((path) => {3654 // convert to absolute path unless relative path already matches3655 if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {3656 if (cwd) path = sysPath.join(cwd, path);3657 path = sysPath.resolve(path);3658 }3659 this._closePath(path);3660 this._ignoredPaths.add(path);3661 if (this._watched.has(path)) {3662 this._ignoredPaths.add(path + SLASH_GLOBSTAR);3663 }3664 // reset the cached userIgnored anymatch fn3665 // to make ignoredPaths changes effective3666 this._userIgnored = undefined;3667 });3668 return this;3669}3670/**3671 * Close watchers and remove all listeners from watched paths.3672 * @returns {Promise<void>}.3673*/3674close() {3675 if (this.closed) return this._closePromise;3676 this.closed = true;3677 // Memory management.3678 this.removeAllListeners();3679 const closers = [];3680 this._closers.forEach(closerList => closerList.forEach(closer => {3681 const promise = closer();3682 if (promise instanceof Promise) closers.push(promise);3683 }));3684 this._streams.forEach(stream => stream.destroy());3685 this._userIgnored = undefined;3686 this._readyCount = 0;3687 this._readyEmitted = false;3688 this._watched.forEach(dirent => dirent.dispose());3689 ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {3690 this[`_${key}`].clear();3691 });3692 this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();3693 return this._closePromise;3694}3695/**3696 * Expose list of watched paths3697 * @returns {Object} for chaining3698*/3699getWatched() {3700 const watchList = {};3701 this._watched.forEach((entry, dir) => {3702 const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;3703 watchList[key || ONE_DOT] = entry.getChildren().sort();3704 });3705 return watchList;3706}3707emitWithAll(event, args) {3708 this.emit(...args);3709 if (event !== EV_ERROR) this.emit(EV_ALL, ...args);3710}3711// Common helpers3712// --------------3713/**3714 * Normalize and emit events.3715 * Calling _emit DOES NOT MEAN emit() would be called!3716 * @param {EventName} event Type of event3717 * @param {Path} path File or directory path3718 * @param {*=} val1 arguments to be passed with event3719 * @param {*=} val23720 * @param {*=} val33721 * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag3722 */3723async _emit(event, path, val1, val2, val3) {3724 if (this.closed) return;3725 const opts = this.options;3726 if (isWindows) path = sysPath.normalize(path);3727 if (opts.cwd) path = sysPath.relative(opts.cwd, path);3728 /** @type Array<any> */3729 const args = [event, path];3730 if (val3 !== undefined) args.push(val1, val2, val3);3731 else if (val2 !== undefined) args.push(val1, val2);3732 else if (val1 !== undefined) args.push(val1);3733 const awf = opts.awaitWriteFinish;3734 let pw;3735 if (awf && (pw = this._pendingWrites.get(path))) {3736 pw.lastChange = new Date();3737 return this;3738 }3739 if (opts.atomic) {3740 if (event === EV_UNLINK) {3741 this._pendingUnlinks.set(path, args);3742 setTimeout(() => {3743 this._pendingUnlinks.forEach((entry, path) => {3744 this.emit(...entry);3745 this.emit(EV_ALL, ...entry);3746 this._pendingUnlinks.delete(path);3747 });3748 }, typeof opts.atomic === 'number' ? opts.atomic : 100);3749 return this;3750 }3751 if (event === EV_ADD && this._pendingUnlinks.has(path)) {3752 event = args[0] = EV_CHANGE;3753 this._pendingUnlinks.delete(path);3754 }3755 }3756 if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {3757 const awfEmit = (err, stats) => {3758 if (err) {3759 event = args[0] = EV_ERROR;3760 args[1] = err;3761 this.emitWithAll(event, args);3762 } else if (stats) {3763 // if stats doesn't exist the file must have been deleted3764 if (args.length > 2) {3765 args[2] = stats;3766 } else {3767 args.push(stats);3768 }3769 this.emitWithAll(event, args);3770 }3771 };3772 this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);3773 return this;3774 }3775 if (event === EV_CHANGE) {3776 const isThrottled = !this._throttle(EV_CHANGE, path, 50);3777 if (isThrottled) return this;3778 }3779 if (opts.alwaysStat && val1 === undefined &&3780 (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)3781 ) {3782 const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;3783 let stats;3784 try {3785 stats = await stat(fullPath);3786 } catch (err) {}3787 // Suppress event when fs_stat fails, to avoid sending undefined 'stat'3788 if (!stats || this.closed) return;3789 args.push(stats);3790 }3791 this.emitWithAll(event, args);3792 return this;3793}3794/**3795 * Common handler for errors3796 * @param {Error} error3797 * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag3798 */3799_handleError(error) {3800 const code = error && error.code;3801 if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&3802 (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))3803 ) {3804 this.emit(EV_ERROR, error);3805 }3806 return error || this.closed;3807}3808/**3809 * Helper utility for throttling3810 * @param {ThrottleType} actionType type being throttled3811 * @param {Path} path being acted upon3812 * @param {Number} timeout duration of time to suppress duplicate actions3813 * @returns {Object|false} tracking object or false if action should be suppressed3814 */3815_throttle(actionType, path, timeout) {3816 if (!this._throttled.has(actionType)) {3817 this._throttled.set(actionType, new Map());3818 }3819 /** @type {Map<Path, Object>} */3820 const action = this._throttled.get(actionType);3821 /** @type {Object} */3822 const actionPath = action.get(path);3823 if (actionPath) {3824 actionPath.count++;3825 return false;3826 }3827 let timeoutObject;3828 const clear = () => {3829 const item = action.get(path);3830 const count = item ? item.count : 0;3831 action.delete(path);3832 clearTimeout(timeoutObject);3833 if (item) clearTimeout(item.timeoutObject);3834 return count;3835 };3836 timeoutObject = setTimeout(clear, timeout);3837 const thr = {timeoutObject, clear, count: 0};3838 action.set(path, thr);3839 return thr;3840}3841_incrReadyCount() {3842 return this._readyCount++;3843}3844/**3845 * Awaits write operation to finish.3846 * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.3847 * @param {Path} path being acted upon3848 * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished3849 * @param {EventName} event3850 * @param {Function} awfEmit Callback to be called when ready for event to be emitted.3851 */3852_awaitWriteFinish(path, threshold, event, awfEmit) {3853 let timeoutHandler;3854 let fullPath = path;3855 if (this.options.cwd && !sysPath.isAbsolute(path)) {3856 fullPath = sysPath.join(this.options.cwd, path);3857 }3858 const now = new Date();3859 const awaitWriteFinish = (prevStat) => {3860 fs.stat(fullPath, (err, curStat) => {3861 if (err || !this._pendingWrites.has(path)) {3862 if (err && err.code !== 'ENOENT') awfEmit(err);3863 return;3864 }3865 const now = Number(new Date());3866 if (prevStat && curStat.size !== prevStat.size) {3867 this._pendingWrites.get(path).lastChange = now;3868 }3869 const pw = this._pendingWrites.get(path);3870 const df = now - pw.lastChange;3871 if (df >= threshold) {3872 this._pendingWrites.delete(path);3873 awfEmit(undefined, curStat);3874 } else {3875 timeoutHandler = setTimeout(3876 awaitWriteFinish,3877 this.options.awaitWriteFinish.pollInterval,3878 curStat3879 );3880 }3881 });3882 };3883 if (!this._pendingWrites.has(path)) {3884 this._pendingWrites.set(path, {3885 lastChange: now,3886 cancelWait: () => {3887 this._pendingWrites.delete(path);3888 clearTimeout(timeoutHandler);3889 return event;3890 }3891 });3892 timeoutHandler = setTimeout(3893 awaitWriteFinish,3894 this.options.awaitWriteFinish.pollInterval3895 );3896 }3897}3898_getGlobIgnored() {3899 return [...this._ignoredPaths.values()];3900}3901/**3902 * Determines whether user has asked to ignore this path.3903 * @param {Path} path filepath or dir3904 * @param {fs.Stats=} stats result of fs.stat3905 * @returns {Boolean}3906 */3907_isIgnored(path, stats) {3908 if (this.options.atomic && DOT_RE.test(path)) return true;3909 if (!this._userIgnored) {3910 const {cwd} = this.options;3911 const ign = this.options.ignored;3912 const ignored = ign && ign.map(normalizeIgnored(cwd));3913 const paths = arrify(ignored)3914 .filter((path) => typeof path === STRING_TYPE && !isGlob(path))3915 .map((path) => path + SLASH_GLOBSTAR);3916 const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);3917 this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);3918 }3919 return this._userIgnored([path, stats]);3920}3921_isntIgnored(path, stat) {3922 return !this._isIgnored(path, stat);3923}3924/**3925 * Provides a set of common helpers and properties relating to symlink and glob handling.3926 * @param {Path} path file, directory, or glob pattern being watched3927 * @param {Number=} depth at any depth > 0, this isn't a glob3928 * @returns {WatchHelper} object containing helpers for this path3929 */3930_getWatchHelpers(path, depth) {3931 const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);3932 const follow = this.options.followSymlinks;3933 return new WatchHelper(path, watchPath, follow, this);3934}3935// Directory helpers3936// -----------------3937/**3938 * Provides directory tracking objects3939 * @param {String} directory path of the directory3940 * @returns {DirEntry} the directory's tracking object3941 */3942_getWatchedDir(directory) {3943 if (!this._boundRemove) this._boundRemove = this._remove.bind(this);3944 const dir = sysPath.resolve(directory);3945 if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));3946 return this._watched.get(dir);3947}3948// File helpers3949// ------------3950/**3951 * Check for read permissions.3952 * Based on this answer on SO: https://stackoverflow.com/a/11781404/13584053953 * @param {fs.Stats} stats - object, result of fs_stat3954 * @returns {Boolean} indicates whether the file can be read3955*/3956_hasReadPermissions(stats) {3957 if (this.options.ignorePermissionErrors) return true;3958 // stats.mode may be bigint3959 const md = stats && Number.parseInt(stats.mode, 10);3960 const st = md & 0o777;3961 const it = Number.parseInt(st.toString(8)[0], 10);3962 return Boolean(4 & it);3963}3964/**3965 * Handles emitting unlink events for3966 * files and directories, and via recursion, for3967 * files and directories within directories that are unlinked3968 * @param {String} directory within which the following item is located3969 * @param {String} item base path of item/directory3970 * @returns {void}3971*/3972_remove(directory, item, isDirectory) {3973 // if what is being deleted is a directory, get that directory's paths3974 // for recursive deleting and cleaning of watched object3975 // if it is not a directory, nestedDirectoryChildren will be empty array3976 const path = sysPath.join(directory, item);3977 const fullPath = sysPath.resolve(path);3978 isDirectory = isDirectory != null3979 ? isDirectory3980 : this._watched.has(path) || this._watched.has(fullPath);3981 // prevent duplicate handling in case of arriving here nearly simultaneously3982 // via multiple paths (such as _handleFile and _handleDir)3983 if (!this._throttle('remove', path, 100)) return;3984 // if the only watched file is removed, watch for its return3985 if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {3986 this.add(directory, item, true);3987 }3988 // This will create a new entry in the watched object in either case3989 // so we got to do the directory check beforehand3990 const wp = this._getWatchedDir(path);3991 const nestedDirectoryChildren = wp.getChildren();3992 // Recursively remove children directories / files.3993 nestedDirectoryChildren.forEach(nested => this._remove(path, nested));3994 // Check if item was on the watched list and remove it3995 const parent = this._getWatchedDir(directory);3996 const wasTracked = parent.has(item);3997 parent.remove(item);3998 // Fixes issue #1042 -> Relative paths were detected and added as symlinks3999 // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),4000 // but never removed from the map in case the path was deleted.4001 // This leads to an incorrect state if the path was recreated:4002 // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L5534003 if (this._symlinkPaths.has(fullPath)) {4004 this._symlinkPaths.delete(fullPath);4005 }4006 // If we wait for this file to be fully written, cancel the wait.4007 let relPath = path;4008 if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);4009 if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {4010 const event = this._pendingWrites.get(relPath).cancelWait();4011 if (event === EV_ADD) return;4012 }4013 // The Entry will either be a directory that just got removed4014 // or a bogus entry to a file, in either case we have to remove it4015 this._watched.delete(path);4016 this._watched.delete(fullPath);4017 const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;4018 if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);4019 // Avoid conflicts if we later create another file with the same name4020 if (!this.options.useFsEvents) {4021 this._closePath(path);4022 }4023}4024/**4025 * Closes all watchers for a path4026 * @param {Path} path4027 */4028_closePath(path) {4029 this._closeFile(path);4030 const dir = sysPath.dirname(path);4031 this._getWatchedDir(dir).remove(sysPath.basename(path));4032}4033/**4034 * Closes only file-specific watchers4035 * @param {Path} path4036 */4037_closeFile(path) {4038 const closers = this._closers.get(path);4039 if (!closers) return;4040 closers.forEach(closer => closer());4041 this._closers.delete(path);4042}4043/**4044 *4045 * @param {Path} path4046 * @param {Function} closer4047 */4048_addPathCloser(path, closer) {4049 if (!closer) return;4050 let list = this._closers.get(path);4051 if (!list) {4052 list = [];4053 this._closers.set(path, list);4054 }4055 list.push(closer);4056}4057_readdirp(root, opts) {4058 if (this.closed) return;4059 const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};4060 let stream = readdirp(root, options);4061 this._streams.add(stream);4062 stream.once(STR_CLOSE, () => {4063 stream = undefined;4064 });4065 stream.once(STR_END, () => {4066 if (stream) {4067 this._streams.delete(stream);4068 stream = undefined;4069 }4070 });4071 return stream;4072}4073}4074// Export FSWatcher class4075chokidar$1.FSWatcher = FSWatcher;4076/**4077 * Instantiates watcher with paths to be tracked.4078 * @param {String|Array<String>} paths file/directory paths and/or globs4079 * @param {Object=} options chokidar opts4080 * @returns an instance of FSWatcher for chaining.4081 */4082const watch = (paths, options) => {4083 const watcher = new FSWatcher(options);4084 watcher.add(paths);4085 return watcher;4086};4087chokidar$1.watch = watch;4088const chokidar = chokidar$1;4089class FileWatcher {4090 constructor(task, chokidarOptions) {4091 this.transformWatchers = new Map();4092 this.chokidarOptions = chokidarOptions;4093 this.task = task;4094 this.watcher = this.createWatcher(null);4095 }4096 close() {4097 this.watcher.close();4098 for (const watcher of this.transformWatchers.values()) {4099 watcher.close();4100 }4101 }4102 unwatch(id) {4103 this.watcher.unwatch(id);4104 const transformWatcher = this.transformWatchers.get(id);4105 if (transformWatcher) {4106 this.transformWatchers.delete(id);4107 transformWatcher.close();4108 }4109 }4110 watch(id, isTransformDependency) {4111 var _a;4112 if (isTransformDependency) {4113 const watcher = (_a = this.transformWatchers.get(id)) !== null && _a !== void 0 ? _a : this.createWatcher(id);4114 watcher.add(id);4115 this.transformWatchers.set(id, watcher);4116 }4117 else {4118 this.watcher.add(id);4119 }4120 }4121 createWatcher(transformWatcherId) {4122 const task = this.task;4123 const isLinux = platform() === 'linux';4124 const isTransformDependency = transformWatcherId !== null;4125 const handleChange = (id, event) => {4126 const changedId = transformWatcherId || id;4127 if (isLinux) {4128 // unwatching and watching fixes an issue with chokidar where on certain systems,4129 // a file that was unlinked and immediately recreated would create a change event4130 // but then no longer any further events4131 watcher.unwatch(changedId);4132 watcher.add(changedId);4133 }4134 task.invalidate(changedId, { event, isTransformDependency });4135 };4136 const watcher = chokidar4137 .watch([], this.chokidarOptions)4138 .on('add', id => handleChange(id, 'create'))4139 .on('change', id => handleChange(id, 'update'))4140 .on('unlink', id => handleChange(id, 'delete'));4141 return watcher;4142 }4143}4144const eventsRewrites = {4145 create: {4146 create: 'buggy',4147 delete: null,4148 update: 'create'4149 },4150 delete: {4151 create: 'update',4152 delete: 'buggy',4153 update: 'buggy'4154 },4155 update: {4156 create: 'buggy',4157 delete: 'delete',4158 update: 'update'4159 }4160};4161class Watcher {4162 constructor(configs, emitter) {4163 this.buildDelay = 0;4164 this.buildTimeout = null;4165 this.invalidatedIds = new Map();4166 this.rerun = false;4167 this.running = true;4168 this.emitter = emitter;4169 emitter.close = this.close.bind(this);4170 this.tasks = configs.map(config => new Task(this, config));4171 this.buildDelay = configs.reduce((buildDelay, { watch }) => watch && typeof watch.buildDelay === 'number'4172 ? Math.max(buildDelay, watch.buildDelay)4173 : buildDelay, this.buildDelay);4174 process$1.nextTick(() => this.run());4175 }4176 close() {4177 if (this.buildTimeout)4178 clearTimeout(this.buildTimeout);4179 for (const task of this.tasks) {4180 task.close();4181 }4182 this.emitter.emit('close');4183 this.emitter.removeAllListeners();4184 }4185 invalidate(file) {4186 if (file) {4187 const prevEvent = this.invalidatedIds.get(file.id);4188 const event = prevEvent ? eventsRewrites[prevEvent][file.event] : file.event;4189 if (event === 'buggy') {4190 //TODO: throws or warn? Currently just ignore, uses new event4191 this.invalidatedIds.set(file.id, file.event);4192 }4193 else if (event === null) {4194 this.invalidatedIds.delete(file.id);4195 }4196 else {4197 this.invalidatedIds.set(file.id, event);4198 }4199 }4200 if (this.running) {4201 this.rerun = true;4202 return;4203 }4204 if (this.buildTimeout)4205 clearTimeout(this.buildTimeout);4206 this.buildTimeout = setTimeout(() => {4207 this.buildTimeout = null;4208 for (const [id, event] of this.invalidatedIds.entries()) {4209 this.emitter.emit('change', id, { event });4210 }4211 this.invalidatedIds.clear();4212 this.emitter.emit('restart');4213 this.run();4214 }, this.buildDelay);4215 }4216 async run() {4217 this.running = true;4218 this.emitter.emit('event', {4219 code: 'START'4220 });4221 for (const task of this.tasks) {4222 await task.run();4223 }4224 this.running = false;4225 this.emitter.emit('event', {4226 code: 'END'4227 });4228 if (this.rerun) {4229 this.rerun = false;4230 this.invalidate();4231 }4232 }4233}4234class Task {4235 constructor(watcher, config) {4236 this.cache = { modules: [] };4237 this.watchFiles = [];4238 this.closed = false;4239 this.invalidated = true;4240 this.watched = new Set();4241 this.watcher = watcher;4242 this.skipWrite = Boolean(config.watch && config.watch.skipWrite);4243 this.options = mergeOptions(config);4244 this.outputs = this.options.output;4245 this.outputFiles = this.outputs.map(output => {4246 if (output.file || output.dir)4247 return resolve(output.file || output.dir);4248 return undefined;4249 });4250 const watchOptions = this.options.watch || {};4251 this.filter = createFilter(watchOptions.include, watchOptions.exclude);4252 this.fileWatcher = new FileWatcher(this, {4253 ...watchOptions.chokidar,4254 disableGlobbing: true,4255 ignoreInitial: true4256 });4257 }4258 close() {4259 this.closed = true;4260 this.fileWatcher.close();4261 }4262 invalidate(id, details) {4263 this.invalidated = true;4264 if (details.isTransformDependency) {4265 for (const module of this.cache.modules) {4266 if (module.transformDependencies.indexOf(id) === -1)4267 continue;4268 // effective invalidation4269 module.originalCode = null;4270 }4271 }4272 this.watcher.invalidate({ event: details.event, id });4273 }4274 async run() {4275 if (!this.invalidated)4276 return;4277 this.invalidated = false;4278 const options = {4279 ...this.options,4280 cache: this.cache4281 };4282 const start = Date.now();4283 this.watcher.emitter.emit('event', {4284 code: 'BUNDLE_START',4285 input: this.options.input,4286 output: this.outputFiles4287 });4288 let result = null;4289 try {4290 result = await rollupInternal(options, this.watcher.emitter);4291 if (this.closed) {4292 return;4293 }4294 this.updateWatchedFiles(result);4295 this.skipWrite || (await Promise.all(this.outputs.map(output => result.write(output))));4296 this.watcher.emitter.emit('event', {4297 code: 'BUNDLE_END',4298 duration: Date.now() - start,4299 input: this.options.input,4300 output: this.outputFiles,4301 result4302 });4303 }4304 catch (error) {4305 if (!this.closed) {4306 if (Array.isArray(error.watchFiles)) {4307 for (const id of error.watchFiles) {4308 this.watchFile(id);4309 }4310 }4311 if (error.id) {4312 this.cache.modules = this.cache.modules.filter(module => module.id !== error.id);4313 }4314 }4315 this.watcher.emitter.emit('event', {4316 code: 'ERROR',4317 error,4318 result4319 });4320 }4321 }4322 updateWatchedFiles(result) {4323 const previouslyWatched = this.watched;4324 this.watched = new Set();4325 this.watchFiles = result.watchFiles;4326 this.cache = result.cache;4327 for (const id of this.watchFiles) {4328 this.watchFile(id);4329 }4330 for (const module of this.cache.modules) {4331 for (const depId of module.transformDependencies) {4332 this.watchFile(depId, true);4333 }4334 }4335 for (const id of previouslyWatched) {4336 if (!this.watched.has(id)) {4337 this.fileWatcher.unwatch(id);4338 }4339 }4340 }4341 watchFile(id, isTransformDependency = false) {4342 if (!this.filter(id))4343 return;4344 this.watched.add(id);4345 if (this.outputFiles.some(file => file === id)) {4346 throw new Error('Cannot import the generated bundle');4347 }4348 // this is necessary to ensure that any 'renamed' files4349 // continue to be watched following an error4350 this.fileWatcher.watch(id, isTransformDependency);4351 }4352}...
rollup
Source:rollup
1#!/usr/bin/env node2'use strict';3function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }4var path = require('path');5var path__default = _interopDefault(path);6var module$1 = _interopDefault(require('module'));7var rollup = require('../dist/rollup.js');8var rollup__default = _interopDefault(rollup);9var assert = _interopDefault(require('assert'));10var events = _interopDefault(require('events'));11var fs = require('fs');12var fs__default = _interopDefault(fs);13var help = "rollup version __VERSION__\n=====================================\n\nUsage: rollup [options] <entry file>\n\nBasic options:\n\n-v, --version Show version number\n-h, --help Show this help message\n-c, --config Use this config file (if argument is used but value\n is unspecified, defaults to rollup.config.js)\n-w, --watch Watch files in bundle and rebuild on changes\n-i, --input Input (alternative to <entry file>)\n-o, --file <output> Output (if absent, prints to stdout)\n-f, --format [es] Type of output (amd, cjs, es, iife, umd)\n-e, --external Comma-separate list of module IDs to exclude\n-g, --globals Comma-separate list of `module ID:Global` pairs\n Any module IDs defined here are added to external\n-n, --name Name for UMD export\n-m, --sourcemap Generate sourcemap (`-m inline` for inline map)\n--amd.id ID for AMD module (default is anonymous)\n--amd.define Function to use in place of `define`\n--no-strict Don't emit a `\"use strict\";` in the generated modules.\n--no-indent Don't indent result\n--environment <values> Settings passed to config file (see example)\n--no-conflict Generate a noConflict method for UMD globals\n--no-treeshake Disable tree-shaking\n--silent Don't print warnings\n--intro Content to insert at top of bundle (inside wrapper)\n--outro Content to insert at end of bundle (inside wrapper)\n--banner Content to insert at top of bundle (outside wrapper)\n--footer Content to insert at end of bundle (outside wrapper)\n--no-interop Do not include interop block\n\nExamples:\n\n# use settings in config file\nrollup -c\n\n# in config file, process.env.INCLUDE_DEPS === 'true'\n# and process.env.BUILD === 'production'\nrollup -c --environment INCLUDE_DEPS,BUILD:production\n\n# create CommonJS bundle.js from src/main.js\nrollup --format=cjs --file=bundle.js -- src/main.js\n\n# create self-executing IIFE using `window.jQuery`\n# and `window._` as external globals\nrollup -f iife --globals jquery:jQuery,lodash:_ \\\n -i src/app.js -o build/app.js -m build/app.js.map\n\nNotes:\n\n* When piping to stdout, only inline sourcemaps are permitted\n\nFor more information visit https://rollupjs.org\n";14var minimist = function (args, opts) {15 if (!opts) opts = {};16 17 var flags = { bools : {}, strings : {}, unknownFn: null };18 if (typeof opts['unknown'] === 'function') {19 flags.unknownFn = opts['unknown'];20 }21 if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {22 flags.allBools = true;23 } else {24 [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {25 flags.bools[key] = true;26 });27 }28 29 var aliases = {};30 Object.keys(opts.alias || {}).forEach(function (key) {31 aliases[key] = [].concat(opts.alias[key]);32 aliases[key].forEach(function (x) {33 aliases[x] = [key].concat(aliases[key].filter(function (y) {34 return x !== y;35 }));36 });37 });38 [].concat(opts.string).filter(Boolean).forEach(function (key) {39 flags.strings[key] = true;40 if (aliases[key]) {41 flags.strings[aliases[key]] = true;42 }43 });44 var defaults = opts['default'] || {};45 46 var argv = { _ : [] };47 Object.keys(flags.bools).forEach(function (key) {48 setArg(key, defaults[key] === undefined ? false : defaults[key]);49 });50 51 var notFlags = [];52 if (args.indexOf('--') !== -1) {53 notFlags = args.slice(args.indexOf('--')+1);54 args = args.slice(0, args.indexOf('--'));55 }56 function argDefined(key, arg) {57 return (flags.allBools && /^--[^=]+$/.test(arg)) ||58 flags.strings[key] || flags.bools[key] || aliases[key];59 }60 function setArg (key, val, arg) {61 if (arg && flags.unknownFn && !argDefined(key, arg)) {62 if (flags.unknownFn(arg) === false) return;63 }64 var value = !flags.strings[key] && isNumber(val)65 ? Number(val) : val66 ;67 setKey(argv, key.split('.'), value);68 69 (aliases[key] || []).forEach(function (x) {70 setKey(argv, x.split('.'), value);71 });72 }73 function setKey (obj, keys, value) {74 var o = obj;75 keys.slice(0,-1).forEach(function (key) {76 if (o[key] === undefined) o[key] = {};77 o = o[key];78 });79 var key = keys[keys.length - 1];80 if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {81 o[key] = value;82 }83 else if (Array.isArray(o[key])) {84 o[key].push(value);85 }86 else {87 o[key] = [ o[key], value ];88 }89 }90 91 function aliasIsBoolean(key) {92 return aliases[key].some(function (x) {93 return flags.bools[x];94 });95 }96 for (var i = 0; i < args.length; i++) {97 var arg = args[i];98 99 if (/^--.+=/.test(arg)) {100 // Using [\s\S] instead of . because js doesn't support the101 // 'dotall' regex modifier. See:102 // http://stackoverflow.com/a/1068308/13216103 var m = arg.match(/^--([^=]+)=([\s\S]*)$/);104 var key = m[1];105 var value = m[2];106 if (flags.bools[key]) {107 value = value !== 'false';108 }109 setArg(key, value, arg);110 }111 else if (/^--no-.+/.test(arg)) {112 var key = arg.match(/^--no-(.+)/)[1];113 setArg(key, false, arg);114 }115 else if (/^--.+/.test(arg)) {116 var key = arg.match(/^--(.+)/)[1];117 var next = args[i + 1];118 if (next !== undefined && !/^-/.test(next)119 && !flags.bools[key]120 && !flags.allBools121 && (aliases[key] ? !aliasIsBoolean(key) : true)) {122 setArg(key, next, arg);123 i++;124 }125 else if (/^(true|false)$/.test(next)) {126 setArg(key, next === 'true', arg);127 i++;128 }129 else {130 setArg(key, flags.strings[key] ? '' : true, arg);131 }132 }133 else if (/^-[^-]+/.test(arg)) {134 var letters = arg.slice(1,-1).split('');135 136 var broken = false;137 for (var j = 0; j < letters.length; j++) {138 var next = arg.slice(j+2);139 140 if (next === '-') {141 setArg(letters[j], next, arg);142 continue;143 }144 145 if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {146 setArg(letters[j], next.split('=')[1], arg);147 broken = true;148 break;149 }150 151 if (/[A-Za-z]/.test(letters[j])152 && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {153 setArg(letters[j], next, arg);154 broken = true;155 break;156 }157 158 if (letters[j+1] && letters[j+1].match(/\W/)) {159 setArg(letters[j], arg.slice(j+2), arg);160 broken = true;161 break;162 }163 else {164 setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);165 }166 }167 168 var key = arg.slice(-1)[0];169 if (!broken && key !== '-') {170 if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])171 && !flags.bools[key]172 && (aliases[key] ? !aliasIsBoolean(key) : true)) {173 setArg(key, args[i+1], arg);174 i++;175 }176 else if (args[i+1] && /true|false/.test(args[i+1])) {177 setArg(key, args[i+1] === 'true', arg);178 i++;179 }180 else {181 setArg(key, flags.strings[key] ? '' : true, arg);182 }183 }184 }185 else {186 if (!flags.unknownFn || flags.unknownFn(arg) !== false) {187 argv._.push(188 flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)189 );190 }191 if (opts.stopEarly) {192 argv._.push.apply(argv._, args.slice(i + 1));193 break;194 }195 }196 }197 198 Object.keys(defaults).forEach(function (key) {199 if (!hasKey(argv, key.split('.'))) {200 setKey(argv, key.split('.'), defaults[key]);201 202 (aliases[key] || []).forEach(function (x) {203 setKey(argv, x.split('.'), defaults[key]);204 });205 }206 });207 208 if (opts['--']) {209 argv['--'] = new Array();210 notFlags.forEach(function(key) {211 argv['--'].push(key);212 });213 }214 else {215 notFlags.forEach(function(key) {216 argv._.push(key);217 });218 }219 return argv;220};221function hasKey (obj, keys) {222 var o = obj;223 keys.slice(0,-1).forEach(function (key) {224 o = (o[key] || {});225 });226 var key = keys[keys.length - 1];227 return key in o;228}229function isNumber (x) {230 if (typeof x === 'number') return true;231 if (/^0x[0-9a-f]+$/i.test(x)) return true;232 return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);233}234var version = "0.63.5";235const __assign = Object.assign || function (target) {236 for (var source, i = 1; i < arguments.length; i++) {237 source = arguments[i];238 for (var prop in source) {239 if (Object.prototype.hasOwnProperty.call(source, prop)) {240 target[prop] = source[prop];241 }242 }243 }244 return target;245};246function deprecateOptions(options, deprecateConfig) {247 var deprecations = [];248 if (deprecateConfig.input)249 deprecateInputOptions();250 if (deprecateConfig.output)251 deprecateOutputOptions();252 return deprecations;253 function deprecateInputOptions() {254 if (!options.input && options.entry)255 deprecate('entry', 'input');256 if (options.dest)257 deprecateToOutputOption('dest', 'file');258 if (options.moduleName)259 deprecateToOutputOption('moduleName', 'name');260 if (options.name)261 deprecateToOutputOption('name', 'name');262 if (options.extend)263 deprecateToOutputOption('extend', 'extend');264 if (options.globals)265 deprecateToOutputOption('globals', 'globals');266 if (options.indent)267 deprecateToOutputOption('indent', 'indent');268 if (options.noConflict)269 deprecateToOutputOption('noConflict', 'noConflict');270 if (options.paths)271 deprecateToOutputOption('paths', 'paths');272 if (options.sourcemap)273 deprecateToOutputOption('sourcemap', 'sourcemap');274 if (options.sourceMap)275 deprecateToOutputOption('sourceMap', 'sourcemap');276 if (options.sourceMapFile)277 deprecateToOutputOption('sourceMapFile', 'sourcemapFile');278 if (options.useStrict)279 deprecateToOutputOption('useStrict', 'strict');280 if (options.strict)281 deprecateToOutputOption('strict', 'strict');282 if (options.format)283 deprecateToOutputOption('format', 'format');284 if (options.banner)285 deprecateToOutputOption('banner', 'banner');286 if (options.footer)287 deprecateToOutputOption('footer', 'footer');288 if (options.intro)289 deprecateToOutputOption('intro', 'intro');290 if (options.outro)291 deprecateToOutputOption('outro', 'outro');292 if (options.interop)293 deprecateToOutputOption('interop', 'interop');294 if (options.freeze)295 deprecateToOutputOption('freeze', 'freeze');296 if (options.exports)297 deprecateToOutputOption('exports', 'exports');298 if (options.targets) {299 deprecations.push({ old: 'targets', new: 'output' });300 // as targets is an array and we need to merge other output options301 // like sourcemap etc.302 options.output = options.targets.map(function (target) { return (__assign({}, target, options.output)); });303 delete options.targets;304 var deprecatedDest_1 = false;305 options.output.forEach(function (outputEntry) {306 if (outputEntry.dest) {307 if (!deprecatedDest_1) {308 deprecations.push({ old: 'targets.dest', new: 'output.file' });309 deprecatedDest_1 = true;310 }311 outputEntry.file = outputEntry.dest;312 delete outputEntry.dest;313 }314 });315 }316 if (options.pureExternalModules) {317 deprecations.push({318 old: 'pureExternalModules',319 new: 'treeshake.pureExternalModules'320 });321 if (options.treeshake === undefined) {322 options.treeshake = {};323 }324 if (options.treeshake) {325 options.treeshake.pureExternalModules = options.pureExternalModules;326 }327 delete options.pureExternalModules;328 }329 }330 function deprecateOutputOptions() {331 if (options.output && options.output.moduleId) {332 options.output.amd = { id: options.moduleId };333 deprecations.push({ old: 'moduleId', new: 'amd' });334 delete options.output.moduleId;335 }336 }337 function deprecate(oldOption, newOption) {338 deprecations.push({ new: newOption, old: oldOption });339 if (!(newOption in options)) {340 options[newOption] = options[oldOption];341 }342 delete options[oldOption];343 }344 function deprecateToOutputOption(oldOption, newOption) {345 deprecations.push({ new: "output." + newOption, old: oldOption });346 options.output = options.output || {};347 if (!(newOption in options.output)) {348 options.output[newOption] = options[oldOption];349 }350 delete options[oldOption];351 }352}353function ensureArray(thing) {354 if (Array.isArray(thing))355 return thing;356 if (thing == undefined)357 return [];358 return [thing];359}360var createGetOption = function (config, command) { return function (name, defaultValue) {361 return command[name] !== undefined362 ? command[name]363 : config[name] !== undefined364 ? config[name]365 : defaultValue;366}; };367var normalizeObjectOptionValue = function (optionValue) {368 if (!optionValue) {369 return optionValue;370 }371 if (typeof optionValue !== 'object') {372 return {};373 }374 return optionValue;375};376var getObjectOption = function (config, command, name) {377 var commandOption = normalizeObjectOptionValue(command[name]);378 var configOption = normalizeObjectOptionValue(config[name]);379 if (commandOption !== undefined) {380 return commandOption && configOption ? __assign({}, configOption, commandOption) : commandOption;381 }382 return configOption;383};384var defaultOnWarn = function (warning) {385 if (typeof warning === 'string') {386 console.warn(warning); // eslint-disable-line no-console387 }388 else {389 console.warn(warning.message); // eslint-disable-line no-console390 }391};392var getOnWarn = function (config, command, defaultOnWarnHandler) {393 if (defaultOnWarnHandler === void 0) { defaultOnWarnHandler = defaultOnWarn; }394 return command.silent395 ? function () { }396 : config.onwarn397 ? function (warning) { return config.onwarn(warning, defaultOnWarnHandler); }398 : defaultOnWarnHandler;399};400var getExternal = function (config, command) {401 var configExternal = config.external;402 return typeof configExternal === 'function'403 ? function (id) {404 var rest = [];405 for (var _i = 1; _i < arguments.length; _i++) {406 rest[_i - 1] = arguments[_i];407 }408 return configExternal.apply(void 0, [id].concat(rest)) || command.external.indexOf(id) !== -1;409 }410 : (configExternal || []).concat(command.external);411};412var commandAliases = {413 c: 'config',414 e: 'external',415 f: 'format',416 g: 'globals',417 h: 'help',418 i: 'input',419 m: 'sourcemap',420 n: 'name',421 o: 'file',422 v: 'version',423 w: 'watch'424};425function mergeOptions(_a) {426 var _b = _a.config, config = _b === void 0 ? {} : _b, _c = _a.command, rawCommandOptions = _c === void 0 ? {} : _c, deprecateConfig = _a.deprecateConfig, defaultOnWarnHandler = _a.defaultOnWarnHandler;427 var deprecations = deprecate(config, rawCommandOptions, deprecateConfig);428 var command = getCommandOptions(rawCommandOptions);429 var inputOptions = getInputOptions(config, command, defaultOnWarnHandler);430 if (command.output) {431 Object.assign(command, command.output);432 }433 var normalizedOutputOptions = ensureArray(config.output);434 if (normalizedOutputOptions.length === 0)435 normalizedOutputOptions.push({});436 var outputOptions = normalizedOutputOptions.map(function (singleOutputOptions) {437 return getOutputOptions(singleOutputOptions, command);438 });439 var unknownOptionErrors = [];440 var validInputOptions = Object.keys(inputOptions);441 addUnknownOptionErrors(unknownOptionErrors, Object.keys(config), validInputOptions, 'input option', /^output$/);442 var validOutputOptions = Object.keys(outputOptions[0]);443 addUnknownOptionErrors(unknownOptionErrors, outputOptions.reduce(function (allKeys, options) { return allKeys.concat(Object.keys(options)); }, []), validOutputOptions, 'output option');444 addUnknownOptionErrors(unknownOptionErrors, Object.keys(command), validInputOptions.concat(validOutputOptions, Object.keys(commandAliases), 'config', 'environment', 'silent'), 'CLI flag', /^_|output|(config.*)$/);445 return {446 inputOptions: inputOptions,447 outputOptions: outputOptions,448 deprecations: deprecations,449 optionError: unknownOptionErrors.length > 0 ? unknownOptionErrors.join('\n') : null450 };451}452function addUnknownOptionErrors(errors, options, validOptions, optionType, ignoredKeys) {453 if (ignoredKeys === void 0) { ignoredKeys = /$./; }454 var unknownOptions = options.filter(function (key) { return validOptions.indexOf(key) === -1 && !ignoredKeys.test(key); });455 if (unknownOptions.length > 0)456 errors.push("Unknown " + optionType + ": " + unknownOptions.join(', ') + ". Allowed options: " + validOptions.sort().join(', '));457}458function getCommandOptions(rawCommandOptions) {459 var command = __assign({}, rawCommandOptions);460 command.external = (rawCommandOptions.external || '').split(',');461 if (rawCommandOptions.globals) {462 command.globals = Object.create(null);463 rawCommandOptions.globals.split(',').forEach(function (str) {464 var names = str.split(':');465 command.globals[names[0]] = names[1];466 // Add missing Module IDs to external.467 if (command.external.indexOf(names[0]) === -1) {468 command.external.push(names[0]);469 }470 });471 }472 return command;473}474function getInputOptions(config, command, defaultOnWarnHandler) {475 if (command === void 0) { command = {}; }476 var getOption = createGetOption(config, command);477 var inputOptions = {478 acorn: config.acorn,479 acornInjectPlugins: config.acornInjectPlugins,480 cache: getOption('cache'),481 context: config.context,482 experimentalCodeSplitting: getOption('experimentalCodeSplitting'),483 experimentalPreserveModules: getOption('experimentalPreserveModules'),484 experimentalTopLevelAwait: getOption('experimentalTopLevelAwait'),485 external: getExternal(config, command),486 inlineDynamicImports: getOption('inlineDynamicImports', false),487 input: getOption('input'),488 manualChunks: getOption('manualChunks'),489 chunkGroupingSize: getOption('chunkGroupingSize', 5000),490 optimizeChunks: getOption('optimizeChunks'),491 moduleContext: config.moduleContext,492 onwarn: getOnWarn(config, command, defaultOnWarnHandler),493 perf: getOption('perf', false),494 plugins: config.plugins,495 preferConst: getOption('preferConst'),496 preserveSymlinks: getOption('preserveSymlinks'),497 treeshake: getObjectOption(config, command, 'treeshake'),498 shimMissingExports: getOption('shimMissingExports'),499 watch: config.watch500 };501 // legacy to make sure certain plugins still work502 if (Array.isArray(inputOptions.input)) {503 inputOptions.entry = inputOptions.input[0];504 }505 else if (typeof inputOptions.input === 'object') {506 for (var name in inputOptions.input) {507 inputOptions.entry = inputOptions.input[name];508 break;509 }510 }511 else {512 inputOptions.entry = inputOptions.input;513 }514 return inputOptions;515}516function getOutputOptions(config, command) {517 if (command === void 0) { command = {}; }518 var getOption = createGetOption(config, command);519 var format = getOption('format');520 return {521 amd: __assign({}, config.amd, command.amd),522 assetFileNames: getOption('assetFileNames'),523 banner: getOption('banner'),524 dir: getOption('dir'),525 chunkFileNames: getOption('chunkFileNames'),526 compact: getOption('compact', false),527 entryFileNames: getOption('entryFileNames'),528 esModule: getOption('esModule', true),529 exports: getOption('exports'),530 extend: getOption('extend'),531 file: getOption('file'),532 footer: getOption('footer'),533 format: format === 'esm' ? 'es' : format,534 freeze: getOption('freeze', true),535 globals: getOption('globals'),536 indent: getOption('indent', true),537 interop: getOption('interop', true),538 intro: getOption('intro'),539 name: getOption('name'),540 namespaceToStringTag: getOption('namespaceToStringTag', false),541 noConflict: getOption('noConflict'),542 outro: getOption('outro'),543 paths: getOption('paths'),544 sourcemap: getOption('sourcemap'),545 sourcemapFile: getOption('sourcemapFile'),546 strict: getOption('strict', true)547 };548}549function deprecate(config, command, deprecateConfig) {550 if (command === void 0) { command = {}; }551 if (deprecateConfig === void 0) { deprecateConfig = { input: true, output: true }; }552 var deprecations = [];553 // CLI554 if (command.id) {555 deprecations.push({556 old: '-u/--id',557 new: '--amd.id'558 });559 (command.amd || (command.amd = {})).id = command.id;560 }561 if (typeof command.output === 'string') {562 deprecations.push({563 old: '--output',564 new: '--file'565 });566 command.output = { file: command.output };567 }568 if (command.d) {569 deprecations.push({570 old: '-d',571 new: '--indent'572 });573 command.indent = command.d;574 }575 // config file576 deprecations.push.apply(deprecations, deprecateOptions(config, deprecateConfig));577 return deprecations;578}579var modules = {};580var getModule = function(dir) {581 var rootPath = dir ? path__default.resolve(dir) : process.cwd();582 var rootName = path__default.join(rootPath, '@root');583 var root = modules[rootName];584 if (!root) {585 root = new module$1(rootName);586 root.filename = rootName;587 root.paths = module$1._nodeModulePaths(rootPath);588 modules[rootName] = root;589 }590 return root;591};592var requireRelative = function(requested, relativeTo) {593 var root = getModule(relativeTo);594 return root.require(requested);595};596requireRelative.resolve = function(requested, relativeTo) {597 var root = getModule(relativeTo);598 return module$1._resolveFilename(requested, root);599};600var requireRelative_1 = requireRelative;601var absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;602function isAbsolute(path$$1) {603 return absolutePath.test(path$$1);604}605function getAliasName(resolved, unresolved) {606 var alias = path.basename(unresolved || resolved);607 var ext = path.extname(resolved);608 if (alias.endsWith(ext))609 alias = alias.substr(0, alias.length - ext.length);610 return alias;611}612function relativeId(id) {613 if (typeof process === 'undefined' || !isAbsolute(id))614 return id;615 return path.relative(process.cwd(), id);616}617const defineProperty = Object.defineProperty;618const Style = (open, close) => ({619 open: `\x1b[${open}m`,620 close: `\x1b[${close}m`,621 strip: new RegExp(`\\x1b\\[${close}m`, "g")622});623const Styles = {624 reset: Style(0, 0),625 bold: Style(1, 22),626 dim: Style(2, 22),627 italic: Style(3, 23),628 underline: Style(4, 24),629 inverse: Style(7, 27),630 hidden: Style(8, 28),631 strikethrough: Style(9, 29),632 black: Style(30, 39),633 red: Style(31, 39),634 green: Style(32, 39),635 yellow: Style(33, 39),636 blue: Style(34, 39),637 magenta: Style(35, 39),638 cyan: Style(36, 39),639 white: Style(37, 39),640 gray: Style(90, 39),641 bgBlack: Style(40, 49),642 bgRed: Style(101, 49),643 bgGreen: Style(102, 49),644 bgYellow: Style(103, 49),645 bgBlue: Style(104, 49),646 bgMagenta: Style(105, 49),647 bgCyan: Style(106, 49),648 bgWhite: Style(107, 49)649};650const turbocolor = {651 Styles,652 enabled:653 process.env.FORCE_COLOR ||654 process.platform === "win32" ||655 (process.stdout.isTTY && process.env.TERM && process.env.TERM !== "dumb")656};657const color = function(out) {658 if (!turbocolor.enabled) return out659 let i, style;660 const names = this.names;661 const length = names.length;662 for (i = 0, out = out + ""; i < length; i++) {663 style = Styles[names[i]];664 out = `${style.open}${out.replace(style.strip, style.open)}${style.close}`;665 }666 return out667};668for (const name in Styles) {669 defineProperty(turbocolor, name, {670 get() {671 if (this.names === undefined) {672 const chain = {};673 const style = color.bind(chain);674 style.__proto__ = turbocolor;675 style.names = chain.names = [name];676 return style677 }678 this.names.push(name);679 return this680 }681 });682}683var turbocolor_1 = turbocolor;684// log to stderr to keep `rollup main.js > bundle.js` from breaking685var stderr = console.error.bind(console); // eslint-disable-line no-console686function handleError(err, recover) {687 if (recover === void 0) { recover = false; }688 var description = err.message || err;689 if (err.name)690 description = err.name + ": " + description;691 var message = (err.plugin692 ? "(" + err.plugin + " plugin) " + description693 : description) || err;694 stderr(turbocolor_1.bold.red("[!] " + turbocolor_1.bold(message.toString())));695 // TODO should this be "err.url || (err.file && err.loc.file) || err.id"?696 if (err.url) {697 stderr(turbocolor_1.cyan(err.url));698 }699 if (err.loc) {700 stderr(relativeId(err.loc.file || err.id) + " (" + err.loc.line + ":" + err.loc.column + ")");701 }702 else if (err.id) {703 stderr(relativeId(err.id));704 }705 if (err.frame) {706 stderr(turbocolor_1.dim(err.frame));707 }708 else if (err.stack) {709 stderr(turbocolor_1.dim(err.stack));710 }711 stderr('');712 if (!recover)713 process.exit(1);714}715function sequence(array, fn) {716 var results = [];717 var promise = Promise.resolve();718 function next(member, i) {719 return fn(member).then(function (value) { return (results[i] = value); });720 }721 var _loop_1 = function (i) {722 promise = promise.then(function () { return next(array[i], i); });723 };724 for (var i = 0; i < array.length; i += 1) {725 _loop_1(i);726 }727 return promise.then(function () { return results; });728}729function batchWarnings() {730 var allWarnings = new Map();731 var count = 0;732 return {733 get count() {734 return count;735 },736 add: function (warning) {737 if (typeof warning === 'string') {738 warning = { code: 'UNKNOWN', message: warning };739 }740 if (warning.code in immediateHandlers) {741 immediateHandlers[warning.code](warning);742 return;743 }744 if (!allWarnings.has(warning.code))745 allWarnings.set(warning.code, []);746 allWarnings.get(warning.code).push(warning);747 count += 1;748 },749 flush: function () {750 if (count === 0)751 return;752 var codes = Array.from(allWarnings.keys()).sort(function (a, b) {753 if (deferredHandlers[a] && deferredHandlers[b]) {754 return deferredHandlers[a].priority - deferredHandlers[b].priority;755 }756 if (deferredHandlers[a])757 return -1;758 if (deferredHandlers[b])759 return 1;760 return allWarnings.get(b).length - allWarnings.get(a).length;761 });762 codes.forEach(function (code) {763 var handler = deferredHandlers[code];764 var warnings = allWarnings.get(code);765 if (handler) {766 handler.fn(warnings);767 }768 else {769 warnings.forEach(function (warning) {770 stderr(turbocolor_1.bold.yellow('(!)') + " " + turbocolor_1.bold.yellow(warning.message));771 if (warning.url)772 info(warning.url);773 var id = (warning.loc && warning.loc.file) || warning.id;774 if (id) {775 var loc = warning.loc776 ? relativeId(id) + ": (" + warning.loc.line + ":" + warning.loc.column + ")"777 : relativeId(id);778 stderr(turbocolor_1.bold(relativeId(loc)));779 }780 if (warning.frame)781 info(warning.frame);782 });783 }784 });785 allWarnings = new Map();786 count = 0;787 }788 };789}790var immediateHandlers = {791 UNKNOWN_OPTION: function (warning) {792 title("You have passed an unrecognized option");793 stderr(warning.message);794 },795 DEPRECATED_OPTIONS: function (warning) {796 title("Some options have been renamed");797 info("https://gist.github.com/Rich-Harris/d472c50732dab03efeb37472b08a3f32");798 warning.deprecations.forEach(function (option) {799 stderr(turbocolor_1.bold(option.old) + " is now " + option.new);800 });801 },802 MISSING_NODE_BUILTINS: function (warning) {803 title("Missing shims for Node.js built-ins");804 var detail = warning.modules.length === 1805 ? "'" + warning.modules[0] + "'"806 : warning.modules807 .slice(0, -1)808 .map(function (name) { return "'" + name + "'"; })809 .join(', ') + " and '" + warning.modules.slice(-1) + "'";810 stderr("Creating a browser bundle that depends on " + detail + ". You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins");811 },812 MIXED_EXPORTS: function () {813 title('Mixing named and default exports');814 stderr("Consumers of your bundle will have to use bundle['default'] to access the default export, which may not be what you want. Use `output.exports: 'named'` to disable this warning");815 },816 EMPTY_BUNDLE: function () {817 title("Generated an empty bundle");818 }819};820// TODO select sensible priorities821var deferredHandlers = {822 UNUSED_EXTERNAL_IMPORT: {823 priority: 1,824 fn: function (warnings) {825 title('Unused external imports');826 warnings.forEach(function (warning) {827 stderr(warning.names + " imported from external module '" + warning.source + "' but never used");828 });829 }830 },831 UNRESOLVED_IMPORT: {832 priority: 1,833 fn: function (warnings) {834 title('Unresolved dependencies');835 info('https://github.com/rollup/rollup/wiki/Troubleshooting#treating-module-as-external-dependency');836 var dependencies = new Map();837 warnings.forEach(function (warning) {838 if (!dependencies.has(warning.source))839 dependencies.set(warning.source, []);840 dependencies.get(warning.source).push(warning.importer);841 });842 Array.from(dependencies.keys()).forEach(function (dependency) {843 var importers = dependencies.get(dependency);844 stderr(turbocolor_1.bold(dependency) + " (imported by " + importers.join(', ') + ")");845 });846 }847 },848 MISSING_EXPORT: {849 priority: 1,850 fn: function (warnings) {851 title('Missing exports');852 info('https://github.com/rollup/rollup/wiki/Troubleshooting#name-is-not-exported-by-module');853 warnings.forEach(function (warning) {854 stderr(turbocolor_1.bold(warning.importer));855 stderr(warning.missing + " is not exported by " + warning.exporter);856 stderr(turbocolor_1.gray(warning.frame));857 });858 }859 },860 THIS_IS_UNDEFINED: {861 priority: 1,862 fn: function (warnings) {863 title('`this` has been rewritten to `undefined`');864 info('https://github.com/rollup/rollup/wiki/Troubleshooting#this-is-undefined');865 showTruncatedWarnings(warnings);866 }867 },868 EVAL: {869 priority: 1,870 fn: function (warnings) {871 title('Use of eval is strongly discouraged');872 info('https://github.com/rollup/rollup/wiki/Troubleshooting#avoiding-eval');873 showTruncatedWarnings(warnings);874 }875 },876 NON_EXISTENT_EXPORT: {877 priority: 1,878 fn: function (warnings) {879 title("Import of non-existent " + (warnings.length > 1 ? 'exports' : 'export'));880 showTruncatedWarnings(warnings);881 }882 },883 NAMESPACE_CONFLICT: {884 priority: 1,885 fn: function (warnings) {886 title("Conflicting re-exports");887 warnings.forEach(function (warning) {888 stderr(turbocolor_1.bold(relativeId(warning.reexporter)) + " re-exports '" + warning.name + "' from both " + relativeId(warning.sources[0]) + " and " + relativeId(warning.sources[1]) + " (will be ignored)");889 });890 }891 },892 MISSING_GLOBAL_NAME: {893 priority: 1,894 fn: function (warnings) {895 title("Missing global variable " + (warnings.length > 1 ? 'names' : 'name'));896 stderr("Use output.globals to specify browser global variable names corresponding to external modules");897 warnings.forEach(function (warning) {898 stderr(turbocolor_1.bold(warning.source) + " (guessing '" + warning.guess + "')");899 });900 }901 },902 SOURCEMAP_BROKEN: {903 priority: 1,904 fn: function (warnings) {905 title("Broken sourcemap");906 info('https://github.com/rollup/rollup/wiki/Troubleshooting#sourcemap-is-likely-to-be-incorrect');907 var plugins = Array.from(new Set(warnings.map(function (w) { return w.plugin; }).filter(Boolean)));908 var detail = plugins.length === 0909 ? ''910 : plugins.length > 1911 ? " (such as " + plugins912 .slice(0, -1)913 .map(function (p) { return "'" + p + "'"; })914 .join(', ') + " and '" + plugins.slice(-1) + "')"915 : " (such as '" + plugins[0] + "')";916 stderr("Plugins that transform code" + detail + " should generate accompanying sourcemaps");917 }918 },919 PLUGIN_WARNING: {920 priority: 1,921 fn: function (warnings) {922 var nestedByPlugin = nest(warnings, 'plugin');923 nestedByPlugin.forEach(function (_a) {924 var plugin = _a.key, items = _a.items;925 var nestedByMessage = nest(items, 'message');926 var lastUrl;927 nestedByMessage.forEach(function (_a) {928 var message = _a.key, items = _a.items;929 title(plugin + " plugin: " + message);930 items.forEach(function (warning) {931 if (warning.url !== lastUrl)932 info((lastUrl = warning.url));933 var loc = warning.loc934 ? relativeId(warning.id) + ": (" + warning.loc.line + ":" + warning.loc.column + ")"935 : relativeId(warning.id);936 stderr(turbocolor_1.bold(relativeId(loc)));937 if (warning.frame)938 info(warning.frame);939 });940 });941 });942 }943 }944};945function title(str) {946 stderr(turbocolor_1.bold.yellow('(!)') + " " + turbocolor_1.bold.yellow(str));947}948function info(url) {949 stderr(turbocolor_1.gray(url));950}951function nest(array, prop) {952 var nested = [];953 var lookup = new Map();954 array.forEach(function (item) {955 var key = item[prop];956 if (!lookup.has(key)) {957 lookup.set(key, {958 key: key,959 items: []960 });961 nested.push(lookup.get(key));962 }963 lookup.get(key).items.push(item);964 });965 return nested;966}967function showTruncatedWarnings(warnings) {968 var nestedByModule = nest(warnings, 'id');969 var sliced = nestedByModule.length > 5 ? nestedByModule.slice(0, 3) : nestedByModule;970 sliced.forEach(function (_a) {971 var id = _a.key, items = _a.items;972 stderr(turbocolor_1.bold(relativeId(id)));973 stderr(turbocolor_1.gray(items[0].frame));974 if (items.length > 1) {975 stderr("...and " + (items.length - 1) + " other " + (items.length > 2 ? 'occurrences' : 'occurrence'));976 }977 });978 if (nestedByModule.length > sliced.length) {979 stderr("\n...and " + (nestedByModule.length - sliced.length) + " other files");980 }981}982var parseMs = function (ms) {983 if (typeof ms !== 'number') {984 throw new TypeError('Expected a number');985 }986 var roundTowardZero = ms > 0 ? Math.floor : Math.ceil;987 return {988 days: roundTowardZero(ms / 86400000),989 hours: roundTowardZero(ms / 3600000) % 24,990 minutes: roundTowardZero(ms / 60000) % 60,991 seconds: roundTowardZero(ms / 1000) % 60,992 milliseconds: roundTowardZero(ms) % 1000993 };994};995const plur = (word, count) => count === 1 ? word : word + 's';996var prettyMs = (ms, opts) => {997 if (!Number.isFinite(ms)) {998 throw new TypeError('Expected a finite number');999 }1000 opts = opts || {};1001 if (ms < 1000) {1002 const msDecimalDigits = typeof opts.msDecimalDigits === 'number' ? opts.msDecimalDigits : 0;1003 return (msDecimalDigits ? ms.toFixed(msDecimalDigits) : Math.ceil(ms)) + (opts.verbose ? ' ' + plur('millisecond', Math.ceil(ms)) : 'ms');1004 }1005 const ret = [];1006 const add = (val, long, short, valStr) => {1007 if (val === 0) {1008 return;1009 }1010 const postfix = opts.verbose ? ' ' + plur(long, val) : short;1011 ret.push((valStr || val) + postfix);1012 };1013 const parsed = parseMs(ms);1014 add(Math.trunc(parsed.days / 365), 'year', 'y');1015 add(parsed.days % 365, 'day', 'd');1016 add(parsed.hours, 'hour', 'h');1017 add(parsed.minutes, 'minute', 'm');1018 if (opts.compact) {1019 add(parsed.seconds, 'second', 's');1020 return '~' + ret[0];1021 }1022 const sec = ms / 1000 % 60;1023 const secDecimalDigits = typeof opts.secDecimalDigits === 'number' ? opts.secDecimalDigits : 1;1024 const secFixed = sec.toFixed(secDecimalDigits);1025 const secStr = opts.keepDecimalsOnWholeSeconds ? secFixed : secFixed.replace(/\.0+$/, '');1026 add(sec, 'second', 's', secStr);1027 return ret.join(' ');1028};1029function mapSequence(array, fn) {1030 var results = [];1031 var promise = Promise.resolve();1032 function next(member, i) {1033 return Promise.resolve(fn(member)).then(function (value) { return (results[i] = value); });1034 }1035 var _loop_1 = function (i) {1036 promise = promise.then(function () { return next(array[i], i); });1037 };1038 for (var i = 0; i < array.length; i += 1) {1039 _loop_1(i);1040 }1041 return promise.then(function () { return results; });1042}1043var SOURCEMAPPING_URL = 'sourceMa';1044SOURCEMAPPING_URL += 'ppingURL';1045var SOURCEMAPPING_URL$1 = SOURCEMAPPING_URL;1046function printTimings(timings) {1047 Object.keys(timings).forEach(function (label) {1048 var color = label[0] === '#' ? (label[1] !== '#' ? turbocolor_1.underline : turbocolor_1.bold) : function (text) { return text; };1049 console.info(color(label + ": " + timings[label].toFixed(0) + "ms"));1050 });1051}1052function build(inputOptions, outputOptions, warnings, silent) {1053 if (silent === void 0) { silent = false; }1054 var useStdout = outputOptions.length === 1 &&1055 !outputOptions[0].file &&1056 !outputOptions[0].dir &&1057 inputOptions.input instanceof Array === false &&1058 typeof inputOptions.input !== 'object';1059 var start = Date.now();1060 var files = useStdout ? ['stdout'] : outputOptions.map(function (t) { return relativeId(t.file || t.dir); });1061 if (!silent) {1062 var inputFiles = void 0;1063 if (typeof inputOptions.input === 'string') {1064 inputFiles = inputOptions.input;1065 }1066 else if (inputOptions.input instanceof Array) {1067 inputFiles = inputOptions.input.join(', ');1068 }1069 else if (typeof inputOptions.input === 'object' && inputOptions.input !== null) {1070 inputFiles = Object.keys(inputOptions.input)1071 .map(function (name) { return inputOptions.input[name]; })1072 .join(', ');1073 }1074 stderr(turbocolor_1.cyan("\n" + turbocolor_1.bold(inputFiles) + " \u2192 " + turbocolor_1.bold(files.join(', ')) + "..."));1075 }1076 return rollup.rollup(inputOptions)1077 .then(function (bundle) {1078 if (useStdout) {1079 var output_1 = outputOptions[0];1080 if (output_1.sourcemap && output_1.sourcemap !== 'inline') {1081 handleError({1082 code: 'MISSING_OUTPUT_OPTION',1083 message: 'You must specify a --file (-o) option when creating a file with a sourcemap'1084 });1085 }1086 return bundle.generate(output_1).then(function (_a) {1087 var code = _a.code, map = _a.map;1088 if (!code)1089 return;1090 if (output_1.sourcemap === 'inline') {1091 code += "\n//# " + SOURCEMAPPING_URL$1 + "=" + map.toUrl() + "\n";1092 }1093 process.stdout.write(code);1094 });1095 }1096 return mapSequence(outputOptions, function (output) { return bundle.write(output); }).then(function () { return bundle; });1097 })1098 .then(function (bundle) {1099 warnings.flush();1100 if (!silent)1101 stderr(turbocolor_1.green("created " + turbocolor_1.bold(files.join(', ')) + " in " + turbocolor_1.bold(prettyMs(Date.now() - start))));1102 if (bundle && bundle.getTimings) {1103 printTimings(bundle.getTimings());1104 }1105 })1106 .catch(handleError);1107}1108function loadConfigFile(configFile, commandOptions) {1109 if (commandOptions === void 0) { commandOptions = {}; }1110 var silent = commandOptions.silent || false;1111 var warnings = batchWarnings();1112 return rollup__default1113 .rollup({1114 input: configFile,1115 external: function (id) {1116 return (id[0] !== '.' && !path__default.isAbsolute(id)) || id.slice(-5, id.length) === '.json';1117 },1118 onwarn: warnings.add1119 })1120 .then(function (bundle) {1121 if (!silent && warnings.count > 0) {1122 stderr(turbocolor_1.bold("loaded " + relativeId(configFile) + " with warnings"));1123 warnings.flush();1124 }1125 return bundle.generate({1126 format: 'cjs'1127 });1128 })1129 .then(function (_a) {1130 var code = _a.code;1131 // temporarily override require1132 var defaultLoader = require.extensions['.js'];1133 require.extensions['.js'] = function (module, filename) {1134 if (filename === configFile) {1135 module._compile(code, filename);1136 }1137 else {1138 defaultLoader(module, filename);1139 }1140 };1141 delete require.cache[configFile];1142 return Promise.resolve(require(configFile))1143 .then(function (configFileContent) {1144 if (typeof configFileContent === 'function') {1145 return configFileContent(commandOptions);1146 }1147 return configFileContent;1148 })1149 .then(function (configs) {1150 if (Object.keys(configs).length === 0) {1151 handleError({1152 code: 'MISSING_CONFIG',1153 message: 'Config file must export an options object, or an array of options objects',1154 url: 'https://rollupjs.org/#using-config-files'1155 });1156 }1157 require.extensions['.js'] = defaultLoader;1158 return Array.isArray(configs) ? configs : [configs];1159 });1160 });1161}1162var timeZone = date => {1163 const offset = (date || new Date()).getTimezoneOffset();1164 const absOffset = Math.abs(offset);1165 const hours = Math.floor(absOffset / 60);1166 const minutes = absOffset % 60;1167 const minutesOut = minutes > 0 ? ':' + ('0' + minutes).slice(-2) : '';1168 return (offset < 0 ? '+' : '-') + hours + minutesOut;1169};1170var dateTime = options => {1171 options = Object.assign({1172 date: new Date(),1173 local: true,1174 showTimeZone: false,1175 showMilliseconds: false1176 }, options);1177 let date = options.date;1178 if (options.local) {1179 // Offset the date so it will return the correct value when getting the ISO string1180 date = new Date(date.getTime() - (date.getTimezoneOffset() * 60000));1181 }1182 let end = '';1183 if (options.showTimeZone) {1184 end = ' UTC' + (options.local ? timeZone(date) : '');1185 }1186 if (options.showMilliseconds && date.getUTCMilliseconds() > 0) {1187 end = ` ${date.getUTCMilliseconds()}ms${end}`;1188 }1189 return date1190 .toISOString()1191 .replace(/T/, ' ')1192 .replace(/\..+/, end);1193};1194function createCommonjsModule(fn, module) {1195 return module = { exports: {} }, fn(module, module.exports), module.exports;1196}1197var signals = createCommonjsModule(function (module) {1198// This is not the set of all possible signals.1199//1200// It IS, however, the set of all signals that trigger1201// an exit on either Linux or BSD systems. Linux is a1202// superset of the signal names supported on BSD, and1203// the unknown signals just fail to register, so we can1204// catch that easily enough.1205//1206// Don't bother with SIGKILL. It's uncatchable, which1207// means that we can't fire any callbacks anyway.1208//1209// If a user does happen to register a handler on a non-1210// fatal signal like SIGWINCH or something, and then1211// exit, it'll end up firing `process.emit('exit')`, so1212// the handler will be fired anyway.1213//1214// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised1215// artificially, inherently leave the process in a1216// state from which it is not safe to try and enter JS1217// listeners.1218module.exports = [1219 'SIGABRT',1220 'SIGALRM',1221 'SIGHUP',1222 'SIGINT',1223 'SIGTERM'1224];1225if (process.platform !== 'win32') {1226 module.exports.push(1227 'SIGVTALRM',1228 'SIGXCPU',1229 'SIGXFSZ',1230 'SIGUSR2',1231 'SIGTRAP',1232 'SIGSYS',1233 'SIGQUIT',1234 'SIGIOT'1235 // should detect profiler and enable/disable accordingly.1236 // see #211237 // 'SIGPROF'1238 );1239}1240if (process.platform === 'linux') {1241 module.exports.push(1242 'SIGIO',1243 'SIGPOLL',1244 'SIGPWR',1245 'SIGSTKFLT',1246 'SIGUNUSED'1247 );1248}1249});1250// Note: since nyc uses this module to output coverage, any lines1251// that are in the direct sync flow of nyc's outputCoverage are1252// ignored, since we can never get coverage for them.1253var signals$1 = signals;1254var EE = events;1255/* istanbul ignore if */1256if (typeof EE !== 'function') {1257 EE = EE.EventEmitter;1258}1259var emitter;1260if (process.__signal_exit_emitter__) {1261 emitter = process.__signal_exit_emitter__;1262} else {1263 emitter = process.__signal_exit_emitter__ = new EE();1264 emitter.count = 0;1265 emitter.emitted = {};1266}1267// Because this emitter is a global, we have to check to see if a1268// previous version of this library failed to enable infinite listeners.1269// I know what you're about to say. But literally everything about1270// signal-exit is a compromise with evil. Get used to it.1271if (!emitter.infinite) {1272 emitter.setMaxListeners(Infinity);1273 emitter.infinite = true;1274}1275var signalExit = function (cb, opts) {1276 assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');1277 if (loaded === false) {1278 load();1279 }1280 var ev = 'exit';1281 if (opts && opts.alwaysLast) {1282 ev = 'afterexit';1283 }1284 var remove = function () {1285 emitter.removeListener(ev, cb);1286 if (emitter.listeners('exit').length === 0 &&1287 emitter.listeners('afterexit').length === 0) {1288 unload();1289 }1290 };1291 emitter.on(ev, cb);1292 return remove1293};1294var unload_1 = unload;1295function unload () {1296 if (!loaded) {1297 return1298 }1299 loaded = false;1300 signals$1.forEach(function (sig) {1301 try {1302 process.removeListener(sig, sigListeners[sig]);1303 } catch (er) {}1304 });1305 process.emit = originalProcessEmit;1306 process.reallyExit = originalProcessReallyExit;1307 emitter.count -= 1;1308}1309function emit (event, code, signal) {1310 if (emitter.emitted[event]) {1311 return1312 }1313 emitter.emitted[event] = true;1314 emitter.emit(event, code, signal);1315}1316// { <signal>: <listener fn>, ... }1317var sigListeners = {};1318signals$1.forEach(function (sig) {1319 sigListeners[sig] = function listener () {1320 // If there are no other listeners, an exit is coming!1321 // Simplest way: remove us and then re-send the signal.1322 // We know that this will kill the process, so we can1323 // safely emit now.1324 var listeners = process.listeners(sig);1325 if (listeners.length === emitter.count) {1326 unload();1327 emit('exit', null, sig);1328 /* istanbul ignore next */1329 emit('afterexit', null, sig);1330 /* istanbul ignore next */1331 process.kill(process.pid, sig);1332 }1333 };1334});1335var signals_1 = function () {1336 return signals$11337};1338var load_1 = load;1339var loaded = false;1340function load () {1341 if (loaded) {1342 return1343 }1344 loaded = true;1345 // This is the number of onSignalExit's that are in play.1346 // It's important so that we can count the correct number of1347 // listeners on signals, and don't wait for the other one to1348 // handle it instead of us.1349 emitter.count += 1;1350 signals$1 = signals$1.filter(function (sig) {1351 try {1352 process.on(sig, sigListeners[sig]);1353 return true1354 } catch (er) {1355 return false1356 }1357 });1358 process.emit = processEmit;1359 process.reallyExit = processReallyExit;1360}1361var originalProcessReallyExit = process.reallyExit;1362function processReallyExit (code) {1363 process.exitCode = code || 0;1364 emit('exit', process.exitCode, null);1365 /* istanbul ignore next */1366 emit('afterexit', process.exitCode, null);1367 /* istanbul ignore next */1368 originalProcessReallyExit.call(process, process.exitCode);1369}1370var originalProcessEmit = process.emit;1371function processEmit (ev, arg) {1372 if (ev === 'exit') {1373 if (arg !== undefined) {1374 process.exitCode = arg;1375 }1376 var ret = originalProcessEmit.apply(this, arguments);1377 emit('exit', process.exitCode, null);1378 /* istanbul ignore next */1379 emit('afterexit', process.exitCode, null);1380 return ret1381 } else {1382 return originalProcessEmit.apply(this, arguments)1383 }1384}1385signalExit.unload = unload_1;1386signalExit.signals = signals_1;1387signalExit.load = load_1;1388var ansiEscapes = createCommonjsModule(function (module) {1389const x = module.exports;1390const ESC = '\u001B[';1391const OSC = '\u001B]';1392const BEL = '\u0007';1393const SEP = ';';1394const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal';1395x.cursorTo = (x, y) => {1396 if (typeof x !== 'number') {1397 throw new TypeError('The `x` argument is required');1398 }1399 if (typeof y !== 'number') {1400 return ESC + (x + 1) + 'G';1401 }1402 return ESC + (y + 1) + ';' + (x + 1) + 'H';1403};1404x.cursorMove = (x, y) => {1405 if (typeof x !== 'number') {1406 throw new TypeError('The `x` argument is required');1407 }1408 let ret = '';1409 if (x < 0) {1410 ret += ESC + (-x) + 'D';1411 } else if (x > 0) {1412 ret += ESC + x + 'C';1413 }1414 if (y < 0) {1415 ret += ESC + (-y) + 'A';1416 } else if (y > 0) {1417 ret += ESC + y + 'B';1418 }1419 return ret;1420};1421x.cursorUp = count => ESC + (typeof count === 'number' ? count : 1) + 'A';1422x.cursorDown = count => ESC + (typeof count === 'number' ? count : 1) + 'B';1423x.cursorForward = count => ESC + (typeof count === 'number' ? count : 1) + 'C';1424x.cursorBackward = count => ESC + (typeof count === 'number' ? count : 1) + 'D';1425x.cursorLeft = ESC + 'G';1426x.cursorSavePosition = ESC + (isTerminalApp ? '7' : 's');1427x.cursorRestorePosition = ESC + (isTerminalApp ? '8' : 'u');1428x.cursorGetPosition = ESC + '6n';1429x.cursorNextLine = ESC + 'E';1430x.cursorPrevLine = ESC + 'F';1431x.cursorHide = ESC + '?25l';1432x.cursorShow = ESC + '?25h';1433x.eraseLines = count => {1434 let clear = '';1435 for (let i = 0; i < count; i++) {1436 clear += x.eraseLine + (i < count - 1 ? x.cursorUp() : '');1437 }1438 if (count) {1439 clear += x.cursorLeft;1440 }1441 return clear;1442};1443x.eraseEndLine = ESC + 'K';1444x.eraseStartLine = ESC + '1K';1445x.eraseLine = ESC + '2K';1446x.eraseDown = ESC + 'J';1447x.eraseUp = ESC + '1J';1448x.eraseScreen = ESC + '2J';1449x.scrollUp = ESC + 'S';1450x.scrollDown = ESC + 'T';1451x.clearScreen = '\u001Bc';1452x.beep = BEL;1453x.link = (text, url) => {1454 return [1455 OSC,1456 '8',1457 SEP,1458 SEP,1459 url,1460 BEL,1461 text,1462 OSC,1463 '8',1464 SEP,1465 SEP,1466 BEL1467 ].join('');1468};1469x.image = (buf, opts) => {1470 opts = opts || {};1471 let ret = OSC + '1337;File=inline=1';1472 if (opts.width) {1473 ret += `;width=${opts.width}`;1474 }1475 if (opts.height) {1476 ret += `;height=${opts.height}`;1477 }1478 if (opts.preserveAspectRatio === false) {1479 ret += ';preserveAspectRatio=0';1480 }1481 return ret + ':' + buf.toString('base64') + BEL;1482};1483x.iTerm = {};1484x.iTerm.setCwd = cwd => OSC + '50;CurrentDir=' + (cwd || process.cwd()) + BEL;1485});1486var SHOW_ALTERNATE_SCREEN = '\u001B[?1049h';1487var HIDE_ALTERNATE_SCREEN = '\u001B[?1049l';1488var isWindows = process.platform === 'win32';1489var isMintty = isWindows && !!(process.env.SHELL || process.env.TERM);1490var isConEmuAnsiOn = (process.env.ConEmuANSI || '').toLowerCase() === 'on';1491var supportsAnsi = !isWindows || isMintty || isConEmuAnsiOn;1492function alternateScreen(enabled) {1493 if (!enabled) {1494 var needAnnounce_1 = true;1495 return {1496 open: function () { },1497 close: function () { },1498 reset: function (heading) {1499 if (needAnnounce_1) {1500 stderr(heading);1501 needAnnounce_1 = false;1502 }1503 }1504 };1505 }1506 return {1507 open: function () {1508 if (supportsAnsi) {1509 process.stderr.write(SHOW_ALTERNATE_SCREEN);1510 }1511 },1512 close: function () {1513 if (supportsAnsi) {1514 process.stderr.write(HIDE_ALTERNATE_SCREEN);1515 }1516 },1517 reset: function (heading) {1518 stderr("" + ansiEscapes.eraseScreen + ansiEscapes.cursorTo(0, 0) + heading);1519 }1520 };1521}1522function watch(configFile, configs, command, silent) {1523 if (silent === void 0) { silent = false; }1524 var isTTY = Boolean(process.stderr.isTTY);1525 var warnings = batchWarnings();1526 var initialConfigs = processConfigs(configs);1527 var clearScreen = initialConfigs.every(function (config) { return config.watch.clearScreen !== false; });1528 var screen = alternateScreen(isTTY && clearScreen);1529 screen.open();1530 var watcher;1531 var configWatcher;1532 var processConfigsErr;1533 function processConfigs(configs) {1534 return configs.map(function (options) {1535 var merged = mergeOptions({1536 config: options,1537 command: command,1538 defaultOnWarnHandler: warnings.add1539 });1540 var result = __assign({}, merged.inputOptions, { output: merged.outputOptions });1541 if (!result.watch)1542 result.watch = {};1543 if (merged.deprecations.length) {1544 result.watch._deprecations = merged.deprecations;1545 }1546 if (merged.optionError)1547 merged.inputOptions.onwarn({1548 message: merged.optionError,1549 code: 'UNKNOWN_OPTION'1550 });1551 if (merged.inputOptions.watch &&1552 merged.inputOptions.watch.clearScreen === false) {1553 processConfigsErr = stderr;1554 }1555 return result;1556 });1557 }1558 function start(configs) {1559 var screenWriter = processConfigsErr || screen.reset;1560 watcher = rollup.watch(configs);1561 watcher.on('event', function (event) {1562 switch (event.code) {1563 case 'FATAL':1564 screen.close();1565 handleError(event.error, true);1566 process.exit(1);1567 break;1568 case 'ERROR':1569 warnings.flush();1570 handleError(event.error, true);1571 break;1572 case 'START':1573 screenWriter(turbocolor_1.underline("rollup v" + rollup.VERSION));1574 break;1575 case 'BUNDLE_START':1576 if (!silent) {1577 var input_1 = event.input;1578 if (typeof input_1 !== 'string') {1579 input_1 = Array.isArray(input_1)1580 ? input_1.join(', ')1581 : Object.keys(input_1)1582 .map(function (key) { return input_1[key]; })1583 .join(', ');1584 }1585 stderr(turbocolor_1.cyan("bundles " + turbocolor_1.bold(input_1) + " \u2192 " + turbocolor_1.bold(event.output.map(relativeId).join(', ')) + "..."));1586 }1587 break;1588 case 'BUNDLE_END':1589 warnings.flush();1590 if (!silent)1591 stderr(turbocolor_1.green("created " + turbocolor_1.bold(event.output.map(relativeId).join(', ')) + " in " + turbocolor_1.bold(prettyMs(event.duration))));1592 if (event.result && event.result.getTimings) {1593 printTimings(event.result.getTimings());1594 }1595 break;1596 case 'END':1597 if (!silent && isTTY) {1598 stderr("\n[" + dateTime() + "] waiting for changes...");1599 }1600 }1601 });1602 }1603 // catch ctrl+c, kill, and uncaught errors1604 var removeOnExit = signalExit(close);1605 process.on('uncaughtException', close);1606 // only listen to stdin if it is a pipe1607 if (!process.stdin.isTTY) {1608 process.stdin.on('end', close); // in case we ever support stdin!1609 process.stdin.resume();1610 }1611 function close(err) {1612 removeOnExit();1613 process.removeListener('uncaughtException', close);1614 // removing a non-existent listener is a no-op1615 process.stdin.removeListener('end', close);1616 screen.close();1617 if (watcher)1618 watcher.close();1619 if (configWatcher)1620 configWatcher.close();1621 if (err) {1622 console.error(err);1623 process.exit(1);1624 }1625 }1626 try {1627 start(initialConfigs);1628 }1629 catch (err) {1630 close(err);1631 return;1632 }1633 if (configFile && !configFile.startsWith('node:')) {1634 var restarting_1 = false;1635 var aborted_1 = false;1636 var configFileData_1 = fs__default.readFileSync(configFile, 'utf-8');1637 var restart_1 = function () {1638 var newConfigFileData = fs__default.readFileSync(configFile, 'utf-8');1639 if (newConfigFileData === configFileData_1)1640 return;1641 configFileData_1 = newConfigFileData;1642 if (restarting_1) {1643 aborted_1 = true;1644 return;1645 }1646 restarting_1 = true;1647 loadConfigFile(configFile, command)1648 .then(function (_configs) {1649 restarting_1 = false;1650 if (aborted_1) {1651 aborted_1 = false;1652 restart_1();1653 }1654 else {1655 watcher.close();1656 start(initialConfigs);1657 }1658 })1659 .catch(function (err) {1660 handleError(err, true);1661 });1662 };1663 configWatcher = fs__default.watch(configFile, function (event) {1664 if (event === 'change')1665 restart_1();1666 });1667 }1668}1669function runRollup(command) {1670 if (command._.length >= 1) {1671 if (command.input) {1672 handleError({1673 code: 'DUPLICATE_IMPORT_OPTIONS',1674 message: 'use --input, or pass input path as argument'1675 });1676 }1677 }1678 if (command.dir) {1679 if (command._.length && !command._.some(function (input) { return input.indexOf('=') !== -1; })) {1680 command.input = command._;1681 }1682 else if (command._.length ||1683 Array.isArray(command.input) ||1684 typeof command.input === 'string') {1685 var input = void 0;1686 if (command._.length)1687 input = command._;1688 else1689 input = typeof command.input === 'string' ? [command.input] : command.input;1690 command.input = {};1691 input.forEach(function (input) {1692 var equalsIndex = input.indexOf('=');1693 var value = input.substr(equalsIndex + 1);1694 var key = input.substr(0, equalsIndex);1695 if (!key)1696 key = getAliasName(input);1697 command.input[key] = value;1698 });1699 }1700 command._ = [];1701 }1702 else if (command._.length === 1) {1703 command.input = command._[0];1704 }1705 if (command.environment) {1706 var environment = Array.isArray(command.environment)1707 ? command.environment1708 : [command.environment];1709 environment.forEach(function (arg) {1710 arg.split(',').forEach(function (pair) {1711 var _a = pair.split(':'), key = _a[0], value = _a[1];1712 if (value) {1713 process.env[key] = value;1714 }1715 else {1716 process.env[key] = String(true);1717 }1718 });1719 });1720 }1721 var configFile = command.config === true ? 'rollup.config.js' : command.config;1722 if (configFile) {1723 if (configFile.slice(0, 5) === 'node:') {1724 var pkgName = configFile.slice(5);1725 try {1726 configFile = requireRelative_1.resolve("rollup-config-" + pkgName, process.cwd());1727 }1728 catch (err) {1729 try {1730 configFile = requireRelative_1.resolve(pkgName, process.cwd());1731 }1732 catch (err) {1733 if (err.code === 'MODULE_NOT_FOUND') {1734 handleError({1735 code: 'MISSING_EXTERNAL_CONFIG',1736 message: "Could not resolve config file " + configFile1737 });1738 }1739 throw err;1740 }1741 }1742 }1743 else {1744 // find real path of config so it matches what Node provides to callbacks in require.extensions1745 configFile = fs.realpathSync(configFile);1746 }1747 if (command.watch)1748 process.env.ROLLUP_WATCH = 'true';1749 loadConfigFile(configFile, command)1750 .then(function (configs) { return execute(configFile, configs, command); })1751 .catch(handleError);1752 }1753 else {1754 return execute(configFile, [{ input: null }], command);1755 }1756}1757function execute(configFile, configs, command) {1758 if (command.watch) {1759 watch(configFile, configs, command, command.silent);1760 }1761 else {1762 return sequence(configs, function (config) {1763 var warnings = batchWarnings();1764 var _a = mergeOptions({1765 config: config,1766 command: command,1767 defaultOnWarnHandler: warnings.add1768 }), inputOptions = _a.inputOptions, outputOptions = _a.outputOptions, deprecations = _a.deprecations, optionError = _a.optionError;1769 if (deprecations.length) {1770 inputOptions.onwarn({1771 code: 'DEPRECATED_OPTIONS',1772 message: "The following options have been renamed \u2014 please update your config: " + deprecations1773 .map(function (option) { return option.old + " -> " + option.new; })1774 .join(', '),1775 deprecations: deprecations1776 });1777 }1778 if (optionError)1779 inputOptions.onwarn({ code: 'UNKNOWN_OPTION', message: optionError });1780 return build(inputOptions, outputOptions, warnings, command.silent);1781 });1782 }1783}1784var command = minimist(process.argv.slice(2), {1785 alias: commandAliases1786});1787if (command.help || (process.argv.length <= 2 && process.stdin.isTTY)) {1788 console.log("\n" + help.replace('__VERSION__', version) + "\n"); // eslint-disable-line no-console1789}1790else if (command.version) {1791 console.log("rollup version " + version); // eslint-disable-line no-console1792}1793else {1794 try {1795 require('source-map-support').install();1796 }1797 catch (err) {1798 // do nothing1799 }1800 runRollup(command);...
1930879d1fea18135b2d139714f8f3f1f41ef063.svn-base
Source:1930879d1fea18135b2d139714f8f3f1f41ef063.svn-base
1#!/usr/bin/env node2'use strict';3function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }4var fs = require('fs');5var fs__default = _interopDefault(fs);6var path = require('path');7var path__default = _interopDefault(path);8var module$1 = _interopDefault(require('module'));9var rollup = require('../dist/rollup.js');10var rollup__default = _interopDefault(rollup);11var assert = _interopDefault(require('assert'));12var events = _interopDefault(require('events'));13var help = "rollup version __VERSION__\n=====================================\n\nUsage: rollup [options] <entry file>\n\nBasic options:\n\n-c, --config <filename> Use this config file (if argument is used but value\n is unspecified, defaults to rollup.config.js)\n-d, --dir <dirname> Directory for chunks (if absent, prints to stdout)\n-e, --external <ids> Comma-separate list of module IDs to exclude\n-f, --format <format> Type of output (amd, cjs, esm, iife, umd)\n-g, --globals <pairs> Comma-separate list of `moduleID:Global` pairs\n-h, --help Show this help message\n-i, --input <filename> Input (alternative to <entry file>)\n-m, --sourcemap Generate sourcemap (`-m inline` for inline map)\n-n, --name <name> Name for UMD export\n-o, --file <output> Single output file (if absent, prints to stdout)\n-v, --version Show version number\n-w, --watch Watch files in bundle and rebuild on changes\n--amd.id <id> ID for AMD module (default is anonymous)\n--amd.define <name> Function to use in place of `define`\n--assetFileNames <pattern> Name pattern for emitted assets\n--banner <text> Code to insert at top of bundle (outside wrapper)\n--chunkFileNames <pattern> Name pattern for emitted secondary chunks\n--compact Minify wrapper code\n--context <variable> Specify top-level `this` value\n--dynamicImportFunction <name> Rename the dynamic `import()` function\n--entryFileNames <pattern> Name pattern for emitted entry chunks\n--environment <values> Settings passed to config file (see example)\n--no-esModule Do not add __esModule property\n--exports <mode> Specify export mode (auto, default, named, none)\n--extend Extend global variable defined by --name\n--footer <text> Code to insert at end of bundle (outside wrapper)\n--no-freeze Do not freeze namespace objects\n--no-indent Don't indent result\n--no-interop Do not include interop block\n--inlineDynamicImports Create single bundle when using dynamic imports\n--intro <text> Code to insert at top of bundle (inside wrapper)\n--namespaceToStringTag Create proper `.toString` methods for namespaces\n--noConflict Generate a noConflict method for UMD globals\n--no-strict Don't emit `\"use strict\";` in the generated modules\n--outro <text> Code to insert at end of bundle (inside wrapper)\n--preferConst Use `const` instead of `var` for exports\n--preserveModules Preserve module structure\n--preserveSymlinks Do not follow symlinks when resolving files\n--shimMissingExports Create shim variables for missing exports\n--silent Don't print warnings\n--sourcemapExcludeSources Do not include source code in source maps\n--sourcemapFile <file> Specify bundle position for source maps\n--no-treeshake Disable tree-shaking optimisations\n--no-treeshake.annotations Ignore pure call annotations\n--no-treeshake.propertyReadSideEffects Ignore property access side-effects\n--treeshake.pureExternalModules Assume side-effect free externals\n\nExamples:\n\n# use settings in config file\nrollup -c\n\n# in config file, process.env.INCLUDE_DEPS === 'true'\n# and process.env.BUILD === 'production'\nrollup -c --environment INCLUDE_DEPS,BUILD:production\n\n# create CommonJS bundle.js from src/main.js\nrollup --format=cjs --file=bundle.js -- src/main.js\n\n# create self-executing IIFE using `window.jQuery`\n# and `window._` as external globals\nrollup -f iife --globals jquery:jQuery,lodash:_ \\\n -i src/app.js -o build/app.js -m build/app.js.map\n\nNotes:\n\n* When piping to stdout, only inline sourcemaps are permitted\n\nFor more information visit https://rollupjs.org\n";14var minimist = function (args, opts) {15 if (!opts) opts = {};16 17 var flags = { bools : {}, strings : {}, unknownFn: null };18 if (typeof opts['unknown'] === 'function') {19 flags.unknownFn = opts['unknown'];20 }21 if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {22 flags.allBools = true;23 } else {24 [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {25 flags.bools[key] = true;26 });27 }28 29 var aliases = {};30 Object.keys(opts.alias || {}).forEach(function (key) {31 aliases[key] = [].concat(opts.alias[key]);32 aliases[key].forEach(function (x) {33 aliases[x] = [key].concat(aliases[key].filter(function (y) {34 return x !== y;35 }));36 });37 });38 [].concat(opts.string).filter(Boolean).forEach(function (key) {39 flags.strings[key] = true;40 if (aliases[key]) {41 flags.strings[aliases[key]] = true;42 }43 });44 var defaults = opts['default'] || {};45 46 var argv = { _ : [] };47 Object.keys(flags.bools).forEach(function (key) {48 setArg(key, defaults[key] === undefined ? false : defaults[key]);49 });50 51 var notFlags = [];52 if (args.indexOf('--') !== -1) {53 notFlags = args.slice(args.indexOf('--')+1);54 args = args.slice(0, args.indexOf('--'));55 }56 function argDefined(key, arg) {57 return (flags.allBools && /^--[^=]+$/.test(arg)) ||58 flags.strings[key] || flags.bools[key] || aliases[key];59 }60 function setArg (key, val, arg) {61 if (arg && flags.unknownFn && !argDefined(key, arg)) {62 if (flags.unknownFn(arg) === false) return;63 }64 var value = !flags.strings[key] && isNumber(val)65 ? Number(val) : val66 ;67 setKey(argv, key.split('.'), value);68 69 (aliases[key] || []).forEach(function (x) {70 setKey(argv, x.split('.'), value);71 });72 }73 function setKey (obj, keys, value) {74 var o = obj;75 keys.slice(0,-1).forEach(function (key) {76 if (o[key] === undefined) o[key] = {};77 o = o[key];78 });79 var key = keys[keys.length - 1];80 if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {81 o[key] = value;82 }83 else if (Array.isArray(o[key])) {84 o[key].push(value);85 }86 else {87 o[key] = [ o[key], value ];88 }89 }90 91 function aliasIsBoolean(key) {92 return aliases[key].some(function (x) {93 return flags.bools[x];94 });95 }96 for (var i = 0; i < args.length; i++) {97 var arg = args[i];98 99 if (/^--.+=/.test(arg)) {100 // Using [\s\S] instead of . because js doesn't support the101 // 'dotall' regex modifier. See:102 // http://stackoverflow.com/a/1068308/13216103 var m = arg.match(/^--([^=]+)=([\s\S]*)$/);104 var key = m[1];105 var value = m[2];106 if (flags.bools[key]) {107 value = value !== 'false';108 }109 setArg(key, value, arg);110 }111 else if (/^--no-.+/.test(arg)) {112 var key = arg.match(/^--no-(.+)/)[1];113 setArg(key, false, arg);114 }115 else if (/^--.+/.test(arg)) {116 var key = arg.match(/^--(.+)/)[1];117 var next = args[i + 1];118 if (next !== undefined && !/^-/.test(next)119 && !flags.bools[key]120 && !flags.allBools121 && (aliases[key] ? !aliasIsBoolean(key) : true)) {122 setArg(key, next, arg);123 i++;124 }125 else if (/^(true|false)$/.test(next)) {126 setArg(key, next === 'true', arg);127 i++;128 }129 else {130 setArg(key, flags.strings[key] ? '' : true, arg);131 }132 }133 else if (/^-[^-]+/.test(arg)) {134 var letters = arg.slice(1,-1).split('');135 136 var broken = false;137 for (var j = 0; j < letters.length; j++) {138 var next = arg.slice(j+2);139 140 if (next === '-') {141 setArg(letters[j], next, arg);142 continue;143 }144 145 if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {146 setArg(letters[j], next.split('=')[1], arg);147 broken = true;148 break;149 }150 151 if (/[A-Za-z]/.test(letters[j])152 && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {153 setArg(letters[j], next, arg);154 broken = true;155 break;156 }157 158 if (letters[j+1] && letters[j+1].match(/\W/)) {159 setArg(letters[j], arg.slice(j+2), arg);160 broken = true;161 break;162 }163 else {164 setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);165 }166 }167 168 var key = arg.slice(-1)[0];169 if (!broken && key !== '-') {170 if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])171 && !flags.bools[key]172 && (aliases[key] ? !aliasIsBoolean(key) : true)) {173 setArg(key, args[i+1], arg);174 i++;175 }176 else if (args[i+1] && /true|false/.test(args[i+1])) {177 setArg(key, args[i+1] === 'true', arg);178 i++;179 }180 else {181 setArg(key, flags.strings[key] ? '' : true, arg);182 }183 }184 }185 else {186 if (!flags.unknownFn || flags.unknownFn(arg) !== false) {187 argv._.push(188 flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)189 );190 }191 if (opts.stopEarly) {192 argv._.push.apply(argv._, args.slice(i + 1));193 break;194 }195 }196 }197 198 Object.keys(defaults).forEach(function (key) {199 if (!hasKey(argv, key.split('.'))) {200 setKey(argv, key.split('.'), defaults[key]);201 202 (aliases[key] || []).forEach(function (x) {203 setKey(argv, x.split('.'), defaults[key]);204 });205 }206 });207 208 if (opts['--']) {209 argv['--'] = new Array();210 notFlags.forEach(function(key) {211 argv['--'].push(key);212 });213 }214 else {215 notFlags.forEach(function(key) {216 argv._.push(key);217 });218 }219 return argv;220};221function hasKey (obj, keys) {222 var o = obj;223 keys.slice(0,-1).forEach(function (key) {224 o = (o[key] || {});225 });226 var key = keys[keys.length - 1];227 return key in o;228}229function isNumber (x) {230 if (typeof x === 'number') return true;231 if (/^0x[0-9a-f]+$/i.test(x)) return true;232 return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);233}234var version = "1.9.0";235/*! *****************************************************************************236Copyright (c) Microsoft Corporation. All rights reserved.237Licensed under the Apache License, Version 2.0 (the "License"); you may not use238this file except in compliance with the License. You may obtain a copy of the239License at http://www.apache.org/licenses/LICENSE-2.0240THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY241KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED242WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,243MERCHANTABLITY OR NON-INFRINGEMENT.244See the Apache Version 2.0 License for specific language governing permissions245and limitations under the License.246***************************************************************************** */247var __assign = function() {248 __assign = Object.assign || function __assign(t) {249 for (var s, i = 1, n = arguments.length; i < n; i++) {250 s = arguments[i];251 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];252 }253 return t;254 };255 return __assign.apply(this, arguments);256};257var createGetOption = function (config, command) { return function (name, defaultValue) {258 return command[name] !== undefined259 ? command[name]260 : config[name] !== undefined261 ? config[name]262 : defaultValue;263}; };264var normalizeObjectOptionValue = function (optionValue) {265 if (!optionValue) {266 return optionValue;267 }268 if (typeof optionValue !== 'object') {269 return {};270 }271 return optionValue;272};273var getObjectOption = function (config, command, name) {274 var commandOption = normalizeObjectOptionValue(command[name]);275 var configOption = normalizeObjectOptionValue(config[name]);276 if (commandOption !== undefined) {277 return commandOption && configOption ? __assign({}, configOption, commandOption) : commandOption;278 }279 return configOption;280};281var defaultOnWarn = function (warning) {282 if (typeof warning === 'string') {283 console.warn(warning); // eslint-disable-line no-console284 }285 else {286 console.warn(warning.message); // eslint-disable-line no-console287 }288};289var getOnWarn = function (config, command, defaultOnWarnHandler) {290 if (defaultOnWarnHandler === void 0) { defaultOnWarnHandler = defaultOnWarn; }291 return command.silent292 ? function () { }293 : config.onwarn294 ? function (warning) { return config.onwarn(warning, defaultOnWarnHandler); }295 : defaultOnWarnHandler;296};297var getExternal = function (config, command) {298 var configExternal = config.external;299 return typeof configExternal === 'function'300 ? function (id) {301 var rest = [];302 for (var _i = 1; _i < arguments.length; _i++) {303 rest[_i - 1] = arguments[_i];304 }305 return configExternal.apply(void 0, [id].concat(rest)) || command.external.indexOf(id) !== -1;306 }307 : (configExternal || []).concat(command.external);308};309var commandAliases = {310 c: 'config',311 d: 'dir',312 e: 'external',313 f: 'format',314 g: 'globals',315 h: 'help',316 i: 'input',317 m: 'sourcemap',318 n: 'name',319 o: 'file',320 v: 'version',321 w: 'watch'322};323function mergeOptions(_a) {324 var _b = _a.config, config = _b === void 0 ? {} : _b, _c = _a.command, rawCommandOptions = _c === void 0 ? {} : _c, defaultOnWarnHandler = _a.defaultOnWarnHandler;325 var command = getCommandOptions(rawCommandOptions);326 var inputOptions = getInputOptions(config, command, defaultOnWarnHandler);327 if (command.output) {328 Object.assign(command, command.output);329 }330 var output = config.output;331 var normalizedOutputOptions = Array.isArray(output) ? output : output ? [output] : [];332 if (normalizedOutputOptions.length === 0)333 normalizedOutputOptions.push({});334 var outputOptions = normalizedOutputOptions.map(function (singleOutputOptions) {335 return getOutputOptions(singleOutputOptions, command);336 });337 var unknownOptionErrors = [];338 var validInputOptions = Object.keys(inputOptions);339 addUnknownOptionErrors(unknownOptionErrors, Object.keys(config), validInputOptions, 'input option', /^output$/);340 var validOutputOptions = Object.keys(outputOptions[0]);341 addUnknownOptionErrors(unknownOptionErrors, outputOptions.reduce(function (allKeys, options) { return allKeys.concat(Object.keys(options)); }, []), validOutputOptions, 'output option');342 var validCliOutputOptions = validOutputOptions.filter(function (option) { return option !== 'sourcemapPathTransform'; });343 addUnknownOptionErrors(unknownOptionErrors, Object.keys(command), validInputOptions.concat(validCliOutputOptions, Object.keys(commandAliases), 'config', 'environment', 'silent'), 'CLI flag', /^_|output|(config.*)$/);344 return {345 inputOptions: inputOptions,346 optionError: unknownOptionErrors.length > 0 ? unknownOptionErrors.join('\n') : null,347 outputOptions: outputOptions348 };349}350function addUnknownOptionErrors(errors, options, validOptions, optionType, ignoredKeys) {351 if (ignoredKeys === void 0) { ignoredKeys = /$./; }352 var unknownOptions = options.filter(function (key) { return validOptions.indexOf(key) === -1 && !ignoredKeys.test(key); });353 if (unknownOptions.length > 0)354 errors.push("Unknown " + optionType + ": " + unknownOptions.join(', ') + ". Allowed options: " + validOptions.sort().join(', '));355}356function getCommandOptions(rawCommandOptions) {357 var command = __assign({}, rawCommandOptions);358 command.external = rawCommandOptions.external ? rawCommandOptions.external.split(',') : [];359 if (rawCommandOptions.globals) {360 command.globals = Object.create(null);361 rawCommandOptions.globals.split(',').forEach(function (str) {362 var names = str.split(':');363 command.globals[names[0]] = names[1];364 // Add missing Module IDs to external.365 if (command.external.indexOf(names[0]) === -1) {366 command.external.push(names[0]);367 }368 });369 }370 return command;371}372function getInputOptions(config, command, defaultOnWarnHandler) {373 if (command === void 0) { command = {}; }374 var getOption = createGetOption(config, command);375 var inputOptions = {376 acorn: config.acorn,377 acornInjectPlugins: config.acornInjectPlugins,378 cache: getOption('cache'),379 chunkGroupingSize: getOption('chunkGroupingSize', 5000),380 context: config.context,381 experimentalCacheExpiry: getOption('experimentalCacheExpiry', 10),382 experimentalOptimizeChunks: getOption('experimentalOptimizeChunks'),383 experimentalTopLevelAwait: getOption('experimentalTopLevelAwait'),384 external: getExternal(config, command),385 inlineDynamicImports: getOption('inlineDynamicImports', false),386 input: getOption('input'),387 manualChunks: getOption('manualChunks'),388 moduleContext: config.moduleContext,389 onwarn: getOnWarn(config, command, defaultOnWarnHandler),390 perf: getOption('perf', false),391 plugins: config.plugins,392 preserveModules: getOption('preserveModules'),393 preserveSymlinks: getOption('preserveSymlinks'),394 shimMissingExports: getOption('shimMissingExports'),395 treeshake: getObjectOption(config, command, 'treeshake'),396 watch: config.watch397 };398 // support rollup({ cache: prevBuildObject })399 if (inputOptions.cache && inputOptions.cache.cache)400 inputOptions.cache = inputOptions.cache.cache;401 return inputOptions;402}403function getOutputOptions(config, command) {404 if (command === void 0) { command = {}; }405 var getOption = createGetOption(config, command);406 var format = getOption('format');407 // Handle format aliases408 switch (format) {409 case 'esm':410 case 'module':411 format = 'es';412 break;413 case 'commonjs':414 format = 'cjs';415 }416 return {417 amd: __assign({}, config.amd, command.amd),418 assetFileNames: getOption('assetFileNames'),419 banner: getOption('banner'),420 chunkFileNames: getOption('chunkFileNames'),421 compact: getOption('compact', false),422 dir: getOption('dir'),423 dynamicImportFunction: getOption('dynamicImportFunction'),424 entryFileNames: getOption('entryFileNames'),425 esModule: getOption('esModule', true),426 exports: getOption('exports'),427 extend: getOption('extend'),428 file: getOption('file'),429 footer: getOption('footer'),430 format: format === 'esm' ? 'es' : format,431 freeze: getOption('freeze', true),432 globals: getOption('globals'),433 indent: getOption('indent', true),434 interop: getOption('interop', true),435 intro: getOption('intro'),436 name: getOption('name'),437 namespaceToStringTag: getOption('namespaceToStringTag', false),438 noConflict: getOption('noConflict'),439 outro: getOption('outro'),440 paths: getOption('paths'),441 preferConst: getOption('preferConst'),442 sourcemap: getOption('sourcemap'),443 sourcemapExcludeSources: getOption('sourcemapExcludeSources'),444 sourcemapFile: getOption('sourcemapFile'),445 sourcemapPathTransform: getOption('sourcemapPathTransform'),446 strict: getOption('strict', true)447 };448}449var modules = {};450var getModule = function(dir) {451 var rootPath = dir ? path__default.resolve(dir) : process.cwd();452 var rootName = path__default.join(rootPath, '@root');453 var root = modules[rootName];454 if (!root) {455 root = new module$1(rootName);456 root.filename = rootName;457 root.paths = module$1._nodeModulePaths(rootPath);458 modules[rootName] = root;459 }460 return root;461};462var requireRelative = function(requested, relativeTo) {463 var root = getModule(relativeTo);464 return root.require(requested);465};466requireRelative.resolve = function(requested, relativeTo) {467 var root = getModule(relativeTo);468 return module$1._resolveFilename(requested, root);469};470var requireRelative_1 = requireRelative;471var absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;472function isAbsolute(path) {473 return absolutePath.test(path);474}475function getAliasName(resolved, unresolved) {476 var alias = path.basename(unresolved || resolved);477 var ext = path.extname(resolved);478 if (alias.endsWith(ext))479 alias = alias.substr(0, alias.length - ext.length);480 return alias;481}482function relativeId(id) {483 if (typeof process === 'undefined' || !isAbsolute(id))484 return id;485 return path.relative(process.cwd(), id);486}487const tc = {488 enabled:489 process.env.FORCE_COLOR ||490 process.platform === "win32" ||491 (process.stdout.isTTY && process.env.TERM && process.env.TERM !== "dumb")492};493const Styles = (tc.Styles = {});494const defineProp = Object.defineProperty;495const init = (style, open, close, re) => {496 let i,497 len = 1,498 seq = [(Styles[style] = { open, close, re })];499 const fn = s => {500 if (tc.enabled) {501 for (i = 0, s += ""; i < len; i++) {502 style = seq[i];503 s =504 (open = style.open) +505 (~s.indexOf((close = style.close), 4) // skip first \x1b[506 ? s.replace(style.re, open)507 : s) +508 close;509 }510 len = 1;511 }512 return s513 };514 defineProp(tc, style, {515 get: () => {516 for (let k in Styles)517 defineProp(fn, k, {518 get: () => ((seq[len++] = Styles[k]), fn)519 });520 delete tc[style];521 return (tc[style] = fn)522 },523 configurable: true524 });525};526init("reset", "\x1b[0m", "\x1b[0m", /\x1b\[0m/g);527init("bold", "\x1b[1m", "\x1b[22m", /\x1b\[22m/g);528init("dim", "\x1b[2m", "\x1b[22m", /\x1b\[22m/g);529init("italic", "\x1b[3m", "\x1b[23m", /\x1b\[23m/g);530init("underline", "\x1b[4m", "\x1b[24m", /\x1b\[24m/g);531init("inverse", "\x1b[7m", "\x1b[27m", /\x1b\[27m/g);532init("hidden", "\x1b[8m", "\x1b[28m", /\x1b\[28m/g);533init("strikethrough", "\x1b[9m", "\x1b[29m", /\x1b\[29m/g);534init("black", "\x1b[30m", "\x1b[39m", /\x1b\[39m/g);535init("red", "\x1b[31m", "\x1b[39m", /\x1b\[39m/g);536init("green", "\x1b[32m", "\x1b[39m", /\x1b\[39m/g);537init("yellow", "\x1b[33m", "\x1b[39m", /\x1b\[39m/g);538init("blue", "\x1b[34m", "\x1b[39m", /\x1b\[39m/g);539init("magenta", "\x1b[35m", "\x1b[39m", /\x1b\[39m/g);540init("cyan", "\x1b[36m", "\x1b[39m", /\x1b\[39m/g);541init("white", "\x1b[37m", "\x1b[39m", /\x1b\[39m/g);542init("gray", "\x1b[90m", "\x1b[39m", /\x1b\[39m/g);543init("bgBlack", "\x1b[40m", "\x1b[49m", /\x1b\[49m/g);544init("bgRed", "\x1b[41m", "\x1b[49m", /\x1b\[49m/g);545init("bgGreen", "\x1b[42m", "\x1b[49m", /\x1b\[49m/g);546init("bgYellow", "\x1b[43m", "\x1b[49m", /\x1b\[49m/g);547init("bgBlue", "\x1b[44m", "\x1b[49m", /\x1b\[49m/g);548init("bgMagenta", "\x1b[45m", "\x1b[49m", /\x1b\[49m/g);549init("bgCyan", "\x1b[46m", "\x1b[49m", /\x1b\[49m/g);550init("bgWhite", "\x1b[47m", "\x1b[49m", /\x1b\[49m/g);551var turbocolor = tc;552// log to stderr to keep `rollup main.js > bundle.js` from breaking553var stderr = console.error.bind(console); // eslint-disable-line no-console554function handleError(err, recover) {555 if (recover === void 0) { recover = false; }556 var description = err.message || err;557 if (err.name)558 description = err.name + ": " + description;559 var message = (err.plugin560 ? "(" + err.plugin + " plugin) " + description561 : description) || err;562 stderr(turbocolor.bold.red("[!] " + turbocolor.bold(message.toString())));563 if (err.url) {564 stderr(turbocolor.cyan(err.url));565 }566 if (err.loc) {567 stderr(relativeId(err.loc.file || err.id) + " (" + err.loc.line + ":" + err.loc.column + ")");568 }569 else if (err.id) {570 stderr(relativeId(err.id));571 }572 if (err.frame) {573 stderr(turbocolor.dim(err.frame));574 }575 if (err.stack) {576 stderr(turbocolor.dim(err.stack));577 }578 stderr('');579 if (!recover)580 process.exit(1);581}582function batchWarnings() {583 var allWarnings = new Map();584 var count = 0;585 return {586 get count() {587 return count;588 },589 add: function (warning) {590 if (typeof warning === 'string') {591 warning = { code: 'UNKNOWN', message: warning };592 }593 if (warning.code in immediateHandlers) {594 immediateHandlers[warning.code](warning);595 return;596 }597 if (!allWarnings.has(warning.code))598 allWarnings.set(warning.code, []);599 allWarnings.get(warning.code).push(warning);600 count += 1;601 },602 flush: function () {603 if (count === 0)604 return;605 var codes = Array.from(allWarnings.keys()).sort(function (a, b) {606 if (deferredHandlers[a] && deferredHandlers[b]) {607 return deferredHandlers[a].priority - deferredHandlers[b].priority;608 }609 if (deferredHandlers[a])610 return -1;611 if (deferredHandlers[b])612 return 1;613 return allWarnings.get(b).length - allWarnings.get(a).length;614 });615 codes.forEach(function (code) {616 var handler = deferredHandlers[code];617 var warnings = allWarnings.get(code);618 if (handler) {619 handler.fn(warnings);620 }621 else {622 warnings.forEach(function (warning) {623 title(warning.message);624 if (warning.url)625 info(warning.url);626 var id = (warning.loc && warning.loc.file) || warning.id;627 if (id) {628 var loc = warning.loc629 ? relativeId(id) + ": (" + warning.loc.line + ":" + warning.loc.column + ")"630 : relativeId(id);631 stderr(turbocolor.bold(relativeId(loc)));632 }633 if (warning.frame)634 info(warning.frame);635 });636 }637 });638 allWarnings = new Map();639 count = 0;640 }641 };642}643var immediateHandlers = {644 UNKNOWN_OPTION: function (warning) {645 title("You have passed an unrecognized option");646 stderr(warning.message);647 },648 MISSING_NODE_BUILTINS: function (warning) {649 title("Missing shims for Node.js built-ins");650 var detail = warning.modules.length === 1651 ? "'" + warning.modules[0] + "'"652 : warning.modules653 .slice(0, -1)654 .map(function (name) { return "'" + name + "'"; })655 .join(', ') + " and '" + warning.modules.slice(-1) + "'";656 stderr("Creating a browser bundle that depends on " + detail + ". You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins");657 },658 MIXED_EXPORTS: function () {659 title('Mixing named and default exports');660 stderr("Consumers of your bundle will have to use bundle['default'] to access the default export, which may not be what you want. Use `output.exports: 'named'` to disable this warning");661 },662 EMPTY_BUNDLE: function () {663 title("Generated an empty bundle");664 }665};666// TODO select sensible priorities667var deferredHandlers = {668 UNUSED_EXTERNAL_IMPORT: {669 fn: function (warnings) {670 title('Unused external imports');671 warnings.forEach(function (warning) {672 stderr(warning.names + " imported from external module '" + warning.source + "' but never used");673 });674 },675 priority: 1676 },677 UNRESOLVED_IMPORT: {678 fn: function (warnings) {679 title('Unresolved dependencies');680 info('https://rollupjs.org/guide/en#warning-treating-module-as-external-dependency');681 var dependencies = new Map();682 warnings.forEach(function (warning) {683 if (!dependencies.has(warning.source))684 dependencies.set(warning.source, []);685 dependencies.get(warning.source).push(warning.importer);686 });687 Array.from(dependencies.keys()).forEach(function (dependency) {688 var importers = dependencies.get(dependency);689 stderr(turbocolor.bold(dependency) + " (imported by " + importers.join(', ') + ")");690 });691 },692 priority: 1693 },694 MISSING_EXPORT: {695 fn: function (warnings) {696 title('Missing exports');697 info('https://rollupjs.org/guide/en#error-name-is-not-exported-by-module-');698 warnings.forEach(function (warning) {699 stderr(turbocolor.bold(warning.importer));700 stderr(warning.missing + " is not exported by " + warning.exporter);701 stderr(turbocolor.gray(warning.frame));702 });703 },704 priority: 1705 },706 THIS_IS_UNDEFINED: {707 fn: function (warnings) {708 title('`this` has been rewritten to `undefined`');709 info('https://rollupjs.org/guide/en#error-this-is-undefined');710 showTruncatedWarnings(warnings);711 },712 priority: 1713 },714 EVAL: {715 fn: function (warnings) {716 title('Use of eval is strongly discouraged');717 info('https://rollupjs.org/guide/en#avoiding-eval');718 showTruncatedWarnings(warnings);719 },720 priority: 1721 },722 NON_EXISTENT_EXPORT: {723 fn: function (warnings) {724 title("Import of non-existent " + (warnings.length > 1 ? 'exports' : 'export'));725 showTruncatedWarnings(warnings);726 },727 priority: 1728 },729 NAMESPACE_CONFLICT: {730 fn: function (warnings) {731 title("Conflicting re-exports");732 warnings.forEach(function (warning) {733 stderr(turbocolor.bold(relativeId(warning.reexporter)) + " re-exports '" + warning.name + "' from both " + relativeId(warning.sources[0]) + " and " + relativeId(warning.sources[1]) + " (will be ignored)");734 });735 },736 priority: 1737 },738 MISSING_GLOBAL_NAME: {739 fn: function (warnings) {740 title("Missing global variable " + (warnings.length > 1 ? 'names' : 'name'));741 stderr("Use output.globals to specify browser global variable names corresponding to external modules");742 warnings.forEach(function (warning) {743 stderr(turbocolor.bold(warning.source) + " (guessing '" + warning.guess + "')");744 });745 },746 priority: 1747 },748 SOURCEMAP_BROKEN: {749 fn: function (warnings) {750 title("Broken sourcemap");751 info('https://rollupjs.org/guide/en#warning-sourcemap-is-likely-to-be-incorrect');752 var plugins = Array.from(new Set(warnings.map(function (w) { return w.plugin; }).filter(Boolean)));753 var detail = plugins.length === 0754 ? ''755 : plugins.length > 1756 ? " (such as " + plugins757 .slice(0, -1)758 .map(function (p) { return "'" + p + "'"; })759 .join(', ') + " and '" + plugins.slice(-1) + "')"760 : " (such as '" + plugins[0] + "')";761 stderr("Plugins that transform code" + detail + " should generate accompanying sourcemaps");762 },763 priority: 1764 },765 PLUGIN_WARNING: {766 fn: function (warnings) {767 var nestedByPlugin = nest(warnings, 'plugin');768 nestedByPlugin.forEach(function (_a) {769 var plugin = _a.key, items = _a.items;770 var nestedByMessage = nest(items, 'message');771 var lastUrl;772 nestedByMessage.forEach(function (_a) {773 var message = _a.key, items = _a.items;774 title(plugin + " plugin: " + message);775 items.forEach(function (warning) {776 if (warning.url !== lastUrl)777 info((lastUrl = warning.url));778 if (warning.id) {779 var loc = relativeId(warning.id);780 if (warning.loc) {781 loc += ": (" + warning.loc.line + ":" + warning.loc.column + ")";782 }783 stderr(turbocolor.bold(loc));784 }785 if (warning.frame)786 info(warning.frame);787 });788 });789 });790 },791 priority: 1792 }793};794function title(str) {795 stderr(turbocolor.bold.yellow('(!)') + " " + turbocolor.bold.yellow(str));796}797function info(url) {798 stderr(turbocolor.gray(url));799}800function nest(array, prop) {801 var nested = [];802 var lookup = new Map();803 array.forEach(function (item) {804 var key = item[prop];805 if (!lookup.has(key)) {806 lookup.set(key, {807 items: [],808 key: key809 });810 nested.push(lookup.get(key));811 }812 lookup.get(key).items.push(item);813 });814 return nested;815}816function showTruncatedWarnings(warnings) {817 var nestedByModule = nest(warnings, 'id');818 var sliced = nestedByModule.length > 5 ? nestedByModule.slice(0, 3) : nestedByModule;819 sliced.forEach(function (_a) {820 var id = _a.key, items = _a.items;821 stderr(turbocolor.bold(relativeId(id)));822 stderr(turbocolor.gray(items[0].frame));823 if (items.length > 1) {824 stderr("...and " + (items.length - 1) + " other " + (items.length > 2 ? 'occurrences' : 'occurrence'));825 }826 });827 if (nestedByModule.length > sliced.length) {828 stderr("\n...and " + (nestedByModule.length - sliced.length) + " other files");829 }830}831var parseMs = ms => {832 if (typeof ms !== 'number') {833 throw new TypeError('Expected a number');834 }835 const roundTowardsZero = ms > 0 ? Math.floor : Math.ceil;836 return {837 days: roundTowardsZero(ms / 86400000),838 hours: roundTowardsZero(ms / 3600000) % 24,839 minutes: roundTowardsZero(ms / 60000) % 60,840 seconds: roundTowardsZero(ms / 1000) % 60,841 milliseconds: roundTowardsZero(ms) % 1000,842 microseconds: roundTowardsZero(ms * 1000) % 1000,843 nanoseconds: roundTowardsZero(ms * 1e6) % 1000844 };845};846const pluralize = (word, count) => count === 1 ? word : word + 's';847var prettyMs = (ms, options = {}) => {848 if (!Number.isFinite(ms)) {849 throw new TypeError('Expected a finite number');850 }851 if (options.compact) {852 options.secDecimalDigits = 0;853 options.msDecimalDigits = 0;854 }855 const ret = [];856 const add = (value, long, short, valueString) => {857 if (value === 0) {858 return;859 }860 const postfix = options.verbose ? ' ' + pluralize(long, value) : short;861 ret.push((valueString || value) + postfix);862 };863 const secDecimalDigits = typeof options.secDecimalDigits === 'number' ? options.secDecimalDigits : 1;864 if (secDecimalDigits < 1) {865 const diff = 1000 - (ms % 1000);866 if (diff < 500) {867 ms += diff;868 }869 }870 const parsed = parseMs(ms);871 add(Math.trunc(parsed.days / 365), 'year', 'y');872 add(parsed.days % 365, 'day', 'd');873 add(parsed.hours, 'hour', 'h');874 add(parsed.minutes, 'minute', 'm');875 if (options.separateMs || options.formatSubMs || ms < 1000) {876 add(parsed.seconds, 'second', 's');877 if (options.formatSubMs) {878 add(parsed.milliseconds, 'millisecond', 'ms');879 add(parsed.microseconds, 'microsecond', 'µs');880 add(parsed.nanoseconds, 'nanosecond', 'ns');881 } else {882 const msAndBelow = parsed.milliseconds + (parsed.microseconds / 1000) + (parsed.nanoseconds / 1e6);883 const msDecimalDigits = typeof options.msDecimalDigits === 'number' ? options.msDecimalDigits : 0;884 const msStr = msDecimalDigits ? msAndBelow.toFixed(msDecimalDigits) : Math.ceil(msAndBelow);885 add(parseFloat(msStr, 10), 'millisecond', 'ms', msStr);886 }887 } else {888 const sec = ms / 1000 % 60;889 const secDecimalDigits = typeof options.secDecimalDigits === 'number' ? options.secDecimalDigits : 1;890 const secFixed = sec.toFixed(secDecimalDigits);891 const secStr = options.keepDecimalsOnWholeSeconds ? secFixed : secFixed.replace(/\.0+$/, '');892 add(parseFloat(secStr, 10), 'second', 's', secStr);893 }894 if (ret.length === 0) {895 return '0' + (options.verbose ? ' milliseconds' : 'ms');896 }897 if (options.compact) {898 return '~' + ret[0];899 }900 if (typeof options.unitCount === 'number') {901 return '~' + ret.slice(0, Math.max(options.unitCount, 1)).join(' ');902 }903 return ret.join(' ');904};905var SOURCEMAPPING_URL = 'sourceMa';906SOURCEMAPPING_URL += 'ppingURL';907var SOURCEMAPPING_URL$1 = SOURCEMAPPING_URL;908const UNITS = [909 'B',910 'kB',911 'MB',912 'GB',913 'TB',914 'PB',915 'EB',916 'ZB',917 'YB'918];919/*920Formats the given number using `Number#toLocaleString`.921- If locale is a string, the value is expected to be a locale-key (for example: `de`).922- If locale is true, the system default locale is used for translation.923- If no value for locale is specified, the number is returned unmodified.924*/925const toLocaleString = (number, locale) => {926 let result = number;927 if (typeof locale === 'string') {928 result = number.toLocaleString(locale);929 } else if (locale === true) {930 result = number.toLocaleString();931 }932 return result;933};934var prettyBytes = (number, options) => {935 if (!Number.isFinite(number)) {936 throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`);937 }938 options = Object.assign({}, options);939 if (options.signed && number === 0) {940 return ' 0 B';941 }942 const isNegative = number < 0;943 const prefix = isNegative ? '-' : (options.signed ? '+' : '');944 if (isNegative) {945 number = -number;946 }947 if (number < 1) {948 const numberString = toLocaleString(number, options.locale);949 return prefix + numberString + ' B';950 }951 const exponent = Math.min(Math.floor(Math.log10(number) / 3), UNITS.length - 1);952 number = Number((number / Math.pow(1000, exponent)).toPrecision(3));953 const numberString = toLocaleString(number, options.locale);954 const unit = UNITS[exponent];955 return prefix + numberString + ' ' + unit;956};957function printTimings(timings) {958 Object.keys(timings).forEach(function (label) {959 var color = label[0] === '#' ? (label[1] !== '#' ? turbocolor.underline : turbocolor.bold) : function (text) { return text; };960 var _a = timings[label], time = _a[0], memory = _a[1], total = _a[2];961 var row = label + ": " + time.toFixed(0) + "ms, " + prettyBytes(memory) + " / " + prettyBytes(total);962 console.info(color(row));963 });964}965function build(inputOptions, outputOptions, warnings, silent) {966 if (silent === void 0) { silent = false; }967 var useStdout = !outputOptions[0].file && !outputOptions[0].dir;968 var start = Date.now();969 var files = useStdout ? ['stdout'] : outputOptions.map(function (t) { return relativeId(t.file || t.dir); });970 if (!silent) {971 var inputFiles = void 0;972 if (typeof inputOptions.input === 'string') {973 inputFiles = inputOptions.input;974 }975 else if (inputOptions.input instanceof Array) {976 inputFiles = inputOptions.input.join(', ');977 }978 else if (typeof inputOptions.input === 'object' && inputOptions.input !== null) {979 inputFiles = Object.keys(inputOptions.input)980 .map(function (name) { return inputOptions.input[name]; })981 .join(', ');982 }983 stderr(turbocolor.cyan("\n" + turbocolor.bold(inputFiles) + " \u2192 " + turbocolor.bold(files.join(', ')) + "..."));984 }985 return rollup.rollup(inputOptions)986 .then(function (bundle) {987 if (useStdout) {988 var output_1 = outputOptions[0];989 if (output_1.sourcemap && output_1.sourcemap !== 'inline') {990 handleError({991 code: 'MISSING_OUTPUT_OPTION',992 message: 'You must specify a --file (-o) option when creating a file with a sourcemap'993 });994 }995 return bundle.generate(output_1).then(function (_a) {996 var outputs = _a.output;997 for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) {998 var file = outputs_1[_i];999 var source = void 0;1000 if (file.isAsset) {1001 source = file.source;1002 }1003 else {1004 source = file.code;1005 if (output_1.sourcemap === 'inline') {1006 source += "\n//# " + SOURCEMAPPING_URL$1 + "=" + file.map.toUrl() + "\n";1007 }1008 }1009 if (outputs.length > 1)1010 process.stdout.write('\n' + turbocolor.cyan(turbocolor.bold('//â ' + file.fileName + ':')) + '\n');1011 process.stdout.write(source);1012 }1013 });1014 }1015 return Promise.all(outputOptions.map(function (output) { return bundle.write(output); })).then(function () { return bundle; });1016 })1017 .then(function (bundle) {1018 warnings.flush();1019 if (!silent)1020 stderr(turbocolor.green("created " + turbocolor.bold(files.join(', ')) + " in " + turbocolor.bold(prettyMs(Date.now() - start))));1021 if (bundle && bundle.getTimings) {1022 printTimings(bundle.getTimings());1023 }1024 })1025 .catch(function (err) {1026 if (warnings.count > 0)1027 warnings.flush();1028 handleError(err);1029 });1030}1031function loadConfigFile(configFile, commandOptions) {1032 if (commandOptions === void 0) { commandOptions = {}; }1033 var silent = commandOptions.silent || false;1034 var warnings = batchWarnings();1035 return rollup__default1036 .rollup({1037 external: function (id) {1038 return (id[0] !== '.' && !path__default.isAbsolute(id)) || id.slice(-5, id.length) === '.json';1039 },1040 input: configFile,1041 onwarn: warnings.add,1042 treeshake: false1043 })1044 .then(function (bundle) {1045 if (!silent && warnings.count > 0) {1046 stderr(turbocolor.bold("loaded " + relativeId(configFile) + " with warnings"));1047 warnings.flush();1048 }1049 return bundle.generate({1050 exports: 'named',1051 format: 'cjs'1052 });1053 })1054 .then(function (_a) {1055 var code = _a.output[0].code;1056 // temporarily override require1057 var defaultLoader = require.extensions['.js'];1058 require.extensions['.js'] = function (module, filename) {1059 if (filename === configFile) {1060 module._compile(code, filename);1061 }1062 else {1063 defaultLoader(module, filename);1064 }1065 };1066 delete require.cache[configFile];1067 return Promise.resolve(require(configFile))1068 .then(function (configFileContent) {1069 if (configFileContent.default)1070 configFileContent = configFileContent.default;1071 if (typeof configFileContent === 'function') {1072 return configFileContent(commandOptions);1073 }1074 return configFileContent;1075 })1076 .then(function (configs) {1077 if (Object.keys(configs).length === 0) {1078 handleError({1079 code: 'MISSING_CONFIG',1080 message: 'Config file must export an options object, or an array of options objects',1081 url: 'https://rollupjs.org/guide/en#configuration-files'1082 });1083 }1084 require.extensions['.js'] = defaultLoader;1085 return Array.isArray(configs) ? configs : [configs];1086 });1087 });1088}1089var timeZone = date => {1090 const offset = (date || new Date()).getTimezoneOffset();1091 const absOffset = Math.abs(offset);1092 const hours = Math.floor(absOffset / 60);1093 const minutes = absOffset % 60;1094 const minutesOut = minutes > 0 ? ':' + ('0' + minutes).slice(-2) : '';1095 return (offset < 0 ? '+' : '-') + hours + minutesOut;1096};1097const dateTime = options => {1098 options = Object.assign({1099 date: new Date(),1100 local: true,1101 showTimeZone: false,1102 showMilliseconds: false1103 }, options);1104 let {date} = options;1105 if (options.local) {1106 // Offset the date so it will return the correct value when getting the ISO string1107 date = new Date(date.getTime() - (date.getTimezoneOffset() * 60000));1108 }1109 let end = '';1110 if (options.showTimeZone) {1111 end = ' UTC' + (options.local ? timeZone(date) : '');1112 }1113 if (options.showMilliseconds && date.getUTCMilliseconds() > 0) {1114 end = ` ${date.getUTCMilliseconds()}ms${end}`;1115 }1116 return date1117 .toISOString()1118 .replace(/T/, ' ')1119 .replace(/\..+/, end);1120};1121var dateTime_1 = dateTime;1122// TODO: Remove this for the next major release1123var default_1 = dateTime;1124dateTime_1.default = default_1;1125function createCommonjsModule(fn, module) {1126 return module = { exports: {} }, fn(module, module.exports), module.exports;1127}1128var signals = createCommonjsModule(function (module) {1129// This is not the set of all possible signals.1130//1131// It IS, however, the set of all signals that trigger1132// an exit on either Linux or BSD systems. Linux is a1133// superset of the signal names supported on BSD, and1134// the unknown signals just fail to register, so we can1135// catch that easily enough.1136//1137// Don't bother with SIGKILL. It's uncatchable, which1138// means that we can't fire any callbacks anyway.1139//1140// If a user does happen to register a handler on a non-1141// fatal signal like SIGWINCH or something, and then1142// exit, it'll end up firing `process.emit('exit')`, so1143// the handler will be fired anyway.1144//1145// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised1146// artificially, inherently leave the process in a1147// state from which it is not safe to try and enter JS1148// listeners.1149module.exports = [1150 'SIGABRT',1151 'SIGALRM',1152 'SIGHUP',1153 'SIGINT',1154 'SIGTERM'1155];1156if (process.platform !== 'win32') {1157 module.exports.push(1158 'SIGVTALRM',1159 'SIGXCPU',1160 'SIGXFSZ',1161 'SIGUSR2',1162 'SIGTRAP',1163 'SIGSYS',1164 'SIGQUIT',1165 'SIGIOT'1166 // should detect profiler and enable/disable accordingly.1167 // see #211168 // 'SIGPROF'1169 );1170}1171if (process.platform === 'linux') {1172 module.exports.push(1173 'SIGIO',1174 'SIGPOLL',1175 'SIGPWR',1176 'SIGSTKFLT',1177 'SIGUNUSED'1178 );1179}1180});1181// Note: since nyc uses this module to output coverage, any lines1182// that are in the direct sync flow of nyc's outputCoverage are1183// ignored, since we can never get coverage for them.1184var signals$1 = signals;1185var EE = events;1186/* istanbul ignore if */1187if (typeof EE !== 'function') {1188 EE = EE.EventEmitter;1189}1190var emitter;1191if (process.__signal_exit_emitter__) {1192 emitter = process.__signal_exit_emitter__;1193} else {1194 emitter = process.__signal_exit_emitter__ = new EE();1195 emitter.count = 0;1196 emitter.emitted = {};1197}1198// Because this emitter is a global, we have to check to see if a1199// previous version of this library failed to enable infinite listeners.1200// I know what you're about to say. But literally everything about1201// signal-exit is a compromise with evil. Get used to it.1202if (!emitter.infinite) {1203 emitter.setMaxListeners(Infinity);1204 emitter.infinite = true;1205}1206var signalExit = function (cb, opts) {1207 assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');1208 if (loaded === false) {1209 load();1210 }1211 var ev = 'exit';1212 if (opts && opts.alwaysLast) {1213 ev = 'afterexit';1214 }1215 var remove = function () {1216 emitter.removeListener(ev, cb);1217 if (emitter.listeners('exit').length === 0 &&1218 emitter.listeners('afterexit').length === 0) {1219 unload();1220 }1221 };1222 emitter.on(ev, cb);1223 return remove1224};1225var unload_1 = unload;1226function unload () {1227 if (!loaded) {1228 return1229 }1230 loaded = false;1231 signals$1.forEach(function (sig) {1232 try {1233 process.removeListener(sig, sigListeners[sig]);1234 } catch (er) {}1235 });1236 process.emit = originalProcessEmit;1237 process.reallyExit = originalProcessReallyExit;1238 emitter.count -= 1;1239}1240function emit (event, code, signal) {1241 if (emitter.emitted[event]) {1242 return1243 }1244 emitter.emitted[event] = true;1245 emitter.emit(event, code, signal);1246}1247// { <signal>: <listener fn>, ... }1248var sigListeners = {};1249signals$1.forEach(function (sig) {1250 sigListeners[sig] = function listener () {1251 // If there are no other listeners, an exit is coming!1252 // Simplest way: remove us and then re-send the signal.1253 // We know that this will kill the process, so we can1254 // safely emit now.1255 var listeners = process.listeners(sig);1256 if (listeners.length === emitter.count) {1257 unload();1258 emit('exit', null, sig);1259 /* istanbul ignore next */1260 emit('afterexit', null, sig);1261 /* istanbul ignore next */1262 process.kill(process.pid, sig);1263 }1264 };1265});1266var signals_1 = function () {1267 return signals$11268};1269var load_1 = load;1270var loaded = false;1271function load () {1272 if (loaded) {1273 return1274 }1275 loaded = true;1276 // This is the number of onSignalExit's that are in play.1277 // It's important so that we can count the correct number of1278 // listeners on signals, and don't wait for the other one to1279 // handle it instead of us.1280 emitter.count += 1;1281 signals$1 = signals$1.filter(function (sig) {1282 try {1283 process.on(sig, sigListeners[sig]);1284 return true1285 } catch (er) {1286 return false1287 }1288 });1289 process.emit = processEmit;1290 process.reallyExit = processReallyExit;1291}1292var originalProcessReallyExit = process.reallyExit;1293function processReallyExit (code) {1294 process.exitCode = code || 0;1295 emit('exit', process.exitCode, null);1296 /* istanbul ignore next */1297 emit('afterexit', process.exitCode, null);1298 /* istanbul ignore next */1299 originalProcessReallyExit.call(process, process.exitCode);1300}1301var originalProcessEmit = process.emit;1302function processEmit (ev, arg) {1303 if (ev === 'exit') {1304 if (arg !== undefined) {1305 process.exitCode = arg;1306 }1307 var ret = originalProcessEmit.apply(this, arguments);1308 emit('exit', process.exitCode, null);1309 /* istanbul ignore next */1310 emit('afterexit', process.exitCode, null);1311 return ret1312 } else {1313 return originalProcessEmit.apply(this, arguments)1314 }1315}1316signalExit.unload = unload_1;1317signalExit.signals = signals_1;1318signalExit.load = load_1;1319var ansiEscapes_1 = createCommonjsModule(function (module) {1320const ansiEscapes = module.exports;1321// TODO: remove this in the next major version1322module.exports.default = ansiEscapes;1323const ESC = '\u001B[';1324const OSC = '\u001B]';1325const BEL = '\u0007';1326const SEP = ';';1327const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal';1328ansiEscapes.cursorTo = (x, y) => {1329 if (typeof x !== 'number') {1330 throw new TypeError('The `x` argument is required');1331 }1332 if (typeof y !== 'number') {1333 return ESC + (x + 1) + 'G';1334 }1335 return ESC + (y + 1) + ';' + (x + 1) + 'H';1336};1337ansiEscapes.cursorMove = (x, y) => {1338 if (typeof x !== 'number') {1339 throw new TypeError('The `x` argument is required');1340 }1341 let ret = '';1342 if (x < 0) {1343 ret += ESC + (-x) + 'D';1344 } else if (x > 0) {1345 ret += ESC + x + 'C';1346 }1347 if (y < 0) {1348 ret += ESC + (-y) + 'A';1349 } else if (y > 0) {1350 ret += ESC + y + 'B';1351 }1352 return ret;1353};1354ansiEscapes.cursorUp = (count = 1) => ESC + count + 'A';1355ansiEscapes.cursorDown = (count = 1) => ESC + count + 'B';1356ansiEscapes.cursorForward = (count = 1) => ESC + count + 'C';1357ansiEscapes.cursorBackward = (count = 1) => ESC + count + 'D';1358ansiEscapes.cursorLeft = ESC + 'G';1359ansiEscapes.cursorSavePosition = ESC + (isTerminalApp ? '7' : 's');1360ansiEscapes.cursorRestorePosition = ESC + (isTerminalApp ? '8' : 'u');1361ansiEscapes.cursorGetPosition = ESC + '6n';1362ansiEscapes.cursorNextLine = ESC + 'E';1363ansiEscapes.cursorPrevLine = ESC + 'F';1364ansiEscapes.cursorHide = ESC + '?25l';1365ansiEscapes.cursorShow = ESC + '?25h';1366ansiEscapes.eraseLines = count => {1367 let clear = '';1368 for (let i = 0; i < count; i++) {1369 clear += ansiEscapes.eraseLine + (i < count - 1 ? ansiEscapes.cursorUp() : '');1370 }1371 if (count) {1372 clear += ansiEscapes.cursorLeft;1373 }1374 return clear;1375};1376ansiEscapes.eraseEndLine = ESC + 'K';1377ansiEscapes.eraseStartLine = ESC + '1K';1378ansiEscapes.eraseLine = ESC + '2K';1379ansiEscapes.eraseDown = ESC + 'J';1380ansiEscapes.eraseUp = ESC + '1J';1381ansiEscapes.eraseScreen = ESC + '2J';1382ansiEscapes.scrollUp = ESC + 'S';1383ansiEscapes.scrollDown = ESC + 'T';1384ansiEscapes.clearScreen = '\u001Bc';1385ansiEscapes.clearTerminal = process.platform === 'win32' ?1386 `${ansiEscapes.eraseScreen}${ESC}0f` :1387 // 1. Erases the screen (Only done in case `2` is not supported)1388 // 2. Erases the whole screen including scrollback buffer1389 // 3. Moves cursor to the top-left position1390 // More info: https://www.real-world-systems.com/docs/ANSIcode.html1391 `${ansiEscapes.eraseScreen}${ESC}3J${ESC}H`;1392ansiEscapes.beep = BEL;1393ansiEscapes.link = (text, url) => {1394 return [1395 OSC,1396 '8',1397 SEP,1398 SEP,1399 url,1400 BEL,1401 text,1402 OSC,1403 '8',1404 SEP,1405 SEP,1406 BEL1407 ].join('');1408};1409ansiEscapes.image = (buffer, options = {}) => {1410 let ret = `${OSC}1337;File=inline=1`;1411 if (options.width) {1412 ret += `;width=${options.width}`;1413 }1414 if (options.height) {1415 ret += `;height=${options.height}`;1416 }1417 if (options.preserveAspectRatio === false) {1418 ret += ';preserveAspectRatio=0';1419 }1420 return ret + ':' + buffer.toString('base64') + BEL;1421};1422ansiEscapes.iTerm = {1423 setCwd: (cwd = process.cwd()) => `${OSC}50;CurrentDir=${cwd}${BEL}`1424};1425});1426var SHOW_ALTERNATE_SCREEN = '\u001B[?1049h';1427var HIDE_ALTERNATE_SCREEN = '\u001B[?1049l';1428var isWindows = process.platform === 'win32';1429var isMintty = isWindows && !!(process.env.SHELL || process.env.TERM);1430var isConEmuAnsiOn = (process.env.ConEmuANSI || '').toLowerCase() === 'on';1431var supportsAnsi = !isWindows || isMintty || isConEmuAnsiOn;1432function alternateScreen(enabled) {1433 if (!enabled) {1434 var needAnnounce_1 = true;1435 return {1436 open: function () { },1437 close: function () { },1438 reset: function (heading) {1439 if (needAnnounce_1) {1440 stderr(heading);1441 needAnnounce_1 = false;1442 }1443 }1444 };1445 }1446 return {1447 open: function () {1448 if (supportsAnsi) {1449 process.stderr.write(SHOW_ALTERNATE_SCREEN);1450 }1451 },1452 close: function () {1453 if (supportsAnsi) {1454 process.stderr.write(HIDE_ALTERNATE_SCREEN);1455 }1456 },1457 reset: function (heading) {1458 stderr("" + ansiEscapes_1.eraseScreen + ansiEscapes_1.cursorTo(0, 0) + heading);1459 }1460 };1461}1462function watch(configFile, configs, command, silent) {1463 if (silent === void 0) { silent = false; }1464 var isTTY = Boolean(process.stderr.isTTY);1465 var warnings = batchWarnings();1466 var initialConfigs = processConfigs(configs);1467 var clearScreen = initialConfigs.every(function (config) { return config.watch.clearScreen !== false; });1468 var screen = alternateScreen(isTTY && clearScreen);1469 screen.open();1470 var watcher;1471 var configWatcher;1472 var processConfigsErr;1473 function processConfigs(configs) {1474 return configs.map(function (options) {1475 var merged = mergeOptions({1476 command: command,1477 config: options,1478 defaultOnWarnHandler: warnings.add1479 });1480 var result = __assign({}, merged.inputOptions, { output: merged.outputOptions });1481 if (!result.watch)1482 result.watch = {};1483 if (merged.optionError)1484 merged.inputOptions.onwarn({1485 code: 'UNKNOWN_OPTION',1486 message: merged.optionError1487 });1488 if (merged.inputOptions.watch &&1489 merged.inputOptions.watch.clearScreen === false) {1490 processConfigsErr = stderr;1491 }1492 return result;1493 });1494 }1495 function start(configs) {1496 var screenWriter = processConfigsErr || screen.reset;1497 watcher = rollup.watch(configs);1498 watcher.on('event', function (event) {1499 switch (event.code) {1500 case 'FATAL':1501 screen.close();1502 handleError(event.error, true);1503 process.exit(1);1504 break;1505 case 'ERROR':1506 warnings.flush();1507 handleError(event.error, true);1508 break;1509 case 'START':1510 if (!silent) {1511 screenWriter(turbocolor.underline("rollup v" + rollup.VERSION));1512 }1513 break;1514 case 'BUNDLE_START':1515 if (!silent) {1516 var input_1 = event.input;1517 if (typeof input_1 !== 'string') {1518 input_1 = Array.isArray(input_1)1519 ? input_1.join(', ')1520 : Object.keys(input_1)1521 .map(function (key) { return input_1[key]; })1522 .join(', ');1523 }1524 stderr(turbocolor.cyan("bundles " + turbocolor.bold(input_1) + " \u2192 " + turbocolor.bold(event.output.map(relativeId).join(', ')) + "..."));1525 }1526 break;1527 case 'BUNDLE_END':1528 warnings.flush();1529 if (!silent)1530 stderr(turbocolor.green("created " + turbocolor.bold(event.output.map(relativeId).join(', ')) + " in " + turbocolor.bold(prettyMs(event.duration))));1531 if (event.result && event.result.getTimings) {1532 printTimings(event.result.getTimings());1533 }1534 break;1535 case 'END':1536 if (!silent && isTTY) {1537 stderr("\n[" + dateTime_1() + "] waiting for changes...");1538 }1539 }1540 });1541 }1542 // catch ctrl+c, kill, and uncaught errors1543 var removeOnExit = signalExit(close);1544 process.on('uncaughtException', close);1545 // only listen to stdin if it is a pipe1546 if (!process.stdin.isTTY) {1547 process.stdin.on('end', close); // in case we ever support stdin!1548 }1549 function close(err) {1550 removeOnExit();1551 process.removeListener('uncaughtException', close);1552 // removing a non-existent listener is a no-op1553 process.stdin.removeListener('end', close);1554 screen.close();1555 if (watcher)1556 watcher.close();1557 if (configWatcher)1558 configWatcher.close();1559 if (err) {1560 console.error(err);1561 process.exit(1);1562 }1563 }1564 try {1565 start(initialConfigs);1566 }1567 catch (err) {1568 close(err);1569 return;1570 }1571 if (configFile && !configFile.startsWith('node:')) {1572 var restarting_1 = false;1573 var aborted_1 = false;1574 var configFileData_1 = fs__default.readFileSync(configFile, 'utf-8');1575 var restart_1 = function () {1576 var newConfigFileData = fs__default.readFileSync(configFile, 'utf-8');1577 if (newConfigFileData === configFileData_1)1578 return;1579 configFileData_1 = newConfigFileData;1580 if (restarting_1) {1581 aborted_1 = true;1582 return;1583 }1584 restarting_1 = true;1585 loadConfigFile(configFile, command)1586 .then(function (_configs) {1587 restarting_1 = false;1588 if (aborted_1) {1589 aborted_1 = false;1590 restart_1();1591 }1592 else {1593 watcher.close();1594 start(initialConfigs);1595 }1596 })1597 .catch(function (err) {1598 handleError(err, true);1599 });1600 };1601 configWatcher = fs__default.watch(configFile, function (event) {1602 if (event === 'change')1603 restart_1();1604 });1605 }1606}1607function runRollup(command) {1608 var inputSource;1609 if (command._.length > 0) {1610 if (command.input) {1611 handleError({1612 code: 'DUPLICATE_IMPORT_OPTIONS',1613 message: 'use --input, or pass input path as argument'1614 });1615 }1616 inputSource = command._;1617 }1618 else if (typeof command.input === 'string') {1619 inputSource = [command.input];1620 }1621 else {1622 inputSource = command.input;1623 }1624 if (inputSource && inputSource.length > 0) {1625 if (inputSource.some(function (input) { return input.indexOf('=') !== -1; })) {1626 command.input = {};1627 inputSource.forEach(function (input) {1628 var equalsIndex = input.indexOf('=');1629 var value = input.substr(equalsIndex + 1);1630 var key = input.substr(0, equalsIndex);1631 if (!key)1632 key = getAliasName(input);1633 command.input[key] = value;1634 });1635 }1636 else {1637 command.input = inputSource;1638 }1639 }1640 if (command.environment) {1641 var environment = Array.isArray(command.environment)1642 ? command.environment1643 : [command.environment];1644 environment.forEach(function (arg) {1645 arg.split(',').forEach(function (pair) {1646 var _a = pair.split(':'), key = _a[0], value = _a[1];1647 if (value) {1648 process.env[key] = value;1649 }1650 else {1651 process.env[key] = String(true);1652 }1653 });1654 });1655 }1656 var configFile = command.config === true ? 'rollup.config.js' : command.config;1657 if (configFile) {1658 if (configFile.slice(0, 5) === 'node:') {1659 var pkgName = configFile.slice(5);1660 try {1661 configFile = requireRelative_1.resolve("rollup-config-" + pkgName, process.cwd());1662 }1663 catch (err) {1664 try {1665 configFile = requireRelative_1.resolve(pkgName, process.cwd());1666 }1667 catch (err) {1668 if (err.code === 'MODULE_NOT_FOUND') {1669 handleError({1670 code: 'MISSING_EXTERNAL_CONFIG',1671 message: "Could not resolve config file " + configFile1672 });1673 }1674 throw err;1675 }1676 }1677 }1678 else {1679 // find real path of config so it matches what Node provides to callbacks in require.extensions1680 configFile = fs.realpathSync(configFile);1681 }1682 if (command.watch)1683 process.env.ROLLUP_WATCH = 'true';1684 loadConfigFile(configFile, command)1685 .then(function (configs) { return execute(configFile, configs, command); })1686 .catch(handleError);1687 }1688 else {1689 return execute(configFile, [{ input: null }], command);1690 }1691}1692function execute(configFile, configs, command) {1693 if (command.watch) {1694 watch(configFile, configs, command, command.silent);1695 }1696 else {1697 var promise = Promise.resolve();1698 var _loop_1 = function (config) {1699 promise = promise.then(function () {1700 var warnings = batchWarnings();1701 var _a = mergeOptions({1702 command: command,1703 config: config,1704 defaultOnWarnHandler: warnings.add1705 }), inputOptions = _a.inputOptions, outputOptions = _a.outputOptions, optionError = _a.optionError;1706 if (optionError)1707 inputOptions.onwarn({ code: 'UNKNOWN_OPTION', message: optionError });1708 return build(inputOptions, outputOptions, warnings, command.silent);1709 });1710 };1711 for (var _i = 0, configs_1 = configs; _i < configs_1.length; _i++) {1712 var config = configs_1[_i];1713 _loop_1(config);1714 }1715 return promise;1716 }1717}1718var command = minimist(process.argv.slice(2), {1719 alias: commandAliases1720});1721if (command.help || (process.argv.length <= 2 && process.stdin.isTTY)) {1722 console.log("\n" + help.replace('__VERSION__', version) + "\n"); // eslint-disable-line no-console1723}1724else if (command.version) {1725 console.log("rollup v" + version); // eslint-disable-line no-console1726}1727else {1728 try {1729 require('source-map-support').install();1730 }1731 catch (err) {1732 // do nothing1733 }1734 runRollup(command);...
build-stanzas.mjs
Source:build-stanzas.mjs
...121 // https://github.com/rollup/rollup/issues/1518122 if (warn.code === 'THIS_IS_UNDEFINED') {123 return;124 }125 defaultOnWarn(warn);126 },127 });128 await bundle.write({129 format: 'esm',130 dir: this.outputPath,131 sourcemap: true,132 entryFileNames({ facadeModuleId }) {133 return facadeModuleId.replace(/^\x00virtual:/, '');134 },135 });136 }137 async copyMetadata(stanzas) {138 return await Promise.all(139 stanzas.map((stanza) =>...
parse.js
Source:parse.js
1const fs = require('fs')2const path = require('path')3const extend = Object.assign4const startsWidth = (source, searchString) => {5 return source.indexOf(searchString) == 06}7const defaultParserOptions = {8 delimiters: [`{{`, `}}`],9 // getNamespace: () => Namespaces.HTML,10 // getTextMode: () => TextModes.DATA,11 // isVoidTag: NO,12 // æ¯å¦ <pre> tag13 isPreTag: 014 // isCustomElement: NO,15 // decodeEntities: (rawText: string): string =>16 // rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),17 // onError: defaultOnError,18 // onWarn: defaultOnWarn,19 // comments: __DEV__20}21// =================== ä¸ä¸ææä½ ====================22/**23 *24 * @param {*} content25 * @param {*} rawOptions26 * @returns27 */28function createParserContext(content, rawOptions) {29 const options = extend({}, defaultParserOptions, rawOptions)30 return {31 options,32 column: 1,33 line: 1,34 offset: 0,35 originalSource: content,36 source: content,37 inPre: false,38 inVPre: false,39 onWarn: options.onWarn40 }41}42/**43 * è·åå½å解æä¸ä¸æä½ç½®44 * @param {Object} context45 * @returns46 */47function getCursor(context) {48 const { column, line, offset } = context49 return { column, line, offset }50}51function advanceBy(context, numberOfCharacters) {52 const { source } = context53 advancePositionWithMutation(context, source, numberOfCharacters)54 context.source = source.slice(numberOfCharacters)55}56function advancePositionWithMutation(57 pos,58 source,59 numberOfCharacters = source.length60) {61 let linesCount = 062 let lastNewLinePos = -163 for (let i = 0; i < numberOfCharacters; i++) {64 if (source.charCodeAt(i) === 10 /* newline char code */) {65 linesCount++66 lastNewLinePos = i67 }68 }69 pos.offset += numberOfCharacters70 pos.line += linesCount71 pos.column =72 lastNewLinePos === -173 ? pos.column + numberOfCharacters74 : numberOfCharacters - lastNewLinePos75 return pos76}77/**78 * å»é¤å¤´é¨ç©ºæ ¼79 * @param {Object} context80 */81function advanceSpaces(context) {82 const match = /^[\t\r\n\f]+/.exec(context.source)83 if (match) {84 advanceBy(context, match[0].length)85 }86}87function getSelection(context, start, end) {88 end = end || getCursor(context)89 return {90 start,91 end,92 source: context.originalSource.slice(start.offset, end.offset)93 }94}95function parseComment(context) {}96function parseBogusComment(context) {97 const start = getCursor(context)98 const contentStart = context.source[1] === '?' ? 1 : 299 const closeIndex = context.source.indexOf('>')100 let content101 if (closeIndex === -1) {102 content = context.source.slice(contentStart)103 advanceBy(context, context.length)104 } else {105 content = context.source.slice(contentStart, closeIndex)106 advanceBy(context, closeIndex + 1)107 }108 return {109 type: 3,110 content,111 loc: getSelection(context, start)112 }113}114/**115 * 解ææ ç¾ <div id="id">div</div>116 * @param {Object} context117 * @param {Number} type 0ï¼ å¼å§æ ç¾ 1ï¼ç»ææ ç¾118 * @param {Element[]}} parent ç¶èç¹119 */120function parseTag(context, type, parent) {121 const start = getCursor(context)122 // </div>123 const match = /<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source)124 // æ ç¾å125 const tag = match[1]126 advanceBy(context, match[0].length)127 const cursor = getCursor(context)128 const currentSource = context.source129 const props = parseAttributes(context)130}131/**132 * 解ææ ç¾å±æ§133 * @param {Object} context134 * @param {Set} nameSet å±æ§åéå135 */136function parseAttribute(context, nameSet) {137 const start = getCursor(context)138 console.log('context: ', context.source)139 const match = /[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source)140 // å±æ§å称141 const name = match[0]142 console.log('name: ', name)143 nameSet.add(name)144 advanceBy(context, name.length)145 let value146 if (/^[\t\r\n\f ]*=/.test(context.source)) {147 advanceSpaces(context)148 // è·³è¿ =149 advanceBy(context, 1)150 // å»é¤çå·åçç©ºæ ¼151 advanceSpaces(context)152 value = parseAttributeValue(context)153 console.log('value: ', value)154 }155 const loc = getSelection(context, start)156 console.log('loc: ', loc)157}158/**159 * 解ææ ç¾å±æ§å¼160 * @param {Object} context161 */162function parseAttributeValue(context) {163 const start = getCursor(context)164 let content165 const quote = context.source[0]166 const isQuoted = quote === `"` || quote === `'`167 if (isQuoted) {168 advanceBy(context, 1)169 const endIndex = context.source.indexOf(quote)170 if (endIndex === -1) {171 } else {172 content = parseTextData()173 }174 }175 return { context, isQuoted, loc: getSelection(context, start) }176}177function parseAttributes(context, type) {178 const props = []179 const attributeNames = new Set()180 const attr = parseAttribute(context, attributeNames)181}182/**183 * 解æå
ç´ 184 * @param {Object} context185 * @param {Element []} ancestors ç¥å
å
ç´ 186 */187function parseElement(context, ancestors) {188 const start = getCursor(context)189 // ç¶èç¹190 const parent = ancestors[ancestors.length - 1]191 // å¼å§æ ç¾192 const element = parseTag(context, 0)193}194// 解ææ槽å¼195function parseInterpolation(context) {196 const [open, close] = context.options.delimiters197 const closeIndex = context.source.indexOf(close, open.length)198 const start = getCursor(context)199 advanceBy(context, open.length)200 const innerStart = getCursor(context)201 const innerEnd = getCursor(context)202 const rawContentLength = closeIndex - open.length203 const rawContent = context.source.slice(0, rawContentLength)204}205function parseTextData(context, length) {206 const rawText = context.source.slice(0, length)207 advanceBy(context, length)208}209function parse(content, options) {210 // å建解æä¸ä¸æ211 const context = createParserContext(content, options)212 //213 let node214 while (context.source) {215 if (startsWidth(context.source, '<!DOCTYPE')) {216 node = parseBogusComment(context)217 continue218 }219 // else if (startsWidth(context.source, '<!--')) {220 // parseComment(context)221 // continue222 // } else if (startsWidth(context.source, context.options.delimiters[0])) {223 // parseInterpolation(context)224 // continue225 // }226 else if (/[a-z]/i.test(context.source[1])) {227 node = parseElement(context, [])228 continue229 }230 //231 break232 }233 //234}235const templatePath = path.resolve(__dirname, './index.html')236let template = fs.readFileSync(templatePath, 'utf-8').replace(/\n/g, '')...
worker.js
Source:worker.js
1import { dim } from 'chalk'2import relative from 'require-relative'3import { EOL } from 'os'4import M from './constants/messages'5import handleFatalErrors from './util/handle-fatal-errors'6import logFatalError from './util/log-fatal-error'7import logWithMetadata from './util/log-with-metadata'8import readRollupConfig from './util/read-rollup-config'9const warnWithMetadata = logWithMetadata('warn')10const resolveRollup = cwd => {11 let rollup12 try {13 rollup = relative('rollup', cwd)14 } catch (err) {15 if (err.code !== 'MODULE_NOT_FOUND') {16 throw err17 }18 rollup = require('rollup')19 }20 return rollup21}22const defaultOnwarn = ({ code, loc, frame, message }) => {23 const fullMessage = message + (code != null ? dim(` [${code}]`) : '')24 const metadata = []25 if (loc != null) {26 metadata.push([27 'Location',28 `${loc.file}${EOL}line ${loc.line}, column ${loc.column}`29 ])30 if (frame != null) {31 metadata.push(['Code', frame])32 }33 }34 warnWithMetadata(fullMessage, metadata)35}36const buildAndRespond = async (rollup, target, config) => {37 let error = null38 try {39 const bundle = await rollup.rollup(config)40 await bundle.write(config.output)41 } catch (err) {42 logFatalError(target, err)43 error = 'Build failed'44 }45 process.send({ type: M.result, detail: { error } })46}47const createContext = () => {48 const { cwd, configPath } = JSON.parse(process.env.FANCY_ROLLUP_CONFIG)49 const rollup = resolveRollup(cwd)50 const configs = readRollupConfig(configPath)51 return { rollup, configs }52}53const createHandlers = () => {54 const { rollup, configs } = createContext()55 return {56 [M.build]: ({ target }) => {57 const config = configs[target]58 if (config.onwarn == null) {59 config.onwarn = defaultOnwarn60 }61 buildAndRespond(rollup, target, config)62 },63 [M.exit]: () => {64 process.exit(0)65 }66 }67}68const runWorker = () => {69 handleFatalErrors(error => {70 console.error(error)71 })72 const handlers = createHandlers()73 process.on('message', ({ type, detail }) => {74 handlers[type](detail)75 })76 process.send({ type: M.ready })77}...
karma.conf.js
Source:karma.conf.js
...21 reporters: [ 'spec' ],22 rollupPreprocessor: {23 onwarn: (warn, defaultOnWarn) => {24 if (![ 'CIRCULAR_DEPENDENCY', 'EVAL' ].includes(warn.code)) {25 defaultOnWarn(warn);26 }27 },28 plugins: [29 babel({30 exclude: 'node_modules/**'31 }),32 alias({33 utils: 'src/utils',34 model: 'src/model',35 modules: 'src/modules',36 'test-utils': 'src/test-utils'37 }),38 commonjs({39 namedExports: {...
Using AI Code Generation
1const { defaultOnWarn } = require('playwright/lib/utils/stackTrace');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 page.on('console', defaultOnWarn);7 await browser.close();8})();9 at CDPSession.Page._onClosed (/home/username/playwright-test/node_modules/playwright/lib/server/page.js:110:9)10 at CDPSession.emit (events.js:315:20)11 at CDPSession._onMessage (/home/username/playwright-test/node_modules/playwright/lib/server/cdpsession.js:123:12)12 at Connection._onMessage (/home/username/playwright-test/node_modules/playwright/lib/server/connection.js:194:24)13 at WebSocketTransport._ws.addEventListener.event (/home/username/playwright-test/node_modules/playwright/lib/server/webSocketTransport.js:54:50)14 at WebSocket.onMessage (/home/username/playwright-test/node_modules/ws/lib/event-target.js:125:16)15 at WebSocket.emit (events.js:315:20)16 at Receiver.receiverOnMessage (/home/username/playwright-test/node_modules/ws/lib/websocket.js:789:20)17 at Receiver.emit (events.js:315:20)18Your name to display (optional):19Your name to display (optional):20You can handle unhandled promise rejection by adding .catch() to the end of the promise chain. For example:21const { chromium } = require('playwright');22(async () => {23 const browser = await chromium.launch();
Using AI Code Generation
1const { defaultOnWarn } = require('playwright-core/lib/utils/utils');2defaultOnWarn((message) => {3});4const { defaultOnWarn } = require('playwright/lib/utils/utils');5defaultOnWarn((message) => {6});7const { defaultOnWarn } = require('playwright/lib/utils/utils');8defaultOnWarn((message) => {9});10const { defaultOnWarn } = require('playwright/lib/utils/utils');11defaultOnWarn((message) => {12 return;13});14const { defaultOnWarn } = require('playwright/lib/utils/utils');15defaultOnWarn((message) => {16 return null;17});18const { defaultOnWarn } = require('playwright/lib/utils/utils');19defaultOnWarn((message) => {20 return undefined;21});22const { defaultOnWarn } = require('playwright/lib/utils/utils');23defaultOnWarn((message) => {24 return false;25});26const { defaultOnWarn } = require('playwright/lib/utils/utils');27defaultOnWarn((message) => {
Using AI Code Generation
1const { defaultOnWarn } = require('@playwright/test/lib/test');2defaultOnWarn((message) => {3 console.log('Playwright warning: ' + message);4});5const { defaultOnWarn } = require('@playwright/test/lib/test');6defaultOnWarn((message) => {7 console.log('Playwright warning: ' + message);8});9const { defaultOnWarn } = require('@playwright/test/lib/test');10defaultOnWarn((message) => {11 console.log('Playwright warning: ' + message);12});13const { defaultOnWarn } = require('@playwright/test/lib/test');14defaultOnWarn((message) => {15 console.log('Playwright warning: ' + message);16});17const { defaultOnWarn } = require('@playwright/test/lib/test');18defaultOnWarn((message) => {19 console.log('Playwright warning: ' + message);20});21const { defaultOnWarn } = require('@playwright/test/lib/test');22defaultOnWarn((message) => {23 console.log('Playwright warning: ' + message);24});25const { defaultOnWarn } = require('@playwright/test/lib/test');26defaultOnWarn((message) => {27 console.log('Playwright warning: ' + message);28});29const { defaultOnWarn } = require('@playwright/test/lib/test');30defaultOnWarn((message) => {31 console.log('Playwright warning: ' + message);32});33const { defaultOnWarn } = require('@playwright/test/lib/test');34defaultOnWarn((message) => {35 console.log('Playwright warning: ' + message);36});37const { defaultOnWarn } = require('@playwright/test/lib/test');38defaultOnWarn((message) => {39 console.log('Playwright warning: ' + message);40});41const { defaultOnWarn } = require
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!