} return new PromiseArray(this).promise(); }; Promise.prototype.error = function (fn) { return this.caught(util$$1.originatesFromRejection, fn); }; Promise.getNewLibraryCopy = module.exports; Promise.is = function (val) { return val instanceof Promise; }; Promise.fromNode = Promise.fromCallback = function(fn) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs : false; var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); if (result === errorObj) { ret._rejectCallback(result.e, true); } if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); return ret; }; Promise.all = function (promises) { return new PromiseArray(promises).promise(); }; Promise.cast = function (obj) { var ret = tryConvertToPromise(obj); if (!(ret instanceof Promise)) { ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._setFulfilled(); ret._rejectionHandler0 = obj; } return ret; }; Promise.resolve = Promise.fulfilled = Promise.cast; Promise.reject = Promise.rejected = function (reason) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._rejectCallback(reason, true); return ret; }; Promise.setScheduler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util$$1.classString(fn)); } return async.setScheduler(fn); }; Promise.prototype._then = function ( didFulfill, didReject, _, receiver, internalData ) { var haveInternalData = internalData !== undefined; var promise = haveInternalData ? internalData : new Promise(INTERNAL); var target = this._target(); var bitField = target._bitField; if (!haveInternalData) { promise._propagateFrom(this, 3); promise._captureStackTrace(); if (receiver === undefined && ((this._bitField & 2097152) !== 0)) { if (!((bitField & 50397184) === 0)) { receiver = this._boundValue(); } else { receiver = target === this ? undefined : this._boundTo; } } this._fireEvent("promiseChained", this, promise); } var domain = getDomain(); if (!((bitField & 50397184) === 0)) { var handler, value, settler = target._settlePromiseCtx; if (((bitField & 33554432) !== 0)) { value = target._rejectionHandler0; handler = didFulfill; } else if (((bitField & 16777216) !== 0)) { value = target._fulfillmentHandler0; handler = didReject; target._unsetRejectionIsUnhandled(); } else { settler = target._settlePromiseLateCancellationObserver; value = new CancellationError("late cancellation observer"); target._attachExtraTrace(value); handler = didReject; } async.invoke(settler, target, { handler: domain === null ? handler : (typeof handler === "function" && util$$1.domainBind(domain, handler)), promise: promise, receiver: receiver, value: value }); } else { target._addCallbacks(didFulfill, didReject, promise, receiver, domain); } return promise; }; Promise.prototype._length = function () { return this._bitField & 65535; }; Promise.prototype._isFateSealed = function () { return (this._bitField & 117506048) !== 0; }; Promise.prototype._isFollowing = function () { return (this._bitField & 67108864) === 67108864; }; Promise.prototype._setLength = function (len) { this._bitField = (this._bitField & -65536) | (len & 65535); }; Promise.prototype._setFulfilled = function () { this._bitField = this._bitField | 33554432; this._fireEvent("promiseFulfilled", this); }; Promise.prototype._setRejected = function () { this._bitField = this._bitField | 16777216; this._fireEvent("promiseRejected", this); }; Promise.prototype._setFollowing = function () { this._bitField = this._bitField | 67108864; this._fireEvent("promiseResolved", this); }; Promise.prototype._setIsFinal = function () { this._bitField = this._bitField | 4194304; }; Promise.prototype._isFinal = function () { return (this._bitField & 4194304) > 0; }; Promise.prototype._unsetCancelled = function() { this._bitField = this._bitField & (~65536); }; Promise.prototype._setCancelled = function() { this._bitField = this._bitField | 65536; this._fireEvent("promiseCancelled", this); }; Promise.prototype._setWillBeCancelled = function() { this._bitField = this._bitField | 8388608; }; Promise.prototype._setAsyncGuaranteed = function() { if (async.hasCustomScheduler()) return; this._bitField = this._bitField | 134217728; }; Promise.prototype._receiverAt = function (index) { var ret = index === 0 ? this._receiver0 : this[ index * 4 - 4 + 3]; if (ret === UNDEFINED_BINDING) { return undefined; } else if (ret === undefined && this._isBound()) { return this._boundValue(); } return ret; }; Promise.prototype._promiseAt = function (index) { return this[ index * 4 - 4 + 2]; }; Promise.prototype._fulfillmentHandlerAt = function (index) { return this[ index * 4 - 4 + 0]; }; Promise.prototype._rejectionHandlerAt = function (index) { return this[ index * 4 - 4 + 1]; }; Promise.prototype._boundValue = function() {}; Promise.prototype._migrateCallback0 = function (follower) { var bitField = follower._bitField; var fulfill = follower._fulfillmentHandler0; var reject = follower._rejectionHandler0; var promise = follower._promise0; var receiver = follower._receiverAt(0); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._migrateCallbackAt = function (follower, index) { var fulfill = follower._fulfillmentHandlerAt(index); var reject = follower._rejectionHandlerAt(index); var promise = follower._promiseAt(index); var receiver = follower._receiverAt(index); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._addCallbacks = function ( fulfill, reject, promise, receiver, domain ) { var index = this._length(); if (index >= 65535 - 4) { index = 0; this._setLength(0); } if (index === 0) { this._promise0 = promise; this._receiver0 = receiver; if (typeof fulfill === "function") { this._fulfillmentHandler0 = domain === null ? fulfill : util$$1.domainBind(domain, fulfill); } if (typeof reject === "function") { this._rejectionHandler0 = domain === null ? reject : util$$1.domainBind(domain, reject); } } else { var base = index * 4 - 4; this[base + 2] = promise; this[base + 3] = receiver; if (typeof fulfill === "function") { this[base + 0] = domain === null ? fulfill : util$$1.domainBind(domain, fulfill); } if (typeof reject === "function") { this[base + 1] = domain === null ? reject : util$$1.domainBind(domain, reject); } } this._setLength(index + 1); return index; }; Promise.prototype._proxy = function (proxyable, arg) { this._addCallbacks(undefined, undefined, arg, proxyable, null); }; Promise.prototype._resolveCallback = function(value, shouldBind) { if (((this._bitField & 117506048) !== 0)) return; if (value === this) return this._rejectCallback(makeSelfResolutionError(), false); var maybePromise = tryConvertToPromise(value, this); if (!(maybePromise instanceof Promise)) return this._fulfill(value); if (shouldBind) this._propagateFrom(maybePromise, 2); var promise = maybePromise._target(); if (promise === this) { this._reject(makeSelfResolutionError()); return; } var bitField = promise._bitField; if (((bitField & 50397184) === 0)) { var len = this._length(); if (len > 0) promise._migrateCallback0(this); for (var i = 1; i < len; ++i) { promise._migrateCallbackAt(this, i); } this._setFollowing(); this._setLength(0); this._setFollowee(promise); } else if (((bitField & 33554432) !== 0)) { this._fulfill(promise._value()); } else if (((bitField & 16777216) !== 0)) { this._reject(promise._reason()); } else { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); this._reject(reason); } }; Promise.prototype._rejectCallback = function(reason, synchronous, ignoreNonErrorWarnings) { var trace = util$$1.ensureErrorObject(reason); var hasStack = trace === reason; if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { var message = "a promise was rejected with a non-error: " + util$$1.classString(reason); this._warn(message, true); } this._attachExtraTrace(trace, synchronous ? hasStack : false); this._reject(reason); }; Promise.prototype._resolveFromExecutor = function (executor) { if (executor === INTERNAL) return; var promise = this; this._captureStackTrace(); this._pushContext(); var synchronous = true; var r = this._execute(executor, function(value) { promise._resolveCallback(value); }, function (reason) { promise._rejectCallback(reason, synchronous); }); synchronous = false; this._popContext(); if (r !== undefined) { promise._rejectCallback(r, true); } }; Promise.prototype._settlePromiseFromHandler = function ( handler, receiver, value, promise ) { var bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; promise._pushContext(); var x; if (receiver === APPLY) { if (!value || typeof value.length !== "number") { x = errorObj; x.e = new TypeError("cannot .spread() a non-array: " + util$$1.classString(value)); } else { x = tryCatch(handler).apply(this._boundValue(), value); } } else { x = tryCatch(handler).call(receiver, value); } var promiseCreated = promise._popContext(); bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; if (x === NEXT_FILTER) { promise._reject(value); } else if (x === errorObj) { promise._rejectCallback(x.e, false); } else { debug.checkForgottenReturns(x, promiseCreated, "", promise, this); promise._resolveCallback(x); } }; Promise.prototype._target = function() { var ret = this; while (ret._isFollowing()) ret = ret._followee(); return ret; }; Promise.prototype._followee = function() { return this._rejectionHandler0; }; Promise.prototype._setFollowee = function(promise) { this._rejectionHandler0 = promise; }; Promise.prototype._settlePromise = function(promise, handler, receiver, value) { var isPromise = promise instanceof Promise; var bitField = this._bitField; var asyncGuaranteed = ((bitField & 134217728) !== 0); if (((bitField & 65536) !== 0)) { if (isPromise) promise._invokeInternalOnCancel(); if (receiver instanceof PassThroughHandlerContext && receiver.isFinallyHandler()) { receiver.cancelPromise = promise; if (tryCatch(handler).call(receiver, value) === errorObj) { promise._reject(errorObj.e); } } else if (handler === reflectHandler) { promise._fulfill(reflectHandler.call(receiver)); } else if (receiver instanceof Proxyable) { receiver._promiseCancelled(promise); } else if (isPromise || promise instanceof PromiseArray) { promise._cancel(); } else { receiver.cancel(); } } else if (typeof handler === "function") { if (!isPromise) { handler.call(receiver, value, promise); } else { if (asyncGuaranteed) promise._setAsyncGuaranteed(); this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (receiver instanceof Proxyable) { if (!receiver._isResolved()) { if (((bitField & 33554432) !== 0)) { receiver._promiseFulfilled(value, promise); } else { receiver._promiseRejected(value, promise); } } } else if (isPromise) { if (asyncGuaranteed) promise._setAsyncGuaranteed(); if (((bitField & 33554432) !== 0)) { promise._fulfill(value); } else { promise._reject(value); } } }; Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { var handler = ctx.handler; var promise = ctx.promise; var receiver = ctx.receiver; var value = ctx.value; if (typeof handler === "function") { if (!(promise instanceof Promise)) { handler.call(receiver, value, promise); } else { this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (promise instanceof Promise) { promise._reject(value); } }; Promise.prototype._settlePromiseCtx = function(ctx) { this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); }; Promise.prototype._settlePromise0 = function(handler, value, bitField) { var promise = this._promise0; var receiver = this._receiverAt(0); this._promise0 = undefined; this._receiver0 = undefined; this._settlePromise(promise, handler, receiver, value); }; Promise.prototype._clearCallbackDataAtIndex = function(index) { var base = index * 4 - 4; this[base + 2] = this[base + 3] = this[base + 0] = this[base + 1] = undefined; }; Promise.prototype._fulfill = function (value) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; if (value === this) { var err = makeSelfResolutionError(); this._attachExtraTrace(err); return this._reject(err); } this._setFulfilled(); this._rejectionHandler0 = value; if ((bitField & 65535) > 0) { if (((bitField & 134217728) !== 0)) { this._settlePromises(); } else { async.settlePromises(this); } } }; Promise.prototype._reject = function (reason) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; this._setRejected(); this._fulfillmentHandler0 = reason; if (this._isFinal()) { return async.fatalError(reason, util$$1.isNode); } if ((bitField & 65535) > 0) { async.settlePromises(this); } else { this._ensurePossibleRejectionHandled(); } }; Promise.prototype._fulfillPromises = function (len, value) { for (var i = 1; i < len; i++) { var handler = this._fulfillmentHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, value); } }; Promise.prototype._rejectPromises = function (len, reason) { for (var i = 1; i < len; i++) { var handler = this._rejectionHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, reason); } }; Promise.prototype._settlePromises = function () { var bitField = this._bitField; var len = (bitField & 65535); if (len > 0) { if (((bitField & 16842752) !== 0)) { var reason = this._fulfillmentHandler0; this._settlePromise0(this._rejectionHandler0, reason, bitField); this._rejectPromises(len, reason); } else { var value = this._rejectionHandler0; this._settlePromise0(this._fulfillmentHandler0, value, bitField); this._fulfillPromises(len, value); } this._setLength(0); } this._clearCancellationData(); }; Promise.prototype._settledValue = function() { var bitField = this._bitField; if (((bitField & 33554432) !== 0)) { return this._rejectionHandler0; } else if (((bitField & 16777216) !== 0)) { return this._fulfillmentHandler0; } }; function deferResolve(v) {this.promise._resolveCallback(v);} function deferReject(v) {this.promise._rejectCallback(v, false);} Promise.defer = Promise.pending = function() { debug.deprecated("Promise.defer", "new Promise"); var promise = new Promise(INTERNAL); return { promise: promise, resolve: deferResolve, reject: deferReject }; }; util$$1.notEnumerableProp(Promise, "_makeSelfResolutionError", makeSelfResolutionError); method(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug); bind(Promise, INTERNAL, tryConvertToPromise, debug); cancel(Promise, PromiseArray, apiRejection, debug); direct_resolve(Promise); synchronous_inspection(Promise); join$9( Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); Promise.Promise = Promise; Promise.version = "3.5.0"; map(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); call_get(Promise); using(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); timers$1(Promise, INTERNAL, debug); generators(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); nodeify(Promise); promisify(Promise, INTERNAL); props(Promise, PromiseArray, tryConvertToPromise, apiRejection); race(Promise, INTERNAL, tryConvertToPromise, apiRejection); reduce(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); settle(Promise, PromiseArray, debug); some(Promise, PromiseArray, apiRejection); filter$1(Promise, INTERNAL); each(Promise, INTERNAL); any(Promise); util$$1.toFastProperties(Promise); util$$1.toFastProperties(Promise.prototype); function fillTypes(value) { var p = new Promise(INTERNAL); p._fulfillmentHandler0 = value; p._rejectionHandler0 = value; p._promise0 = value; p._receiver0 = value; } // Complete slack tracking, opt out of field-type tracking and // stabilize map fillTypes({a: 1}); fillTypes({b: 2}); fillTypes({c: 3}); fillTypes(1); fillTypes(function(){}); fillTypes(undefined); fillTypes(false); fillTypes(new Promise(INTERNAL)); debug.setBounds(Async.firstLineError, util$$1.lastLineError); return Promise; }; }); var old; if (typeof Promise !== "undefined") old = Promise; function noConflict() { try { if (Promise === bluebird) Promise = old; } catch (e) {} return bluebird; } var bluebird = promise(); bluebird.noConflict = noConflict; var bluebird_1 = bluebird; // Based on iniparser by shockie <https://npmjs.org/package/iniparser> /* * get the file handler */ /* * define the possible values: * section: [section] * param: key=value * comment: ;this is a comment */ var regex = { section: /^\s*\[(([^#;]|\\#|\\;)+)\]\s*([#;].*)?$/, param: /^\s*([\w\.\-\_]+)\s*[=:]\s*(.*?)\s*([#;].*)?$/, comment: /^\s*[#;].*$/ }; /* * parses a .ini file * @param: {String} file, the location of the .ini file * @param: {Function} callback, the function that will be called when parsing is done * @return: none */ var parse_1 = function (file, callback) { if (!callback) { return; } fs.readFile(file, 'utf8', function (err, data) { if (err) { callback(err); } else { callback(null, parse(data)); } }); }; var parseSync$1 = function (file) { return parse(fs.readFileSync(file, 'utf8')); }; var parseString$1 = function (data) { var sectionBody = {}; var sectionName = null; var value = [[sectionName, sectionBody]]; var lines = data.split(/\r\n|\r|\n/); lines.forEach(function (line) { var match; if (regex.comment.test(line)) { return; } else if (regex.param.test(line)) { match = line.match(regex.param); sectionBody[match[1]] = match[2]; } else if (regex.section.test(line)) { match = line.match(regex.section); sectionName = match[1]; sectionBody = {}; value.push([sectionName, sectionBody]); } }); return value; }; var ini = { parse: parse_1, parseSync: parseSync$1, parseString: parseString$1 }; var hasOwnProperty = Object.prototype.hasOwnProperty; var pseudomap = PseudoMap; function PseudoMap (set) { if (!(this instanceof PseudoMap)) // whyyyyyyy throw new TypeError("Constructor PseudoMap requires 'new'") this.clear(); if (set) { if ((set instanceof PseudoMap) || (typeof Map === 'function' && set instanceof Map)) set.forEach(function (value, key) { this.set(key, value); }, this); else if (Array.isArray(set)) set.forEach(function (kv) { this.set(kv[0], kv[1]); }, this); else throw new TypeError('invalid argument') } } PseudoMap.prototype.forEach = function (fn, thisp) { thisp = thisp || this; Object.keys(this._data).forEach(function (k) { if (k !== 'size') fn.call(thisp, this._data[k].value, this._data[k].key); }, this); }; PseudoMap.prototype.has = function (k) { return !!find(this._data, k) }; PseudoMap.prototype.get = function (k) { var res = find(this._data, k); return res && res.value }; PseudoMap.prototype.set = function (k, v) { set(this._data, k, v); }; PseudoMap.prototype.delete = function (k) { var res = find(this._data, k); if (res) { delete this._data[res._index]; this._data.size--; } }; PseudoMap.prototype.clear = function () { var data = Object.create(null); data.size = 0; Object.defineProperty(this, '_data', { value: data, enumerable: false, configurable: true, writable: false }); }; Object.defineProperty(PseudoMap.prototype, 'size', { get: function () { return this._data.size }, set: function (n) {}, enumerable: true, configurable: true }); PseudoMap.prototype.values = PseudoMap.prototype.keys = PseudoMap.prototype.entries = function () { throw new Error('iterators are not implemented in this version') }; // Either identical, or both NaN function same (a, b) { return a === b || a !== a && b !== b } function Entry$1 (k, v, i) { this.key = k; this.value = v; this._index = i; } function find (data, k) { for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) { if (same(data[key].key, k)) return data[key] } } function set (data, k, v) { for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) { if (same(data[key].key, k)) { data[key].value = v; return } } data.size++; data[key] = new Entry$1(k, v, key); } var map$2 = createCommonjsModule(function (module) { if (process.env.npm_package_name === 'pseudomap' && process.env.npm_lifecycle_script === 'test') process.env.TEST_PSEUDOMAP = 'true'; if (typeof Map === 'function' && !process.env.TEST_PSEUDOMAP) { module.exports = Map; } else { module.exports = pseudomap; } }); var lruCache = LRUCache; // This will be a proper iterable 'Map' in engines that support it, // or a fakey-fake PseudoMap in older versions. function naiveLength () { return 1 } function LRUCache (options) { if (!(this instanceof LRUCache)) return new LRUCache(options) if (typeof options === 'number') options = { max: options }; if (!options) options = {}; this._max = options.max; // Kind of weird to have a default max of Infinity, but oh well. if (!this._max || !(typeof this._max === "number") || this._max <= 0 ) this._max = Infinity; this._lengthCalculator = options.length || naiveLength; if (typeof this._lengthCalculator !== "function") this._lengthCalculator = naiveLength; this._allowStale = options.stale || false; this._maxAge = options.maxAge || null; this._dispose = options.dispose; this.reset(); } // resize the cache when the max changes. Object.defineProperty(LRUCache.prototype, "max", { set : function (mL) { if (!mL || !(typeof mL === "number") || mL <= 0 ) mL = Infinity; this._max = mL; if (this._length > this._max) trim(this); } , get : function () { return this._max } , enumerable : true }); // resize the cache when the lengthCalculator changes. Object.defineProperty(LRUCache.prototype, "lengthCalculator", { set : function (lC) { if (typeof lC !== "function") { this._lengthCalculator = naiveLength; this._length = this._lruList.size; this._cache.forEach(function (value, key) { value.length = 1; }); } else { this._lengthCalculator = lC; this._length = 0; this._cache.forEach(function (value, key) { value.length = this._lengthCalculator(value.value, key); this._length += value.length; }, this); } if (this._length > this._max) trim(this); } , get : function () { return this._lengthCalculator } , enumerable : true }); Object.defineProperty(LRUCache.prototype, "length", { get : function () { return this._length } , enumerable : true }); Object.defineProperty(LRUCache.prototype, "itemCount", { get : function () { return this._lruList.size } , enumerable : true }); function reverseKeys (map) { // keys live in lruList map in insertion order. // we want them in reverse insertion order. // flip the list of keys. var itemCount = map.size; var keys = new Array(itemCount); var i = itemCount; map.forEach(function (value, key) { keys[--i] = key; }); return keys } LRUCache.prototype.rforEach = function (fn, thisp) { thisp = thisp || this; this._lruList.forEach(function (hit) { forEachStep(this, fn, hit, thisp); }, this); }; function forEachStep (self, fn, hit, thisp) { if (isStale(self, hit)) { del(self, hit); if (!self._allowStale) { hit = undefined; } } if (hit) { fn.call(thisp, hit.value, hit.key, self); } } LRUCache.prototype.forEach = function (fn, thisp) { thisp = thisp || this; var keys = reverseKeys(this._lruList); for (var k = 0; k < keys.length; k++) { var hit = this._lruList.get(keys[k]); forEachStep(this, fn, hit, thisp); } }; LRUCache.prototype.keys = function () { return reverseKeys(this._lruList).map(function (k) { return this._lruList.get(k).key }, this) }; LRUCache.prototype.values = function () { return reverseKeys(this._lruList).map(function (k) { return this._lruList.get(k).value }, this) }; LRUCache.prototype.reset = function () { if (this._dispose && this._cache) { this._cache.forEach(function (entry, key) { this._dispose(key, entry.value); }, this); } this._cache = new map$2(); // hash of items by key this._lruList = new map$2(); // list of items in order of use recency this._mru = 0; // most recently used this._lru = 0; // least recently used this._length = 0; // number of items in the list }; LRUCache.prototype.dump = function () { var arr = []; var i = 0; var size = this._lruList.size; return reverseKeys(this._lruList).map(function (k) { var hit = this._lruList.get(k); if (!isStale(this, hit)) { return { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) } } }, this).filter(function (h) { return h }) }; LRUCache.prototype.dumpLru = function () { return this._lruList }; LRUCache.prototype.set = function (key, value, maxAge) { maxAge = maxAge || this._maxAge; var now = maxAge ? Date.now() : 0; var len = this._lengthCalculator(value, key); if (this._cache.has(key)) { if (len > this._max) { del(this, this._cache.get(key)); return false } var item = this._cache.get(key); // dispose of the old one before overwriting if (this._dispose) this._dispose(key, item.value); item.now = now; item.maxAge = maxAge; item.value = value; this._length += (len - item.length); item.length = len; this.get(key); if (this._length > this._max) trim(this); return true } var hit = new Entry(key, value, this._mru, len, now, maxAge); incMru(this); // oversized objects fall out of cache automatically. if (hit.length > this._max) { if (this._dispose) this._dispose(key, value); return false } this._length += hit.length; this._cache.set(key, hit); this._lruList.set(hit.lu, hit); if (this._length > this._max) trim(this); return true }; LRUCache.prototype.has = function (key) { if (!this._cache.has(key)) return false var hit = this._cache.get(key); if (isStale(this, hit)) { return false } return true }; LRUCache.prototype.get = function (key) { return get(this, key, true) }; LRUCache.prototype.peek = function (key) { return get(this, key, false) }; LRUCache.prototype.pop = function () { var hit = this._lruList.get(this._lru); del(this, hit); return hit || null }; LRUCache.prototype.del = function (key) { del(this, this._cache.get(key)); }; LRUCache.prototype.load = function (arr) { //reset the cache this.reset(); var now = Date.now(); // A previous serialized cache has the most recent items first for (var l = arr.length - 1; l >= 0; l--) { var hit = arr[l]; var expiresAt = hit.e || 0; if (expiresAt === 0) { // the item was created without expiration in a non aged cache this.set(hit.k, hit.v); } else { var maxAge = expiresAt - now; // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge); } } } }; function get (self, key, doUse) { var hit = self._cache.get(key); if (hit) { if (isStale(self, hit)) { del(self, hit); if (!self._allowStale) hit = undefined; } else { if (doUse) use(self, hit); } if (hit) hit = hit.value; } return hit } function isStale(self, hit) { if (!hit || (!hit.maxAge && !self._maxAge)) return false var stale = false; var diff = Date.now() - hit.now; if (hit.maxAge) { stale = diff > hit.maxAge; } else { stale = self._maxAge && (diff > self._maxAge); } return stale; } function use (self, hit) { shiftLU(self, hit); hit.lu = self._mru; incMru(self); self._lruList.set(hit.lu, hit); } function trim (self) { if (self._length > self._max) { var keys = reverseKeys(self._lruList); for (var k = keys.length - 1; self._length > self._max; k--) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. self._lru = keys[k - 1]; del(self, self._lruList.get(keys[k])); } } } function shiftLU (self, hit) { self._lruList.delete(hit.lu); if (hit.lu === self._lru) self._lru = reverseKeys(self._lruList).pop(); } function del (self, hit) { if (hit) { if (self._dispose) self._dispose(hit.key, hit.value); self._length -= hit.length; self._cache.delete(hit.key); shiftLU(self, hit); } } // classy, since V8 prefers predictable objects. function Entry (key, value, lu, length, now, maxAge) { this.key = key; this.value = value; this.lu = lu; this.length = length; this.now = now; if (maxAge) this.maxAge = maxAge; } // Incrementers and decrementers that loop at MAX_SAFE_INTEGER // only relevant for the lu, lru, and mru counters, since they // get touched a lot and can get very large. Also, since they // only go upwards, and the sets will tend to be much smaller than // the max, we can very well assume that a very small number comes // after a very large number, rather than before it. var maxSafeInt = Number.MAX_SAFE_INTEGER || 9007199254740991; function intInc (number) { return (number === maxSafeInt) ? 0 : number + 1 } function incMru (self) { do { self._mru = intInc(self._mru); } while (self._lruList.has(self._mru)) } var sigmund_1 = sigmund; function sigmund (subject, maxSessions) { maxSessions = maxSessions || 10; var notes = []; var analysis = ''; var RE = RegExp; function psychoAnalyze (subject, session) { if (session > maxSessions) return; if (typeof subject === 'function' || typeof subject === 'undefined') { return; } if (typeof subject !== 'object' || !subject || (subject instanceof RE)) { analysis += subject; return; } if (notes.indexOf(subject) !== -1 || session === maxSessions) return; notes.push(subject); analysis += '{'; Object.keys(subject).forEach(function (issue, _, __) { // pseudo-private values. skip those. if (issue.charAt(0) === '_') return; var to = typeof subject[issue]; if (to === 'function' || to === 'undefined') return; analysis += issue; psychoAnalyze(subject[issue], session + 1); }); } psychoAnalyze(subject, 0); return analysis; } // vim: set softtabstop=4 shiftwidth=4: var fnmatch$1 = createCommonjsModule(function (module, exports) { // Based on minimatch.js by isaacs <https://npmjs.org/package/minimatch> var platform = typeof process === "object" ? process.platform : "win32"; if (module) module.exports = minimatch; else exports.minimatch = minimatch; minimatch.Minimatch = Minimatch; var cache = minimatch.cache = new lruCache({max: 100}) , GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}; var qmark = "[^/]" // * => any number of characters , star = qmark + "*?" // ** when dots are allowed. Anything goes, except .. and . // not (^ or / followed by one or two dots followed by $ or /), // followed by anything, any number of times. , twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?" // not a ^ or / followed by a dot, // followed by anything, any number of times. , twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?" // characters that need to be escaped in RegExp. , reSpecials = charSet("().*{}+?[]^$\\!"); // "abc" -> { a:true, b:true, c:true } function charSet (s) { return s.split("").reduce(function (set, c) { set[c] = true; return set }, {}) } // normalizes slashes. var slashSplit = /\/+/; minimatch.monkeyPatch = monkeyPatch; function monkeyPatch () { var desc = Object.getOwnPropertyDescriptor(String.prototype, "match"); var orig = desc.value; desc.value = function (p) { if (p instanceof Minimatch) return p.match(this) return orig.call(this, p) }; Object.defineProperty(String.prototype, desc); } minimatch.filter = filter; function filter (pattern, options) { options = options || {}; return function (p, i, list) { return minimatch(p, pattern, options) } } function ext (a, b) { a = a || {}; b = b || {}; var t = {}; Object.keys(b).forEach(function (k) { t[k] = b[k]; }); Object.keys(a).forEach(function (k) { t[k] = a[k]; }); return t } minimatch.defaults = function (def) { if (!def || !Object.keys(def).length) return minimatch var orig = minimatch; var m = function minimatch (p, pattern, options) { return orig.minimatch(p, pattern, ext(def, options)) }; m.Minimatch = function Minimatch (pattern, options) { return new orig.Minimatch(pattern, ext(def, options)) }; return m }; Minimatch.defaults = function (def) { if (!def || !Object.keys(def).length) return Minimatch return minimatch.defaults(def).Minimatch }; function minimatch (p, pattern, options) { if (typeof pattern !== "string") { throw new TypeError("glob pattern string required") } if (!options) options = {}; // shortcut: comments match nothing. if (!options.nocomment && pattern.charAt(0) === "#") { return false } // "" only matches "" if (pattern.trim() === "") return p === "" return new Minimatch(pattern, options).match(p) } function Minimatch (pattern, options) { if (!(this instanceof Minimatch)) { return new Minimatch(pattern, options, cache) } if (typeof pattern !== "string") { throw new TypeError("glob pattern string required") } if (!options) options = {}; // windows: need to use /, not \ // On other platforms, \ is a valid (albeit bad) filename char. if (platform === "win32") { pattern = pattern.split("\\").join("/"); } // lru storage. // these things aren't particularly big, but walking down the string // and turning it into a regexp can get pretty costly. var cacheKey = pattern + "\n" + sigmund_1(options); var cached = minimatch.cache.get(cacheKey); if (cached) return cached minimatch.cache.set(cacheKey, this); this.options = options; this.set = []; this.pattern = pattern; this.regexp = null; this.negate = false; this.comment = false; this.empty = false; // make the set of regexps etc. this.make(); } Minimatch.prototype.make = make; function make () { // don't do it more than once. if (this._made) return var pattern = this.pattern; var options = this.options; // empty patterns and comments match nothing. if (!options.nocomment && pattern.charAt(0) === "#") { this.comment = true; return } if (!pattern) { this.empty = true; return } // step 1: figure out negation, etc. this.parseNegate(); // step 2: expand braces var set = this.globSet = this.braceExpand(); if (options.debug) console.error(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion // matching patterns. // These will be regexps, except in the case of "**", which is // set to the GLOBSTAR object for globstar behavior, // and will not contain any / characters set = this.globParts = set.map(function (s) { return s.split(slashSplit) }); if (options.debug) console.error(this.pattern, set); // glob --> regexps set = set.map(function (s, si, set) { return s.map(this.parse, this) }, this); if (options.debug) console.error(this.pattern, set); // filter out everything that didn't compile properly. set = set.filter(function (s) { return -1 === s.indexOf(false) }); if (options.debug) console.error(this.pattern, set); this.set = set; } Minimatch.prototype.parseNegate = parseNegate; function parseNegate () { var pattern = this.pattern , negate = false , options = this.options , negateOffset = 0; if (options.nonegate) return for ( var i = 0, l = pattern.length ; i < l && pattern.charAt(i) === "!" ; i ++) { negate = !negate; negateOffset ++; } if (negateOffset) this.pattern = pattern.substr(negateOffset); this.negate = negate; } // Brace expansion: // a{b,c}d -> abd acd // a{b,}c -> abc ac // a{0..3}d -> a0d a1d a2d a3d // a{b,c{d,e}f}g -> abg acdfg acefg // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg // // Invalid sets are not expanded. // a{2..}b -> a{2..}b // a{b}c -> a{b}c minimatch.braceExpand = function (pattern, options) { return new Minimatch(pattern, options).braceExpand() }; Minimatch.prototype.braceExpand = braceExpand; function braceExpand (pattern, options) { options = options || this.options; pattern = typeof pattern === "undefined" ? this.pattern : pattern; if (typeof pattern === "undefined") { throw new Error("undefined pattern") } if (options.nobrace || !pattern.match(/\{.*\}/)) { // shortcut. no need to expand. return [pattern] } var escaping = false; // examples and comments refer to this crazy pattern: // a{b,c{d,e},{f,g}h}x{y,z} // expected: // abxy // abxz // acdxy // acdxz // acexy // acexz // afhxy // afhxz // aghxy // aghxz // everything before the first \{ is just a prefix. // So, we pluck that off, and work with the rest, // and then prepend it to everything we find. if (pattern.charAt(0) !== "{") { // console.error(pattern) var prefix = null; for (var i = 0, l = pattern.length; i < l; i ++) { var c = pattern.charAt(i); // console.error(i, c) if (c === "\\") { escaping = !escaping; } else if (c === "{" && !escaping) { prefix = pattern.substr(0, i); break } } // actually no sets, all { were escaped. if (prefix === null) { // console.error("no sets") return [pattern] } var tail = braceExpand(pattern.substr(i), options); return tail.map(function (t) { return prefix + t }) } // now we have something like: // {b,c{d,e},{f,g}h}x{y,z} // walk through the set, expanding each part, until // the set ends. then, we'll expand the suffix. // If the set only has a single member, then'll put the {} back // first, handle numeric sets, since they're easier var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/); if (numset) { // console.error("numset", numset[1], numset[2]) var suf = braceExpand(pattern.substr(numset[0].length), options) , start = +numset[1] , end = +numset[2] , inc = start > end ? -1 : 1 , set = []; for (var i = start; i != (end + inc); i += inc) { // append all the suffixes for (var ii = 0, ll = suf.length; ii < ll; ii ++) { set.push(i + suf[ii]); } } return set } // ok, walk through the set // We hope, somewhat optimistically, that there // will be a } at the end. // If the closing brace isn't found, then the pattern is // interpreted as braceExpand("\\" + pattern) so that // the leading \{ will be interpreted literally. var i = 1 // skip the \{ , depth = 1 , set = [] , member = "" , sawEnd = false , escaping = false; function addMember () { set.push(member); member = ""; } // console.error("Entering for") FOR: for (i = 1, l = pattern.length; i < l; i ++) { var c = pattern.charAt(i); // console.error("", i, c) if (escaping) { escaping = false; member += "\\" + c; } else { switch (c) { case "\\": escaping = true; continue case "{": depth ++; member += "{"; continue case "}": depth --; // if this closes the actual set, then we're done if (depth === 0) { addMember(); // pluck off the close-brace i ++; break FOR } else { member += c; continue } case ",": if (depth === 1) { addMember(); } else { member += c; } continue default: member += c; continue } // switch } // else } // for // now we've either finished the set, and the suffix is // pattern.substr(i), or we have *not* closed the set, // and need to escape the leading brace if (depth !== 0) { // console.error("didn't close", pattern) return braceExpand("\\" + pattern, options) } // x{y,z} -> ["xy", "xz"] // console.error("set", set) // console.error("suffix", pattern.substr(i)) var suf = braceExpand(pattern.substr(i), options); // ["b", "c{d,e}","{f,g}h"] -> // [["b"], ["cd", "ce"], ["fh", "gh"]] var addBraces = set.length === 1; // console.error("set pre-expanded", set) set = set.map(function (p) { return braceExpand(p, options) }); // console.error("set expanded", set) // [["b"], ["cd", "ce"], ["fh", "gh"]] -> // ["b", "cd", "ce", "fh", "gh"] set = set.reduce(function (l, r) { return l.concat(r) }); if (addBraces) { set = set.map(function (s) { return "{" + s + "}" }); } // now attach the suffixes. var ret = []; for (var i = 0, l = set.length; i < l; i ++) { for (var ii = 0, ll = suf.length; ii < ll; ii ++) { ret.push(set[i] + suf[ii]); } } return ret } // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full // pattern, split on '/', and then turned into a regular expression. // A regexp is made at the end which joins each array with an // escaped /, and another full one which joins each regexp with |. // // Following the lead of Bash 4.1, note that "**" only has special meaning // when it is the *only* thing in a path portion. Otherwise, any series // of * is equivalent to a single *. Globstar behavior is enabled by // default, and can be disabled by setting options.noglobstar. Minimatch.prototype.parse = parse; var SUBPARSE = {}; function parse (pattern, isSub) { var options = this.options; // shortcuts if (!options.noglobstar && pattern === "**") return GLOBSTAR if (pattern === "") return "" var re = "" , hasMagic = !!options.nocase , escaping = false // ? => one single character , patternListStack = [] , plType , stateChar , inClass = false , reClassStart = -1 , classStart = -1 // . and .. never match anything that doesn't start with ., // even when options.dot is set. , patternStart = pattern.charAt(0) === "." ? "" // anything // not (start or / followed by . or .. followed by / or end) : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" : "(?!\\.)"; function clearStateChar () { if (stateChar) { // we had some state-tracking character // that wasn't consumed by this pass. switch (stateChar) { case "*": re += star; hasMagic = true; break case "?": re += qmark; hasMagic = true; break default: re += "\\"+stateChar; break } stateChar = false; } } for ( var i = 0, len = pattern.length, c ; (i < len) && (c = pattern.charAt(i)) ; i ++ ) { if (options.debug) { console.error("%s\t%s %s %j", pattern, i, re, c); } // skip over any that are escaped. if (escaping && reSpecials[c]) { re += "\\" + c; escaping = false; continue } SWITCH: switch (c) { case "/": // completely not allowed, even escaped. // Should already be path-split by now. return false case "\\": clearStateChar(); escaping = true; continue // the various stateChar values // for the "extglob" stuff. case "?": case "*": case "+": case "@": case "!": if (options.debug) { console.error("%s\t%s %s %j <-- stateChar", pattern, i, re, c); } // all of those are literals inside a class, except that // the glob [!a] means [^a] in regexp if (inClass) { if (c === "!" && i === classStart + 1) c = "^"; re += c; continue } // if we already have a stateChar, then it means // that there was something like ** or +? in there. // Handle the stateChar, then proceed with this one. clearStateChar(); stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing. // just clear the statechar *now*, rather than even diving into // the patternList stuff. if (options.noext) clearStateChar(); continue case "(": if (inClass) { re += "("; continue } if (!stateChar) { re += "\\("; continue } plType = stateChar; patternListStack.push({ type: plType , start: i - 1 , reStart: re.length }); // negation is (?:(?!js)[^/]*) re += stateChar === "!" ? "(?:(?!" : "(?:"; stateChar = false; continue case ")": if (inClass || !patternListStack.length) { re += "\\)"; continue } hasMagic = true; re += ")"; plType = patternListStack.pop().type; // negation is (?:(?!js)[^/]*) // The others are (?:<pattern>)<type> switch (plType) { case "!": re += "[^/]*?)"; break case "?": case "+": case "*": re += plType; case "@": break // the default anyway } continue case "|": if (inClass || !patternListStack.length || escaping) { re += "\\|"; escaping = false; continue } re += "|"; continue // these are mostly the same in regexp and glob case "[": // swallow any state-tracking char before the [ clearStateChar(); if (inClass) { re += "\\" + c; continue } inClass = true; classStart = i; reClassStart = re.length; re += c; continue case "]": // a right bracket shall lose its special // meaning and represent itself in // a bracket expression if it occurs // first in the list. -- POSIX.2 2.8.3.2 if (i === classStart + 1 || !inClass) { re += "\\" + c; escaping = false; continue } // finish up the class. hasMagic = true; inClass = false; re += c; continue default: // swallow any state char that wasn't consumed clearStateChar(); if (escaping) { // no need escaping = false; } else if (reSpecials[c] && !(c === "^" && inClass)) { re += "\\"; } re += c; } // switch } // for // handle the case where we left a class open. // "[abc" is valid, equivalent to "\[abc" if (inClass) { // split where the last [ was, and escape it // this is a huge pita. We now have to re-walk // the contents of the would-be class to re-translate // any characters that were passed through as-is var cs = pattern.substr(classStart + 1) , sp = this.parse(cs, SUBPARSE); re = re.substr(0, reClassStart) + "\\[" + sp[0]; hasMagic = hasMagic || sp[1]; } // handle the case where we had a +( thing at the *end* // of the pattern. // each pattern list stack adds 3 chars, and we need to go through // and escape any | chars that were passed through as-is for the regexp. // Go through and escape them, taking care not to double-escape any // | chars that were already escaped. var pl; while (pl = patternListStack.pop()) { var tail = re.slice(pl.reStart + 3); // maybe some even number of \, then maybe 1 \, followed by a | tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) { if (!$2) { // the | isn't already escaped, so escape it. $2 = "\\"; } // need to escape all those slashes *again*, without escaping the // one that we need for escaping the | character. As it works out, // escaping an even number of slashes can be done by simply repeating // it exactly after itself. That's why this trick works. // // I am sorry that you have to see this. return $1 + $1 + $2 + "|" }); // console.error("tail=%j\n %s", tail, tail) var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type; hasMagic = true; re = re.slice(0, pl.reStart) + t + "\\(" + tail; } // handle trailing things that only matter at the very end. clearStateChar(); if (escaping) { // trailing \\ re += "\\\\"; } // only need to apply the nodot start if the re starts with // something that could conceivably capture a dot var addPatternStart = false; switch (re.charAt(0)) { case ".": case "[": case "(": addPatternStart = true; } // if the re is not "" at this point, then we need to make sure // it doesn't match against an empty path part. // Otherwise a/* will match a/, which it should not. if (re !== "" && hasMagic) re = "(?=.)" + re; if (addPatternStart) re = patternStart + re; // parsing just a piece of a larger pattern. if (isSub === SUBPARSE) { return [ re, hasMagic ] } // skip the regexp for non-magical patterns // unescape anything in it, though, so that it'll be // an exact match against a file etc. if (!hasMagic) { return globUnescape(pattern) } var flags = options.nocase ? "i" : "" , regExp = new RegExp("^" + re + "$", flags); regExp._glob = pattern; regExp._src = re; return regExp } minimatch.makeRe = function (pattern, options) { return new Minimatch(pattern, options || {}).makeRe() }; Minimatch.prototype.makeRe = makeRe; function makeRe () { if (this.regexp || this.regexp === false) return this.regexp // at this point, this.set is a 2d array of partial // pattern strings, or "**". // // It's better to use .match(). This function shouldn't // be used, really, but it's pretty convenient sometimes, // when you just want to work with a regex. var set = this.set; if (!set.length) return this.regexp = false var options = this.options; var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot , flags = options.nocase ? "i" : ""; var re = set.map(function (pattern) { return pattern.map(function (p) { return (p === GLOBSTAR) ? twoStar : (typeof p === "string") ? regExpEscape(p) : p._src }).join("\\\/") }).join("|"); // must match entire pattern // ending in a * or ** will make it less strict. re = "^(?:" + re + ")$"; // can match anything, as long as it's not this. if (this.negate) re = "^(?!" + re + ").*$"; try { return this.regexp = new RegExp(re, flags) } catch (ex) { return this.regexp = false } } minimatch.match = function (list, pattern, options) { var mm = new Minimatch(pattern, options); list = list.filter(function (f) { return mm.match(f) }); if (options.nonull && !list.length) { list.push(pattern); } return list }; Minimatch.prototype.match = match; function match (f, partial) { // console.error("match", f, this.pattern) // short-circuit in the case of busted things. // comments, etc. if (this.comment) return false if (this.empty) return f === "" if (f === "/" && partial) return true var options = this.options; // windows: need to use /, not \ // On other platforms, \ is a valid (albeit bad) filename char. if (platform === "win32") { f = f.split("\\").join("/"); } // treat the test path as a set of pathparts. f = f.split(slashSplit); if (options.debug) { console.error(this.pattern, "split", f); } // just ONE of the pattern sets in this.set needs to match // in order for it to be valid. If negating, then just one // match means that we have failed. // Either way, return on the first hit. var set = this.set; // console.error(this.pattern, "set", set) for (var i = 0, l = set.length; i < l; i ++) { var pattern = set[i]; var hit = this.matchOne(f, pattern, partial); if (hit) { if (options.flipNegate) return true return !this.negate } } // didn't get any hits. this is success if it's a negative // pattern, failure otherwise. if (options.flipNegate) return false return this.negate } // set partial to true to test if, for example, // "/a/b" matches the start of "/*/b/*/d" // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. Minimatch.prototype.matchOne = function (file, pattern, partial) { var options = this.options; if (options.debug) { console.error("matchOne", { "this": this , file: file , pattern: pattern }); } if (options.matchBase && pattern.length === 1) { file = path.basename(file.join("/")).split("/"); } if (options.debug) { console.error("matchOne", file.length, pattern.length); } for ( var fi = 0 , pi = 0 , fl = file.length , pl = pattern.length ; (fi < fl) && (pi < pl) ; fi ++, pi ++ ) { if (options.debug) { console.error("matchOne loop"); } var p = pattern[pi] , f = file[fi]; if (options.debug) { console.error(pattern, p, f); } // should be impossible. // some invalid regexp stuff in the set. if (p === false) return false if (p === GLOBSTAR) { if (options.debug) console.error('GLOBSTAR', [pattern, p, f]); // "**" // a/**/b/**/c would match the following: // a/b/x/y/z/c // a/x/y/z/b/c // a/b/x/b/x/c // a/b/c // To do this, take the rest of the pattern after // the **, and see if it would match the file remainder. // If so, return success. // If not, the ** "swallows" a segment, and try again. // This is recursively awful. // // a/**/b/**/c matching a/b/x/y/z/c // - a matches a // - doublestar // - matchOne(b/x/y/z/c, b/**/c) // - b matches b // - doublestar // - matchOne(x/y/z/c, c) -> no // - matchOne(y/z/c, c) -> no // - matchOne(z/c, c) -> no // - matchOne(c, c) yes, hit var fr = fi , pr = pi + 1; if (pr === pl) { if (options.debug) console.error('** at the end'); // a ** at the end will just swallow the rest. // We have found a match. // however, it will not swallow /.x, unless // options.dot is set. // . and .. are *never* matched by **, for explosively // exponential reasons. for ( ; fi < fl; fi ++) { if (file[fi] === "." || file[fi] === ".." || (!options.dot && file[fi].charAt(0) === ".")) return false } return true } // ok, let's see if we can swallow whatever we can. WHILE: while (fr < fl) { var swallowee = file[fr]; if (options.debug) { console.error('\nglobstar while', file, fr, pattern, pr, swallowee); } // XXX remove this slice. Just pass the start index. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { if (options.debug) console.error('globstar found match!', fr, fl, swallowee); // found a match. return true } else { // can't swallow "." or ".." ever. // can only swallow ".foo" when explicitly asked. if (swallowee === "." || swallowee === ".." || (!options.dot && swallowee.charAt(0) === ".")) { if (options.debug) console.error("dot detected!", file, fr, pattern, pr); break WHILE } // ** swallows a segment, and continue. if (options.debug) console.error('globstar swallow a segment, and continue'); fr ++; } } // no match was found. // However, in partial mode, we can't say this is necessarily over. // If there's more *pattern* left, then if (partial) { // ran out of file // console.error("\n>>> no match, partial?", file, fr, pattern, pr) if (fr === fl) return true } return false } // something other than ** // non-magic patterns just have to match exactly // patterns with magic have been turned into regexps. var hit; if (typeof p === "string") { if (options.nocase) { hit = f.toLowerCase() === p.toLowerCase(); } else { hit = f === p; } if (options.debug) { console.error("string match", p, f, hit); } } else { hit = f.match(p); if (options.debug) { console.error("pattern match", p, f, hit); } } if (!hit) return false } // Note: ending in / means that we'll get a final "" // at the end of the pattern. This can only match a // corresponding "" at the end of the file. // If the file ends in /, then it can only match a // a pattern that ends in /, unless the pattern just // doesn't have any more for it. But, a/b/ should *not* // match "a/b/*", even though "" matches against the // [^/]*? pattern, except in partial mode, where it might // simply not be reached yet. // However, a/b/ should still satisfy a/* // now either we fell off the end of the pattern, or we're done. if (fi === fl && pi === pl) { // ran out of pattern and filename at the same time. // an exact hit! return true } else if (fi === fl) { // ran out of file, but still had pattern left. // this is ok if we're doing the match as part of // a glob fs traversal. return partial } else if (pi === pl) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ var emptyFileEnd = (fi === fl - 1) && (file[fi] === ""); return emptyFileEnd } // should be unreachable. throw new Error("wtf?") }; // replace stuff like \* with * function globUnescape (s) { return s.replace(/\\(.)/g, "$1") } function regExpEscape (s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") } }); var name$1 = "editorconfig"; var version$2 = "0.14.2"; var description$1 = "EditorConfig File Locator and Interpreter for Node.js"; var keywords = ["editorconfig","core"]; var main$1 = "editorconfig.js"; var bin$1 = {"editorconfig":"bin/editorconfig"}; var contributors = ["Hong Xu (topbug.net)","Jed Mao (https://github.com/jedmao/)","Trey Hunner (http://treyhunner.com)"]; var directories = {"bin":"./bin","lib":"./lib"}; var scripts$1 = {"pretest":"cmake .","test":"npm run lint && ctest .","test-verbose":"npm run lint && ctest -VV --output-on-failure .","lint":"eclint check --indent_size ignore editorconfig.js README.md \"bin/**\" \"lib/**\""}; var repository$1 = {"type":"git","url":"git://github.com/editorconfig/editorconfig-core-js.git"}; var bugs$1 = "https://github.com/editorconfig/editorconfig-core-js/issues"; var author$1 = "EditorConfig Team"; var license$1 = "MIT"; var dependencies$1 = {"bluebird":"^3.0.5","commander":"^2.9.0","lru-cache":"^3.2.0","semver":"^5.1.0","sigmund":"^1.0.1"}; var devDependencies$1 = {"eclint":"^1.1.5","mocha":"^2.3.4","should":"^7.1.1"}; var _package$2 = { name: name$1, version: version$2, description: description$1, keywords: keywords, main: main$1, bin: bin$1, contributors: contributors, directories: directories, scripts: scripts$1, repository: repository$1, bugs: bugs$1, author: author$1, license: license$1, dependencies: dependencies$1, devDependencies: devDependencies$1 }; var _package$3 = Object.freeze({ name: name$1, version: version$2, description: description$1, keywords: keywords, main: main$1, bin: bin$1, contributors: contributors, directories: directories, scripts: scripts$1, repository: repository$1, bugs: bugs$1, author: author$1, license: license$1, dependencies: dependencies$1, devDependencies: devDependencies$1, default: _package$2 }); var pkg = ( _package$3 && _package$2 ) || _package$3; var whenReadFile = bluebird_1.promisify(fs.readFile); var knownProps = [ 'end_of_line', 'indent_style', 'indent_size', 'insert_final_newline', 'trim_trailing_whitespace', 'charset' ].reduce(function (set, prop) { set[prop] = true; return set; }, {}); function fnmatch(filepath, glob) { var matchOptions = {matchBase: true, dot: true, noext: true}; glob = glob.replace(/\*\*/g, '{*,**/**/**}'); return fnmatch$1(filepath, glob, matchOptions); } function getConfigFileNames(filepath, options) { var paths = []; do { filepath = path.dirname(filepath); paths.push(path.join(filepath, options.config)); } while (filepath !== options.root); return paths; } function getFilepathRoot(filepath) { if (path.parse !== undefined) { // Node.js >= 0.11.15 return path.parse(filepath).root; } if (os.platform() === 'win32') { return path.resolve(filepath).match(/^(\\\\[^\\]+\\)?[^\\]+\\/)[0]; } return '/'; } function processMatches(matches, version) { // Set indent_size to "tab" if indent_size is unspecified and // indent_style is set to "tab". if ("indent_style" in matches && matches.indent_style === "tab" && !("indent_size" in matches) && semver.gte(version, "0.10.0")) { matches.indent_size = "tab"; } // Set tab_width to indent_size if indent_size is specified and // tab_width is unspecified if ("indent_size" in matches && !("tab_width" in matches) && matches.indent_size !== "tab") matches.tab_width = matches.indent_size; // Set indent_size to tab_width if indent_size is "tab" if("indent_size" in matches && "tab_width" in matches && matches.indent_size === "tab") matches.indent_size = matches.tab_width; return matches; } function processOptions(options, filepath) { options = options || {}; return { config: options.config || '.editorconfig', version: options.version || pkg.version, root: path.resolve(options.root || getFilepathRoot(filepath)) }; } function buildFullGlob(pathPrefix, glob) { switch (glob.indexOf('/')) { case -1: glob = "**/" + glob; break; case 0: glob = glob.substring(1); break; } return path.join(pathPrefix, glob); } function extendProps(props, options) { for (var key in options) { var value = options[key]; key = key.toLowerCase(); if (knownProps[key]) { value = value.toLowerCase(); } try { value = JSON.parse(value); } catch(e) {} if (typeof value === 'undefined' || value === null) { // null and undefined are values specific to JSON (no special meaning // in editorconfig) & should just be returned as regular strings. value = String(value); } props[key] = value; } return props; } function parseFromFiles(filepath, files, options) { return getConfigsForFiles(files).then(function (configs) { return configs.reverse(); }).reduce(function (matches, file) { var pathPrefix = path.dirname(file.name); file.contents.forEach(function (section) { var glob = section[0], options = section[1]; if (!glob) return; var fullGlob = buildFullGlob(pathPrefix, glob); if (!fnmatch(filepath, fullGlob)) return; matches = extendProps(matches, options); }); return matches; }, {}).then(function (matches) { return processMatches(matches, options.version); }); } function parseFromFilesSync(filepath, files, options) { var configs = getConfigsForFilesSync(files); configs.reverse(); var matches = {}; configs.forEach(function(config) { var pathPrefix = path.dirname(config.name); config.contents.forEach(function(section) { var glob = section[0], options = section[1]; if (!glob) return; var fullGlob = buildFullGlob(pathPrefix, glob); if (!fnmatch(filepath, fullGlob)) return; matches = extendProps(matches, options); }); }); return processMatches(matches, options.version); } function StopReduce(array) { this.array = array; } StopReduce.prototype = Object.create(Error.prototype); function getConfigsForFiles(files) { return bluebird_1.reduce(files, function (configs, file) { var contents = ini.parseString(file.contents); configs.push({ name: file.name, contents: contents }); if ((contents[0][1].root || '').toLowerCase() === 'true') { return bluebird_1.reject(new StopReduce(configs)); } return configs; }, []).catch(StopReduce, function (stop) { return stop.array; }); } function getConfigsForFilesSync(files) { var configs = []; for (var i in files) { var file = files[i]; var contents = ini.parseString(file.contents); configs.push({ name: file.name, contents: contents }); if ((contents[0][1].root || '').toLowerCase() === 'true') { break; } } return configs; } function readConfigFiles(filepaths) { return bluebird_1.map(filepaths, function (path$$2) { return whenReadFile(path$$2, 'utf-8').catch(function () { return ''; }).then(function (contents) { return {name: path$$2, contents: contents}; }); }); } function readConfigFilesSync(filepaths) { var files = []; var file; filepaths.forEach(function(filepath) { try { file = fs.readFileSync(filepath, 'utf8'); } catch (e) { file = ''; } files.push({name: filepath, contents: file}); }); return files; } var parseFromFiles_1 = function (filepath, files, options) { return new bluebird_1 (function (resolve, reject) { filepath = path.resolve(filepath); options = processOptions(options, filepath); resolve(parseFromFiles(filepath, files, options)); }); }; var parseFromFilesSync_1 = function (filepath, files, options) { filepath = path.resolve(filepath); options = processOptions(options, filepath); return parseFromFilesSync(filepath, files, options); }; var parse$6 = function (filepath, options) { return new bluebird_1 (function (resolve, reject) { filepath = path.resolve(filepath); options = processOptions(options, filepath); var filepaths = getConfigFileNames(filepath, options); var files = readConfigFiles(filepaths); resolve(parseFromFiles(filepath, files, options)); }); }; var parseSync = function (filepath, options) { filepath = path.resolve(filepath); options = processOptions(options, filepath); var filepaths = getConfigFileNames(filepath, options); var files = readConfigFilesSync(filepaths); return parseFromFilesSync(filepath, files, options); }; var parseString = ini.parseString; var editorconfig = { parseFromFiles: parseFromFiles_1, parseFromFilesSync: parseFromFilesSync_1, parse: parse$6, parseSync: parseSync, parseString: parseString }; var editorconfigToPrettier = editorConfigToPrettier; function editorConfigToPrettier(editorConfig) { if (!editorConfig || Object.keys(editorConfig).length === 0) { return null; } const result = {}; if (editorConfig.indent_style) { result.useTabs = editorConfig.indent_style === "tab"; } if (editorConfig.indent_size === "tab") { result.useTabs = true; } if (result.useTabs && editorConfig.tab_width) { result.tabWidth = editorConfig.tab_width; } else if ( editorConfig.indent_style === "space" && editorConfig.indent_size && editorConfig.indent_size !== "tab" ) { result.tabWidth = editorConfig.indent_size; } else if (editorConfig.tab_width !== undefined) { result.tabWidth = editorConfig.tab_width; } if (editorConfig.max_line_length && editorConfig.max_line_length !== "off") { result.printWidth = editorConfig.max_line_length; } if (editorConfig.quote_type === "single") { result.singleQuote = true; } else if (editorConfig.quote_type === "double") { result.singleQuote = false; } return result; } function markerExists (files, markers) { return markers.some(function(marker) { return files.some(function(file) { return file === marker; }); }); } function traverseFolder (directory, levels, markers) { var files = fs.readdirSync(directory); if (levels === 0) { return null; } else if (markerExists(files, markers)) { return directory; } else { return traverseFolder(path.resolve(directory, '..'), levels - 1, markers); } } var findProjectRoot = function findRoot(dir, opts) { if (!dir) throw new Error("Directory not defined"); opts = opts || {}; var levels = opts.maxDepth || findRoot.MAX_DEPTH; var markers = opts.markers || findRoot.MARKERS; return traverseFolder(dir, levels, markers); }; var MAX_DEPTH = 9; var MARKERS = [ '.git', '.hg' ]; findProjectRoot.MAX_DEPTH = MAX_DEPTH; findProjectRoot.MARKERS = MARKERS; var resolveConfigEditorconfig = createCommonjsModule(function (module) { "use strict"; const maybeParse = (filePath, config, parse) => { const root = findProjectRoot(path.dirname(path.resolve(filePath))); return filePath && parse(filePath, { root }); }; const editorconfigAsyncNoCache = (filePath, config) => { return Promise.resolve(maybeParse(filePath, config, editorconfig.parse)).then( editorconfigToPrettier ); }; const editorconfigAsyncWithCache = mem(editorconfigAsyncNoCache); const editorconfigSyncNoCache = (filePath, config) => { return editorconfigToPrettier( maybeParse(filePath, config, editorconfig.parseSync) ); }; const editorconfigSyncWithCache = mem(editorconfigSyncNoCache); function getLoadFunction(opts) { if (!opts.editorconfig) { return () => null; } if (opts.sync) { return opts.cache ? editorconfigSyncWithCache : editorconfigSyncNoCache; } return opts.cache ? editorconfigAsyncWithCache : editorconfigAsyncNoCache; } function clearCache() { mem.clear(editorconfigSyncWithCache); mem.clear(editorconfigAsyncWithCache); } module.exports = { getLoadFunction, clearCache }; }); var thirdParty$1 = ( thirdParty && thirdParty__default ) || thirdParty; var resolveConfig_1 = createCommonjsModule(function (module) { "use strict"; const getExplorerMemoized = mem(opts => thirdParty$1.cosmiconfig("prettier", { sync: opts.sync, cache: opts.cache, rcExtensions: true, transform: result => { if (result && result.config) { delete result.config.$schema; } return result; } }) ); /** @param {{ cache: boolean, sync: boolean }} opts */ function getLoadFunction(opts) { // Normalize opts before passing to a memoized function opts = Object.assign({ sync: false, cache: false }, opts); return getExplorerMemoized(opts).load; } function _resolveConfig(filePath, opts, sync) { opts = Object.assign({ useCache: true }, opts); const loadOpts = { cache: !!opts.useCache, sync: !!sync, editorconfig: !!opts.editorconfig }; const load = getLoadFunction(loadOpts); const loadEditorConfig = resolveConfigEditorconfig.getLoadFunction(loadOpts); const arr = [load, loadEditorConfig].map(l => l(filePath, opts.config)); const unwrapAndMerge = arr => { const result = arr[0]; const editorConfigured = arr[1]; const merged = Object.assign( {}, editorConfigured, mergeOverrides(Object.assign({}, result), filePath) ); if (!result && !editorConfigured) { return null; } return merged; }; if (loadOpts.sync) { return unwrapAndMerge(arr); } return Promise.all(arr).then(unwrapAndMerge); } const resolveConfig = (filePath, opts) => _resolveConfig(filePath, opts, false); resolveConfig.sync = (filePath, opts) => _resolveConfig(filePath, opts, true); function clearCache() { mem.clear(getExplorerMemoized); resolveConfigEditorconfig.clearCache(); } function resolveConfigFile(filePath) { const load = getLoadFunction({ sync: false }); return load(filePath).then(result => { return result ? result.filepath : null; }); } resolveConfigFile.sync = filePath => { const load = getLoadFunction({ sync: true }); const result = load(filePath); return result ? result.filepath : null; }; function mergeOverrides(configResult, filePath) { const options = Object.assign({}, configResult.config); if (filePath && options.overrides) { const relativeFilePath = path.relative( path.dirname(configResult.filepath), filePath ); for (const override of options.overrides) { if ( pathMatchesGlobs( relativeFilePath, override.files, override.excludeFiles ) ) { Object.assign(options, override.options); } } } delete options.overrides; return options; } // Based on eslint: https://github.com/eslint/eslint/blob/master/lib/config/config-ops.js function pathMatchesGlobs(filePath, patterns, excludedPatterns) { const patternList = [].concat(patterns); const excludedPatternList = [].concat(excludedPatterns || []); const opts = { matchBase: true }; return ( patternList.some(pattern => minimatch_1(filePath, pattern, opts)) && !excludedPatternList.some(excludedPattern => minimatch_1(filePath, excludedPattern, opts) ) ); } module.exports = { resolveConfig, resolveConfigFile, clearCache }; }); const version = require$$0$11.version; const getSupportInfo = support.getSupportInfo; const normalizeOptions = options$12.normalize; const printDocToString = doc.printer.printDocToString; const printDocToDebug = doc.debug.printDocToDebug; function guessLineEnding(text) { const index = text.indexOf("\n"); if (index >= 0 && text.charAt(index - 1) === "\r") { return "\r\n"; } return "\n"; } function attachComments(text, ast, opts) { const astComments = ast.comments; if (astComments) { delete ast.comments; comments.attach(astComments, ast, text, opts); } ast.tokens = []; opts.originalText = text.trimRight(); return astComments; } function hasPragma(text) { const pragmas = Object.keys(build.parse(build.extract(text))); return pragmas.indexOf("prettier") !== -1 || pragmas.indexOf("format") !== -1; } function ensureAllCommentsPrinted(astComments) { if (!astComments) { return; } for (let i = 0; i < astComments.length; ++i) { if (astComments[i].value.trim() === "prettier-ignore") { // If there's a prettier-ignore, we're not printing that sub-tree so we // don't know if the comments was printed or not. return; } } astComments.forEach(comment => { if (!comment.printed) { throw new Error( 'Comment "' + comment.value.trim() + '" was not printed. Please report this error!' ); } delete comment.printed; }); } function formatWithCursor(text, opts, addAlignmentSize) { if (opts.requirePragma && !hasPragma(text)) { return { formatted: text }; } const UTF8BOM = 0xfeff; const hasUnicodeBOM = text.charCodeAt(0) === UTF8BOM; if (hasUnicodeBOM) { text = text.substring(1); } if ( opts.insertPragma && !hasPragma(text) && opts.rangeStart === 0 && opts.rangeEnd === Infinity ) { const parsedDocblock = build.parseWithComments(build.extract(text)); const pragmas = Object.assign({ format: "" }, parsedDocblock.pragmas); const newDocblock = build.print({ pragmas, comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines }); const strippedText = build.strip(text); const separatingNewlines = strippedText.startsWith("\n") ? "\n" : "\n\n"; text = newDocblock + separatingNewlines + strippedText; } addAlignmentSize = addAlignmentSize || 0; const result = parser$3.parse(text, opts); const ast = result.ast; text = result.text; const formattedRangeOnly = formatRange(text, opts, ast); if (formattedRangeOnly) { return { formatted: formattedRangeOnly }; } let cursorOffset; if (opts.cursorOffset >= 0) { const cursorNodeAndParents = findNodeAtOffset(ast, opts.cursorOffset, opts); const cursorNode = cursorNodeAndParents.node; if (cursorNode) { cursorOffset = opts.cursorOffset - opts.locStart(cursorNode); opts.cursorNode = cursorNode; } } const astComments = attachComments(text, ast, opts); const doc$$1 = astToDoc(ast, opts, addAlignmentSize); opts.newLine = guessLineEnding(text); const toStringResult = printDocToString(doc$$1, opts); let str = toStringResult.formatted; if (hasUnicodeBOM) { str = String.fromCharCode(UTF8BOM) + str; } const cursorOffsetResult = toStringResult.cursor; ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline if (addAlignmentSize > 0) { return { formatted: str.trim() + opts.newLine }; } if (cursorOffset !== undefined) { return { formatted: str, cursorOffset: cursorOffsetResult + cursorOffset }; } return { formatted: str }; } function format(text, opts, addAlignmentSize) { return formatWithCursor(text, opts, addAlignmentSize).formatted; } function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) { let resultStartNode = startNodeAndParents.node; let resultEndNode = endNodeAndParents.node; if (resultStartNode === resultEndNode) { return { startNode: resultStartNode, endNode: resultEndNode }; } for (const endParent of endNodeAndParents.parentNodes) { if ( endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node) ) { resultEndNode = endParent; } else { break; } } for (const startParent of startNodeAndParents.parentNodes) { if ( startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node) ) { resultStartNode = startParent; } else { break; } } return { startNode: resultStartNode, endNode: resultEndNode }; } function findNodeAtOffset(node, offset, options, predicate, parentNodes) { predicate = predicate || (() => true); parentNodes = parentNodes || []; const start = options.locStart(node, options.locStart); const end = options.locEnd(node, options.locEnd); if (start <= offset && offset <= end) { for (const childNode of comments.getSortedChildNodes( node, undefined /* text */, options )) { const childResult = findNodeAtOffset( childNode, offset, options, predicate, [node].concat(parentNodes) ); if (childResult) { return childResult; } } if (predicate(node)) { return { node: node, parentNodes: parentNodes }; } } } // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 function isSourceElement(opts, node) { if (node == null) { return false; } // JS and JS like to avoid repetitions const jsSourceElements = [ "FunctionDeclaration", "BlockStatement", "BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "EmptyStatement", "ExpressionStatement", "ForInStatement", "ForStatement", "IfStatement", "LabeledStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "TryStatement", "VariableDeclaration", "WhileStatement", "WithStatement", "ClassDeclaration", // ES 2015 "ImportDeclaration", // Module "ExportDefaultDeclaration", // Module "ExportNamedDeclaration", // Module "ExportAllDeclaration", // Module "TypeAlias", // Flow "InterfaceDeclaration", // Flow, TypeScript "TypeAliasDeclaration", // TypeScript "ExportAssignment", // TypeScript "ExportDeclaration" // TypeScript ]; const jsonSourceElements = [ "ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral" ]; const graphqlSourceElements = [ "OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition" ]; switch (opts.parser) { case "flow": case "babylon": case "typescript": return jsSourceElements.indexOf(node.type) > -1; case "json": return jsonSourceElements.indexOf(node.type) > -1; case "graphql": return graphqlSourceElements.indexOf(node.kind) > -1; } return false; } function calculateRange(text, opts, ast) { // Contract the range so that it has non-whitespace characters at its endpoints. // This ensures we can format a range that doesn't end on a node. const rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd); const startNonWhitespace = Math.max( opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart ); let endNonWhitespace; for ( endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace ) { if (text[endNonWhitespace - 1].match(/\S/)) { break; } } const startNodeAndParents = findNodeAtOffset( ast, startNonWhitespace, opts, node => isSourceElement(opts, node) ); const endNodeAndParents = findNodeAtOffset( ast, endNonWhitespace, opts, node => isSourceElement(opts, node) ); if (!startNodeAndParents || !endNodeAndParents) { return { rangeStart: 0, rangeEnd: 0 }; } const siblingAncestors = findSiblingAncestors( startNodeAndParents, endNodeAndParents, opts ); const startNode = siblingAncestors.startNode; const endNode = siblingAncestors.endNode; const rangeStart = Math.min( opts.locStart(startNode, opts.locStart), opts.locStart(endNode, opts.locStart) ); const rangeEnd = Math.max( opts.locEnd(startNode, opts.locEnd), opts.locEnd(endNode, opts.locEnd) ); return { rangeStart: rangeStart, rangeEnd: rangeEnd }; } function formatRange(text, opts, ast) { if (opts.rangeStart <= 0 && text.length <= opts.rangeEnd) { return; } const range = calculateRange(text, opts, ast); const rangeStart = range.rangeStart; const rangeEnd = range.rangeEnd; const rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line. // This is so we can detect indentation correctly and restore it. // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0 const rangeStart2 = Math.min( rangeStart, text.lastIndexOf("\n", rangeStart) + 1 ); const indentString = text.slice(rangeStart2, rangeStart); const alignmentSize = util$1.getAlignmentSize( indentString, opts.tabWidth ); const rangeFormatted = format( rangeString, Object.assign({}, opts, { rangeStart: 0, rangeEnd: Infinity, printWidth: opts.printWidth - alignmentSize }), alignmentSize ); // Since the range contracts to avoid trailing whitespace, // we need to remove the newline that was inserted by the `format` call. const rangeTrimmed = rangeFormatted.trimRight(); return text.slice(0, rangeStart) + rangeTrimmed + text.slice(rangeEnd); } var prettier = { formatWithCursor: function(text, opts) { return formatWithCursor(text, normalizeOptions(opts)); }, format: function(text, opts) { return format(text, normalizeOptions(opts)); }, check: function(text, opts) { try { const formatted = format(text, normalizeOptions(opts)); return formatted === text; } catch (e) { return false; } }, doc, resolveConfig: resolveConfig_1.resolveConfig, clearConfigCache: resolveConfig_1.clearCache, getSupportInfo, version, util: utilShared, /* istanbul ignore next */ __debug: { parse: function(text, opts) { opts = normalizeOptions(opts); return parser$3.parse(text, opts); }, formatAST: function(ast, opts) { opts = normalizeOptions(opts); const doc$$1 = astToDoc(ast, opts); const str = printDocToString(doc$$1, opts); return str; }, // Doesn't handle shebang for now formatDoc: function(doc$$1, opts) { opts = normalizeOptions(opts); const debug = printDocToDebug(doc$$1); const str = format(debug, opts); return str; }, printToDoc: function(text, opts) { opts = normalizeOptions(opts); const result = parser$3.parse(text, opts); const ast = result.ast; text = result.text; attachComments(text, ast, opts); const doc$$1 = astToDoc(ast, opts); return doc$$1; }, printDocToString: function(doc$$1, opts) { opts = normalizeOptions(opts); const str = printDocToString(doc$$1, opts); return str; } } }; module.exports = prettier; kodo - Gogs: Go Git Service

暂无描述

Brightcells: 597ee33ba6 Pai2 => Kodo 8 年之前
..
migrations a7cbbf15a7 Update max_length for CharField 8 年之前
templates 597ee33ba6 Pai2 => Kodo 8 年之前
__init__.py 4defb80fdc gogs first init 11 年之前
admin.py 627187a7d7 Update Kodo 8 年之前
models.py 018d52f61d Update package django_xxx 8 年之前
serializers.py f72ccb1875 isort import 10 年之前
tests.py fabef63211 set line_length=200 for isort 10 年之前
urls.py 4defb80fdc gogs first init 11 年之前
views.py 018d52f61d Update package django_xxx 8 年之前