diff --git a/frontend/web-editor/public/bundle.js b/frontend/web-editor/public/bundle.js index 1c92f53..0a1512d 100644 --- a/frontend/web-editor/public/bundle.js +++ b/frontend/web-editor/public/bundle.js @@ -13,7 +13,185 @@ app.mount('body') -},{"./src/store.js":135,"./src/views/main.js":145,"choo":22,"choo-devtools":9}],2:[function(require,module,exports){ +},{"./src/store.js":228,"./src/views/main.js":238,"choo":33,"choo-devtools":20}],2:[function(require,module,exports){ + +/** + * Expose `Emitter`. + */ + +exports.Emitter = Emitter; + +/** + * Initialize a new `Emitter`. + * + * @api public + */ + +function Emitter(obj) { + if (obj) return mixin(obj); +} + +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} + +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []) + .push(fn); + return this; +}; + +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.once = function(event, fn){ + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; +}; + +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } + + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + + // Remove event specific arrays for event types that no + // one is subscribed for to avoid memory leak. + if (callbacks.length === 0) { + delete this._callbacks['$' + event]; + } + + return this; +}; + +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + + var args = new Array(arguments.length - 1) + , callbacks = this._callbacks['$' + event]; + + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; +}; + +// alias used for reserved events (protected method) +Emitter.prototype.emitReserved = Emitter.prototype.emit; + +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; +}; + +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; + +},{}],3:[function(require,module,exports){ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : @@ -5634,7 +5812,1139 @@ app.mount('body') })); -},{}],3:[function(require,module,exports){ +},{}],4:[function(require,module,exports){ +(function (global){(function (){ +'use strict'; + +var objectAssign = require('object-assign'); + +// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js +// original notice: + +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +function compare(a, b) { + if (a === b) { + return 0; + } + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; +} +function isBuffer(b) { + if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { + return global.Buffer.isBuffer(b); + } + return !!(b != null && b._isBuffer); +} + +// based on node assert, original notice: +// NB: The URL to the CommonJS spec is kept just for tradition. +// node-assert has evolved a lot since then, both in API and behavior. + +// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 +// +// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! +// +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the 'Software'), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +var util = require('util/'); +var hasOwn = Object.prototype.hasOwnProperty; +var pSlice = Array.prototype.slice; +var functionsHaveNames = (function () { + return function foo() {}.name === 'foo'; +}()); +function pToString (obj) { + return Object.prototype.toString.call(obj); +} +function isView(arrbuf) { + if (isBuffer(arrbuf)) { + return false; + } + if (typeof global.ArrayBuffer !== 'function') { + return false; + } + if (typeof ArrayBuffer.isView === 'function') { + return ArrayBuffer.isView(arrbuf); + } + if (!arrbuf) { + return false; + } + if (arrbuf instanceof DataView) { + return true; + } + if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { + return true; + } + return false; +} +// 1. The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. + +var assert = module.exports = ok; + +// 2. The AssertionError is defined in assert. +// new assert.AssertionError({ message: message, +// actual: actual, +// expected: expected }) + +var regex = /\s*function\s+([^\(\s]*)\s*/; +// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js +function getName(func) { + if (!util.isFunction(func)) { + return; + } + if (functionsHaveNames) { + return func.name; + } + var str = func.toString(); + var match = str.match(regex); + return match && match[1]; +} +assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = getName(stackStartFunction); + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } + } +}; + +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); + +function truncate(s, n) { + if (typeof s === 'string') { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} +function inspect(something) { + if (functionsHaveNames || !util.isFunction(something)) { + return util.inspect(something); + } + var rawname = getName(something); + var name = rawname ? ': ' + rawname : ''; + return '[Function' + name + ']'; +} +function getMessage(self) { + return truncate(inspect(self.actual), 128) + ' ' + + self.operator + ' ' + + truncate(inspect(self.expected), 128); +} + +// At present only the three keys mentioned above are used and +// understood by the spec. Implementations or sub modules can pass +// other keys to the AssertionError's constructor - they will be +// ignored. + +// 3. All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. + +function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); +} + +// EXTENSION! allows for well behaved errors defined elsewhere. +assert.fail = fail; + +// 4. Pure assertion tests whether a value is truthy, as determined +// by !!guard. +// assert.ok(guard, message_opt); +// This statement is equivalent to assert.equal(true, !!guard, +// message_opt);. To test strictly for the value true, use +// assert.strictEqual(true, guard, message_opt);. + +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = ok; + +// 5. The equality assertion tests shallow, coercive equality with +// ==. +// assert.equal(actual, expected, message_opt); + +assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); +}; + +// 6. The non-equality assertion tests for whether two objects are not equal +// with != assert.notEqual(actual, expected, message_opt); + +assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } +}; + +// 7. The equivalence assertion tests a deep equality relation. +// assert.deepEqual(actual, expected, message_opt); + +assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } +}; + +assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); + } +}; + +function _deepEqual(actual, expected, strict, memos) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + } else if (isBuffer(actual) && isBuffer(expected)) { + return compare(actual, expected) === 0; + + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if ((actual === null || typeof actual !== 'object') && + (expected === null || typeof expected !== 'object')) { + return strict ? actual === expected : actual == expected; + + // If both values are instances of typed arrays, wrap their underlying + // ArrayBuffers in a Buffer each to increase performance + // This optimization requires the arrays to have the same type as checked by + // Object.prototype.toString (aka pToString). Never perform binary + // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their + // bit patterns are not identical. + } else if (isView(actual) && isView(expected) && + pToString(actual) === pToString(expected) && + !(actual instanceof Float32Array || + actual instanceof Float64Array)) { + return compare(new Uint8Array(actual.buffer), + new Uint8Array(expected.buffer)) === 0; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else if (isBuffer(actual) !== isBuffer(expected)) { + return false; + } else { + memos = memos || {actual: [], expected: []}; + + var actualIndex = memos.actual.indexOf(actual); + if (actualIndex !== -1) { + if (actualIndex === memos.expected.indexOf(expected)) { + return true; + } + } + + memos.actual.push(actual); + memos.expected.push(expected); + + return objEquiv(actual, expected, strict, memos); + } +} + +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} + +function objEquiv(a, b, strict, actualVisitedObjects) { + if (a === null || a === undefined || b === null || b === undefined) + return false; + // if one is a primitive, the other must be same + if (util.isPrimitive(a) || util.isPrimitive(b)) + return a === b; + if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) + return false; + var aIsArgs = isArguments(a); + var bIsArgs = isArguments(b); + if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) + return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b, strict); + } + var ka = objectKeys(a); + var kb = objectKeys(b); + var key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length !== kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) + return false; + } + return true; +} + +// 8. The non-equivalence assertion tests for any deep inequality. +// assert.notDeepEqual(actual, expected, message_opt); + +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } +}; + +assert.notDeepStrictEqual = notDeepStrictEqual; +function notDeepStrictEqual(actual, expected, message) { + if (_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); + } +} + + +// 9. The strict equality assertion tests strict equality, as determined by ===. +// assert.strictEqual(actual, expected, message_opt); + +assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } +}; + +// 10. The strict non-equality assertion tests for strict inequality, as +// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } +}; + +function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } + + try { + if (actual instanceof expected) { + return true; + } + } catch (e) { + // Ignore. The instanceof check doesn't work for arrow functions. + } + + if (Error.isPrototypeOf(expected)) { + return false; + } + + return expected.call({}, actual) === true; +} + +function _tryBlock(block) { + var error; + try { + block(); + } catch (e) { + error = e; + } + return error; +} + +function _throws(shouldThrow, block, expected, message) { + var actual; + + if (typeof block !== 'function') { + throw new TypeError('"block" argument must be a function'); + } + + if (typeof expected === 'string') { + message = expected; + expected = null; + } + + actual = _tryBlock(block); + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + var userProvidedMessage = typeof message === 'string'; + var isUnwantedException = !shouldThrow && util.isError(actual); + var isUnexpectedException = !shouldThrow && actual && !expected; + + if ((isUnwantedException && + userProvidedMessage && + expectedException(actual, expected)) || + isUnexpectedException) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} + +// 11. Expected to throw an error: +// assert.throws(block, Error_opt, message_opt); + +assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws(true, block, error, message); +}; + +// EXTENSION! This is annoying to write outside this module. +assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { + _throws(false, block, error, message); +}; + +assert.ifError = function(err) { if (err) throw err; }; + +// Expose a strict only variant of assert +function strict(value, message) { + if (!value) fail(value, true, message, '==', strict); +} +assert.strict = objectAssign(strict, assert, { + equal: assert.strictEqual, + deepEqual: assert.deepStrictEqual, + notEqual: assert.notStrictEqual, + notDeepEqual: assert.notDeepStrictEqual +}); +assert.strict.strict = assert.strict; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"object-assign":145,"util/":7}],5:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],6:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} +},{}],7:[function(require,module,exports){ +(function (process,global){(function (){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":6,"_process":155,"inherits":5}],8:[function(require,module,exports){ (function (global, factory) { if (typeof define === "function" && define.amd) { define(['exports', './defaultTraveler', './attachComments'], factory); @@ -5685,7 +6995,7 @@ app.mount('body') exports.makeTraveler = makeTraveler; }); -},{"./attachComments":4,"./defaultTraveler":5}],4:[function(require,module,exports){ +},{"./attachComments":9,"./defaultTraveler":10}],9:[function(require,module,exports){ (function (global, factory) { if (typeof define === "function" && define.amd) { define(['exports', './defaultTraveler'], factory); @@ -5811,7 +7121,7 @@ app.mount('body') ); }); -},{"./defaultTraveler":5}],5:[function(require,module,exports){ +},{"./defaultTraveler":10}],10:[function(require,module,exports){ (function (global, factory) { if (typeof define === "function" && define.amd) { define(['exports'], factory); @@ -6253,7 +7563,7 @@ app.mount('body') }; }); -},{}],6:[function(require,module,exports){ +},{}],11:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -7445,20546 +8755,157 @@ function generate(node, options) { } -},{}],7:[function(require,module,exports){ -'use strict'; +},{}],12:[function(require,module,exports){ -var GetIntrinsic = require('get-intrinsic'); +/** + * Expose `Backoff`. + */ -var callBind = require('./'); +module.exports = Backoff; -var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); +/** + * Initialize backoff timer with `opts`. + * + * - `min` initial timeout in milliseconds [100] + * - `max` max timeout [10000] + * - `jitter` [0] + * - `factor` [2] + * + * @param {Object} opts + * @api public + */ -module.exports = function callBoundIntrinsic(name, allowMissing) { - var intrinsic = GetIntrinsic(name, !!allowMissing); - if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { - return callBind(intrinsic); - } - return intrinsic; -}; - -},{"./":8,"get-intrinsic":36}],8:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); -var GetIntrinsic = require('get-intrinsic'); - -var $apply = GetIntrinsic('%Function.prototype.apply%'); -var $call = GetIntrinsic('%Function.prototype.call%'); -var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); -var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); -var $max = GetIntrinsic('%Math.max%'); - -if ($defineProperty) { - try { - $defineProperty({}, 'a', { value: 1 }); - } catch (e) { - // IE 8 has a broken defineProperty - $defineProperty = null; - } +function Backoff(opts) { + opts = opts || {}; + this.ms = opts.min || 100; + this.max = opts.max || 10000; + this.factor = opts.factor || 2; + this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; + this.attempts = 0; } -module.exports = function callBind(originalFunction) { - var func = $reflectApply(bind, $call, arguments); - if ($gOPD && $defineProperty) { - var desc = $gOPD(func, 'length'); - if (desc.configurable) { - // original length, plus the receiver, minus any additional arguments (after the receiver) - $defineProperty( - func, - 'length', - { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } - ); - } - } - return func; -}; +/** + * Return the backoff duration. + * + * @return {Number} + * @api public + */ -var applyBind = function applyBind() { - return $reflectApply(bind, $apply, arguments); -}; - -if ($defineProperty) { - $defineProperty(module.exports, 'apply', { value: applyBind }); -} else { - module.exports.apply = applyBind; -} - -},{"function-bind":35,"get-intrinsic":36}],9:[function(require,module,exports){ -var EventEmitter = require('events').EventEmitter - -var storage = require('./lib/storage') -var logger = require('./lib/logger') -var debug = require('./lib/debug') -var copy = require('./lib/copy') -var help = require('./lib/help') -var perf = require('./lib/perf') -var log = require('./lib/log') -var getAllRoutes = require('wayfarer/get-all-routes') - -module.exports = expose - -function expose (opts) { - opts = opts || {} - store.storeName = 'choo-devtools' - return store - function store (state, emitter, app) { - var localEmitter = new EventEmitter() - - if (typeof window !== 'undefined') { - logger(state, emitter, opts) - } - - emitter.on('DOMContentLoaded', function () { - if (typeof window === 'undefined') return - window.choo = {} - - window.choo.state = state - window.choo.emit = function () { - emitter.emit.apply(emitter, arguments) - } - window.choo.on = function (eventName, listener) { - emitter.on(eventName, listener) - } - - debug(state, emitter, app, localEmitter) - - log(state, emitter, app, localEmitter) - perf(state, emitter, app, localEmitter) - window.choo.copy = copy - if (app.router && app.router.router) { - window.choo.routes = Object.keys(getAllRoutes(app.router.router)) - } - - storage() - help() - }) +Backoff.prototype.duration = function(){ + var ms = this.ms * Math.pow(this.factor, this.attempts++); + if (this.jitter) { + var rand = Math.random(); + var deviation = Math.floor(rand * this.jitter * ms); + ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation; } -} + return Math.min(ms, this.max) | 0; +}; -},{"./lib/copy":10,"./lib/debug":11,"./lib/help":12,"./lib/log":13,"./lib/logger":14,"./lib/perf":15,"./lib/storage":16,"events":154,"wayfarer/get-all-routes":130}],10:[function(require,module,exports){ -var stateCopy = require('state-copy') -var pluck = require('plucker') +/** + * Reset the number of attempts. + * + * @api public + */ -module.exports = copy +Backoff.prototype.reset = function(){ + this.attempts = 0; +}; -function copy (state) { - var isStateString = state && typeof state === 'string' - var isChooPath = isStateString && arguments.length === 1 && state.indexOf('state.') === 0 +/** + * Set the minimum duration + * + * @api public + */ - if (!state || typeof state === 'function') state = window.choo.state - if (isChooPath) [].push.call(arguments, { state: window.choo.state }) +Backoff.prototype.setMin = function(min){ + this.ms = min; +}; - stateCopy(isStateString ? pluck.apply(this, arguments) : state) -} +/** + * Set the maximum duration + * + * @api public + */ -},{"plucker":113,"state-copy":123}],11:[function(require,module,exports){ -/* eslint-disable node/no-deprecated-api */ -var onChange = require('object-change-callsite') -var nanologger = require('nanologger') -var assert = require('assert') +Backoff.prototype.setMax = function(max){ + this.max = max; +}; -var enabledMessage = 'Debugging enabled. To disable run: `choo.debug = false`' -var disabledMessage = 'Debugging disabled. We hope it was helpful! 🙌' +/** + * Set the jitter + * + * @api public + */ -module.exports = debug +Backoff.prototype.setJitter = function(jitter){ + this.jitter = jitter; +}; -function debug (state, emitter, app, localEmitter) { - var log = nanologger('choo-devtools') - var enabled = window.localStorage.logLevel === 'debug' - if (enabled) log.info(enabledMessage) - - state = onChange(state, function (attr, value, callsite) { - if (!enabled) return - callsite = callsite.split('\n')[1].replace(/^ +/, '') - log.info('state.' + attr, value, '\n' + callsite) - }) - - app.state = state - - Object.defineProperty(window.choo, 'debug', { - get: function () { - window.localStorage.logLevel = 'debug' - localEmitter.emit('debug', true) - enabled = true - return enabledMessage - }, - set: function (bool) { - assert.equal(typeof bool, 'boolean', 'choo-devtools.debug: bool should be type boolean') - window.localStorage.logLevel = bool ? 'debug' : 'info' - enabled = bool - localEmitter.emit('debug', enabled) - if (enabled) log.info(enabledMessage) - else log.info(disabledMessage) - } - }) -} - -},{"assert":147,"nanologger":99,"object-change-callsite":109}],12:[function(require,module,exports){ -module.exports = help - -function help () { - Object.defineProperty(window.choo, 'help', { - get: get, - set: noop - }) - - function get () { - setTimeout(function () { - print('copy', 'Serialize the current state to the clipboard.') - print('debug', 'Enable Choo debug mode.') - print('emit', 'Emit an event in the Choo emitter.') - print('help', 'Print usage information.') - print('log', 'Print the last 150 events emitted.') - print('on', 'Listen for an event in the Choo emitter.') - print('once', 'Listen for an event once in the Choo emitter.') - print('perf', 'Print out performance metrics') - print('state', 'Print the Choo state object.') - print('storage', 'Print browser storage information.') - }, 0) - return 'Choo command overview' - } -} - -function print (cmd, desc) { - var color = '#cc99cc' - console.log(' %cchoo.' + cmd, 'color: ' + color, '— ' + desc) -} - -function noop () {} },{}],13:[function(require,module,exports){ -var removeItems = require('remove-array-items') -var scheduler = require('nanoscheduler')() -var nanologger = require('nanologger') -var _log = nanologger('choo') -var clone = require('clone') - -var MAX_HISTORY_LENGTH = 150 // How many items we should keep around - -module.exports = log - -function log (state, emitter, app, localEmitter) { - var shouldDebug = window.localStorage.logLevel === 'debug' - var history = [] - var i = 0 - var shouldWarn = true - - localEmitter.on('debug', function (bool) { - shouldDebug = bool - }) - - window.choo._history = history - window.choo.history = showHistory - - Object.defineProperty(window.choo, 'log', { get: showHistory, set: noop }) - Object.defineProperty(window.choo, 'history', { get: showHistory, set: noop }) - - emitter.on('*', function (name, data) { - i += 1 - var entry = new Event(name, data, state) - history.push(entry) - scheduler.push(function () { - var length = history.length - if (length > MAX_HISTORY_LENGTH) { - removeItems(history, 0, length - MAX_HISTORY_LENGTH) - } - }) - }) - - function showHistory () { - setTimeout(function () { - console.table(history) - }, 0) - var events = i === 1 ? 'event' : 'events' - var msg = i + ' ' + events + ' recorded, showing the last ' + MAX_HISTORY_LENGTH + '.' - if (shouldDebug === false) { - msg += ' Enable state capture by calling `choo.debug`.' - } else { - msg += ' Disable state capture by calling `choo.debug = false`.' - } - return msg - } - - function Event (name, data, state) { - this.name = name - this.data = data === undefined ? '' : data - this.state = shouldDebug - ? tryClone(state) - : '' - } - - function tryClone (state) { - try { - var _state = clone(state) - if (!shouldWarn) shouldWarn = true - return _state - } catch (ex) { - if (shouldWarn) { - _log.warn('Could not clone your app state. Make sure to have a serializable state so it can be cloned') - shouldWarn = false - } - return '' - } - } -} - -function noop () {} - -},{"clone":24,"nanologger":99,"nanoscheduler":107,"remove-array-items":17}],14:[function(require,module,exports){ -var scheduler = require('nanoscheduler')() -var nanologger = require('nanologger') -var Hooks = require('choo-hooks') - -module.exports = logger - -function logger (state, emitter, opts) { - var initialRender = true - var hooks = Hooks(emitter) - var log = nanologger('choo') - - hooks.on('log:debug', logger('debug')) - hooks.on('log:info', logger('info')) - hooks.on('log:warn', logger('warn')) - hooks.on('log:error', logger('error')) - hooks.on('log:fatal', logger('fatal')) - - hooks.on('event', function (eventName, data, timing) { - if (opts.filter && !opts.filter(eventName, data, timing)) return - - if (timing) { - var duration = timing.duration.toFixed() - var level = duration < 50 ? 'info' : 'warn' - if (data !== undefined) logger(level)(eventName, data, duration + 'ms') - else logger(level)(eventName, duration + 'ms') - } else { - if (data !== undefined) logger('info')(eventName, data) - else logger('info')(eventName) - } - }) - - hooks.on('unhandled', function (eventName, data) { - logger('error')('No listeners for ' + eventName) - }) - - hooks.on('DOMContentLoaded', function (timing) { - if (!timing) return logger('info')('DOMContentLoaded') - var level = timing.interactive < 1000 ? 'info' : 'warn' - logger(level)('DOMContentLoaded', timing.interactive + 'ms to interactive') - }) - - hooks.on('render', function (timings) { - if (!timings || !timings.render) return logger('info')('render') - var duration = timings.render.duration.toFixed() - var msg = 'render' - - if (initialRender) { - initialRender = false - msg = 'initial ' + msg - } - - // each frame has 10ms available for userland stuff - var fps = Math.min((600 / duration).toFixed(), 60) - - if (fps === 60) { - logger('info')(msg, fps + 'fps', duration + 'ms') - } else { - var times = { - render: timings.render.duration.toFixed() + 'ms' - } - if (timings.morph) times.morph = timings.morph.duration.toFixed() + 'ms' - logger('warn')(msg, fps + 'fps', duration + 'ms', times) - } - }) - - hooks.on('resource-timing-buffer-full', function () { - logger('error')("The browser's Resource Resource timing buffer is full. Cannot store any more timing information") - }) - - hooks.start() - - function logger (level) { - return function () { - var args = [] - for (var i = 0, len = arguments.length; i < len; i++) { - args.push(arguments[i]) - } - scheduler.push(function () { - log[level].apply(log, args) - }) - } - } -} - -},{"choo-hooks":18,"nanologger":99,"nanoscheduler":107}],15:[function(require,module,exports){ -var onPerformance = require('on-performance') - -var BAR = '█' - -module.exports = perf - -function perf (state, emitter, app, localEmitter) { - var stats = {} - - window.choo.perf = {} - - // Print all events - var all = new Perf(stats, 'all') - Object.defineProperty(window.choo.perf, 'all', { - get: all.get.bind(all), - set: noop - }) - - // Print only Choo core events - var core = new Perf(stats, 'core', function (name) { - return /^choo/.test(name) - }) - Object.defineProperty(window.choo.perf, 'core', { - get: core.get.bind(core), - set: noop - }) - - // Print component data - var components = new Perf(stats, 'components', function (name) { - return !/^choo/.test(name) && !/^bankai/.test(name) - }) - Object.defineProperty(window.choo.perf, 'components', { - get: components.get.bind(components), - set: noop - }) - - // Print choo userland events (event emitter) - var events = new Perf(stats, 'events', function (name) { - return /^choo\.emit/.test(name) - }, function (name) { - return name.replace(/^choo\.emit\('/, '').replace(/'\)$/, '') - }) - Object.defineProperty(window.choo.perf, 'events', { - get: events.get.bind(events), - set: noop - }) - - onPerformance(function (entry) { - if (entry.entryType !== 'measure') return - var name = entry.name.replace(/ .*$/, '') - - if (!stats[name]) { - stats[name] = { - name: name, - count: 0, - entries: [] - } - } - - var stat = stats[name] - stat.count += 1 - stat.entries.push(entry.duration) - }) -} - -// Create a new Perf instance by passing it a filter -function Perf (stats, name, filter, rename) { - this.stats = stats - this.name = name - this.filter = filter || function () { return true } - this.rename = rename || function (name) { return name } -} - -// Compute a table of performance entries based on a filter -Perf.prototype.get = function () { - var filtered = Object.keys(this.stats).filter(this.filter) - var self = this - - var maxTime = 0 - var maxMedian = 0 - var fmt = filtered.map(function (key) { - var stat = self.stats[key] - var totalTime = Number(stat.entries.reduce(function (time, entry) { - return time + entry - }, 0).toFixed(2)) - if (totalTime > maxTime) maxTime = totalTime - - var median = getMedian(stat.entries) - if (median > maxMedian) maxMedian = median - - var name = self.rename(stat.name) - return new PerfEntry(name, totalTime, median, stat.count) - }) - - var barLength = 10 - fmt.forEach(function (entry) { - var totalTime = entry['Total Time (ms)'] - var median = entry['Median (ms)'] - entry[' '] = createBar(totalTime / maxTime * 100 / barLength) - entry[' '] = createBar(median / maxMedian * 100 / barLength) - }) - - function createBar (len) { - var str = '' - for (var i = 0, max = Math.round(len); i < max; i++) { - str += BAR - } - return str - } - - var res = fmt.sort(function (a, b) { - return b['Total Time (ms)'] - a['Total Time (ms)'] - }) - console.table(res) - return "Showing performance events for '" + this.name + "'" -} - -// An entry for the performance timeline. -function PerfEntry (name, totalTime, median, count) { - this.Name = name - this['Total Time (ms)'] = totalTime - this[' '] = 0 - this['Median (ms)'] = median - this[' '] = 0 - this['Total Count'] = count -} - -// Get the median from an array of numbers. -function getMedian (args) { - if (!args.length) return 0 - var numbers = args.slice(0).sort(function (a, b) { return a - b }) - var middle = Math.floor(numbers.length / 2) - var isEven = numbers.length % 2 === 0 - var res = isEven ? (numbers[middle] + numbers[middle - 1]) / 2 : numbers[middle] - return Number(res.toFixed(2)) -} - -// Do nothing. -function noop () {} - -},{"on-performance":112}],16:[function(require,module,exports){ -var pretty = require('prettier-bytes') - -module.exports = storage - -function storage () { - Object.defineProperty(window.choo, 'storage', { - get: get, - set: noop - }) - - function get () { - if (navigator.storage) { - navigator.storage.estimate().then(function (estimate) { - var value = (estimate.usage / estimate.quota).toFixed() - clr('Max storage:', fmt(estimate.quota)) - clr('Storage used:', fmt(estimate.usage) + ' (' + value + '%)') - navigator.storage.persisted().then(function (bool) { - var val = bool ? 'enabled' : 'disabled' - clr('Persistent storage:', val) - }) - }) - return 'Calculating storage quota…' - } else { - var protocol = window.location.protocol - return (/https/.test(protocol)) - ? "The Storage API is unavailable in this browser. We're sorry!" - : 'The Storage API is unavailable. Serving this site over HTTPS might help enable it!' - } - } -} - -function clr (msg, arg) { - var color = '#cc99cc' - console.log('%c' + msg, 'color: ' + color, arg) -} - -function fmt (num) { - return pretty(num).replace(' ', '') -} - -function noop () {} - -},{"prettier-bytes":114}],17:[function(require,module,exports){ -'use strict'; - -/** - * Remove a range of items from an array - * - * @function removeItems - * @param {Array<*>} arr The target array - * @param {number} startIdx The index to begin removing from (inclusive) - * @param {number} removeCount How many items to remove +/* + * base64-arraybuffer 1.0.1 + * Copyright (c) 2021 Niklas von Hertzen + * Released under MIT License */ -function removeItems (arr, startIdx, removeCount) { - var i, length = arr.length; +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global['base64-arraybuffer'] = {})); +}(this, (function (exports) { 'use strict'; - if (startIdx >= length || removeCount <= 0 || startIdx < 0) { - return - } - - removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount); - - var len = length - removeCount; - - for (i = startIdx; i < len; ++i) { - arr[i] = arr[i + removeCount]; - } - - arr.length = len; -} - -module.exports = removeItems; - -},{}],18:[function(require,module,exports){ -var onPerformance = require('on-performance') -var scheduler = require('nanoscheduler')() -var assert = require('assert') - -module.exports = ChooHooks - -function ChooHooks (emitter) { - if (!(this instanceof ChooHooks)) return new ChooHooks(emitter) - - assert.equal(typeof emitter, 'object') - - this.hasWindow = typeof window !== 'undefined' - this.hasIdleCallback = this.hasWindow && window.requestIdleCallback - this.hasPerformance = this.hasWindow && - window.performance && - window.performance.getEntriesByName - - this.emitter = emitter - this.listeners = {} - this.buffer = { - render: {}, - events: {} - } -} - -ChooHooks.prototype.on = function (name, handler) { - this.listeners[name] = handler -} - -ChooHooks.prototype.start = function () { - var self = this - if (this.hasPerformance) { - window.performance.onresourcetimingbufferfull = function () { - var listener = self.listeners['resource-timing-buffer-full'] - if (listener) listener() + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + // Use a lookup table to find the index. + var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256); + for (var i = 0; i < chars.length; i++) { + lookup[chars.charCodeAt(i)] = i; } - } - - // TODO also handle log events - onPerformance(function (timing) { - if (!timing) return - if (timing.entryType !== 'measure') return - - var eventName = timing.name - if (/choo\.morph/.test(eventName)) { - self.buffer.render.morph = timing - } else if (/choo\.route/.test(eventName)) { - self.buffer.render.route = timing - } else if (/choo\.render/.test(eventName)) { - self.buffer.render.render = timing - } else if (/choo\.emit/.test(eventName) && !/log:/.test(eventName)) { - var eventListener = self.listeners['event'] - if (eventListener) { - var timingName = eventName.match(/choo\.emit\('(.*)'\)/)[1] - if (timingName === 'render' || timingName === 'DOMContentLoaded') return - - var traceId = eventName.match(/\[(\d+)\]/)[1] - var data = self.buffer.events[traceId] - - self.buffer.events[traceId] = null - eventListener(timingName, data, timing) - } - } - - var rBuf = self.buffer.render - if (rBuf.render && rBuf.route && rBuf.morph) { - var renderListener = self.listeners['render'] - if (!renderListener) return - var timings = {} - while (self.buffer.render.length) { - var _timing = self.buffer.render.pop() - var name = _timing.name - if (/choo\.render/.test(name)) timings.render = _timing - else if (/choo\.morph/.test(name)) timings.morph = _timing - else timings.route = _timing - } - rBuf.render = rBuf.route = rBuf.morph = void 0 - renderListener(timings) - } - }) - - // Check if there's timings without any listeners - // and trigger the DOMContentLoaded event. - // If the timing API is not available, we handle all events here - this.emitter.on('*', function (eventName, data, uuid) { - var logLevel = /^log:(\w{4,5})/.exec(eventName) - - if (!self.hasPerformance && eventName === 'render') { - // Render - var renderListener = self.listeners['render'] - if (renderListener) renderListener() - } else if (eventName === 'DOMContentLoaded') { - // DOMContentLoaded - self._emitLoaded() - } else if (logLevel) { - logLevel = logLevel[1] - // Log:* - var logListener = self.listeners['log:' + logLevel] - if (logListener) { - logListener.apply(null, Array.prototype.slice.call(arguments, 0, arguments.length - 1)) - } - } else if (!self.emitter.listeners(eventName).length) { - // Unhandled - var unhandledListener = self.listeners['unhandled'] - if (unhandledListener) unhandledListener(eventName, data) - } else if (eventName !== 'render') { - // * - if (self.hasPerformance) self.buffer.events[uuid] = data - } - }) -} - -// compute and log time till interactive when DOMContentLoaded event fires -ChooHooks.prototype._emitLoaded = function () { - var self = this - scheduler.push(function clear () { - var listener = self.listeners['DOMContentLoaded'] - var timing = self.hasWindow && window.performance && window.performance.timing - - if (listener && timing) { - listener({ - interactive: timing.domInteractive - timing.navigationStart, - loaded: timing.domContentLoadedEventEnd - timing.navigationStart - }) - } - }) -} - -},{"assert":147,"nanoscheduler":107,"on-performance":112}],19:[function(require,module,exports){ -var assert = require('assert') -var LRU = require('nanolru') - -module.exports = ChooComponentCache - -function ChooComponentCache (state, emit, lru) { - assert.ok(this instanceof ChooComponentCache, 'ChooComponentCache should be created with `new`') - - assert.equal(typeof state, 'object', 'ChooComponentCache: state should be type object') - assert.equal(typeof emit, 'function', 'ChooComponentCache: emit should be type function') - - if (typeof lru === 'number') this.cache = new LRU(lru) - else this.cache = lru || new LRU(100) - this.state = state - this.emit = emit -} - -// Get & create component instances. -ChooComponentCache.prototype.render = function (Component, id) { - assert.equal(typeof Component, 'function', 'ChooComponentCache.render: Component should be type function') - assert.ok(typeof id === 'string' || typeof id === 'number', 'ChooComponentCache.render: id should be type string or type number') - - var el = this.cache.get(id) - if (!el) { - var args = [] - for (var i = 2, len = arguments.length; i < len; i++) { - args.push(arguments[i]) - } - args.unshift(Component, id, this.state, this.emit) - el = newCall.apply(newCall, args) - this.cache.set(id, el) - } - - return el -} - -// Because you can't call `new` and `.apply()` at the same time. This is a mad -// hack, but hey it works so we gonna go for it. Whoop. -function newCall (Cls) { - return new (Cls.bind.apply(Cls, arguments)) // eslint-disable-line -} - -},{"assert":88,"nanolru":100}],20:[function(require,module,exports){ -module.exports = require('nanocomponent') - -},{"nanocomponent":90}],21:[function(require,module,exports){ -module.exports = require('nanohtml') - -},{"nanohtml":95}],22:[function(require,module,exports){ -var scrollToAnchor = require('scroll-to-anchor') -var documentReady = require('document-ready') -var nanotiming = require('nanotiming') -var nanorouter = require('nanorouter') -var nanomorph = require('nanomorph') -var nanoquery = require('nanoquery') -var nanohref = require('nanohref') -var nanoraf = require('nanoraf') -var nanobus = require('nanobus') -var assert = require('assert') - -var Cache = require('./component/cache') - -module.exports = Choo - -var HISTORY_OBJECT = {} - -function Choo (opts) { - var timing = nanotiming('choo.constructor') - if (!(this instanceof Choo)) return new Choo(opts) - opts = opts || {} - - assert.equal(typeof opts, 'object', 'choo: opts should be type object') - - var self = this - - // define events used by choo - this._events = { - DOMCONTENTLOADED: 'DOMContentLoaded', - DOMTITLECHANGE: 'DOMTitleChange', - REPLACESTATE: 'replaceState', - PUSHSTATE: 'pushState', - NAVIGATE: 'navigate', - POPSTATE: 'popState', - RENDER: 'render' - } - - // properties for internal use only - this._historyEnabled = opts.history === undefined ? true : opts.history - this._hrefEnabled = opts.href === undefined ? true : opts.href - this._hashEnabled = opts.hash === undefined ? false : opts.hash - this._hasWindow = typeof window !== 'undefined' - this._cache = opts.cache - this._loaded = false - this._stores = [ondomtitlechange] - this._tree = null - - // state - var _state = { - events: this._events, - components: {} - } - if (this._hasWindow) { - this.state = window.initialState - ? Object.assign({}, window.initialState, _state) - : _state - delete window.initialState - } else { - this.state = _state - } - - // properties that are part of the API - this.router = nanorouter({ curry: true }) - this.emitter = nanobus('choo.emit') - this.emit = this.emitter.emit.bind(this.emitter) - - // listen for title changes; available even when calling .toString() - if (this._hasWindow) this.state.title = document.title - function ondomtitlechange (state) { - self.emitter.prependListener(self._events.DOMTITLECHANGE, function (title) { - assert.equal(typeof title, 'string', 'events.DOMTitleChange: title should be type string') - state.title = title - if (self._hasWindow) document.title = title - }) - } - timing() -} - -Choo.prototype.route = function (route, handler) { - var routeTiming = nanotiming("choo.route('" + route + "')") - assert.equal(typeof route, 'string', 'choo.route: route should be type string') - assert.equal(typeof handler, 'function', 'choo.handler: route should be type function') - this.router.on(route, handler) - routeTiming() -} - -Choo.prototype.use = function (cb) { - assert.equal(typeof cb, 'function', 'choo.use: cb should be type function') - var self = this - this._stores.push(function (state) { - var msg = 'choo.use' - msg = cb.storeName ? msg + '(' + cb.storeName + ')' : msg - var endTiming = nanotiming(msg) - cb(state, self.emitter, self) - endTiming() - }) -} - -Choo.prototype.start = function () { - assert.equal(typeof window, 'object', 'choo.start: window was not found. .start() must be called in a browser, use .toString() if running in Node') - var startTiming = nanotiming('choo.start') - - var self = this - if (this._historyEnabled) { - this.emitter.prependListener(this._events.NAVIGATE, function () { - self._matchRoute(self.state) - if (self._loaded) { - self.emitter.emit(self._events.RENDER) - setTimeout(scrollToAnchor.bind(null, window.location.hash), 0) - } - }) - - this.emitter.prependListener(this._events.POPSTATE, function () { - self.emitter.emit(self._events.NAVIGATE) - }) - - this.emitter.prependListener(this._events.PUSHSTATE, function (href) { - assert.equal(typeof href, 'string', 'events.pushState: href should be type string') - window.history.pushState(HISTORY_OBJECT, null, href) - self.emitter.emit(self._events.NAVIGATE) - }) - - this.emitter.prependListener(this._events.REPLACESTATE, function (href) { - assert.equal(typeof href, 'string', 'events.replaceState: href should be type string') - window.history.replaceState(HISTORY_OBJECT, null, href) - self.emitter.emit(self._events.NAVIGATE) - }) - - window.onpopstate = function () { - self.emitter.emit(self._events.POPSTATE) - } - - if (self._hrefEnabled) { - nanohref(function (location) { - var href = location.href - var hash = location.hash - if (href === window.location.href) { - if (!self._hashEnabled && hash) scrollToAnchor(hash) - return + var encode = function (arraybuffer) { + var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = ''; + for (i = 0; i < len; i += 3) { + base64 += chars[bytes[i] >> 2]; + base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; + base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; + base64 += chars[bytes[i + 2] & 63]; } - self.emitter.emit(self._events.PUSHSTATE, href) - }) - } - } - - this._setCache(this.state) - this._matchRoute(this.state) - this._stores.forEach(function (initStore) { - initStore(self.state) - }) - - this._tree = this._prerender(this.state) - assert.ok(this._tree, 'choo.start: no valid DOM node returned for location ' + this.state.href) - - this.emitter.prependListener(self._events.RENDER, nanoraf(function () { - var renderTiming = nanotiming('choo.render') - var newTree = self._prerender(self.state) - assert.ok(newTree, 'choo.render: no valid DOM node returned for location ' + self.state.href) - - assert.equal(self._tree.nodeName, newTree.nodeName, 'choo.render: The target node <' + - self._tree.nodeName.toLowerCase() + '> is not the same type as the new node <' + - newTree.nodeName.toLowerCase() + '>.') - - var morphTiming = nanotiming('choo.morph') - nanomorph(self._tree, newTree) - morphTiming() - - renderTiming() - })) - - documentReady(function () { - self.emitter.emit(self._events.DOMCONTENTLOADED) - self._loaded = true - }) - - startTiming() - return this._tree -} - -Choo.prototype.mount = function mount (selector) { - var mountTiming = nanotiming("choo.mount('" + selector + "')") - if (typeof window !== 'object') { - assert.ok(typeof selector === 'string', 'choo.mount: selector should be type String') - this.selector = selector - mountTiming() - return this - } - - assert.ok(typeof selector === 'string' || typeof selector === 'object', 'choo.mount: selector should be type String or HTMLElement') - - var self = this - - documentReady(function () { - var renderTiming = nanotiming('choo.render') - var newTree = self.start() - if (typeof selector === 'string') { - self._tree = document.querySelector(selector) - } else { - self._tree = selector - } - - assert.ok(self._tree, 'choo.mount: could not query selector: ' + selector) - assert.equal(self._tree.nodeName, newTree.nodeName, 'choo.mount: The target node <' + - self._tree.nodeName.toLowerCase() + '> is not the same type as the new node <' + - newTree.nodeName.toLowerCase() + '>.') - - var morphTiming = nanotiming('choo.morph') - nanomorph(self._tree, newTree) - morphTiming() - - renderTiming() - }) - mountTiming() -} - -Choo.prototype.toString = function (location, state) { - state = state || {} - state.components = state.components || {} - state.events = Object.assign({}, state.events, this._events) - - assert.notEqual(typeof window, 'object', 'choo.mount: window was found. .toString() must be called in Node, use .start() or .mount() if running in the browser') - assert.equal(typeof location, 'string', 'choo.toString: location should be type string') - assert.equal(typeof state, 'object', 'choo.toString: state should be type object') - - this._setCache(state) - this._matchRoute(state, location) - this.emitter.removeAllListeners() - this._stores.forEach(function (initStore) { - initStore(state) - }) - - var html = this._prerender(state) - assert.ok(html, 'choo.toString: no valid value returned for the route ' + location) - assert(!Array.isArray(html), 'choo.toString: return value was an array for the route ' + location) - return typeof html.outerHTML === 'string' ? html.outerHTML : html.toString() -} - -Choo.prototype._matchRoute = function (state, locationOverride) { - var location, queryString - if (locationOverride) { - location = locationOverride.replace(/\?.+$/, '').replace(/\/$/, '') - if (!this._hashEnabled) location = location.replace(/#.+$/, '') - queryString = locationOverride - } else { - location = window.location.pathname.replace(/\/$/, '') - if (this._hashEnabled) location += window.location.hash.replace(/^#/, '/') - queryString = window.location.search - } - var matched = this.router.match(location) - this._handler = matched.cb - state.href = location - state.query = nanoquery(queryString) - state.route = matched.route - state.params = matched.params -} - -Choo.prototype._prerender = function (state) { - var routeTiming = nanotiming("choo.prerender('" + state.route + "')") - var res = this._handler(state, this.emit) - routeTiming() - return res -} - -Choo.prototype._setCache = function (state) { - var cache = new Cache(state, this.emitter.emit.bind(this.emitter), this._cache) - state.cache = renderComponent - - function renderComponent (Component, id) { - assert.equal(typeof Component, 'function', 'choo.state.cache: Component should be type function') - var args = [] - for (var i = 0, len = arguments.length; i < len; i++) { - args.push(arguments[i]) - } - return cache.render.apply(cache, args) - } - - // When the state gets stringified, make sure `state.cache` isn't - // stringified too. - renderComponent.toJSON = function () { - return null - } -} - -},{"./component/cache":19,"assert":88,"document-ready":32,"nanobus":89,"nanohref":92,"nanomorph":101,"nanoquery":104,"nanoraf":105,"nanorouter":106,"nanotiming":108,"scroll-to-anchor":121}],23:[function(require,module,exports){ -/*! clipboard-copy. MIT License. Feross Aboukhadijeh */ -/* global DOMException */ - -module.exports = clipboardCopy - -function clipboardCopy (text) { - // Use the Async Clipboard API when available. Requires a secure browsing - // context (i.e. HTTPS) - if (navigator.clipboard) { - return navigator.clipboard.writeText(text).catch(function (err) { - throw (err !== undefined ? err : new DOMException('The request is not allowed', 'NotAllowedError')) - }) - } - - // ...Otherwise, use document.execCommand() fallback - - // Put the text to copy into a - var span = document.createElement('span') - span.textContent = text - - // Preserve consecutive spaces and newlines - span.style.whiteSpace = 'pre' - span.style.webkitUserSelect = 'auto' - span.style.userSelect = 'all' - - // Add the to the page - document.body.appendChild(span) - - // Make a selection object representing the range of text selected by the user - var selection = window.getSelection() - var range = window.document.createRange() - selection.removeAllRanges() - range.selectNode(span) - selection.addRange(range) - - // Copy text to the clipboard - var success = false - try { - success = window.document.execCommand('copy') - } catch (err) { - console.log('error', err) - } - - // Cleanup - selection.removeAllRanges() - window.document.body.removeChild(span) - - return success - ? Promise.resolve() - : Promise.reject(new DOMException('The request is not allowed', 'NotAllowedError')) -} - -},{}],24:[function(require,module,exports){ -(function (Buffer){(function (){ -var clone = (function() { -'use strict'; - -function _instanceof(obj, type) { - return type != null && obj instanceof type; -} - -var nativeMap; -try { - nativeMap = Map; -} catch(_) { - // maybe a reference error because no `Map`. Give it a dummy value that no - // value will ever be an instanceof. - nativeMap = function() {}; -} - -var nativeSet; -try { - nativeSet = Set; -} catch(_) { - nativeSet = function() {}; -} - -var nativePromise; -try { - nativePromise = Promise; -} catch(_) { - nativePromise = function() {}; -} - -/** - * Clones (copies) an Object using deep copying. - * - * This function supports circular references by default, but if you are certain - * there are no circular references in your object, you can save some CPU time - * by calling clone(obj, false). - * - * Caution: if `circular` is false and `parent` contains circular references, - * your program may enter an infinite loop and crash. - * - * @param `parent` - the object to be cloned - * @param `circular` - set to true if the object to be cloned may contain - * circular references. (optional - true by default) - * @param `depth` - set to a number if the object is only to be cloned to - * a particular depth. (optional - defaults to Infinity) - * @param `prototype` - sets the prototype to be used when cloning an object. - * (optional - defaults to parent prototype). - * @param `includeNonEnumerable` - set to true if the non-enumerable properties - * should be cloned as well. Non-enumerable properties on the prototype - * chain will be ignored. (optional - false by default) -*/ -function clone(parent, circular, depth, prototype, includeNonEnumerable) { - if (typeof circular === 'object') { - depth = circular.depth; - prototype = circular.prototype; - includeNonEnumerable = circular.includeNonEnumerable; - circular = circular.circular; - } - // maintain two arrays for circular references, where corresponding parents - // and children have the same index - var allParents = []; - var allChildren = []; - - var useBuffer = typeof Buffer != 'undefined'; - - if (typeof circular == 'undefined') - circular = true; - - if (typeof depth == 'undefined') - depth = Infinity; - - // recurse this function so we don't reset allParents and allChildren - function _clone(parent, depth) { - // cloning null always returns null - if (parent === null) - return null; - - if (depth === 0) - return parent; - - var child; - var proto; - if (typeof parent != 'object') { - return parent; - } - - if (_instanceof(parent, nativeMap)) { - child = new nativeMap(); - } else if (_instanceof(parent, nativeSet)) { - child = new nativeSet(); - } else if (_instanceof(parent, nativePromise)) { - child = new nativePromise(function (resolve, reject) { - parent.then(function(value) { - resolve(_clone(value, depth - 1)); - }, function(err) { - reject(_clone(err, depth - 1)); - }); - }); - } else if (clone.__isArray(parent)) { - child = []; - } else if (clone.__isRegExp(parent)) { - child = new RegExp(parent.source, __getRegExpFlags(parent)); - if (parent.lastIndex) child.lastIndex = parent.lastIndex; - } else if (clone.__isDate(parent)) { - child = new Date(parent.getTime()); - } else if (useBuffer && Buffer.isBuffer(parent)) { - if (Buffer.allocUnsafe) { - // Node.js >= 4.5.0 - child = Buffer.allocUnsafe(parent.length); - } else { - // Older Node.js versions - child = new Buffer(parent.length); - } - parent.copy(child); - return child; - } else if (_instanceof(parent, Error)) { - child = Object.create(parent); - } else { - if (typeof prototype == 'undefined') { - proto = Object.getPrototypeOf(parent); - child = Object.create(proto); - } - else { - child = Object.create(prototype); - proto = prototype; - } - } - - if (circular) { - var index = allParents.indexOf(parent); - - if (index != -1) { - return allChildren[index]; - } - allParents.push(parent); - allChildren.push(child); - } - - if (_instanceof(parent, nativeMap)) { - parent.forEach(function(value, key) { - var keyChild = _clone(key, depth - 1); - var valueChild = _clone(value, depth - 1); - child.set(keyChild, valueChild); - }); - } - if (_instanceof(parent, nativeSet)) { - parent.forEach(function(value) { - var entryChild = _clone(value, depth - 1); - child.add(entryChild); - }); - } - - for (var i in parent) { - var attrs; - if (proto) { - attrs = Object.getOwnPropertyDescriptor(proto, i); - } - - if (attrs && attrs.set == null) { - continue; - } - child[i] = _clone(parent[i], depth - 1); - } - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(parent); - for (var i = 0; i < symbols.length; i++) { - // Don't need to worry about cloning a symbol because it is a primitive, - // like a number or string. - var symbol = symbols[i]; - var descriptor = Object.getOwnPropertyDescriptor(parent, symbol); - if (descriptor && !descriptor.enumerable && !includeNonEnumerable) { - continue; + if (len % 3 === 2) { + base64 = base64.substring(0, base64.length - 1) + '='; } - child[symbol] = _clone(parent[symbol], depth - 1); - if (!descriptor.enumerable) { - Object.defineProperty(child, symbol, { - enumerable: false - }); + else if (len % 3 === 1) { + base64 = base64.substring(0, base64.length - 2) + '=='; } - } - } - - if (includeNonEnumerable) { - var allPropertyNames = Object.getOwnPropertyNames(parent); - for (var i = 0; i < allPropertyNames.length; i++) { - var propertyName = allPropertyNames[i]; - var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName); - if (descriptor && descriptor.enumerable) { - continue; - } - child[propertyName] = _clone(parent[propertyName], depth - 1); - Object.defineProperty(child, propertyName, { - enumerable: false - }); - } - } - - return child; - } - - return _clone(parent, depth); -} - -/** - * Simple flat clone using prototype, accepts only objects, usefull for property - * override on FLAT configuration object (no nested props). - * - * USE WITH CAUTION! This may not behave as you wish if you do not know how this - * works. - */ -clone.clonePrototype = function clonePrototype(parent) { - if (parent === null) - return null; - - var c = function () {}; - c.prototype = parent; - return new c(); -}; - -// private utility functions - -function __objToStr(o) { - return Object.prototype.toString.call(o); -} -clone.__objToStr = __objToStr; - -function __isDate(o) { - return typeof o === 'object' && __objToStr(o) === '[object Date]'; -} -clone.__isDate = __isDate; - -function __isArray(o) { - return typeof o === 'object' && __objToStr(o) === '[object Array]'; -} -clone.__isArray = __isArray; - -function __isRegExp(o) { - return typeof o === 'object' && __objToStr(o) === '[object RegExp]'; -} -clone.__isRegExp = __isRegExp; - -function __getRegExpFlags(re) { - var flags = ''; - if (re.global) flags += 'g'; - if (re.ignoreCase) flags += 'i'; - if (re.multiline) flags += 'm'; - return flags; -} -clone.__getRegExpFlags = __getRegExpFlags; - -return clone; -})(); - -if (typeof module === 'object' && module.exports) { - module.exports = clone; -} - -}).call(this)}).call(this,require("buffer").Buffer) -},{"buffer":153}],25:[function(require,module,exports){ -(function(r){"object"==typeof exports&&"object"==typeof module?r(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],r):r(CodeMirror)})(function(r){function I(c){c=c.search(w);return-1==c?0:c}function J(c,d,a){return/\bstring\b/.test(c.getTokenTypeAt(l(d.line,0)))&&!/^['"`]/.test(a)}function G(c,d){var a=c.getMode();return!1!==a.useInnerComments&&a.innerMode?c.getModeAt(d):a}var E={},w=/[^\s\u00a0]/,l=r.Pos,K=r.cmpPos;r.commands.toggleComment=function(c){c.toggleComment()}; -r.defineExtension("toggleComment",function(c){c||(c=E);for(var d=Infinity,a=this.listSelections(),b=null,e=a.length-1;0<=e;e--){var g=a[e].from(),f=a[e].to();g.line>=d||(f.line>=d&&(f=l(d,0)),d=g.line,null==b?this.uncomment(g,f,c)?b="un":(this.lineComment(g,f,c),b="line"):"un"==b?this.uncomment(g,f,c):this.lineComment(g,f,c))}});r.defineExtension("lineComment",function(c,d,a){a||(a=E);var b=this,e=G(b,c),g=b.getLine(c.line);if(null!=g&&!J(b,c,g)){var f=a.lineComment||e.lineComment;if(f){var m=Math.min(0!= -d.ch||d.line==c.line?d.line+1:d.line,b.lastLine()+1),u=null==a.padding?" ":a.padding,k=a.commentBlankLines||c.line==d.line;b.operation(function(){if(a.indent){for(var p=null,h=c.line;hq.length)p=q}for(h=c.line;hm||b.operation(function(){if(0!= -a.fullLines){var k=w.test(b.getLine(m));b.replaceRange(u+f,l(m));b.replaceRange(g+u,l(c.line,0));var p=a.blockCommentLead||e.blockCommentLead;if(null!=p)for(var h=c.line+1;h<=m;++h)(h!=m||k)&&b.replaceRange(p+u,l(h,0))}else k=0==K(b.getCursor("to"),d),p=!b.somethingSelected(),b.replaceRange(f,d),k&&b.setSelection(p?d:b.getCursor("from"),d),b.replaceRange(g,c)})}});r.defineExtension("uncomment",function(c,d,a){a||(a=E);var b=this,e=G(b,c),g=Math.min(0!=d.ch||d.line==c.line?d.line:d.line-1,b.lastLine()), -f=Math.min(c.line,g),m=a.lineComment||e.lineComment,u=[],k=null==a.padding?" ":a.padding,p;a:if(m){for(var h=f;h<=g;++h){var q=b.getLine(h),t=q.indexOf(m);-1x||(A.slice(v,v+k.length)==k&&(v+=k.length),p=!0,b.replaceRange("",l(n,x),l(n,v)))}});if(p)return!0}var y=a.blockCommentStart|| -e.blockCommentStart,z=a.blockCommentEnd||e.blockCommentEnd;if(!y||!z)return!1;var H=a.blockCommentLead||e.blockCommentLead,C=b.getLine(f),D=C.indexOf(y);if(-1==D)return!1;var F=g==f?C:b.getLine(g),B=F.indexOf(z,g==f?D+y.length:0);a=l(f,D+1);e=l(g,B+1);if(-1==B||!/comment/.test(b.getTokenTypeAt(a))||!/comment/.test(b.getTokenTypeAt(e))||-1c.ch&&(d.end=c.ch,d.string=d.string.slice(0, -c.ch-d.start)):d={start:c.ch,end:c.ch,string:"",state:d.state,type:"."==d.string?"property":null};for(g=d;"property"==g.type;){g=l(a,r(c.line,g.start));if("."!=g.string)return;g=l(a,r(c.line,g.start));if(!p)var p=[];p.push(g)}return{list:u(d,p,b,e),from:r(c.line,d.start),to:r(c.line,d.end)}}}}function v(a,b){a=a.getTokenAt(b);b.ch==a.start+1&&"."==a.string.charAt(0)?(a.end=a.start,a.string=".",a.type="property"):/^\.[\w$_]*$/.test(a.string)&&(a.type="property",a.start++,a.string=a.string.replace(/\./, -""));return a}function u(a,b,l,e){function c(h){var k;if(k=0==h.lastIndexOf(p,0)){a:if(Array.prototype.indexOf)k=-1!=g.indexOf(h);else{for(k=g.length;k--;)if(g[k]===h){k=!0;break a}k=!1}k=!k}k&&g.push(h)}function d(h){"string"==typeof h?q(w,c):h instanceof Array?q(x,c):h instanceof Function&&q(y,c);if(Object.getOwnPropertyNames&&Object.getPrototypeOf)for(;h;h=Object.getPrototypeOf(h))Object.getOwnPropertyNames(h).forEach(c);else for(var k in h)c(k)}var g=[],p=a.string,n=e&&e.globalScope||window;if(b&& -b.length){a=b.pop();var f;a.type&&0===a.type.indexOf("variable")?(e&&e.additionalContext&&(f=e.additionalContext[a.string]),e&&!1===e.useGlobalScope||(f=f||n[a.string])):"string"==a.type?f="":"atom"==a.type?f=1:"function"==a.type&&(null==n.jQuery||"$"!=a.string&&"jQuery"!=a.string||"function"!=typeof n.jQuery?null!=n._&&"_"==a.string&&"function"==typeof n._&&(f=n._()):f=n.jQuery());for(;null!=f&&b.length;)f=f[b.pop().string];null!=f&&d(f)}else{for(b=a.state.localVars;b;b=b.next)c(b.name);for(f=a.state.context;f;f= -f.prev)for(b=f.vars;b;b=b.next)c(b.name);for(b=a.state.globalVars;b;b=b.next)c(b.name);if(e&&null!=e.additionalContext)for(var z in e.additionalContext)c(z);e&&!1===e.useGlobalScope||d(n);q(l,c)}return g}var r=m.Pos;m.registerHelper("hint","javascript",function(a,b){return t(a,A,function(l,e){return l.getTokenAt(e)},b)});m.registerHelper("hint","coffeescript",function(a,b){return t(a,B,v,b)});var w="charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight toUpperCase toLowerCase split concat match replace search".split(" "), -x="length concat join splice push pop shift unshift slice reverse sort indexOf lastIndexOf every some filter forEach map reduce reduceRight ".split(" "),y=["prototype","apply","call","bind"],A="break case catch class const continue debugger default delete do else export extends false finally for function if in import instanceof new null return super switch this throw true try typeof var void while with yield".split(" "),B="and break catch class continue delete do else extends false finally for if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes".split(" ")}); - -},{"../../lib/codemirror":29}],27:[function(require,module,exports){ -(function(h){"object"==typeof exports&&"object"==typeof module?h(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],h):h(CodeMirror)})(function(h){function B(a,b){this.cm=a;this.options=b;this.widget=null;this.tick=this.debounce=0;this.startPos=this.cm.getCursor("start");this.startLen=this.cm.getLine(this.startPos.line).length-this.cm.getSelection().length;if(this.options.updateOnCursorActivity){var c=this;a.on("cursorActivity",this.activityFunc= -function(){c.cursorActivity()})}}function J(a,b){function c(r,g){var m="string"!=typeof g?function(k){return g(k,b)}:d.hasOwnProperty(g)?d[g]:g;p[r]=m}var d={Up:function(){b.moveFocus(-1)},Down:function(){b.moveFocus(1)},PageUp:function(){b.moveFocus(-b.menuSize()+1,!0)},PageDown:function(){b.moveFocus(b.menuSize()-1,!0)},Home:function(){b.setFocus(0)},End:function(){b.setFocus(b.length-1)},Enter:b.pick,Tab:b.pick,Esc:b.close};/Mac/.test(navigator.platform)&&(d["Ctrl-P"]=function(){b.moveFocus(-1)}, -d["Ctrl-N"]=function(){b.moveFocus(1)});var e=a.options.customKeys,p=e?{}:d;if(e)for(var f in e)e.hasOwnProperty(f)&&c(f,e[f]);if(a=a.options.extraKeys)for(f in a)a.hasOwnProperty(f)&&c(f,a[f]);return p}function C(a,b){for(;b&&b!=a;){if("LI"===b.nodeName.toUpperCase()&&b.parentNode==a)return b;b=b.parentNode}}function D(a,b){this.id="cm-complete-"+Math.floor(Math.random(1E6));this.completion=a;this.data=b;this.picked=!1;var c=this,d=a.cm,e=d.getInputField().ownerDocument,p=e.defaultView||e.parentWindow, -f=this.hints=e.createElement("ul");f.setAttribute("role","listbox");f.setAttribute("aria-expanded","true");f.id=this.id;f.className="CodeMirror-hints "+a.cm.options.theme;this.selectedHint=b.selectedHint||0;for(var r=b.list,g=0;g -f.clientHeight+1:!1;var u;setTimeout(function(){u=d.getScrollInfo()});if(0y&&(f.style.height=y-5+"px",f.style.top=(w=g.bottom-l.top-q)+"px",q=d.getCursor(),b.from.ch!=q.ch&&(g=d.cursorCoords(q),f.style.left=(v=g.left-m)+"px",l=f.getBoundingClientRect()))}q=l.right-k;t&&(q+=d.display.nativeBarWidth);0k&&(f.style.width=k-5+"px",q-=l.right-l.left-k),f.style.left=(v=g.left-q-m)+"px"); -if(t)for(g=f.firstChild;g;g=g.nextSibling)g.style.paddingRight=d.display.nativeBarWidth+"px";d.addKeyMap(this.keyMap=J(a,{moveFocus:function(n,x){c.changeActive(c.selectedHint+n,x)},setFocus:function(n){c.changeActive(n)},menuSize:function(){return c.screenAmount()},length:r.length,close:function(){a.close()},pick:function(){c.pick()},data:b}));if(a.options.closeOnUnfocus){var F;d.on("blur",this.onBlur=function(){F=setTimeout(function(){a.close()},100)});d.on("focus",this.onFocus=function(){clearTimeout(F)})}d.on("scroll", -this.onScroll=function(){var n=d.getScrollInfo(),x=d.getWrapperElement().getBoundingClientRect();u||(u=d.getScrollInfo());var G=w+u.top-n.top,A=G-(p.pageYOffset||(e.documentElement||e.body).scrollTop);E||(A+=f.offsetHeight);if(A<=x.top||A>=x.bottom)return a.close();f.style.top=G+"px";f.style.left=v+u.left-n.left+"px"});h.on(f,"dblclick",function(n){(n=C(f,n.target||n.srcElement))&&null!=n.hintId&&(c.changeActive(n.hintId),c.pick())});h.on(f,"click",function(n){(n=C(f,n.target||n.srcElement))&&null!= -n.hintId&&(c.changeActive(n.hintId),a.options.completeOnSingleClick&&c.pick())});h.on(f,"mousedown",function(){setTimeout(function(){d.focus()},20)});g=this.getSelectedHintRange();0===g.from&&0===g.to||this.scrollToActive();h.signal(b,"select",r[this.selectedHint],f.childNodes[this.selectedHint]);return!0}function K(a,b){if(!a.somethingSelected())return b;a=[];for(var c=0;c=this.data.list.length?a=b?this.data.list.length-1:0:0>a&&(a=b?0:this.data.list.length-1);if(this.selectedHint!=a){if(b=this.hints.childNodes[this.selectedHint])b.className=b.className.replace(" CodeMirror-hint-active",""),b.removeAttribute("aria-selected");b=this.hints.childNodes[this.selectedHint=a];b.className+=" CodeMirror-hint-active";b.setAttribute("aria-selected", -"true");this.completion.cm.getInputField().setAttribute("aria-activedescendant",b.id);this.scrollToActive();h.signal(this.data,"select",this.data.list[this.selectedHint],b)}},scrollToActive:function(){var a=this.getSelectedHintRange(),b=this.hints.childNodes[a.from];a=this.hints.childNodes[a.to];var c=this.hints.firstChild;b.offsetTopthis.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=a.offsetTop+ -a.offsetHeight-this.hints.clientHeight+c.offsetTop)},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1},getSelectedHintRange:function(){var a=this.completion.options.scrollMargin||0;return{from:Math.max(0,this.selectedHint-a),to:Math.min(this.data.list.length-1,this.selectedHint+a)}}};h.registerHelper("hint","auto",{resolve:function(a,b){var c=a.getHelpers(b,"hint"),d;return c.length?(a=function(e,p,f){function r(m){if(m==g.length)return p(null); -H(g[m],e,f,function(k){k&&0,]/,closeOnPick:!0,closeOnUnfocus:!0,updateOnCursorActivity:!0,completeOnSingleClick:!0,container:null,customKeys:null,extraKeys:null,paddingForScrollbar:!0,moveOnOverlap:!0};h.defineOption("hintOptions",null)}); - -},{"../../lib/codemirror":29}],28:[function(require,module,exports){ -(function (global){(function (){ -var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.findInternal=function(a,d,c){a instanceof String&&(a=String(a));for(var e=a.length,f=0;f>>0,$jscomp.propertyToPolyfillSymbol[f]=$jscomp.IS_SYMBOL_NATIVE? -$jscomp.global.Symbol(f):$jscomp.POLYFILL_PREFIX+c+"$"+f),$jscomp.defineProperty(e,$jscomp.propertyToPolyfillSymbol[f],{configurable:!0,writable:!0,value:d})))};$jscomp.polyfill("Array.prototype.find",function(a){return a?a:function(d,c){return $jscomp.findInternal(this,d,c).v}},"es6","es3"); -(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})(function(a){function d(b){b.state.markedSelection&&b.operation(function(){r(b)})}function c(b){b.state.markedSelection&&b.state.markedSelection.length&&b.operation(function(){f(b)})}function e(b,g,h,k){if(0!=p(g,h))for(var l=b.state.markedSelection,n=b.state.markedSelectionStyle,q=g.line;;){var t=q==g.line?g:v(q, -0);q+=u;var w=q>=h.line,x=w?h:v(q,0);t=b.markText(t,x,{className:n});null==k?l.push(t):l.splice(k++,0,t);if(w)break}}function f(b){b=b.state.markedSelection;for(var g=0;g=p(h,l.from))return m(b);for(;0p(g,l.from)&&(l.to.line-g.linep(h,n.to);)k.pop().clear(),n=k[k.length-1].find();0>>0,$jscomp.propertyToPolyfillSymbol[M]= -$jscomp.IS_SYMBOL_NATIVE?$jscomp.global.Symbol(M):$jscomp.POLYFILL_PREFIX+D+"$"+M),$jscomp.defineProperty(v,$jscomp.propertyToPolyfillSymbol[M],{configurable:!0,writable:!0,value:E})))};$jscomp.polyfill("Array.prototype.find",function(y){return y?y:function(E,D){return $jscomp.findInternal(this,E,D).v}},"es6","es3"); -(function(y,E){"object"===typeof exports&&"undefined"!==typeof module?module.exports=E():"function"===typeof define&&define.amd?define(E):(y=y||self,y.CodeMirror=E())})(this,function(){function y(a){return new RegExp("(^|\\s)"+a+"(?:$|\\s)\\s*")}function E(a){for(var b=a.childNodes.length;0f||f>=b)return e+(b- -c);e+=f-c;e+=d-e%d;c=f+1}}function ea(a,b){for(var d=0;d=b)return c+Math.min(g,b-e);e+=f-c;e+=d-e%d;c=f+1;if(e>=b)return c}}function hd(a){for(;tc.length<=a;)tc.push(J(tc)+" ");return tc[a]}function J(a){return a[a.length-1]}function uc(a,b){for(var d=[],c=0;cd?0d?-1:1;;){if(b==d)return b;var e=(b+d)/2;e=0>c?Math.ceil(e):Math.floor(e);if(e==b)return a(e)?b:d;a(e)?d=e:b=e+c}}function zg(a,b,d,c){if(!a)return c(b,d,"ltr",0);for(var e=!1,f=0;fb||b==d&&g.to==b)c(Math.max(g.from,b),Math.min(g.to,d),1==g.level?"rtl":"ltr",f),e=!0}e||c(b,d,"ltr")}function Ib(a,b,d){var c;Jb=null;for(var e=0;eb)return e;f.to==b&&(f.from!=f.to&&"before"== -d?c=e:Jb=e);f.from==b&&(f.from!=f.to&&"before"!=d?c=e:Jb=e)}return null!=c?c:Jb}function Ia(a,b){var d=a.order;null==d&&(d=a.order=Ag(a.text,b));return d}function sa(a,b,d){if(a.removeEventListener)a.removeEventListener(b,d,!1);else if(a.detachEvent)a.detachEvent("on"+b,d);else{var c=(a=a._handlers)&&a[b];c&&(d=ea(c,d),-1b||b>=a.size)throw Error("There is no line "+(b+a.first)+" in the document.");for(;!a.lines;)for(var d=0;;++d){var c=a.children[d],e=c.chunkSize();if(b=a.first&&bB(a,b)?b:a} -function zc(a,b){return 0>B(a,b)?a:b}function C(a,b){if(b.lined)return t(d,w(a,d).text.length);a=w(a,b.line).text.length;d=b.ch;b=null==d||d>a?t(b.line,a):0>d?t(b.line,0):b;return b}function we(a,b){for(var d=[],c=0;cp&&e.splice(m,1,p,e[m+1],u);m+=2;n=Math.min(p,u)}if(q)if(l.opaque)e.splice(r,m-r,p,"overlay "+q),m=r+2;else for(;ra.options.maxHighlightLength&& -Ya(a.doc.mode,c.state),f=xe(a,b,c);e&&(c.state=e);b.stateAfter=c.save(!e);b.styles=f.styles;f.classes?b.styleClasses=f.classes:b.styleClasses&&(b.styleClasses=null);d===a.doc.highlightFrontier&&(a.doc.modeFrontier=Math.max(a.doc.modeFrontier,++a.doc.highlightFrontier))}return b.styles}function Mb(a,b,d){var c=a.doc,e=a.display;if(!c.mode.startState)return new Da(c,!0,b);var f=Dg(a,b,d),g=f>c.first&&w(c,f-1).stateAfter,h=g?Da.fromSaved(c,g,f):new Da(c,ve(c.mode),f);c.iter(f,b,function(k){sd(a,k.text, -h);var l=h.line;k.stateAfter=l==b-1||0==l%5||l>=e.viewFrom&&le;e++){c&&(c[0]=nd(a,d).mode);var f=a.token(b, -d);if(b.pos>b.start)return f}throw Error("Mode "+a.name+" failed to advance stream.");}function Be(a,b,d,c){var e=a.doc,f=e.mode;b=C(e,b);var g=w(e,b.line);d=Mb(a,b.line,d);a=new X(g.text,a.options.tabSize,d);var h;for(c&&(h=[]);(c||a.posa.options.maxHighlightLength){h=!1;g&&sd(a,b,c,m.pos);m.pos=b.length;var p=null}else p=De(td(d,m,c.state,n),f);if(n){var q=n[0].name;q&&(p="m-"+(p?q+" "+ -p:q))}if(!h||l!=p){for(;kg;--b){if(b<=f.first)return f.first;var h=w(f,b-1),k=h.stateAfter;if(k&&(!d||b+(k instanceof Ac?k.lookAhead:0)<=f.modeFrontier))return b;h=va(h.text,null,a.options.tabSize);if(null==e||c>h)e=b-1,c=h}return e}function Eg(a,b){a.modeFrontier=Math.min(a.modeFrontier,b);if(!(a.highlightFrontier< -b-10)){for(var d=a.first,c=b-1;c>d;c--){var e=w(a,c).stateAfter;if(e&&(!(e instanceof Ac)||c+e.lookAhead=a:k.to>a);(g||(g=[])).push(new Bc(l,k.from,m?null:k.to))}}d=g;var n;if(c)for(g=0;g=e:h.to>e)||h.from==e&&"bookmark"==k.type&&(!f||h.marker.insertLeft))l=null==h.from||(k.inclusiveLeft?h.from<=e:h.from< -e),(n||(n=[])).push(new Bc(k,l?null:h.from-e,null==h.to?null:h.to-e));c=1==b.text.length;e=J(b.text).length+(c?a:0);if(d)for(f=0;fB(g.to,e.from)||0k||!d.inclusiveLeft&&!k)&&h.push({from:g.from,to:e.from});(0vd(e,d.marker)))var e=d.marker;return e}function He(a,b,d,c,e){a=w(a,b);if(a=Ja&&a.markedSpans)for(b=0;b=k||0>=h&&0<=k)&&(0>=h&&(f.marker.inclusiveRight&&e.inclusiveLeft?0<=B(g.to,d):0=B(g.from,c):0>B(g.from,c))))return!0}}}function Ea(a){for(var b;b=qb(a,!0);)a=b.find(-1,!0).line;return a}function wd(a,b){a=w(a,b);var d=Ea(a);return a==d?b:N(d)} -function Ie(a,b){if(b>a.lastLine())return b;var d=w(a,b);if(!Oa(a,d))return b;for(;a=qb(d,!1);)d=a.find(1,!0).line;return N(d)+1}function Oa(a,b){var d=Ja&&b.markedSpans;if(d)for(var c,e=0;eb.maxLineLength&&(b.maxLineLength=c,b.maxLine=d)})}function Je(a,b){if(!a||/^\s*$/.test(a))return null;b=b.addModeClass?Gg:Hg;return b[a]||(b[a]=a.replace(/\S+/g,"cm-$&"))}function Ke(a, -b){var d=M("span",null,null,fa?"padding-right: .1px":null);d={pre:M("pre",[d],"CodeMirror-line"),content:d,col:0,pos:0,cm:a,trailingSpace:!1,splitSpaces:a.getOption("lineWrapping")};b.measure={};for(var c=0;c<=(b.rest?b.rest.length:0);c++){var e=c?b.rest[c-1]:b.line,f=void 0;d.pos=0;d.addToken=Ig;var g=a.display.measure;if(null!=zd)g=zd;else{var h=D(g,document.createTextNode("A\u062eA")),k=Ob(h,0,1).getBoundingClientRect();h=Ob(h,1,2).getBoundingClientRect();E(g);g=k&&k.left!=k.right?zd=3>h.right- -k.right:!1}g&&(f=Ia(e,a.doc.direction))&&(d.addToken=Jg(d.addToken,f));d.map=[];var l=b!=a.display.externalMeasured&&N(e);a:{var m=h=k=g=void 0,n=void 0,p=void 0,q=void 0;f=d;l=ze(a,e,l);var r=e.markedSpans,u=e.text,A=0;if(r)for(var Y=u.length,x=0,P=1,K="",Q=0;;){if(Q==x){n=m=h=p="";k=g=null;Q=Infinity;for(var S=[],F=void 0,R=0;Rx||L.collapsed&&H.to==x&&H.from==x)){null!= -H.to&&H.to!=x&&Q>H.to&&(Q=H.to,m="");L.className&&(n+=" "+L.className);L.css&&(p=(p?p+";":"")+L.css);L.startStyle&&H.from==x&&(h+=" "+L.startStyle);L.endStyle&&H.to==Q&&(F||(F=[])).push(L.endStyle,H.to);L.title&&((g||(g={})).title=L.title);if(L.attributes)for(var ha in L.attributes)(g||(g={}))[ha]=L.attributes[ha];L.collapsed&&(!k||0>vd(k.marker,L))&&(k=H)}else H.from>x&&Q>H.from&&(Q=H.from)}if(F)for(R=0;R=Y)break;for(S=Math.min(Y,Q);;){if(K){F=x+K.length;k||(R=F>S?K.slice(0,S-x):K,f.addToken(f,R,q?q+n:n,h,x+R.length==Q?m:"",p,g));if(F>=S){K=K.slice(S-x);x=S;break}x=F;h=""}K=u.slice(A,A=l[P++]);q=Je(l[P++],f.cm.options)}}else for(g=1;g=m.offsetWidth&&2T))),h=Ad?v("span","\u200b"):v("span","\u00a0",null,"display: inline-block; width: 1px; margin-right: -1px"),h.setAttribute("cm-text",""),f.call(e,0,0,k.call(g, -h)));0==c?(b.measure.map=d.map,b.measure.cache={}):((b.measure.maps||(b.measure.maps=[])).push(d.map),(b.measure.caches||(b.measure.caches=[])).push({}))}fa&&(ha=d.content.lastChild,/\bcm-tab\b/.test(ha.className)||ha.querySelector&&ha.querySelector(".cm-tab"))&&(d.content.className="cm-tab-wrap-hack");W(a,"renderLine",a,b.line,d.pre);d.pre.className&&(d.textClass=ed(d.pre.className,d.textClass||""));return d}function Kg(a){var b=v("span","\u2022","cm-invalidchar");b.title="\\u"+a.charCodeAt(0).toString(16); -b.setAttribute("aria-label",b.title);return b}function Ig(a,b,d,c,e,f,g){if(b){if(a.splitSpaces){var h=a.trailingSpace;if(1T?h.appendChild(v("span",[r])):h.appendChild(r);a.map.push(a.pos,a.pos+q,r);a.col+=q;a.pos+=q}if(!p)break;n+=q+1;"\t"==p[0]?(p=a.cm.options.tabSize,p-=a.col%p,q=h.appendChild(v("span",hd(p),"cm-tab")),q.setAttribute("role","presentation"),q.setAttribute("cm-text","\t"),a.col+=p):("\r"==p[0]||"\n"==p[0]?(q=h.appendChild(v("span","\r"==p[0]?"\u240d":"\u2424","cm-invalidchar")),q.setAttribute("cm-text",p[0])):(q=a.cm.options.specialCharPlaceholder(p[0]),q.setAttribute("cm-text",p[0]),G&&9>T? -h.appendChild(v("span",[q])):h.appendChild(q)),a.col+=1);a.map.push(a.pos,a.pos+1,q);a.pos++}}else a.col+=b.length,h=document.createTextNode(k),a.map.push(a.pos,a.pos+b.length,h),G&&9>T&&(m=!0),a.pos+=b.length;a.trailingSpace=32==k.charCodeAt(b.length-1);if(d||c||e||m||f||g){b=d||"";c&&(b+=c);e&&(b+=e);c=v("span",[h],b,f);if(g)for(var u in g)g.hasOwnProperty(u)&&"style"!=u&&"class"!=u&&c.setAttribute(u,g[u]);return a.content.appendChild(c)}a.content.appendChild(h)}}function Jg(a,b){return function(d, -c,e,f,g,h,k){e=e?e+" cm-force-border":"cm-force-border";for(var l=d.pos,m=l+c.length;;){for(var n=void 0,p=0;pl&&n.from<=l);p++);if(n.to>=m)return a(d,c,e,f,g,h,k);a(d,c.slice(0,n.to-l),e,f,null,h,k);f=null;c=c.slice(n.to-l);l=n.to}}}function Le(a,b,d,c){var e=!c&&d.widgetNode;e&&a.map.push(a.pos,a.pos+b,e);!c&&a.cm.display.input.needsContentAttribute&&(e||(e=a.content.appendChild(document.createElement("span"))),e.setAttribute("cm-marker",d.id));e&&(a.cm.display.input.setUneditable(e), -a.content.appendChild(e));a.pos+=b;a.trailingSpace=!1}function Me(a,b,d){for(var c=this.line=b,e;c=qb(c,!1);)c=c.find(1,!0).line,(e||(e=[])).push(c);this.size=(this.rest=e)?N(J(this.rest))-d+1:1;this.node=this.text=null;this.hidden=Oa(a,b)}function Dc(a,b,d){var c=[],e;for(e=b;eT&&(a.node.style.zIndex=2));return a.node}function Oe(a,b){var d=a.display.externalMeasured;return d&&d.line==b.line?(a.display.externalMeasured=null,b.measure=d.measure,d.built):Ke(a,b)}function Bd(a,b){var d=b.bgClass?b.bgClass+" "+ -(b.line.bgClass||""):b.line.bgClass;d&&(d+=" CodeMirror-linebackground");if(b.background)d?b.background.className=d:(b.background.parentNode.removeChild(b.background),b.background=null);else if(d){var c=Qb(b);b.background=c.insertBefore(v("div",null,d),c.firstChild);a.display.input.setUneditable(b.background)}b.line.wrapClass?Qb(b).className=b.line.wrapClass:b.node!=b.text&&(b.node.className="");b.text.className=(b.textClass?b.textClass+" "+(b.line.textClass||""):b.line.textClass)||""}function Pe(a, -b,d,c){b.gutter&&(b.node.removeChild(b.gutter),b.gutter=null);b.gutterBackground&&(b.node.removeChild(b.gutterBackground),b.gutterBackground=null);if(b.line.gutterClass){var e=Qb(b);b.gutterBackground=v("div",null,"CodeMirror-gutter-background "+b.line.gutterClass,"left: "+(a.options.fixedGutter?c.fixedPos:-c.gutterTotalWidth)+"px; width: "+c.gutterTotalWidth+"px");a.display.input.setUneditable(b.gutterBackground);e.insertBefore(b.gutterBackground,b.text)}e=b.line.gutterMarkers;if(a.options.lineNumbers|| -e){var f=Qb(b),g=b.gutter=v("div",null,"CodeMirror-gutter-wrapper","left: "+(a.options.fixedGutter?c.fixedPos:-c.gutterTotalWidth)+"px");g.setAttribute("aria-hidden","true");a.display.input.setUneditable(g);f.insertBefore(g,b.text);b.line.gutterClass&&(g.className+=" "+b.line.gutterClass);!a.options.lineNumbers||e&&e["CodeMirror-linenumbers"]||(b.lineNumber=g.appendChild(v("div",pd(a.options,d),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+c.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+ -a.display.lineNumInnerWidth+"px")));if(e)for(b=0;bd)return{map:a.measure.maps[b],cache:a.measure.caches[b],before:!0}}}function Ed(a,b){if(b>=a.display.viewFrom&&b=a.lineN&&bp;p++){for(;h&&jd(b.line.text.charAt(g.coverStart+h));)--h;for(;g.coverStart+kT&&0==h&&k==g.coverEnd-g.coverStart)var q=c.parentNode.getBoundingClientRect();else{q=Ob(c,h,k).getClientRects();k=Ve;if("left"==m)for(l=0;lT&&((p=!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI)||(null!=Gd?p=Gd:(m=D(a.display.measure,v("span","x")),p=m.getBoundingClientRect(),m=Ob(m,0,1).getBoundingClientRect(),p=Gd=1T)||h||q&&(q.left||q.right)||(q=(q=c.parentNode.getClientRects()[0])?{left:q.left,right:q.left+sb(a.display),top:q.top,bottom:q.bottom}:Ve);c=q.top-b.rect.top;h=q.bottom-b.rect.top;p=(c+h)/2;m=b.view.measure.heights;for(g=0;gb)f=k-h,e=f-1,b>=k&&(g="right");if(null!=e){c=a[l+2];h==k&&d==(c.insertLeft?"left":"right")&&(g=d);if("left"== -d&&0==e)for(;l&&a[l-2]==a[l-3]&&a[l-1].insertLeft;)c=a[(l-=3)+2],g="left";if("right"==d&&e==k-h)for(;l=c.text.length?(l=c.text.length,b="before"):0>=l&&(l=0,b="after");if(!k)return g("before"==b?l-1:l,"before"==b);var m=Ib(k,l,b),n=Jb;m=h(l,m,"before"==b);null!=n&&(m.other=h(l,n,"before"!=b));return m}function af(a,b){var d=0;b=C(a.doc,b);a.options.lineWrapping||(d=sb(a.display)*b.ch);b=w(a.doc,b.line);a=Fa(b)+a.display.lineSpace.offsetTop;return{left:d,right:d, -top:a,bottom:a+b.height}}function Id(a,b,d,c,e){a=t(a,b,d);a.xRel=e;c&&(a.outside=c);return a}function Jd(a,b,d){var c=a.doc;d+=a.display.viewOffset;if(0>d)return Id(c.first,0,null,-1,-1);var e=$a(c,d),f=c.first+c.size-1;if(e>f)return Id(c.first+c.size-1,w(c,f).text.length,null,1,1);0>b&&(b=0);for(var g=w(c,e);;){f=Og(a,g,e,b,d);var h=void 0;var k=f.ch+(0k)&&(!h||0>vd(h,m.marker))&&(h=m.marker)}if(!h)return f;f=h.find(1);if(f.line==e)return f;g=w(c,e=f.line)}}function bf(a,b,d,c){c-=Hd(b);b=b.text.length;var e=Hb(function(f){return ya(a,d,f-1).bottom<=c},b,0);b=Hb(function(f){return ya(a,d,f).top>c},e,b);return{begin:e,end:b}}function cf(a,b,d,c){d||(d=cb(a,b));c=Gc(a,b,ya(a,d,c),"line").top;return bf(a,b,d,c)}function Kd(a,b,d,c){return a.bottom<=d?!1:a.top>d?!0:(c?a.left:a.right)>b}function Og(a,b,d,c,e){e-=Fa(b);var f=cb(a,b),g=Hd(b),h=0, -k=b.text.length,l=!0,m=Ia(b,a.doc.direction);m&&(m=(a.options.lineWrapping?Pg:Qg)(a,b,d,f,m,c,e),h=(l=1!=m.level)?m.from:m.to-1,k=l?m.to:m.from-1);var n=null,p=null;m=Hb(function(r){var u=ya(a,f,r);u.top+=g;u.bottom+=g;if(!Kd(u,c,e,!1))return!1;u.top<=e&&u.left<=c&&(n=r,p=u);return!0},h,k);var q=!1;p?(h=c-p.left=q.bottom?1:0);m=re(b.text,m,1);return Id(d,m,l,q,c-h)}function Qg(a,b,d,c,e,f,g){var h=Hb(function(m){m=e[m];var n=1!=m.level;return Kd(za(a,t(d,n?m.to:m.from,n?"before":"after"),"line",b,c),f,g,!0)},0,e.length-1),k=e[h];if(0g&&(k=e[h-1])}return k}function Pg(a,b,d,c,e,f,g){g=bf(a,b,c,g);d=g.begin;g=g.end;/\s/.test(b.text.charAt(g-1))&&g--;for(var h=b=null, -k=0;k=g||l.to<=d)){var m=ya(a,c,1!=l.level?Math.min(g,l.to)-1:Math.max(d,l.from)).right;m=mm)b=l,h=m}}b||(b=e[e.length-1]);b.fromg&&(b={from:b.from,to:g,level:b.level});return b}function tb(a){if(null!=a.cachedTextHeight)return a.cachedTextHeight;if(null==db){db=v("pre",null,"CodeMirror-line-like");for(var b=0;49>b;++b)db.appendChild(document.createTextNode("x")),db.appendChild(v("br"));db.appendChild(document.createTextNode("x"))}D(a.measure, -db);b=db.offsetHeight/50;3=a.display.viewTo)return null;b-=a.display.viewFrom;if(0>b)return null;a=a.display.view;for(var d=0;db)return d}function ma(a,b,d,c){null==b&&(b=a.doc.first);null==d&&(d=a.doc.first+a.doc.size);c||(c=0);var e=a.display;c&&db)&&(e.updateLineNumbers=b);a.curOp.viewChanged=!0;if(b>=e.viewTo)Ja&&wd(a.doc,b)e.viewFrom?Pa(a):(e.viewFrom+=c,e.viewTo+=c);else if(b<=e.viewFrom&&d>=e.viewTo)Pa(a);else if(b<=e.viewFrom){var f=Ic(a,d,d+c,1);f?(e.view=e.view.slice(f.index),e.viewFrom=f.lineN,e.viewTo+=c):Pa(a)}else if(d>=e.viewTo)(f=Ic(a,b,b,-1))?(e.view=e.view.slice(0,f.index),e.viewTo=f.lineN):Pa(a);else{f=Ic(a,b,b,-1);var g=Ic(a,d,d+c,1);f&&g?(e.view=e.view.slice(0,f.index).concat(Dc(a,f.lineN,g.lineN)).concat(e.view.slice(g.index)),e.viewTo+=c):Pa(a)}if(a=e.externalMeasured)d< -a.lineN?a.lineN+=c:b=e.lineN&&b=c.viewTo||(a=c.view[bb(a,b)],null!=a.node&&(a=a.changes||(a.changes=[]),-1==ea(a,d)&&a.push(d)))}function Pa(a){a.display.viewFrom=a.display.viewTo=a.doc.first;a.display.view=[];a.display.viewOffset=0}function Ic(a,b,d,c){var e=bb(a,b),f=a.display.view;if(!Ja||d==a.doc.first+ -a.doc.size)return{index:e,lineN:d};for(var g=a.display.viewFrom,h=0;hc?0:f.length-1))return null;d+=c*f[e-(0>c?1:0)].size;e+=c}return{index:e,lineN:d}}function ef(a){a=a.display.view;for(var b=0,d=0;d=a.display.viewTo||k.to().liner&&(r=0);r=Math.round(r);A=Math.round(A);h.appendChild(v("div",null,"CodeMirror-selected","position: absolute; left: "+q+"px;\n top: "+r+"px; width: "+(null==u?m-q:u)+"px;\n height: "+(A-r)+"px"))}function e(q,r,u){function A(F,R){return Hc(a,t(q,F),"div",x,R)}function Y(F,R,H){F=cf(a,x,null,F);R="ltr"==R==("after"== -H)?"left":"right";H="after"==H?F.begin:F.end-(/\s/.test(x.text.charAt(F.end-1))?2:1);return A(H,R)[R]}var x=w(g,q),P=x.text.length,K,Q,S=Ia(x,g.direction);zg(S,r||0,null==u?P:u,function(F,R,H,L){var ha="ltr"==H,na=A(F,ha?"left":"right"),ta=A(R-1,ha?"right":"left"),fb=null==r&&0==F,gb=null==u&&R==P,Od=0==L;L=!S||L==S.length-1;3>=ta.top-na.top?(R=(n?fb:gb)&&Od?l:(ha?na:ta).left,c(R,na.top,((n?gb:fb)&&L?m:(ha?ta:na).right)-R,na.bottom)):(ha?(ha=n&&fb&&Od?l:na.left,fb=n?m:Y(F,H,"before"),F=n?l:Y(R,H, -"after"),gb=n&&gb&&L?m:ta.right):(ha=n?Y(F,H,"before"):l,fb=!n&&fb&&Od?m:na.right,F=!n&&gb&&L?l:ta.left,gb=n?Y(R,H,"after"):m),c(ha,na.top,fb-ha,na.bottom),na.bottomJc(na,K))K=na;0>Jc(ta,K)&&(K=ta);if(!Q||0>Jc(na,Q))Q=na;0>Jc(ta,Q)&&(Q=ta)});return{start:K,end:Q}}var f=a.display,g=a.doc,h=document.createDocumentFragment(),k=Se(a.display),l=k.left,m=Math.max(f.sizerWidth,ab(a)-f.sizer.offsetLeft)-k.right,n="ltr"==g.direction; -f=b.from();b=b.to();if(f.line==b.line)e(f.line,f.ch,b.ch);else{var p=w(g,f.line);k=w(g,b.line);k=Ea(p)==Ea(k);f=e(f.line,f.ch,k?p.text.length+1:null).end;b=e(b.line,k?0:null,b.ch).start;k&&(f.topa.options.cursorBlinkRate&&(b.cursorDiv.style.visibility="hidden")}}function gf(a){a.hasFocus()||(a.display.input.focus(),a.state.focused||Qd(a))}function Rd(a){a.state.delayingBlurEvent=!0;setTimeout(function(){a.state.delayingBlurEvent&&(a.state.delayingBlurEvent=!1,a.state.focused&&ub(a))},100)}function Qd(a,b){a.state.delayingBlurEvent&&!a.state.draggingText&&(a.state.delayingBlurEvent= -!1);"nocursor"!=a.options.readOnly&&(a.state.focused||(W(a,"focus",a,b),a.state.focused=!0,Wa(a.display.wrapper,"CodeMirror-focused"),a.curOp||a.display.selForContextMenu==a.doc.sel||(a.display.input.reset(),fa&&setTimeout(function(){return a.display.input.reset(!0)},20)),a.display.input.receivedFocus()),Pd(a))}function ub(a,b){a.state.delayingBlurEvent||(a.state.focused&&(W(a,"blur",a,b),a.state.focused=!1,hb(a.display.wrapper,"CodeMirror-focused")),clearInterval(a.display.blinker),setTimeout(function(){a.state.focused|| -(a.display.shift=!1)},150))}function Kc(a){for(var b=a.display,d=b.lineDiv.offsetTop,c=Math.max(0,b.scroller.getBoundingClientRect().top),e=b.lineDiv.getBoundingClientRect().top,f=0,g=0;gT){k=h.node.offsetTop+h.node.offsetHeight;var m=k-d;d=k}else{var n=h.node.getBoundingClientRect();m=n.bottom-n.top;!k&&h.text.firstChild&&(l=h.text.firstChild.getBoundingClientRect().right-n.left-1)}k=h.line.height- -m;if(.005k)if(ea.display.sizerWidth&&(l=Math.ceil(l/sb(a.display)),l>a.display.maxLineLength&&(a.display.maxLineLength=l,a.display.maxLine=h.line,a.display.maxLineChanged=!0))}}2=e&&(c=$a(b,Fa(w(b,d))-a.wrapper.clientHeight),e=d)}return{from:c,to:Math.max(e,c+1)}}function Sd(a,b){var d=a.display,c=tb(a.display);0>b.top&&(b.top=0);var e=a.curOp&&null!=a.curOp.scrollTop?a.curOp.scrollTop:d.scroller.scrollTop, -f=Dd(a),g={};b.bottom-b.top>f&&(b.bottom=b.top+f);var h=a.doc.height+Cd(d),k=b.toph-c;b.tope+f&&(f=Math.min(b.top,(c?h:b.bottom)-f),f!=e&&(g.scrollTop=f));e=a.options.fixedGutter?0:d.gutters.offsetWidth;f=a.curOp&&null!=a.curOp.scrollLeft?a.curOp.scrollLeft:d.scroller.scrollLeft-e;a=ab(a)-d.gutters.offsetWidth;if(d=b.right-b.left>a)b.right=b.left+a;10>b.left?g.scrollLeft=0:b.lefta+f-3&&(g.scrollLeft= -b.right+(d?0:10)-a);return g}function Mc(a,b){null!=b&&(Nc(a),a.curOp.scrollTop=(null==a.curOp.scrollTop?a.doc.scrollTop:a.curOp.scrollTop)+b)}function vb(a){Nc(a);var b=a.getCursor();a.curOp.scrollToPos={from:b,to:b,margin:a.options.cursorScrollMargin}}function Ub(a,b,d){null==b&&null==d||Nc(a);null!=b&&(a.curOp.scrollLeft=b);null!=d&&(a.curOp.scrollTop=d)}function Nc(a){var b=a.curOp.scrollToPos;if(b){a.curOp.scrollToPos=null;var d=af(a,b.from),c=af(a,b.to);jf(a,d,c,b.margin)}}function jf(a,b,d, -c){b=Sd(a,{left:Math.min(b.left,d.left),top:Math.min(b.top,d.top)-c,right:Math.max(b.right,d.right),bottom:Math.max(b.bottom,d.bottom)+c});Ub(a,b.scrollLeft,b.scrollTop)}function Vb(a,b){2>Math.abs(a.doc.scrollTop-b)||(La||Td(a,{top:b}),kf(a,b,!0),La&&Td(a),Wb(a,100))}function kf(a,b,d){b=Math.max(0,Math.min(a.display.scroller.scrollHeight-a.display.scroller.clientHeight,b));if(a.display.scroller.scrollTop!=b||d)a.doc.scrollTop=b,a.display.scrollbars.setScrollTop(b),a.display.scroller.scrollTop!= -b&&(a.display.scroller.scrollTop=b)}function ib(a,b,d,c){b=Math.max(0,Math.min(b,a.display.scroller.scrollWidth-a.display.scroller.clientWidth));(d?b==a.doc.scrollLeft:2>Math.abs(a.doc.scrollLeft-b))&&!c||(a.doc.scrollLeft=b,lf(a),a.display.scroller.scrollLeft!=b&&(a.display.scroller.scrollLeft=b),a.display.scrollbars.setScrollLeft(b))}function Xb(a){var b=a.display,d=b.gutters.offsetWidth,c=Math.round(a.doc.height+Cd(a.display));return{clientHeight:b.scroller.clientHeight,viewHeight:b.wrapper.clientHeight, -scrollWidth:b.scroller.scrollWidth,clientWidth:b.scroller.clientWidth,viewWidth:b.wrapper.clientWidth,barLeft:a.options.fixedGutter?d:0,docHeight:c,scrollHeight:c+Ga(a)+b.barHeight,nativeBarWidth:b.nativeBarWidth,gutterWidth:d}}function wb(a,b){b||(b=Xb(a));var d=a.display.barWidth,c=a.display.barHeight;mf(a,b);for(b=0;4>b&&d!=a.display.barWidth||c!=a.display.barHeight;b++)d!=a.display.barWidth&&a.options.lineWrapping&&Kc(a),mf(a,Xb(a)),d=a.display.barWidth,c=a.display.barHeight}function mf(a,b){var d= -a.display,c=d.scrollbars.update(b);d.sizer.style.paddingRight=(d.barWidth=c.right)+"px";d.sizer.style.paddingBottom=(d.barHeight=c.bottom)+"px";d.heightForcer.style.borderBottom=c.bottom+"px solid transparent";c.right&&c.bottom?(d.scrollbarFiller.style.display="block",d.scrollbarFiller.style.height=c.bottom+"px",d.scrollbarFiller.style.width=c.right+"px"):d.scrollbarFiller.style.display="";c.bottom&&a.options.coverGutterNextToScrollbar&&a.options.fixedGutter?(d.gutterFiller.style.display="block", -d.gutterFiller.style.height=c.bottom+"px",d.gutterFiller.style.width=b.gutterWidth+"px"):d.gutterFiller.style.display=""}function nf(a){a.display.scrollbars&&(a.display.scrollbars.clear(),a.display.scrollbars.addClass&&hb(a.display.wrapper,a.display.scrollbars.addClass));a.display.scrollbars=new of[a.options.scrollbarStyle](function(b){a.display.wrapper.insertBefore(b,a.display.scrollbarFiller);z(b,"mousedown",function(){a.state.focused&&setTimeout(function(){return a.display.input.focus()},0)}); -b.setAttribute("cm-not-content","true")},function(b,d){"horizontal"==d?ib(a,b):Vb(a,b)},a);a.display.scrollbars.addClass&&Wa(a.display.wrapper,a.display.scrollbars.addClass)}function jb(a){a.curOp={cm:a,viewChanged:!1,startHeight:a.doc.height,forceUpdate:!1,updateInput:0,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++Sg,markArrays:null};a=a.curOp;rb?rb.ops.push(a):a.ownsGroup= -rb={ops:[a],delayedCallbacks:[]}}function kb(a){(a=a.curOp)&&Lg(a,function(b){for(var d=0;d=f.viewTo)||f.maxLineChanged&&e.options.lineWrapping;c.update=c.mustUpdate&&new Oc(e,c.mustUpdate&&{top:c.scrollTop,ensure:c.scrollToPos},c.forceUpdate)}for(d=0;dn;n++){var p=!1;h=za(e, -k);var q=l&&l!=k?za(e,l):h;h={left:Math.min(h.left,q.left),top:Math.min(h.top,q.top)-m,right:Math.max(h.left,q.left),bottom:Math.max(h.bottom,q.bottom)+m};q=Sd(e,h);var r=e.doc.scrollTop,u=e.doc.scrollLeft;null!=q.scrollTop&&(Vb(e,q.scrollTop),1l.top+n.top?k=!0:l.bottom+n.top>(window.innerHeight|| -document.documentElement.clientHeight)&&(k=!1),null==k||Tg||(l=v("div","\u200b",null,"position: absolute;\n top: "+(l.top-m.viewOffset-e.display.lineSpace.offsetTop)+"px;\n height: "+(l.bottom-l.top+Ga(e)+m.barHeight)+"px;\n left: "+l.left+"px; width: "+Math.max(2,l.right-l.left)+"px;"),e.display.lineSpace.appendChild(l),l.scrollIntoView(k),e.display.lineSpace.removeChild(l)))}l=c.maybeHiddenMarkers;k=c.maybeUnhiddenMarkers;if(l)for(m= -0;m=a.display.viewTo)){var d=+new Date+a.options.workTime,c=Mb(a,b.highlightFrontier),e=[];b.iter(c.line,Math.min(b.first+b.size,a.display.viewTo+ -500),function(f){if(c.line>=a.display.viewFrom){var g=f.styles,h=f.text.length>a.options.maxHighlightLength?Ya(b.mode,c.state):null,k=xe(a,f,c,!0);h&&(c.state=h);f.styles=k.styles;h=f.styleClasses;(k=k.classes)?f.styleClasses=k:h&&(f.styleClasses=null);k=!g||g.length!=f.styles.length||h!=k&&(!h||!k||h.bgClass!=k.bgClass||h.textClass!=k.textClass);for(h=0;!k&&hd)return Wb(a,a.options.workDelay),!0});b.highlightFrontier=c.line;b.modeFrontier=Math.max(b.modeFrontier,c.line);e.length&&qa(a,function(){for(var f=0;f=d.viewFrom&&b.visible.to<=d.viewTo&&(null==d.updateLineNumbers||d.updateLineNumbers>=d.viewTo)&&d.renderedView==d.view&&0==ef(a))return!1;qf(a)&& -(Pa(a),b.dims=Fd(a));var e=c.first+c.size,f=Math.max(b.visible.from-a.options.viewportMargin,c.first),g=Math.min(e,b.visible.to+a.options.viewportMargin);d.viewFromf-d.viewFrom&&(f=Math.max(c.first,d.viewFrom));d.viewTo>g&&20>d.viewTo-g&&(g=Math.min(e,d.viewTo));Ja&&(f=wd(a.doc,f),g=Ie(a.doc,g));c=f!=d.viewFrom||g!=d.viewTo||d.lastWrapHeight!=b.wrapperHeight||d.lastWrapWidth!=b.wrapperWidth;e=a.display;0==e.view.length||f>=e.viewTo||g<=e.viewFrom?(e.view=Dc(a,f,g),e.viewFrom=f):(e.viewFrom> -f?e.view=Dc(a,f,e.viewFrom).concat(e.view):e.viewFromg&&(e.view=e.view.slice(0,bb(a,g))));e.viewTo=g;d.viewOffset=Fa(w(a.doc,d.viewFrom));a.display.mover.style.top=d.viewOffset+"px";g=ef(a);if(!c&&0==g&&!b.force&&d.renderedView==d.view&&(null==d.updateLineNumbers||d.updateLineNumbers>=d.viewTo))return!1;a.hasFocus()?f=null:(f=ka())&&ja(a.display.lineDiv,f)?(f={activeElt:f},window.getSelection&& -(e=window.getSelection(),e.anchorNode&&e.extend&&ja(a.display.lineDiv,e.anchorNode)&&(f.anchorNode=e.anchorNode,f.anchorOffset=e.anchorOffset,f.focusNode=e.focusNode,f.focusOffset=e.focusOffset))):f=null;4=a.display.viewFrom&&b.visible.to<=a.display.viewTo)break;if(!Ud(a,b))break;Kc(a);c=Xb(a);Tb(a);wb(a,c);Vd(a,c);b.force=!1}b.signal(a,"update",a);if(a.display.viewFrom!=a.display.reportedViewFrom||a.display.viewTo!=a.display.reportedViewTo)b.signal(a,"viewportChange",a,a.display.viewFrom,a.display.viewTo),a.display.reportedViewFrom=a.display.viewFrom, -a.display.reportedViewTo=a.display.viewTo}function Td(a,b){b=new Oc(a,b);if(Ud(a,b)){Kc(a);pf(a,b);var d=Xb(a);Tb(a);wb(a,d);Vd(a,d);b.finish()}}function Vg(a,b,d){function c(p){var q=p.nextSibling;fa&&xa&&a.display.currentWheelTarget==p?p.style.display="none":p.parentNode.removeChild(p);return q}var e=a.display,f=a.options.lineNumbers,g=e.lineDiv,h=g.firstChild,k=e.view;e=e.viewFrom;for(var l=0;lT&&(this.gutters.style.zIndex=-1,this.scroller.style.paddingRight= -0);fa||La&&Zb||(this.scroller.draggable=!0);a&&(a.appendChild?a.appendChild(this.wrapper):a(this.wrapper));this.reportedViewFrom=this.reportedViewTo=this.viewFrom=this.viewTo=b.first;this.view=[];this.externalMeasured=this.renderedView=null;this.lastWrapHeight=this.lastWrapWidth=this.viewOffset=0;this.updateLineNumbers=null;this.nativeBarWidth=this.barHeight=this.barWidth=0;this.scrollbarsClipped=!1;this.lineNumWidth=this.lineNumInnerWidth=this.lineNumChars=null;this.alignWidgets=!1;this.maxLine= -this.cachedCharWidth=this.cachedTextHeight=this.cachedPaddingH=null;this.maxLineLength=0;this.maxLineChanged=!1;this.wheelDX=this.wheelDY=this.wheelStartX=this.wheelStartY=null;this.shift=!1;this.activeTouch=this.selForContextMenu=null;this.gutterSpecs=Xd(c.gutters,c.lineNumbers);rf(this);d.init(this)}function sf(a){var b=a.wheelDeltaX,d=a.wheelDeltaY;null==b&&a.detail&&a.axis==a.HORIZONTAL_AXIS&&(b=a.detail);null==d&&a.detail&&a.axis==a.VERTICAL_AXIS?d=a.detail:null==d&&(d=a.wheelDelta);return{x:b, -y:d}}function Xg(a){a=sf(a);a.x*=Ma;a.y*=Ma;return a}function tf(a,b){var d=sf(b),c=d.x;d=d.y;var e=Ma;0===b.deltaMode&&(c=b.deltaX,d=b.deltaY,e=1);var f=a.display,g=f.scroller,h=g.scrollWidth>g.clientWidth,k=g.scrollHeight>g.clientHeight;if(c&&h||d&&k){if(d&&xa&&fa){h=b.target;var l=f.view;a:for(;h!=g;h=h.parentNode)for(var m=0;me?k=Math.max(0, -k+e-50):h=Math.min(a.doc.height,h+e+50),Td(a,{top:k,bottom:h})),20>Pc&&0!==b.deltaMode&&(null==f.wheelStartX?(f.wheelStartX=g.scrollLeft,f.wheelStartY=g.scrollTop,f.wheelDX=c,f.wheelDY=d,setTimeout(function(){if(null!=f.wheelStartX){var n=g.scrollLeft-f.wheelStartX,p=g.scrollTop-f.wheelStartY;n=p&&f.wheelDY&&p/f.wheelDY||n&&f.wheelDX&&n/f.wheelDX;f.wheelStartX=f.wheelStartY=null;n&&(Ma=(Ma*Pc+n)/(Pc+1),++Pc)}},200)):(f.wheelDX+=c,f.wheelDY+=d))):(d&&k&&Vb(a,Math.max(0,g.scrollTop+d*e)),ib(a,Math.max(0, -g.scrollLeft+c*e)),(!d||d&&k)&&la(b),f.wheelStartX=null)}}function Ba(a,b,d){a=a&&a.options.selectionsMayTouch;d=b[d];b.sort(function(k,l){return B(k.from(),l.from())});d=ea(b,d);for(var c=1;cB(a,b.from))return a;if(0>=B(a,b.to))return Ra(b);var d=a.line+b.text.length-(b.to.line-b.from.line)-1,c=a.ch;a.line==b.to.line&&(c+=Ra(b).ch-b.to.ch);return t(d,c)}function Yd(a,b){for(var d=[],c=0;cf-(a.cm?a.cm.options.historyEventDelay:500)||"*"==b.origin.charAt(0))){if(e.lastOp==c){Af(e.done);var h=J(e.done)}else e.done.length&&!J(e.done).ranges?h=J(e.done):1e.undoDepth;)e.done.shift(), -e.done[0].ranges||e.done.shift();e.done.push(d);e.generation=++e.maxGeneration;e.lastModTime=e.lastSelTime=f;e.lastOp=e.lastSelOp=c;e.lastOrigin=e.lastSelOrigin=b.origin;k||W(a,"historyAdded")}function Rc(a,b){var d=J(b);d&&d.ranges&&d.equals(a)||b.push(a)}function zf(a,b,d,c){var e=b["spans_"+a.id],f=0;a.iter(Math.max(a.first,d),Math.min(a.first+a.size,c),function(g){g.markedSpans&&((e||(e=b["spans_"+a.id]={}))[f]=g.markedSpans);++f})}function Cf(a,b){var d;if(d=b["spans_"+a.id]){for(var c=[],e= -0;eB(b,a),c!=0>B(d,a)?(a=b,b=d):c!=0>B(b,d)&&(b=d)),new I(a,b)):new I(d||b,b)}function Sc(a,b,d,c,e){null==e&&(e=a.cm&&(a.cm.display.shift||a.extend));da(a,new ua([be(a.sel.primary(), -b,d,e)],0),c)}function Df(a,b,d){for(var c=[],e=a.cm&&(a.cm.display.shift||a.extend),f=0;fB(b.primary().head,a.sel.primary().head)?-1:1);Ff(a,Gf(a,b,c,!0));d&&!1===d.scroll||!a.cm||"nocursor"==a.cm.getOption("readOnly")||vb(a.cm)}function Ff(a,b){b.equals(a.sel)|| -(a.sel=b,a.cm&&(a.cm.curOp.updateInput=1,a.cm.curOp.selectionChanged=!0,se(a.cm)),aa(a,"cursorActivity",a))}function Hf(a){Ff(a,Gf(a,a.sel,null,!1))}function Gf(a,b,d,c){for(var e,f=0;f=b.ch:h.to>b.ch))){if(e&&(W(k,"beforeCursorEnter"),k.explicitlyCleared))if(f.markedSpans){--g;continue}else break;if(k.atomic){if(d){g=k.find(0>c?1:-1);h=void 0;if(0>c?m:l)g=If(a,g,-c,g&&g.line==b.line?f:null);if(g&&g.line==b.line&&(h=B(g,d))&&(0>c?0>h:0c?-1:1);if(0>c?l:m)d=If(a,d,c,d.line==b.line?f:null);return d?zb(a,d,b,c,e):null}}}return b}function Uc(a,b,d,c,e){c=c||1;b=zb(a,b,d,c,e)||!e&&zb(a,b,d,c,!0)||zb(a,b,d,-c,e)||!e&&zb(a,b,d,-c,!0);return b?b:(a.cantEdit=!0,t(a.first,0))}function If(a,b,d,c){return 0>d&&0==b.ch?b.line>a.first?C(a,t(b.line-1)):null:0a.lastLine())){if(b.from.linee&&(b={from:b.from,to:t(e, -w(a,e).text.length),text:[b.text[0]],origin:b.origin});b.removed=Za(a,b.from,b.to);d||(d=Yd(a,b));a.cm?$g(a.cm,b,c):$d(a,b,c);Tc(a,d,Ha);a.cantEdit&&Uc(a,t(a.firstLine(),0))&&(a.cantEdit=!1)}}function $g(a,b,d){var c=a.doc,e=a.display,f=b.from,g=b.to,h=!1,k=f.line;a.options.lineWrapping||(k=N(Ea(w(c,f.line))),c.iter(k,g.line+1,function(l){if(l==e.maxLine)return h=!0}));-1e.maxLineLength&&(e.maxLine=l,e.maxLineLength=m,e.maxLineChanged=!0,h=!1)}),h&&(a.curOp.updateMaxLine=!0));Eg(c,f.line);Wb(a,400);d=b.text.length-(g.line-f.line)-1;b.full?ma(a):f.line!=g.line||1!=b.text.length||wf(a.doc,b)?ma(a,f.line,g.line+1,d):Qa(a,f.line,"text");d=wa(a,"changes");if((c=wa(a,"change"))||d)b={from:f,to:g,text:b.text,removed:b.removed,origin:b.origin},c&&aa(a,"change",a,b),d&&(a.curOp.changeObjs||(a.curOp.changeObjs=[])).push(b);a.display.selForContextMenu=null}function Bb(a,b, -d,c,e){c||(c=d);0>B(c,d)&&(c=[c,d],d=c[0],c=c[1]);"string"==typeof b&&(b=a.splitLines(b));Ab(a,{from:d,to:c,text:b,origin:e})}function Pf(a,b,d,c){d=B(f.from,J(c).to);){var g=c.pop();if(0>B(g.from,f.from)){f.from=g.from;break}}c.push(f)}qa(a,function(){for(var h=c.length-1;0<=h;h--)Bb(a.doc,"",c[h].from,c[h].to,"+delete");vb(a)})}function de(a,b,d){b=re(a.text,b+d,d);return 0>b||b>a.text.length?null:b}function ee(a,b,d){a= -de(a,b.ch,d);return null==a?null:new t(b.line,a,0>d?"after":"before")}function fe(a,b,d,c,e){if(a&&("rtl"==b.doc.direction&&(e=-e),a=Ia(d,b.doc.direction))){a=0>e?J(a):a[0];var f=0>e==(1==a.level)?"after":"before";if(0e?d.text.length-1:0;var k=ya(b,g,h).top;h=Hb(function(l){return ya(b,g,l).top==k},0>e==(1==a.level)?a.from:a.to-1,h);"before"==f&&(h=de(d,h,1))}else h=0>e?a.to:a.from;return new t(c,h,f)}return new t(c,0>e?d.text.length:0,0>e?"before": -"after")}function ih(a,b,d,c){var e=Ia(b,a.doc.direction);if(!e)return ee(b,d,c);d.ch>=b.text.length?(d.ch=b.text.length,d.sticky="before"):0>=d.ch&&(d.ch=0,d.sticky="after");var f=Ib(e,d.ch,d.sticky),g=e[f];if("ltr"==a.doc.direction&&0==g.level%2&&(0d.ch:g.fromc,p=h(d,n?1:-1);if(null!=p&&(n?p<=g.to&&p<=m.end:p>=g.from&&p>=m.begin))return new t(d.line,p,n?"before":"after")}g=function(q,r,u){for(var A=function(K,Q){return Q?new t(d.line,h(K,1),"before"):new t(d.line,K,"after")};0<=q&&qT&&27==a.keyCode&&(a.returnValue=!1);var b=a.keyCode;this.display.shift=16==b||a.shiftKey;var d=cg(this,a);Aa&&(ge=d?b:null,!d&&88==b&&!lh&&(xa?a.metaKey:a.ctrlKey)&&this.replaceSelection("",null,"cut"));La&&!xa&&!d&&46==b&&a.shiftKey&&!a.ctrlKey&&document.execCommand&&document.execCommand("cut");18!=b||/\bCodeMirror-crosshair\b/.test(this.display.lineDiv.className)||mh(this)}}function mh(a){function b(c){18!=c.keyCode&& -c.altKey||(hb(d,"CodeMirror-crosshair"),sa(document,"keyup",b),sa(document,"mouseover",b))}var d=a.display.lineDiv;Wa(d,"CodeMirror-crosshair");z(document,"keyup",b);z(document,"mouseover",b)}function eg(a){16==a.keyCode&&(this.doc.sel.shift=!1);Z(this,a)}function fg(a){if(!(a.target&&a.target!=this.display.input.getField()||Ka(this.display,a)||Z(this,a)||a.ctrlKey&&!a.altKey||xa&&a.metaKey)){var b=a.keyCode,d=a.charCode;if(Aa&&b==ge)ge=null,la(a);else if(!Aa||a.which&&!(10>a.which)||!cg(this,a))if(b= -String.fromCharCode(null==d?b:d),"\b"!=b&&!kh(this,a,b))this.display.input.onKeyPress(a)}}function nh(a,b){var d=+new Date;if(jc&&jc.compare(d,a,b))return kc=jc=null,"triple";if(kc&&kc.compare(d,a,b))return jc=new he(d,a,b),kc=null,"double";kc=new he(d,a,b);jc=null;return"single"}function gg(a){var b=this.display;if(!(Z(this,a)||b.activeTouch&&b.input.supportsTouch()))if(b.input.ensurePolled(),b.shift=a.shiftKey,Ka(b,a))fa||(b.scroller.draggable=!1,setTimeout(function(){return b.scroller.draggable= -!0},100));else if(!Zc(this,a,"gutterClick",!0)){var d=eb(this,a),c=ue(a),e=d?nh(d,c):"single";window.focus();1==c&&this.state.selectingText&&this.state.selectingText(a);if(!d||!oh(this,c,d,e,a))if(1==c)d?ph(this,d,e,a):(a.target||a.srcElement)==b.scroller&&la(a);else if(2==c)d&&Sc(this.doc,d),setTimeout(function(){return b.input.focus()},20);else if(3==c)if(ie)this.display.input.onContextMenu(a);else Rd(this)}}function oh(a,b,d,c,e){var f="Click";"double"==c?f="Double"+f:"triple"==c&&(f="Triple"+ -f);return ic(a,Xf((1==b?"Left":2==b?"Middle":"Right")+f,e),e,function(g){"string"==typeof g&&(g=hc[g]);if(!g)return!1;var h=!1;try{a.isReadOnly()&&(a.state.suppressEdits=!0),h=g(a,d)!=Yc}finally{a.state.suppressEdits=!1}return h})}function ph(a,b,d,c){G?setTimeout(fd(gf,a),0):a.curOp.focus=ka();var e=a.getOption("configureMouse");e=e?e(a,d,c):{};null==e.unit&&(e.unit=(qh?c.shiftKey&&c.metaKey:c.altKey)?"rectangle":"single"==d?"char":"double"==d?"word":"line");if(null==e.extend||a.doc.extend)e.extend= -a.doc.extend||c.shiftKey;null==e.addNew&&(e.addNew=xa?c.metaKey:c.ctrlKey);null==e.moveOnDrag&&(e.moveOnDrag=!(xa?c.altKey:c.ctrlKey));var f=a.doc.sel,g;a.options.dragDrop&&rh&&!a.isReadOnly()&&"single"==d&&-1<(g=f.contains(b))&&(0>B((g=f.ranges[g]).from(),b)||0b.xRel)?sh(a,c,b,e):th(a,c,b,e)}function sh(a,b,d,c){var e=a.display,f=!1,g=ba(a,function(l){fa&&(e.scroller.draggable=!1);a.state.draggingText=!1;a.state.delayingBlurEvent&&(a.hasFocus()?a.state.delayingBlurEvent= -!1:Rd(a));sa(e.wrapper.ownerDocument,"mouseup",g);sa(e.wrapper.ownerDocument,"mousemove",h);sa(e.scroller,"dragstart",k);sa(e.scroller,"drop",g);f||(la(l),c.addNew||Sc(a.doc,d,null,null,c.extend),fa&&!$c||G&&9==T?setTimeout(function(){e.wrapper.ownerDocument.body.focus({preventScroll:!0});e.input.focus()},20):e.input.focus())}),h=function(l){f=f||10<=Math.abs(b.clientX-l.clientX)+Math.abs(b.clientY-l.clientY)},k=function(){return f=!0};fa&&(e.scroller.draggable=!0);a.state.draggingText=g;g.copy=!c.moveOnDrag; -z(e.wrapper.ownerDocument,"mouseup",g);z(e.wrapper.ownerDocument,"mousemove",h);z(e.scroller,"dragstart",k);z(e.scroller,"drop",g);a.state.delayingBlurEvent=!0;setTimeout(function(){return e.input.focus()},20);e.scroller.dragDrop&&e.scroller.dragDrop()}function hg(a,b,d){if("char"==d)return new I(b,b);if("word"==d)return a.findWordAt(b);if("line"==d)return new I(t(b.line,0),C(a.doc,t(b.line+1,0)));a=d(a,b);return new I(a.from,a.to)}function th(a,b,d,c){function e(x){if(0!=B(q,x))if(q=x,"rectangle"== -c.unit){var P=[],K=a.options.tabSize,Q=va(w(k,d.line).text,d.ch,K),S=va(w(k,x.line).text,x.ch,K),F=Math.min(Q,S);Q=Math.max(Q,S);S=Math.min(d.line,x.line);for(var R=Math.min(a.lastLine(),Math.max(d.line,x.line));S<=R;S++){var H=w(k,S).text,L=gd(H,F,K);F==Q?P.push(new I(t(S,L),t(S,L))):H.length>L&&P.push(new I(t(S,L),t(S,gd(H,Q,K))))}P.length||P.push(new I(d,d));da(k,Ba(a,l.ranges.slice(0,n).concat(P),n),{origin:"*mouse",scroll:!1});a.scrollIntoView(x)}else P=p,F=hg(a,x,c.unit),x=P.anchor,0=Q.to||K.liner.bottom?20:0;S&&setTimeout(ba(a,function(){u==P&&(h.scroller.scrollTop+=S,f(x))}),50)}}function g(x){a.state.selectingText=!1;u=Infinity; -x&&(la(x),h.input.focus());sa(h.wrapper.ownerDocument,"mousemove",A);sa(h.wrapper.ownerDocument,"mouseup",Y);k.history.lastSelOrigin=null}G&&Rd(a);var h=a.display,k=a.doc;la(b);var l=k.sel,m=l.ranges;if(c.addNew&&!c.extend){var n=k.sel.contains(d);var p=-1f:0=Math.floor(a.display.gutters.getBoundingClientRect().right))return!1;c&&la(b);c=a.display;var g=c.lineDiv.getBoundingClientRect();if(f>g.bottom||!wa(a,d))return kd(b);f-=g.top-c.viewOffset;for(g=0;g=e)return e=$a(a.doc,f),W(a,d,a,e,a.display.gutterSpecs[g].className,b),kd(b)}}function ig(a,b){var d; -(d=Ka(a.display,b))||(d=wa(a,"gutterContextMenu")?Zc(a,b,"gutterContextMenu",!1):!1);if(!d&&!Z(a,b,"contextmenu")&&!ie)a.display.input.onContextMenu(b)}function jg(a){a.display.wrapper.className=a.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+a.options.theme.replace(/(^|\s)\s*/g," cm-s-");Sb(a)}function vh(a,b,d){!b!=!(d&&d!=Fb)&&(d=a.display.dragFunctions,b=b?z:sa,b(a.display.scroller,"dragstart",d.start),b(a.display.scroller,"dragenter",d.enter),b(a.display.scroller,"dragover",d.over),b(a.display.scroller, -"dragleave",d.leave),b(a.display.scroller,"drop",d.drop))}function wh(a){a.options.lineWrapping?(Wa(a.display.wrapper,"CodeMirror-wrap"),a.display.sizer.style.minWidth="",a.display.sizerWidth=null):(hb(a.display.wrapper,"CodeMirror-wrap"),yd(a));Md(a);ma(a);Sb(a);setTimeout(function(){return wb(a)},100)}function U(a,b){var d=this;if(!(this instanceof U))return new U(a,b);this.options=b=b?Xa(b):{};Xa(kg,b,!1);var c=b.value;"string"==typeof c?c=new oa(c,b.mode,null,b.lineSeparator,b.direction):b.mode&& -(c.modeOption=b.mode);this.doc=c;var e=new U.inputStyles[b.inputStyle](this);a=this.display=new Wg(a,c,e,b);a.wrapper.CodeMirror=this;jg(this);b.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap");nf(this);this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:-1,cutIncoming:-1,selectingText:!1,draggingText:!1,highlight:new Va,keySeq:null,specialChars:null};b.autofocus&&!Zb&&a.input.focus();G&&11>T&&setTimeout(function(){return d.display.input.reset(!0)}, -20);xh(this);lg||(eh(),lg=!0);jb(this);this.curOp.forceUpdate=!0;xf(this,c);b.autofocus&&!Zb||this.hasFocus()?setTimeout(function(){d.hasFocus()&&!d.state.focused&&Qd(d)},20):ub(this);for(var f in ad)if(ad.hasOwnProperty(f))ad[f](this,b[f],Fb);qf(this);b.finishInit&&b.finishInit(this);for(c=0;cT?z(c.scroller,"dblclick",ba(a,function(h){if(!Z(a,h)){var k=eb(a,h);!k||Zc(a,h,"gutterClick",!0)||Ka(a.display,h)||(la(h),h=a.findWordAt(k),Sc(a.doc,h.anchor,h.head))}})):z(c.scroller,"dblclick",function(h){return Z(a,h)||la(h)});z(c.scroller,"contextmenu",function(h){return ig(a, -h)});z(c.input.getField(),"contextmenu",function(h){c.scroller.contains(h.target)||ig(a,h)});var e,f={end:0};z(c.scroller,"touchstart",function(h){var k;if(k=!Z(a,h))1!=h.touches.length?k=!1:(k=h.touches[0],k=1>=k.radiusX&&1>=k.radiusY),k=!k;k&&!Zc(a,h,"gutterClick",!0)&&(c.input.ensurePolled(),clearTimeout(e),k=+new Date,c.activeTouch={start:k,moved:!1,prev:300>=k-f.end?f:null},1==h.touches.length&&(c.activeTouch.left=h.touches[0].pageX,c.activeTouch.top=h.touches[0].pageY))});z(c.scroller,"touchmove", -function(){c.activeTouch&&(c.activeTouch.moved=!0)});z(c.scroller,"touchend",function(h){var k=c.activeTouch;if(k&&!Ka(c,h)&&null!=k.left&&!k.moved&&300>new Date-k.start){var l=a.coordsChar(c.activeTouch,"page");k=!k.prev||d(k,k.prev)?new I(l,l):!k.prev.prev||d(k,k.prev.prev)?a.findWordAt(l):new I(t(l.line,0),C(a.doc,t(l.line+1,0)));a.setSelection(k.anchor,k.head);a.focus();la(h)}b()});z(c.scroller,"touchcancel",b);z(c.scroller,"scroll",function(){c.scroller.clientHeight&&(Vb(a,c.scroller.scrollTop), -ib(a,c.scroller.scrollLeft,!0),W(a,"scroll",a))});z(c.scroller,"mousewheel",function(h){return tf(a,h)});z(c.scroller,"DOMMouseScroll",function(h){return tf(a,h)});z(c.wrapper,"scroll",function(){return c.wrapper.scrollTop=c.wrapper.scrollLeft=0});c.dragFunctions={enter:function(h){Z(a,h)||Kb(h)},over:function(h){if(!Z(a,h)){var k=eb(a,h);if(k){var l=document.createDocumentFragment();Nd(a,k,l);a.display.dragCursor||(a.display.dragCursor=v("div",null,"CodeMirror-cursors CodeMirror-dragcursors"),a.display.lineSpace.insertBefore(a.display.dragCursor, -a.display.cursorDiv));D(a.display.dragCursor,l)}Kb(h)}},start:function(h){if(G&&(!a.state.draggingText||100>+new Date-Uf))Kb(h);else if(!Z(a,h)&&!Ka(a.display,h)&&(h.dataTransfer.setData("Text",a.getSelection()),h.dataTransfer.effectAllowed="copyMove",h.dataTransfer.setDragImage&&!$c)){var k=v("img",null,null,"position: fixed; left: 0; top: 0;");k.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";Aa&&(k.width=k.height=1,a.display.wrapper.appendChild(k),k._top=k.offsetTop); -h.dataTransfer.setDragImage(k,0,0);Aa&&k.parentNode.removeChild(k)}},drop:ba(a,dh),leave:function(h){Z(a,h)||Tf(a)}};var g=c.input.getField();z(g,"keyup",function(h){return eg.call(a,h)});z(g,"keydown",ba(a,dg));z(g,"keypress",ba(a,fg));z(g,"focus",function(h){return Qd(a,h)});z(g,"blur",function(h){return ub(a,h)})}function lc(a,b,d,c){var e=a.doc,f;null==d&&(d="add");"smart"==d&&(e.mode.indent?f=Mb(a,b).state:d="prev");var g=a.options.tabSize,h=w(e,b),k=va(h.text,null,g);h.stateAfter&&(h.stateAfter= -null);var l=h.text.match(/^\s*/)[0];if(!c&&!/\S/.test(h.text)){var m=0;d="not"}else if("smart"==d&&(m=e.mode.indent(f,h.text.slice(l.length),h.text),m==Yc||150e.first?va(w(e,b-1).text,null,g):0:"add"==d?m=k+a.options.indentUnit:"subtract"==d?m=k-a.options.indentUnit:"number"==typeof d&&(m=k+d);m=Math.max(0,m);d="";c=0;if(a.options.indentWithTabs)for(a=Math.floor(m/g);a;--a)c+=g,d+="\t";cg,k=me(b),l=null;if(h&&1g?"cut":"+input")};Ab(a.doc,p);aa(a,"inputRead",a,p)}b&&!h&&mg(a,b);vb(a);2>a.curOp.updateInput&& -(a.curOp.updateInput=m);a.curOp.typing=!0;a.state.pasteIncoming=a.state.cutIncoming=-1}function ng(a,b){var d=a.clipboardData&&a.clipboardData.getData("Text");if(d)return a.preventDefault(),b.isReadOnly()||b.options.disableInput||qa(b,function(){return le(b,d,0,null,"paste")}),!0}function mg(a,b){if(a.options.electricChars&&a.options.smartIndent)for(var d=a.doc.sel,c=d.ranges.length-1;0<=c;c--){var e=d.ranges[c];if(!(100A:56320<=A&&57343>A)?2:1))),-d)}else A=e?ih(a.cm,k,b,d):ee(k,b,d);if(null==A){if(u=!u)u=b.line+l,u=a.first+a.size?u=!1:(b=new t(u,b.ch,b.sticky),u=k=w(a,u));if(u)b=fe(e,a.cm,k,b.line,l);else return!1}else b=A;return!0}var g=b,h=d,k=w(a,b.line),l=e&&"rtl"==a.direction?-d:d;if("char"==c||"codepoint"==c)f();else if("column"== -c)f(!0);else if("word"==c||"group"==c)for(var m=null,n="group"==c,p=a.cm&&a.cm.getHelper(b,"wordChars"),q=!0;!(0>d)||f(!q);q=!1){var r=k.text.charAt(b.ch)||"\n";r=vc(r,p)?"w":n&&"\n"==r?"n":!n||/\s/.test(r)?null:"p";!n||q||r||(r="s");if(m&&m!=r){0>d&&(d=1,f(),b.sticky="after");break}r&&(m=r);if(0d?0>=g:g>=e.height){b.hitSide=!0;break}g+=5*d}return b}function sg(a,b){var d=Ed(a,b.line);if(!d||d.hidden)return null;var c=w(a.doc,b.line);d=Te(d,c,b.line);a=Ia(c,a.doc.direction);c="left";a&&(c=Ib(a,b.ch)%2?"right":"left");b=Ue(d.map,b.ch,c);b.offset="right"==b.collapse?b.end:b.start;return b}function yh(a){for(;a;a=a.parentNode)if(/CodeMirror-gutter-wrapper/.test(a.className))return!0; -return!1}function Gb(a,b){b&&(a.bad=!0);return a}function zh(a,b,d,c,e){function f(q){return function(r){return r.id==q}}function g(){m&&(l+=n,p&&(l+=n),m=p=!1)}function h(q){q&&(g(),l+=q)}function k(q){if(1==q.nodeType){var r=q.getAttribute("cm-text");if(r)h(r);else{r=q.getAttribute("cm-marker");var u;if(r)q=a.findMarks(t(c,0),t(e+1,0),f(+r)),q.length&&(u=q[0].find(0))&&h(Za(a.doc,u.from,u.to).join(n));else if("false"!=q.getAttribute("contenteditable")&&(u=/^(pre|div|p|li|table|br)$/i.test(q.nodeName), -/^br$/i.test(q.nodeName)||0!=q.textContent.length)){u&&g();for(r=0;rq?k.map:l[q],u=0;uq?a.line:a.rest[q]);q=r[u]+p;if(0>p||A!=m)q=r[u+(p?1:0)];return t(n,q)}}}var e=a.text.firstChild,f=!1;if(!b||!ja(e,b))return Gb(t(N(a.line),0),!0); -if(b==e&&(f=!0,b=e.childNodes[d],d=0,!b))return d=a.rest?J(a.rest):a.line,Gb(t(N(d),d.text.length),f);var g=3==b.nodeType?b:null,h=b;g||1!=b.childNodes.length||3!=b.firstChild.nodeType||(g=b.firstChild,d&&(d=g.nodeValue.length));for(;h.parentNode!=e;)h=h.parentNode;var k=a.measure,l=k.maps;if(b=c(g,h,d))return Gb(b,f);e=h.nextSibling;for(g=g?g.nodeValue.length-d:0;e;e=e.nextSibling){if(b=c(e,e.firstChild,0))return Gb(t(b.line,b.ch-g),f);g+=e.textContent.length}for(h=h.previousSibling;h;h=h.previousSibling){if(b= -c(h,h.firstChild,-1))return Gb(t(b.line,b.ch+d),f);d+=h.textContent.length}}var pa=navigator.userAgent,tg=navigator.platform,La=/gecko\/\d/i.test(pa),ug=/MSIE \d/.test(pa),vg=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(pa),cd=/Edge\/(\d+)/.exec(pa),G=ug||vg||cd,T=G&&(ug?document.documentMode||6:+(cd||vg)[1]),fa=!cd&&/WebKit\//.test(pa),Bh=fa&&/Qt\/\d+\.\d+/.test(pa),Ec=!cd&&/Chrome\//.test(pa),Aa=/Opera\//.test(pa),$c=/Apple Computer/.test(navigator.vendor),Ch=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(pa), -Tg=/PhantomJS/.test(pa),mc=$c&&(/Mobile\/\w+/.test(pa)||2lb)),ie=La||G&&9<=T,hb=function(a,b){var d=a.className;if(b=y(b).exec(d)){var c=d.slice(b.index+b[0].length);a.className=d.slice(0,b.index)+ -(c?b[1]+c:"")}};var Ob=document.createRange?function(a,b,d,c){var e=document.createRange();e.setEnd(c||a,d);e.setStart(a,b);return e}:function(a,b,d){var c=document.body.createTextRange();try{c.moveToElementText(a.parentNode)}catch(e){return c}c.collapse(!0);c.moveEnd("character",d);c.moveStart("character",b);return c};var nc=function(a){a.select()};mc?nc=function(a){a.selectionStart=0;a.selectionEnd=a.value.length}:G&&(nc=function(a){try{a.select()}catch(b){}});var Va=function(){this.f=this.id=null; -this.time=0;this.handler=fd(this.onTimeout,this)};Va.prototype.onTimeout=function(a){a.id=0;a.time<=+new Date?a.f():setTimeout(a.handler,a.time-+new Date)};Va.prototype.set=function(a,b){this.f=b;b=+new Date+a;if(!this.id||b=r?"bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN".charAt(r): -1424<=r&&1524>=r?"R":1536<=r&&1785>=r?"nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111".charAt(r-1536):1774<=r&&2220>=r?"r":8192<=r&&8203>=r?"w":8204==r?"b":"L";q.call(p,r)}n=0;for(p=k;nT)return!1;var a=v("div");return"draggable"in a||"dragDrop"in a}(),Ad,zd,me=3!="\n\nb".split(/\n/).length?function(a){for(var b=0,d=[],c=a.length;b<=c;){var e=a.indexOf("\n",b);-1==e&&(e=a.length);var f=a.slice(b,"\r"==a.charAt(e-1)?e-1:e),g=f.indexOf("\r"); --1!=g?(d.push(f.slice(0,g)),b+=g+1):(d.push(f),b=e+1)}return d}:function(a){return a.split(/\r\n?|\n/)},Eh=window.getSelection?function(a){try{return a.selectionStart!=a.selectionEnd}catch(b){return!1}}:function(a){try{var b=a.ownerDocument.selection.createRange()}catch(d){}return b&&b.parentElement()==a?0!=b.compareEndPoints("StartToEnd",b):!1},lh=function(){var a=v("div");if("oncopy"in a)return!0;a.setAttribute("oncopy","return;");return"function"==typeof a.oncopy}(),Gd=null,ld={},ob={},pb={},X= -function(a,b,d){this.pos=this.start=0;this.string=a;this.tabSize=b||8;this.lineStart=this.lastColumnPos=this.lastColumnValue=0;this.lineOracle=d};X.prototype.eol=function(){return this.pos>=this.string.length};X.prototype.sol=function(){return this.pos==this.lineStart};X.prototype.peek=function(){return this.string.charAt(this.pos)||void 0};X.prototype.next=function(){if(this.posb};X.prototype.eatSpace=function(){for(var a=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>a};X.prototype.skipToEnd=function(){this.pos=this.string.length};X.prototype.skipTo=function(a){a=this.string.indexOf(a,this.pos);if(-1this.maxLookAhead&&(this.maxLookAhead=a);return b};Da.prototype.baseToken=function(a){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=a;)this.baseTokenPos+=2;var b=this.baseTokens[this.baseTokenPos+ -1];return{type:b&&b.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-a}};Da.prototype.nextLine=function(){this.line++;0T&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};mb.prototype.update=function(a){var b=a.scrollWidth>a.clientWidth+1,d=a.scrollHeight>a.clientHeight+1,c=a.nativeBarWidth;d?(this.vert.style.display="block",this.vert.style.bottom=b?c+"px":"0",this.vert.firstChild.style.height=Math.max(0,a.scrollHeight-a.clientHeight+(a.viewHeight- -(b?c:0)))+"px"):(this.vert.scrollTop=0,this.vert.style.display="",this.vert.firstChild.style.height="0");b?(this.horiz.style.display="block",this.horiz.style.right=d?c+"px":"0",this.horiz.style.left=a.barLeft+"px",this.horiz.firstChild.style.width=Math.max(0,a.scrollWidth-a.clientWidth+(a.viewWidth-a.barLeft-(d?c:0)))+"px"):(this.horiz.style.display="",this.horiz.firstChild.style.width="0");!this.checkedZeroWidth&&0=B(a,c.to()))return d}return-1}; -var I=function(a,b){this.anchor=a;this.head=b};I.prototype.from=function(){return zc(this.anchor,this.head)};I.prototype.to=function(){return yc(this.anchor,this.head)};I.prototype.empty=function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch};cc.prototype={chunkSize:function(){return this.lines.length},removeInner:function(a,b){for(var d=a,c=a+b;dthis.size-b&&(1=this.children.length)){var a=this;do{var b=a.children.splice(a.children.length-5,5);b=new dc(b);if(a.parent){a.size-=b.size;a.height-=b.height;var d=ea(a.parent.children,a);a.parent.children.splice(d+1,0,b)}else d=new dc(a.children),d.parent=a,a.children=[d,b],a=d;b.parent=a.parent}while(10< -a.children.length);a.parent.maybeSpill()}},iterN:function(a,b,d){for(var c=0;ca.display.maxLineLength&&(a.display.maxLine=f,a.display.maxLineLength=g,a.display.maxLineChanged=!0);null!=d&&a&&this.collapsed&&ma(a,d,c+1);this.lines.length=0;this.explicitlyCleared=!0;this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,a&&Hf(a.doc));a&&aa(a,"markerCleared",a,this,d, -c);b&&kb(a);this.parent&&this.parent.clear()}};Ta.prototype.find=function(a,b){null==a&&"bookmark"==this.type&&(a=1);for(var d,c,e=0;eB(h.head,h.anchor),a[f]=new I(h?k:g,h?g:k)):a[f]=new I(g,g)}a=new ua(a,this.sel.primIndex)}b= -a;for(a=c.length-1;0<=a;a--)Ab(this,c[a]);b?Ef(this,b):this.cm&&vb(this.cm)}),undo:ca(function(){Vc(this,"undo")}),redo:ca(function(){Vc(this,"redo")}),undoSelection:ca(function(){Vc(this,"undo",!0)}),redoSelection:ca(function(){Vc(this,"redo",!0)}),setExtending:function(a){this.extend=a},getExtending:function(){return this.extend},historySize:function(){for(var a=this.history,b=0,d=0,c=0;c=a.ch)&&b.push(e.marker.parent|| -e.marker)}return b},findMarks:function(a,b,d){a=C(this,a);b=C(this,b);var c=[],e=a.line;this.iter(a.line,b.line+1,function(f){if(f=f.markedSpans)for(var g=0;g=h.to||null==h.from&&e!=a.line||null!=h.from&&e==b.line&&h.from>=b.ch||d&&!d(h.marker)||c.push(h.marker.parent||h.marker)}++e});return c},getAllMarks:function(){var a=[];this.iter(function(b){if(b=b.markedSpans)for(var d=0;da)return b=a,!0;a-=e;++d});return C(this,t(d,b))},indexFromPos:function(a){a=C(this,a);var b=a.ch;if(a.linea.ch)return 0;var d=this.lineSeparator().length;this.iter(this.first,a.line,function(c){b+=c.text.length+d});return b},copy:function(a){var b=new oa(od(this,this.first,this.first+this.size),this.modeOption,this.first,this.lineSep,this.direction);b.scrollTop=this.scrollTop;b.scrollLeft=this.scrollLeft; -b.sel=this.sel;b.extend=!1;a&&(b.history.undoDepth=this.history.undoDepth,b.setHistory(this.getHistory()));return b},linkedDoc:function(a){a||(a={});var b=this.first,d=this.first+this.size;null!=a.from&&a.from>b&&(b=a.from);null!=a.to&&a.toqc;qc++)Ua[qc+48]=Ua[qc+96]=String(qc);for(var dd=65;90>=dd;dd++)Ua[dd]=String.fromCharCode(dd);for(var rc=1;12>=rc;rc++)Ua[rc+111]=Ua[rc+63235]="F"+rc;var gc={basic:{Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto", -Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},pcDefault:{"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev", -"Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},emacsy:{"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars", -"Ctrl-O":"openLine"},macDefault:{"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace", -"Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]}};gc["default"]=xa?gc.macDefault:gc.pcDefault;var hc={selectAll:Jf,singleSelection:function(a){return a.setSelection(a.getCursor("anchor"),a.getCursor("head"),Ha)},killLine:function(a){return Eb(a,function(b){if(b.empty()){var d= -w(a.doc,b.head.line).text.length;return b.head.ch==d&&b.head.linea.doc.first){var g=w(a.doc,e.line-1).text;g&&(e=new t(e.line,1),a.replaceRange(f.charAt(0)+a.doc.lineSeparator()+g.charAt(g.length-1),t(e.line-1,g.length-1),e,"+transpose"))}d.push(new I(e,e))}a.setSelections(d)})},newlineAndIndent:function(a){return qa(a,function(){for(var b=a.listSelections(), -d=b.length-1;0<=d;d--)a.replaceRange(a.doc.lineSeparator(),b[d].anchor,b[d].head,"+input");b=a.listSelections();for(d=0;da&&0==B(b,this.pos)&&d==this.button};var kc,jc,Fb={toString:function(){return"CodeMirror.Init"}}, -kg={},ad={};U.defaults=kg;U.optionHandlers=ad;var ke=[];U.defineInitHook=function(a){return ke.push(a)};var ra=null,O=function(a){this.cm=a;this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null;this.polling=new Va;this.composing=null;this.gracePeriod=!1;this.readDOMTimeout=null};O.prototype.init=function(a){function b(h){for(h=h.target;h;h=h.parentNode){if(h==g)return!0;if(/\bCodeMirror-(?:line)?widget\b/.test(h.className))break}return!1}function d(h){if(b(h)&&!Z(f, -h)){if(f.somethingSelected())ra={lineWise:!1,text:f.getSelections()},"cut"==h.type&&f.replaceSelection("",null,"cut");else if(f.options.lineWiseCopyCut){var k=og(f);ra={lineWise:!0,text:k.text};"cut"==h.type&&f.operation(function(){f.setSelections(k.ranges,0,Ha);f.replaceSelection("",null,"cut")})}else return;if(h.clipboardData){h.clipboardData.clearData();var l=ra.text.join("\n");h.clipboardData.setData("Text",l);if(h.clipboardData.getData("Text")==l){h.preventDefault();return}}var m=qg();h=m.firstChild; -f.display.lineSpace.insertBefore(m,f.display.lineSpace.firstChild);h.value=ra.text.join("\n");var n=ka();nc(h);setTimeout(function(){f.display.lineSpace.removeChild(m);n.focus();n==g&&e.showPrimarySelection()},50)}}var c=this,e=this,f=e.cm,g=e.div=a.lineDiv;g.contentEditable=!0;pg(g,f.options.spellcheck,f.options.autocorrect,f.options.autocapitalize);z(g,"paste",function(h){!b(h)||Z(f,h)||ng(h,f)||11>=T&&setTimeout(ba(f,function(){return c.updateFromDOM()}),20)});z(g,"compositionstart",function(h){c.composing= -{data:h.data,done:!1}});z(g,"compositionupdate",function(h){c.composing||(c.composing={data:h.data,done:!1})});z(g,"compositionend",function(h){c.composing&&(h.data!=c.composing.data&&c.readFromDOMSoon(),c.composing.done=!0)});z(g,"touchstart",function(){return e.forceCompositionEnd()});z(g,"input",function(){c.composing||c.readFromDOMSoon()});z(g,"copy",d);z(g,"cut",d)};O.prototype.screenReaderLabelChanged=function(a){a?this.div.setAttribute("aria-label",a):this.div.removeAttribute("aria-label")}; -O.prototype.prepareSelection=function(){var a=ff(this.cm,!1);a.focus=ka()==this.div;return a};O.prototype.showSelection=function(a,b){a&&this.cm.display.view.length&&((a.focus||b)&&this.showPrimarySelection(),this.showMultipleSelections(a))};O.prototype.getSelection=function(){return this.cm.display.wrapper.ownerDocument.getSelection()};O.prototype.showPrimarySelection=function(){var a=this.getSelection(),b=this.cm,d=b.doc.sel.primary(),c=d.from();d=d.to();if(b.display.viewTo==b.display.viewFrom|| -c.line>=b.display.viewTo||d.line=b.display.viewFrom&&sg(b,c)||{node:e[0].measure.map[2],offset:0},d=d.linea.firstLine()&&(c=t(c.line-1,w(a.doc,c.line-1).length));e.ch==w(a.doc,e.line).text.length&&e.lineb.viewTo-1)return!1;var f;c.line==b.viewFrom||0==(f=bb(a,c.line))?(d=N(b.view[0].line),f=b.view[0].node):(d=N(b.view[f].line),f=b.view[f-1].node.nextSibling);var g=bb(a,e.line);g==b.view.length-1?(e=b.viewTo-1,b=b.lineDiv.lastChild):(e=N(b.view[g+1].line)-1,b=b.view[g+1].node.previousSibling);if(!f)return!1; -b=a.doc.splitLines(zh(a,f,b,d,e));for(f=Za(a.doc,t(d,0),t(e,w(a.doc,e).text.length));1 -c.ch&&k.charCodeAt(k.length-g-1)==l.charCodeAt(l.length-g-1);)h--,g++;b[b.length-1]=k.slice(0,k.length-g).replace(/^\u200b+/,"");b[0]=b[0].slice(h).replace(/\u200b+$/,"");c=t(d,h);d=t(e,f.length?J(f).length-g:0);if(1T&&f.scrollbars.setScrollTop(f.scroller.scrollTop=k),null!=g.selectionStart)){(!G||G&&9>T)&&b();var q=0,r=function(){f.selForContextMenu==e.doc.sel&&0==g.selectionStart&&0q++?f.detectingSelectAll=setTimeout(r,500):(f.selForContextMenu=null,f.input.reset())};f.detectingSelectAll=setTimeout(r,200)}}var c=this,e=c.cm,f=e.display,g=c.textarea;c.contextMenuPending&&c.contextMenuPending();var h=eb(e, -a),k=f.scroller.scrollTop;if(h&&!Aa){e.options.resetSelectionOnContextMenu&&-1==e.doc.sel.contains(h)&&ba(e,da)(e.doc,Na(h),Ha);var l=g.style.cssText,m=c.wrapper.style.cssText;h=c.wrapper.offsetParent.getBoundingClientRect();c.wrapper.style.cssText="position: static";g.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(a.clientY-h.top-5)+"px; left: "+(a.clientX-h.left-5)+"px;\n z-index: 1000; background: "+(G?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; -if(fa)var n=window.scrollY;f.input.focus();fa&&window.scrollTo(null,n);f.input.reset();e.somethingSelected()||(g.value=c.prevInput=" ");c.contextMenuPending=d;f.selForContextMenu=e.doc.sel;clearTimeout(f.detectingSelectAll);G&&9<=T&&b();if(ie){Kb(a);var p=function(){sa(window,"mouseup",p);setTimeout(d,20)};z(window,"mouseup",p)}else setTimeout(d,50)}};V.prototype.readOnlyChanged=function(a){a||this.reset();this.textarea.disabled="nocursor"==a;this.textarea.readOnly=!!a};V.prototype.setUneditable= -function(){};V.prototype.needsContentAttribute=!1;(function(a){function b(c,e,f,g){a.defaults[c]=e;f&&(d[c]=g?function(h,k,l){l!=Fb&&f(h,k,l)}:f)}var d=a.optionHandlers;a.defineOption=b;a.Init=Fb;b("value","",function(c,e){return c.setValue(e)},!0);b("mode",null,function(c,e){c.doc.modeOption=e;Zd(c)},!0);b("indentUnit",2,Zd,!0);b("indentWithTabs",!1);b("smartIndent",!0);b("tabSize",4,function(c){$b(c);Sb(c);ma(c)},!0);b("lineSeparator",null,function(c,e){if(c.doc.lineSep=e){var f=[],g=c.doc.first; -c.doc.iter(function(k){for(var l=0;;){var m=k.text.indexOf(e,l);if(-1==m)break;l=m+e.length;f.push(t(g,m))}g++});for(var h=f.length-1;0<=h;h--)Bb(c.doc,e,f[h],t(f[h].line,f[h].ch+e.length))}});b("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g,function(c,e,f){c.state.specialChars=new RegExp(e.source+(e.test("\t")?"":"|\t"),"g");f!=Fb&&c.refresh()});b("specialCharPlaceholder",Kg,function(c){return c.refresh()},!0);b("electricChars",!0);b("inputStyle", -Zb?"contenteditable":"textarea",function(){throw Error("inputStyle can not (yet) be changed in a running editor");},!0);b("spellcheck",!1,function(c,e){return c.getInputField().spellcheck=e},!0);b("autocorrect",!1,function(c,e){return c.getInputField().autocorrect=e},!0);b("autocapitalize",!1,function(c,e){return c.getInputField().autocapitalize=e},!0);b("rtlMoveVisually",!Dh);b("wholeLineUpdateBefore",!0);b("theme","default",function(c){jg(c);Yb(c)},!0);b("keyMap","default",function(c,e,f){e=Wc(e); -(f=f!=Fb&&Wc(f))&&f.detach&&f.detach(c,e);e.attach&&e.attach(c,f||null)});b("extraKeys",null);b("configureMouse",null);b("lineWrapping",!1,wh,!0);b("gutters",[],function(c,e){c.display.gutterSpecs=Xd(e,c.options.lineNumbers);Yb(c)},!0);b("fixedGutter",!0,function(c,e){c.display.gutters.style.left=e?Ld(c.display)+"px":"0";c.refresh()},!0);b("coverGutterNextToScrollbar",!1,function(c){return wb(c)},!0);b("scrollbarStyle","native",function(c){nf(c);wb(c);c.display.scrollbars.setScrollTop(c.doc.scrollTop); -c.display.scrollbars.setScrollLeft(c.doc.scrollLeft)},!0);b("lineNumbers",!1,function(c,e){c.display.gutterSpecs=Xd(c.options.gutters,e);Yb(c)},!0);b("firstLineNumber",1,Yb,!0);b("lineNumberFormatter",function(c){return c},Yb,!0);b("showCursorWhenSelecting",!1,Tb,!0);b("resetSelectionOnContextMenu",!0);b("lineWiseCopyCut",!0);b("pasteLinesPerSelection",!0);b("selectionsMayTouch",!1);b("readOnly",!1,function(c,e){"nocursor"==e&&(ub(c),c.display.input.blur());c.display.input.readOnlyChanged(e)});b("screenReaderLabel", -null,function(c,e){c.display.input.screenReaderLabelChanged(""===e?null:e)});b("disableInput",!1,function(c,e){e||c.display.input.reset()},!0);b("dragDrop",!0,vh);b("allowDropFileTypes",null);b("cursorBlinkRate",530);b("cursorScrollMargin",0);b("cursorHeight",1,Tb,!0);b("singleCursorHeightPerLine",!0,Tb,!0);b("workTime",100);b("workDelay",100);b("flattenSpans",!0,$b,!0);b("addModeClass",!1,$b,!0);b("pollInterval",100);b("undoDepth",200,function(c,e){return c.doc.history.undoDepth=e});b("historyEventDelay", -1250);b("viewportMargin",10,function(c){return c.refresh()},!0);b("maxHighlightLength",1E4,$b,!0);b("moveInputWithCursor",!0,function(c,e){e||c.display.input.resetPosition()});b("tabindex",null,function(c,e){return c.display.input.getField().tabIndex=e||""});b("autofocus",null);b("direction","ltr",function(c,e){return c.doc.setDirection(e)},!0);b("phrases",null)})(U);(function(a){var b=a.optionHandlers,d=a.helpers={};a.prototype={constructor:a,focus:function(){window.focus();this.display.input.focus()}, -setOption:function(c,e){var f=this.options,g=f[c];if(f[c]!=e||"mode"==c)f[c]=e,b.hasOwnProperty(c)&&ba(this,b[c])(this,e,g),W(this,"optionChange",this,c)},getOption:function(c){return this.options[c]},getDoc:function(){return this.doc},addKeyMap:function(c,e){this.state.keyMaps[e?"push":"unshift"](Wc(c))},removeKeyMap:function(c){for(var e=this.state.keyMaps,f=0;ff&&(lc(this,h.head.line,c,!0),f=h.head.line,g==this.doc.sel.primIndex&&vb(this));else{var k=h.from();h=h.to();var l=Math.max(f,k.line);f=Math.min(this.lastLine(),h.line-(h.ch?0:1))+1;for(h=l;h>1;if((h?e[2*h-1]:0)>=c)g=h;else if(e[2*h+1]f?e:0==f?null:e.slice(0,f-1)},getModeAt:function(c){var e=this.doc.mode;return e.innerMode?a.innerMode(e,this.getTokenAt(c).state).mode:e},getHelper:function(c,e){return this.getHelpers(c, -e)[0]},getHelpers:function(c,e){var f=[];if(!d.hasOwnProperty(e))return f;var g=d[e];c=this.getModeAt(c);if("string"==typeof c[e])g[c[e]]&&f.push(g[c[e]]);else if(c[e])for(var h=0;hh&&(c=h,g=!0);c=w(this.doc,c)}return Gc(this,c,{top:0,left:0},e||"page",f||g).top+(g?this.doc.height-Fa(c):0)},defaultTextHeight:function(){return tb(this.display)},defaultCharWidth:function(){return sb(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(c,e,f,g,h){var k=this.display;c=za(this,C(this.doc,c));var l=c.bottom,m=c.left;e.style.position= -"absolute";e.setAttribute("cm-ignore-events","true");this.display.input.setUneditable(e);k.sizer.appendChild(e);if("over"==g)l=c.top;else if("above"==g||"near"==g){var n=Math.max(k.wrapper.clientHeight,this.doc.height),p=Math.max(k.sizer.clientWidth,k.lineSpace.clientWidth);("above"==g||c.bottom+e.offsetHeight>n)&&c.top>e.offsetHeight?l=c.top-e.offsetHeight:c.bottom+e.offsetHeight<=n&&(l=c.bottom);m+e.offsetWidth>p&&(m=p-e.offsetWidth)}e.style.top=l+"px";e.style.left=e.style.right="";"right"==h?(m= -k.sizer.clientWidth-e.offsetWidth,e.style.right="0px"):("left"==h?m=0:"middle"==h&&(m=(k.sizer.clientWidth-e.offsetWidth)/2),e.style.left=m+"px");f&&(c=Sd(this,{left:m,top:l,right:m+e.offsetWidth,bottom:l+e.offsetHeight}),null!=c.scrollTop&&Vb(this,c.scrollTop),null!=c.scrollLeft&&ib(this,c.scrollLeft))},triggerOnKeyDown:ia(dg),triggerOnKeyPress:ia(fg),triggerOnKeyUp:eg,triggerOnMouseDown:ia(gg),execCommand:function(c){if(hc.hasOwnProperty(c))return hc[c].call(null,this)},triggerElectric:ia(function(c){mg(this, -c)}),findPosH:function(c,e,f,g){var h=1;0>e&&(h=-1,e=-e);c=C(this.doc,c);for(var k=0;kc?g.from():g.to()},oc)}),deleteH:ia(function(c,e){var f=this.doc;this.doc.sel.somethingSelected()?f.replaceSelection("",null,"+delete"):Eb(this,function(g){var h=ne(f,g.head,c,e,!1);return 0>c? -{from:h,to:g.head}:{from:g.head,to:h}})}),findPosV:function(c,e,f,g){var h=1;0>e&&(h=-1,e=-e);var k=C(this.doc,c);for(c=0;cc?m.from():m.to();var n=za(f,m.head,"div");null!=m.goalColumn&&(n.left=m.goalColumn);h.push(n.left);var p=rg(f,n,c,e);"page"==e&& -m==g.sel.primary()&&Mc(f,Hc(f,p,"div").top-n.top);return p},oc);if(h.length)for(var l=0;lea(Gh,sc)&&(U.prototype[sc]=function(a){return function(){return a.apply(this.doc,arguments)}}(oa.prototype[sc]));nb(oa);U.inputStyles={textarea:V,contenteditable:O};U.defineMode=function(a){U.defaults.mode||"null"==a||(U.defaults.mode= -a);Bg.apply(this,arguments)};U.defineMIME=function(a,b){ob[a]=b};U.defineMode("null",function(){return{token:function(a){return a.skipToEnd()}}});U.defineMIME("text/plain","null");U.defineExtension=function(a,b){U.prototype[a]=b};U.defineDocExtension=function(a,b){oa.prototype[a]=b};U.fromTextArea=function(a,b){function d(){a.value=h.getValue()}b=b?Xa(b):{};b.value=a.value;!b.tabindex&&a.tabIndex&&(b.tabindex=a.tabIndex);!b.placeholder&&a.placeholder&&(b.placeholder=a.placeholder);if(null==b.autofocus){var c= -ka();b.autofocus=c==a||null!=a.getAttribute("autofocus")&&c==document.body}if(a.form&&(z(a.form,"submit",d),!b.leaveSubmitMethodAlone)){var e=a.form;var f=e.submit;try{var g=e.submit=function(){d();e.submit=f;e.submit();e.submit=g}}catch(k){}}b.finishInit=function(k){k.save=d;k.getTextArea=function(){return a};k.toTextArea=function(){k.toTextArea=isNaN;d();a.parentNode.removeChild(k.getWrapperElement());a.style.display="";a.form&&(sa(a.form,"submit",d),b.leaveSubmitMethodAlone||"function"!=typeof a.form.submit|| -(a.form.submit=f))}};a.style.display="none";var h=U(function(k){return a.parentNode.insertBefore(k,a.nextSibling)},b);return h};(function(a){a.off=sa;a.on=z;a.wheelEventPixels=Xg;a.Doc=oa;a.splitLines=me;a.countColumn=va;a.findColumn=gd;a.isWordChar=id;a.Pass=Yc;a.signal=W;a.Line=xb;a.changeEnd=Ra;a.scrollbarModel=of;a.Pos=t;a.cmpPos=B;a.modes=ld;a.mimeModes=ob;a.resolveMode=xc;a.getMode=md;a.modeExtensions=pb;a.extendMode=Cg;a.copyState=Ya;a.startState=ve;a.innerMode=nd;a.commands=hc;a.keyMap=gc; -a.keyName=Zf;a.isModifierKey=Wf;a.lookupKey=Db;a.normalizeKeyMap=hh;a.StringStream=X;a.SharedTextMarker=fc;a.TextMarker=Ta;a.LineWidget=ec;a.e_preventDefault=la;a.e_stopPropagation=te;a.e_stop=Kb;a.addClass=Wa;a.contains=ja;a.rmClass=hb;a.keyNames=Ua})(U);U.version="5.65.0";return U}); - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],30:[function(require,module,exports){ -(function(v){"object"==typeof exports&&"object"==typeof module?v(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],v):v(CodeMirror)})(function(v){v.defineMode("javascript",function(Ua,A){var p,w,f;function u(a,b,d){V=a;ca=d;return b}function I(a,b){var d=a.next();if('"'==d||"'"==d)return b.tokenize=Va(d),b.tokenize(a,b);if("."==d&&a.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/))return u("number","number");if("."==d&&a.match(".."))return u("spread","meta"); -if(/[\[\]{}\(\),;:\.]/.test(d))return u(d);if("="==d&&a.eat(">"))return u("=>","operator");if("0"==d&&a.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/))return u("number","number");if(/\d/.test(d))return a.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/),u("number","number");if("/"==d){if(a.eat("*"))return b.tokenize=da,da(a,b);if(a.eat("/"))return a.skipToEnd(),u("comment","comment");if(Aa(a,b,1)){a:for(var e=b=!1;null!=(d=a.next());){if(!b){if("/"==d&&!e)break a;"["==d?e=!0:e&&"]"==d&&(e= -!1)}b=!b&&"\\"==d}a.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);return u("regexp","string-2")}a.eat("=");return u("operator","operator",a.current())}if("`"==d)return b.tokenize=W,W(a,b);if("#"==d&&"!"==a.peek())return a.skipToEnd(),u("meta","meta");if("#"==d&&a.eatWhile(ea))return u("variable","property");if("<"==d&&a.match("!--")||"-"==d&&a.match("->")&&!/\S/.test(a.string.slice(0,a.start)))return a.skipToEnd(),u("comment","comment");if(Ba.test(d))return">"==d&&b.lexical&&">"==b.lexical.type||(a.eat("=")? -"!"!=d&&"="!=d||a.eat("="):/[<>*+\-|&?]/.test(d)&&(a.eat(d),">"==d&&a.eat(d))),"?"==d&&a.eat(".")?u("."):u("operator","operator",a.current());if(ea.test(d)){a.eatWhile(ea);d=a.current();if("."!=b.lastType){if(Ca.propertyIsEnumerable(d))return a=Ca[d],u(a.type,a.style,d);if("async"==d&&a.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/,!1))return u("async","keyword",d)}return u("variable","variable",d)}}function Va(a){return function(b,d){var e=!1,h;if(fa&&"@"==b.peek()&&b.match(Wa))return d.tokenize= -I,u("jsonld-keyword","meta");for(;null!=(h=b.next())&&(h!=a||e);)e=!e&&"\\"==h;e||(d.tokenize=I);return u("string","string")}}function da(a,b){for(var d=!1,e;e=a.next();){if("/"==e&&d){b.tokenize=I;break}d="*"==e}return u("comment","comment")}function W(a,b){for(var d=!1,e;null!=(e=a.next());){if(!d&&("`"==e||"$"==e&&a.eat("{"))){b.tokenize=I;break}d=!d&&"\\"==e}return u("quasi","string-2",a.current())}function pa(a,b){b.fatArrowAt&&(b.fatArrowAt=null);var d=a.string.indexOf("=>",a.start);if(!(0> -d)){if(r){var e=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(a.string.slice(a.start,d));e&&(d=e.index)}e=0;var h=!1;for(--d;0<=d;--d){var m=a.string.charAt(d),y="([{}])".indexOf(m);if(0<=y&&3>y){if(!e){++d;break}if(0==--e){"("==m&&(h=!0);break}}else if(3<=y&&6>y)++e;else if(ea.test(m))h=!0;else if(/["'\/`]/.test(m))for(;;--d){if(0==d)return;if(a.string.charAt(d-1)==m&&"\\"!=a.string.charAt(d-2)){d--;break}}else if(h&&!e){++d;break}}h&&!e&&(b.fatArrowAt=d)}}function Da(a,b,d,e,h,m){this.indented= -a;this.column=b;this.type=d;this.prev=h;this.info=m;null!=e&&(this.align=e)}function Ea(a,b,d,e,h){var m=a.cc;p=a;w=h;f=null;qa=m;X=b;a.lexical.hasOwnProperty("align")||(a.lexical.align=!0);for(;;)if((m.length?m.pop():J?t:x)(d,e)){for(;m.length&&m[m.length-1].lex;)m.pop()();if(f)return f;if(d="variable"==d)a:if(Fa){for(d=a.localVars;d;d=d.next)if(d.name==e){d=!0;break a}for(a=a.context;a;a=a.prev)for(d=a.vars;d;d=d.next)if(d.name==e){d=!0;break a}d=void 0}else d=!1;return d?"variable-2":b}}function k(){for(var a= -arguments.length-1;0<=a;a--)qa.push(arguments[a])}function c(){k.apply(null,arguments);return!0}function ra(a,b){for(;b;b=b.next)if(b.name==a)return!0;return!1}function N(a){var b=p;f="def";if(Fa){if(b.context)if("var"==b.lexical.info&&b.context&&b.context.block){var d=Ga(a,b.context);if(null!=d){b.context=d;return}}else if(!ra(a,b.localVars)){b.localVars=new Y(a,b.localVars);return}A.globalVars&&!ra(a,b.globalVars)&&(b.globalVars=new Y(a,b.globalVars))}}function Ga(a,b){return b?b.block?(a=Ga(a, -b.prev))?a==b.prev?b:new Z(a,b.vars,!0):null:ra(a,b.vars)?b:new Z(b.prev,new Y(a,b.vars),!1):null}function ha(a){return"public"==a||"private"==a||"protected"==a||"abstract"==a||"readonly"==a}function Z(a,b,d){this.prev=a;this.vars=b;this.block=d}function Y(a,b){this.name=a;this.next=b}function O(){p.context=new Z(p.context,p.localVars,!1);p.localVars=Xa}function sa(){p.context=new Z(p.context,p.localVars,!0);p.localVars=null}function C(){p.localVars=p.context.vars;p.context=p.context.prev}function l(a, -b){var d=function(){var e=p,h=e.indented;if("stat"==e.lexical.type)h=e.lexical.indented;else for(var m=e.lexical;m&&")"==m.type&&m.align;m=m.prev)h=m.indented;e.lexical=new Da(h,w.column(),a,null,e.lexical,b)};d.lex=!0;return d}function g(){var a=p;a.lexical.prev&&(")"==a.lexical.type&&(a.indented=a.lexical.indented),a.lexical=a.lexical.prev)}function n(a){function b(d){return d==a?c():";"==a||"}"==d||")"==d||"]"==d?k():c(b)}return b}function x(a,b){return"var"==a?c(l("vardef",b),ta,n(";"),g):"keyword a"== -a?c(l("form"),ua,x,g):"keyword b"==a?c(l("form"),x,g):"keyword d"==a?w.match(/^\s*$/,!1)?c():c(l("stat"),P,n(";"),g):"debugger"==a?c(n(";")):"{"==a?c(l("}"),sa,ia,g,C):";"==a?c():"if"==a?("else"==p.lexical.info&&p.cc[p.cc.length-1]==g&&p.cc.pop()(),c(l("form"),ua,x,g,Ha)):"function"==a?c(G):"for"==a?c(l("form"),sa,Ia,x,C,g):"class"==a||r&&"interface"==b?(f="keyword",c(l("form","class"==a?a:b),Ja,g)):"variable"==a?r&&"declare"==b?(f="keyword",c(x)):r&&("module"==b||"enum"==b||"type"==b)&&w.match(/^\s*\w/, -!1)?(f="keyword","enum"==b?c(Ka):"type"==b?c(La,n("operator"),q,n(";")):c(l("form"),D,n("{"),l("}"),ia,g,g)):r&&"namespace"==b?(f="keyword",c(l("form"),t,x,g)):r&&"abstract"==b?(f="keyword",c(x)):c(l("stat"),Ya):"switch"==a?c(l("form"),ua,n("{"),l("}","switch"),sa,ia,g,g,C):"case"==a?c(t,n(":")):"default"==a?c(n(":")):"catch"==a?c(l("form"),O,Za,x,g,C):"export"==a?c(l("stat"),$a,g):"import"==a?c(l("stat"),ab,g):"async"==a?c(x):"@"==b?c(t,x):k(l("stat"),t,n(";"),g)}function Za(a){if("("==a)return c(K, -n(")"))}function t(a,b){return Ma(a,b,!1)}function B(a,b){return Ma(a,b,!0)}function ua(a){return"("!=a?k():c(l(")"),P,n(")"),g)}function Ma(a,b,d){if(p.fatArrowAt==w.start){var e=d?Na:Oa;if("("==a)return c(O,l(")"),z(K,")"),g,n("=>"),e,C);if("variable"==a)return k(O,D,n("=>"),e,C)}e=d?Q:L;return bb.hasOwnProperty(a)?c(e):"function"==a?c(G,e):"class"==a||r&&"interface"==b?(f="keyword",c(l("form"),cb,g)):"keyword c"==a||"async"==a?c(d?B:t):"("==a?c(l(")"),P,n(")"),g,e):"operator"==a||"spread"==a?c(d? -B:t):"["==a?c(l("]"),db,g,e):"{"==a?aa(ja,"}",null,e):"quasi"==a?k(ka,e):"new"==a?c(eb(d)):c()}function P(a){return a.match(/[;\}\)\],]/)?k():k(t)}function L(a,b){return","==a?c(P):Q(a,b,!1)}function Q(a,b,d){var e=0==d?L:Q,h=0==d?t:B;if("=>"==a)return c(O,d?Na:Oa,C);if("operator"==a)return/\+\+|--/.test(b)||r&&"!"==b?c(e):r&&"<"==b&&w.match(/^([^<>]|<[^<>]*>)*>\s*\(/,!1)?c(l(">"),z(q,">"),g,e):"?"==b?c(t,n(":"),h):c(h);if("quasi"==a)return k(ka,e);if(";"!=a){if("("==a)return aa(B,")","call",e);if("."== -a)return c(fb,e);if("["==a)return c(l("]"),P,n("]"),g,e);if(r&&"as"==b)return f="keyword",c(q,e);if("regexp"==a)return p.lastType=f="operator",w.backUp(w.pos-w.start-1),c(h)}}function ka(a,b){return"quasi"!=a?k():"${"!=b.slice(b.length-2)?c(ka):c(P,gb)}function gb(a){if("}"==a)return f="string-2",p.tokenize=W,c(ka)}function Oa(a){pa(w,p);return k("{"==a?x:t)}function Na(a){pa(w,p);return k("{"==a?x:B)}function eb(a){return function(b){return"."==b?c(a?hb:ib):"variable"==b&&r?c(jb,a?Q:L):k(a?B:t)}} -function ib(a,b){if("target"==b)return f="keyword",c(L)}function hb(a,b){if("target"==b)return f="keyword",c(Q)}function Ya(a){return":"==a?c(g,x):k(L,n(";"),g)}function fb(a){if("variable"==a)return f="property",c()}function ja(a,b){if("async"==a)return f="property",c(ja);if("variable"==a||"keyword"==X){f="property";if("get"==b||"set"==b)return c(kb);var d;r&&p.fatArrowAt==w.start&&(d=w.match(/^\s*:\s*/,!1))&&(p.fatArrowAt=w.pos+d[0].length);return c(M)}if("number"==a||"string"==a)return f=fa?"property": -X+" property",c(M);if("jsonld-keyword"==a)return c(M);if(r&&ha(b))return f="keyword",c(ja);if("["==a)return c(t,R,n("]"),M);if("spread"==a)return c(B,M);if("*"==b)return f="keyword",c(ja);if(":"==a)return k(M)}function kb(a){if("variable"!=a)return k(M);f="property";return c(G)}function M(a){if(":"==a)return c(B);if("("==a)return k(G)}function z(a,b,d){function e(h,m){return(d?-1"),q);if("quasi"==a)return k(ya,E)}function nb(a){if("=>"==a)return c(q)}function wa(a){return a.match(/[\}\)\]]/)?c():","==a||";"==a?c(wa): -k(ba,wa)}function ba(a,b){if("variable"==a||"keyword"==X)return f="property",c(ba);if("?"==b||"number"==a||"string"==a)return c(ba);if(":"==a)return c(q);if("["==a)return c(n("variable"),lb,n("]"),ba);if("("==a)return k(S,ba);if(!a.match(/[;\}\)\],]/))return c()}function ya(a,b){return"quasi"!=a?k():"${"!=b.slice(b.length-2)?c(ya):c(q,ob)}function ob(a){if("}"==a)return f="string-2",p.tokenize=W,c(ya)}function xa(a,b){return"variable"==a&&w.match(/^\s*[?:]/,!1)||"?"==b?c(xa):":"==a?c(q):"spread"== -a?c(xa):k(q)}function E(a,b){if("<"==b)return c(l(">"),z(q,">"),g,E);if("|"==b||"."==a||"&"==b)return c(q);if("["==a)return c(q,n("]"),E);if("extends"==b||"implements"==b)return f="keyword",c(q);if("?"==b)return c(q,n(":"),q)}function jb(a,b){if("<"==b)return c(l(">"),z(q,">"),g,E)}function la(){return k(q,pb)}function pb(a,b){if("="==b)return c(q)}function ta(a,b){return"enum"==b?(f="keyword",c(Ka)):k(D,R,H,qb)}function D(a,b){if(r&&ha(b))return f="keyword",c(D);if("variable"==a)return N(b),c(); -if("spread"==a)return c(D);if("["==a)return aa(rb,"]");if("{"==a)return aa(Qa,"}")}function Qa(a,b){if("variable"==a&&!w.match(/^\s*:/,!1))return N(b),c(H);"variable"==a&&(f="property");return"spread"==a?c(D):"}"==a?k():"["==a?c(t,n("]"),n(":"),Qa):c(n(":"),D,H)}function rb(){return k(D,H)}function H(a,b){if("="==b)return c(B)}function qb(a){if(","==a)return c(ta)}function Ha(a,b){if("keyword b"==a&&"else"==b)return c(l("form","else"),x,g)}function Ia(a,b){if("await"==b)return c(Ia);if("("==a)return c(l(")"), -sb,g)}function sb(a){return"var"==a?c(ta,T):"variable"==a?c(T):k(T)}function T(a,b){return")"==a?c():";"==a?c(T):"in"==b||"of"==b?(f="keyword",c(t,T)):k(t,T)}function G(a,b){if("*"==b)return f="keyword",c(G);if("variable"==a)return N(b),c(G);if("("==a)return c(O,l(")"),z(K,")"),g,Pa,x,C);if(r&&"<"==b)return c(l(">"),z(la,">"),g,G)}function S(a,b){if("*"==b)return f="keyword",c(S);if("variable"==a)return N(b),c(S);if("("==a)return c(O,l(")"),z(K,")"),g,Pa,C);if(r&&"<"==b)return c(l(">"),z(la,">"), -g,S)}function La(a,b){if("keyword"==a||"variable"==a)return f="type",c(La);if("<"==b)return c(l(">"),z(la,">"),g)}function K(a,b){"@"==b&&c(t,K);return"spread"==a?c(K):r&&ha(b)?(f="keyword",c(K)):r&&"this"==a?c(R,H):k(D,R,H)}function cb(a,b){return"variable"==a?Ja(a,b):ma(a,b)}function Ja(a,b){if("variable"==a)return N(b),c(ma)}function ma(a,b){if("<"==b)return c(l(">"),z(la,">"),g,ma);if("extends"==b||"implements"==b||r&&","==a)return"implements"==b&&(f="keyword"),c(r?q:t,ma);if("{"==a)return c(l("}"), -F,g)}function F(a,b){if("async"==a||"variable"==a&&("static"==b||"get"==b||"set"==b||r&&ha(b))&&w.match(/^\s+[\w$\xa1-\uffff]/,!1))return f="keyword",c(F);if("variable"==a||"keyword"==X)return f="property",c(na,F);if("number"==a||"string"==a)return c(na,F);if("["==a)return c(t,R,n("]"),na,F);if("*"==b)return f="keyword",c(F);if(r&&"("==a)return k(S,F);if(";"==a||","==a)return c(F);if("}"==a)return c();if("@"==b)return c(t,F)}function na(a,b){if("!"==b||"?"==b)return c(na);if(":"==a)return c(q,H); -if("="==b)return c(B);a=p.lexical.prev;return k(a&&"interface"==a.info?S:G)}function $a(a,b){return"*"==b?(f="keyword",c(za,n(";"))):"default"==b?(f="keyword",c(t,n(";"))):"{"==a?c(z(Ra,"}"),za,n(";")):k(x)}function Ra(a,b){if("as"==b)return f="keyword",c(n("variable"));if("variable"==a)return k(B,Ra)}function ab(a){return"string"==a?c():"("==a?k(t):"."==a?k(L):k(oa,Sa,za)}function oa(a,b){if("{"==a)return aa(oa,"}");"variable"==a&&N(b);"*"==b&&(f="keyword");return c(tb)}function Sa(a){if(","==a)return c(oa, -Sa)}function tb(a,b){if("as"==b)return f="keyword",c(oa)}function za(a,b){if("from"==b)return f="keyword",c(t)}function db(a){return"]"==a?c():k(z(B,"]"))}function Ka(){return k(l("form"),D,n("{"),l("}"),z(ub,"}"),g,g)}function ub(){return k(D,H)}function Aa(a,b,d){return b.tokenize==I&&/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(b.lastType)||"quasi"==b.lastType&&/\{\s*$/.test(a.string.slice(0,a.pos-(d||0)))}var U=Ua.indentUnit,Ta=A.statementIndent,fa=A.jsonld, -J=A.json||fa,Fa=!1!==A.trackScope,r=A.typescript,ea=A.wordCharacters||/[\w$\xa1-\uffff]/,Ca=function(){function a(va){return{type:va,style:"keyword"}}var b=a("keyword a"),d=a("keyword b"),e=a("keyword c"),h=a("keyword d"),m=a("operator"),y={type:"atom",style:"atom"};return{"if":a("if"),"while":b,"with":b,"else":d,"do":d,"try":d,"finally":d,"return":h,"break":h,"continue":h,"new":a("new"),"delete":e,"void":e,"throw":e,"debugger":a("debugger"),"var":a("var"),"const":a("var"),let:a("var"),"function":a("function"), -"catch":a("catch"),"for":a("for"),"switch":a("switch"),"case":a("case"),"default":a("default"),"in":m,"typeof":m,"instanceof":m,"true":y,"false":y,"null":y,undefined:y,NaN:y,Infinity:y,"this":a("this"),"class":a("class"),"super":a("atom"),yield:e,"export":a("export"),"import":a("import"),"extends":e,await:e}}(),Ba=/[+\-*&%=<>!?|~^@]/,Wa=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,V,ca,bb={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,"this":!0,"import":!0, -"jsonld-keyword":!0};var qa=f=p=null;var X=w=void 0;var Xa=new Y("this",new Y("arguments",null));C.lex=!0;g.lex=!0;return{startState:function(a){a={tokenize:I,lastType:"sof",cc:[],lexical:new Da((a||0)-U,0,"block",!1),localVars:A.localVars,context:A.localVars&&new Z(null,null,!1),indented:a||0};A.globalVars&&"object"==typeof A.globalVars&&(a.globalVars=A.globalVars);return a},token:function(a,b){a.sol()&&(b.lexical.hasOwnProperty("align")||(b.lexical.align=!1),b.indented=a.indentation(),pa(a,b)); -if(b.tokenize!=da&&a.eatSpace())return null;var d=b.tokenize(a,b);if("comment"==V)return d;b.lastType="operator"!=V||"++"!=ca&&"--"!=ca?V:"incdec";return Ea(b,d,V,ca,a)},indent:function(a,b){if(a.tokenize==da||a.tokenize==W)return v.Pass;if(a.tokenize!=I)return 0;var d=b&&b.charAt(0),e=a.lexical,h;if(!/^\s*else\b/.test(b))for(var m=a.cc.length-1;0<=m;--m){var y=a.cc[m];if(y==g)e=e.prev;else if(y!=Ha&&y!=C)break}for(;!("stat"!=e.type&&"form"!=e.type||"}"!=d&&(!(h=a.cc[a.cc.length-1])||h!=L&&h!=Q|| -/^[,\.=+\-*:?[\(]/.test(b)));)e=e.prev;Ta&&")"==e.type&&"stat"==e.prev.type&&(e=e.prev);h=e.type;m=d==h;return"vardef"==h?e.indented+("operator"==a.lastType||","==a.lastType?e.info.length+1:0):"form"==h&&"{"==d?e.indented:"form"==h?e.indented+U:"stat"==h?(d=e.indented,a="operator"==a.lastType||","==a.lastType||Ba.test(b.charAt(0))||/[,.]/.test(b.charAt(0)),d+(a?Ta||U:0)):"switch"!=e.info||m||0==A.doubleIndentSwitch?e.align?e.column+(m?0:1):e.indented+(m?0:U):e.indented+(/^(?:case|default)\b/.test(b)? -U:2*U)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:J?null:"/*",blockCommentEnd:J?null:"*/",blockCommentContinue:J?null:" * ",lineComment:J?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:J?"json":"javascript",jsonldMode:fa,jsonMode:J,expressionAllowed:Aa,skipExpression:function(a){Ea(a,"atom","atom","true",new v.StringStream("",2,null))}}});v.registerHelper("wordChars","javascript",/[\w$]/);v.defineMIME("text/javascript","javascript");v.defineMIME("text/ecmascript", -"javascript");v.defineMIME("application/javascript","javascript");v.defineMIME("application/x-javascript","javascript");v.defineMIME("application/ecmascript","javascript");v.defineMIME("application/json",{name:"javascript",json:!0});v.defineMIME("application/x-json",{name:"javascript",json:!0});v.defineMIME("application/manifest+json",{name:"javascript",json:!0});v.defineMIME("application/ld+json",{name:"javascript",jsonld:!0});v.defineMIME("text/typescript",{name:"javascript",typescript:!0});v.defineMIME("application/typescript", -{name:"javascript",typescript:!0})}); - -},{"../../lib/codemirror":29}],31:[function(require,module,exports){ - -/** - * Expose `Emitter`. - */ - -if (typeof module !== 'undefined') { - module.exports = Emitter; -} - -/** - * Initialize a new `Emitter`. - * - * @api public - */ - -function Emitter(obj) { - if (obj) return mixin(obj); -}; - -/** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; - } - return obj; -} - -/** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.on = -Emitter.prototype.addEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - (this._callbacks['$' + event] = this._callbacks['$' + event] || []) - .push(fn); - return this; -}; - -/** - * Adds an `event` listener that will be invoked a single - * time then automatically removed. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.once = function(event, fn){ - function on() { - this.off(event, on); - fn.apply(this, arguments); - } - - on.fn = fn; - this.on(event, on); - return this; -}; - -/** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.off = -Emitter.prototype.removeListener = -Emitter.prototype.removeAllListeners = -Emitter.prototype.removeEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - - // all - if (0 == arguments.length) { - this._callbacks = {}; - return this; - } - - // specific event - var callbacks = this._callbacks['$' + event]; - if (!callbacks) return this; - - // remove all handlers - if (1 == arguments.length) { - delete this._callbacks['$' + event]; - return this; - } - - // remove specific handler - var cb; - for (var i = 0; i < callbacks.length; i++) { - cb = callbacks[i]; - if (cb === fn || cb.fn === fn) { - callbacks.splice(i, 1); - break; - } - } - - // Remove event specific arrays for event types that no - // one is subscribed for to avoid memory leak. - if (callbacks.length === 0) { - delete this._callbacks['$' + event]; - } - - return this; -}; - -/** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} - */ - -Emitter.prototype.emit = function(event){ - this._callbacks = this._callbacks || {}; - - var args = new Array(arguments.length - 1) - , callbacks = this._callbacks['$' + event]; - - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - - if (callbacks) { - callbacks = callbacks.slice(0); - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args); - } - } - - return this; -}; - -/** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public - */ - -Emitter.prototype.listeners = function(event){ - this._callbacks = this._callbacks || {}; - return this._callbacks['$' + event] || []; -}; - -/** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public - */ - -Emitter.prototype.hasListeners = function(event){ - return !! this.listeners(event).length; -}; - -},{}],32:[function(require,module,exports){ -'use strict' - -module.exports = ready - -function ready (callback) { - if (typeof document === 'undefined') { - throw new Error('document-ready only runs in the browser') - } - var state = document.readyState - if (state === 'complete' || state === 'interactive') { - return setTimeout(callback, 0) - } - - document.addEventListener('DOMContentLoaded', function onLoad () { - callback() - }) -} - -},{}],33:[function(require,module,exports){ -module.exports = stringify -stringify.default = stringify -stringify.stable = deterministicStringify -stringify.stableStringify = deterministicStringify - -var LIMIT_REPLACE_NODE = '[...]' -var CIRCULAR_REPLACE_NODE = '[Circular]' - -var arr = [] -var replacerStack = [] - -function defaultOptions () { - return { - depthLimit: Number.MAX_SAFE_INTEGER, - edgesLimit: Number.MAX_SAFE_INTEGER - } -} - -// Regular stringify -function stringify (obj, replacer, spacer, options) { - if (typeof options === 'undefined') { - options = defaultOptions() - } - - decirc(obj, '', 0, [], undefined, 0, options) - var res - try { - if (replacerStack.length === 0) { - res = JSON.stringify(obj, replacer, spacer) - } else { - res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) - } - } catch (_) { - return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') - } finally { - while (arr.length !== 0) { - var part = arr.pop() - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]) - } else { - part[0][part[1]] = part[2] - } - } - } - return res -} - -function setReplace (replace, val, k, parent) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) - if (propertyDescriptor.get !== undefined) { - if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: replace }) - arr.push([parent, k, val, propertyDescriptor]) - } else { - replacerStack.push([val, k, replace]) - } - } else { - parent[k] = replace - arr.push([parent, k, val]) - } -} - -function decirc (val, k, edgeIndex, stack, parent, depth, options) { - depth += 1 - var i - if (typeof val === 'object' && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - setReplace(CIRCULAR_REPLACE_NODE, val, k, parent) - return - } - } - - if ( - typeof options.depthLimit !== 'undefined' && - depth > options.depthLimit - ) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent) - return - } - - if ( - typeof options.edgesLimit !== 'undefined' && - edgeIndex + 1 > options.edgesLimit - ) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent) - return - } - - stack.push(val) - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - decirc(val[i], i, i, stack, val, depth, options) - } - } else { - var keys = Object.keys(val) - for (i = 0; i < keys.length; i++) { - var key = keys[i] - decirc(val[key], key, i, stack, val, depth, options) - } - } - stack.pop() - } -} - -// Stable-stringify -function compareFunction (a, b) { - if (a < b) { - return -1 - } - if (a > b) { - return 1 - } - return 0 -} - -function deterministicStringify (obj, replacer, spacer, options) { - if (typeof options === 'undefined') { - options = defaultOptions() - } - - var tmp = deterministicDecirc(obj, '', 0, [], undefined, 0, options) || obj - var res - try { - if (replacerStack.length === 0) { - res = JSON.stringify(tmp, replacer, spacer) - } else { - res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) - } - } catch (_) { - return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') - } finally { - // Ensure that we restore the object as it was. - while (arr.length !== 0) { - var part = arr.pop() - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]) - } else { - part[0][part[1]] = part[2] - } - } - } - return res -} - -function deterministicDecirc (val, k, edgeIndex, stack, parent, depth, options) { - depth += 1 - var i - if (typeof val === 'object' && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - setReplace(CIRCULAR_REPLACE_NODE, val, k, parent) - return - } - } - try { - if (typeof val.toJSON === 'function') { - return - } - } catch (_) { - return - } - - if ( - typeof options.depthLimit !== 'undefined' && - depth > options.depthLimit - ) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent) - return - } - - if ( - typeof options.edgesLimit !== 'undefined' && - edgeIndex + 1 > options.edgesLimit - ) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent) - return - } - - stack.push(val) - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - deterministicDecirc(val[i], i, i, stack, val, depth, options) - } - } else { - // Create a temporary object in the required way - var tmp = {} - var keys = Object.keys(val).sort(compareFunction) - for (i = 0; i < keys.length; i++) { - var key = keys[i] - deterministicDecirc(val[key], key, i, stack, val, depth, options) - tmp[key] = val[key] - } - if (typeof parent !== 'undefined') { - arr.push([parent, k, val]) - parent[k] = tmp - } else { - return tmp - } - } - stack.pop() - } -} - -// wraps replacer function to handle values we couldn't replace -// and mark them as replaced value -function replaceGetterValues (replacer) { - replacer = - typeof replacer !== 'undefined' - ? replacer - : function (k, v) { - return v - } - return function (key, val) { - if (replacerStack.length > 0) { - for (var i = 0; i < replacerStack.length; i++) { - var part = replacerStack[i] - if (part[1] === key && part[0] === val) { - val = part[2] - replacerStack.splice(i, 1) - break - } - } - } - return replacer.call(this, key, val) - } -} - -},{}],34:[function(require,module,exports){ -'use strict'; - -/* eslint no-invalid-this: 1 */ - -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slice.call(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; + return base64; + }; + var decode = function (base64) { + var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4; + if (base64[base64.length - 1] === '=') { + bufferLength--; + if (base64[base64.length - 2] === '=') { + bufferLength--; } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); } + var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); + for (i = 0; i < len; i += 4) { + encoded1 = lookup[base64.charCodeAt(i)]; + encoded2 = lookup[base64.charCodeAt(i + 1)]; + encoded3 = lookup[base64.charCodeAt(i + 2)]; + encoded4 = lookup[base64.charCodeAt(i + 3)]; + bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); + bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); + bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); + } + return arraybuffer; }; - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } + exports.decode = decode; + exports.encode = encode; - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + Object.defineProperty(exports, '__esModule', { value: true }); - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } +}))); - return bound; -}; -},{}],35:[function(require,module,exports){ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = Function.prototype.bind || implementation; - -},{"./implementation":34}],36:[function(require,module,exports){ -'use strict'; - -var undefined; - -var $SyntaxError = SyntaxError; -var $Function = Function; -var $TypeError = TypeError; - -// eslint-disable-next-line consistent-return -var getEvalledConstructor = function (expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); - } catch (e) {} -}; - -var $gOPD = Object.getOwnPropertyDescriptor; -if ($gOPD) { - try { - $gOPD({}, ''); - } catch (e) { - $gOPD = null; // this is IE 8, which has a broken gOPD - } -} - -var throwTypeError = function () { - throw new $TypeError(); -}; -var ThrowTypeError = $gOPD - ? (function () { - try { - // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties - arguments.callee; // IE 8 does not throw here - return throwTypeError; - } catch (calleeThrows) { - try { - // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') - return $gOPD(arguments, 'callee').get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }()) - : throwTypeError; - -var hasSymbols = require('has-symbols')(); - -var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto - -var needsEval = {}; - -var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); - -var INTRINSICS = { - '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, - '%Array%': Array, - '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, - '%AsyncFromSyncIteratorPrototype%': undefined, - '%AsyncFunction%': needsEval, - '%AsyncGenerator%': needsEval, - '%AsyncGeneratorFunction%': needsEval, - '%AsyncIteratorPrototype%': needsEval, - '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, - '%Boolean%': Boolean, - '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '%Date%': Date, - '%decodeURI%': decodeURI, - '%decodeURIComponent%': decodeURIComponent, - '%encodeURI%': encodeURI, - '%encodeURIComponent%': encodeURIComponent, - '%Error%': Error, - '%eval%': eval, // eslint-disable-line no-eval - '%EvalError%': EvalError, - '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, - '%Function%': $Function, - '%GeneratorFunction%': needsEval, - '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '%isFinite%': isFinite, - '%isNaN%': isNaN, - '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, - '%JSON%': typeof JSON === 'object' ? JSON : undefined, - '%Map%': typeof Map === 'undefined' ? undefined : Map, - '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), - '%Math%': Math, - '%Number%': Number, - '%Object%': Object, - '%parseFloat%': parseFloat, - '%parseInt%': parseInt, - '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '%RangeError%': RangeError, - '%ReferenceError%': ReferenceError, - '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '%RegExp%': RegExp, - '%Set%': typeof Set === 'undefined' ? undefined : Set, - '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), - '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '%String%': String, - '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, - '%Symbol%': hasSymbols ? Symbol : undefined, - '%SyntaxError%': $SyntaxError, - '%ThrowTypeError%': ThrowTypeError, - '%TypedArray%': TypedArray, - '%TypeError%': $TypeError, - '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '%URIError%': URIError, - '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, - '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet -}; - -var doEval = function doEval(name) { - var value; - if (name === '%AsyncFunction%') { - value = getEvalledConstructor('async function () {}'); - } else if (name === '%GeneratorFunction%') { - value = getEvalledConstructor('function* () {}'); - } else if (name === '%AsyncGeneratorFunction%') { - value = getEvalledConstructor('async function* () {}'); - } else if (name === '%AsyncGenerator%') { - var fn = doEval('%AsyncGeneratorFunction%'); - if (fn) { - value = fn.prototype; - } - } else if (name === '%AsyncIteratorPrototype%') { - var gen = doEval('%AsyncGenerator%'); - if (gen) { - value = getProto(gen.prototype); - } - } - - INTRINSICS[name] = value; - - return value; -}; - -var LEGACY_ALIASES = { - '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], - '%ArrayPrototype%': ['Array', 'prototype'], - '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], - '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], - '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], - '%ArrayProto_values%': ['Array', 'prototype', 'values'], - '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], - '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], - '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], - '%BooleanPrototype%': ['Boolean', 'prototype'], - '%DataViewPrototype%': ['DataView', 'prototype'], - '%DatePrototype%': ['Date', 'prototype'], - '%ErrorPrototype%': ['Error', 'prototype'], - '%EvalErrorPrototype%': ['EvalError', 'prototype'], - '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], - '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], - '%FunctionPrototype%': ['Function', 'prototype'], - '%Generator%': ['GeneratorFunction', 'prototype'], - '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], - '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], - '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], - '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], - '%JSONParse%': ['JSON', 'parse'], - '%JSONStringify%': ['JSON', 'stringify'], - '%MapPrototype%': ['Map', 'prototype'], - '%NumberPrototype%': ['Number', 'prototype'], - '%ObjectPrototype%': ['Object', 'prototype'], - '%ObjProto_toString%': ['Object', 'prototype', 'toString'], - '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], - '%PromisePrototype%': ['Promise', 'prototype'], - '%PromiseProto_then%': ['Promise', 'prototype', 'then'], - '%Promise_all%': ['Promise', 'all'], - '%Promise_reject%': ['Promise', 'reject'], - '%Promise_resolve%': ['Promise', 'resolve'], - '%RangeErrorPrototype%': ['RangeError', 'prototype'], - '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], - '%RegExpPrototype%': ['RegExp', 'prototype'], - '%SetPrototype%': ['Set', 'prototype'], - '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], - '%StringPrototype%': ['String', 'prototype'], - '%SymbolPrototype%': ['Symbol', 'prototype'], - '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], - '%TypedArrayPrototype%': ['TypedArray', 'prototype'], - '%TypeErrorPrototype%': ['TypeError', 'prototype'], - '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], - '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], - '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], - '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], - '%URIErrorPrototype%': ['URIError', 'prototype'], - '%WeakMapPrototype%': ['WeakMap', 'prototype'], - '%WeakSetPrototype%': ['WeakSet', 'prototype'] -}; - -var bind = require('function-bind'); -var hasOwn = require('has'); -var $concat = bind.call(Function.call, Array.prototype.concat); -var $spliceApply = bind.call(Function.apply, Array.prototype.splice); -var $replace = bind.call(Function.call, String.prototype.replace); -var $strSlice = bind.call(Function.call, String.prototype.slice); - -/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ -var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; -var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ -var stringToPath = function stringToPath(string) { - var first = $strSlice(string, 0, 1); - var last = $strSlice(string, -1); - if (first === '%' && last !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); - } else if (last === '%' && first !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); - } - var result = []; - $replace(string, rePropName, function (match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; - }); - return result; -}; -/* end adaptation */ - -var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { - var intrinsicName = name; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = '%' + alias[0] + '%'; - } - - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === 'undefined' && !allowMissing) { - throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } - - return { - alias: alias, - name: intrinsicName, - value: value - }; - } - - throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); -}; - -module.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== 'string' || name.length === 0) { - throw new $TypeError('intrinsic name must be a non-empty string'); - } - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } - - var parts = stringToPath(name); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; - - var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; - - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } - - for (var i = 1, isOwn = true; i < parts.length; i += 1) { - var part = parts[i]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ( - ( - (first === '"' || first === "'" || first === '`') - || (last === '"' || last === "'" || last === '`') - ) - && first !== last - ) { - throw new $SyntaxError('property names with quotes must have matching quotes'); - } - if (part === 'constructor' || !isOwn) { - skipFurtherCaching = true; - } - - intrinsicBaseName += '.' + part; - intrinsicRealName = '%' + intrinsicBaseName + '%'; - - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); - } - return void undefined; - } - if ($gOPD && (i + 1) >= parts.length) { - var desc = $gOPD(value, part); - isOwn = !!desc; - - // By convention, when a data property is converted to an accessor - // property to emulate a data property that does not suffer from - // the override mistake, that accessor's getter is marked with - // an `originalValue` property. Here, when we detect this, we - // uphold the illusion by pretending to see that original data - // property, i.e., returning the value rather than the getter - // itself. - if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { - value = desc.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } - - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; -}; - -},{"function-bind":35,"has":41,"has-symbols":39}],37:[function(require,module,exports){ -(function (global){(function (){ -var topLevel = typeof global !== 'undefined' ? global : - typeof window !== 'undefined' ? window : {} -var minDoc = require('min-document'); - -var doccy; - -if (typeof document !== 'undefined') { - doccy = document; -} else { - doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; - - if (!doccy) { - doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; - } -} - -module.exports = doccy; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"min-document":152}],38:[function(require,module,exports){ -(function (global){(function (){ -var win; - -if (typeof window !== "undefined") { - win = window; -} else if (typeof global !== "undefined") { - win = global; -} else if (typeof self !== "undefined"){ - win = self; -} else { - win = {}; -} - -module.exports = win; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],39:[function(require,module,exports){ -'use strict'; - -var origSymbol = typeof Symbol !== 'undefined' && Symbol; -var hasSymbolSham = require('./shams'); - -module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== 'function') { return false; } - if (typeof Symbol !== 'function') { return false; } - if (typeof origSymbol('foo') !== 'symbol') { return false; } - if (typeof Symbol('bar') !== 'symbol') { return false; } - - return hasSymbolSham(); -}; - -},{"./shams":40}],40:[function(require,module,exports){ -'use strict'; - -/* eslint complexity: [2, 18], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } - - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } - - if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } - if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } - - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } - - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - - if (typeof Object.getOwnPropertyDescriptor === 'function') { - var descriptor = Object.getOwnPropertyDescriptor(obj, sym); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } - - return true; -}; - -},{}],41:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); - -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); - -},{"function-bind":35}],42:[function(require,module,exports){ -const Output = require('./src/output.js') -const loop = require('raf-loop') -const Source = require('./src/hydra-source.js') -const Mouse = require('./src/lib/mouse.js')() -const Audio = require('./src/lib/audio.js') -const VidRecorder = require('./src/lib/video-recorder.js') -const ArrayUtils = require('./src/lib/array-utils.js') -const Sandbox = require('./src/eval-sandbox.js') - -const Generator = require('./src/generator-factory.js') - -// to do: add ability to pass in certain uniforms and transforms -class HydraRenderer { - - constructor ({ - pb = null, - width = 1280, - height = 720, - numSources = 4, - numOutputs = 4, - makeGlobal = true, - autoLoop = true, - detectAudio = true, - enableStreamCapture = true, - canvas, - precision, - extendTransforms = {} // add your own functions on init - } = {}) { - - ArrayUtils.init() - - this.pb = pb - - this.width = width - this.height = height - this.renderAll = false - this.detectAudio = detectAudio - - this._initCanvas(canvas) - - - // object that contains all properties that will be made available on the global context and during local evaluation - this.synth = { - time: 0, - bpm: 30, - width: this.width, - height: this.height, - fps: undefined, - stats: { - fps: 0 - }, - speed: 1, - mouse: Mouse, - render: this._render.bind(this), - setResolution: this.setResolution.bind(this), - update: (dt) => {},// user defined update function - hush: this.hush.bind(this) - } - - if (makeGlobal) window.loadScript = this.loadScript - - - this.timeSinceLastUpdate = 0 - this._time = 0 // for internal use, only to use for deciding when to render frames - - // only allow valid precision options - let precisionOptions = ['lowp','mediump','highp'] - if(precision && precisionOptions.includes(precision.toLowerCase())) { - this.precision = precision.toLowerCase() - // - // if(!precisionValid){ - // console.warn('[hydra-synth warning]\nConstructor was provided an invalid floating point precision value of "' + precision + '". Using default value of "mediump" instead.') - // } - } else { - let isIOS = - (/iPad|iPhone|iPod/.test(navigator.platform) || - (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) && - !window.MSStream; - this.precision = isIOS ? 'highp' : 'mediump' - } - - - - this.extendTransforms = extendTransforms - - // boolean to store when to save screenshot - this.saveFrame = false - - // if stream capture is enabled, this object contains the capture stream - this.captureStream = null - - this.generator = undefined - - this._initRegl() - this._initOutputs(numOutputs) - this._initSources(numSources) - this._generateGlslTransforms() - - this.synth.screencap = () => { - this.saveFrame = true - } - - if (enableStreamCapture) { - try { - this.captureStream = this.canvas.captureStream(25) - // to do: enable capture stream of specific sources and outputs - this.synth.vidRecorder = new VidRecorder(this.captureStream) - } catch (e) { - console.warn('[hydra-synth warning]\nnew MediaSource() is not currently supported on iOS.') - console.error(e) - } - } - - if(detectAudio) this._initAudio() - - if(autoLoop) loop(this.tick.bind(this)).start() - - // final argument is properties that the user can set, all others are treated as read-only - this.sandbox = new Sandbox(this.synth, makeGlobal, ['speed', 'update', 'bpm', 'fps']) - } - - eval(code) { - this.sandbox.eval(code) - } - - getScreenImage(callback) { - this.imageCallback = callback - this.saveFrame = true - } - - hush() { - this.s.forEach((source) => { - source.clear() - }) - this.o.forEach((output) => { - this.synth.solid(0, 0, 0, 0).out(output) - }) - this.synth.render(this.o[0]) - } - - loadScript(url = "") { - const p = new Promise((res, rej) => { - var script = document.createElement("script"); - script.onload = function () { - console.log(`loaded script ${url}`); - res(); - }; - script.onerror = (err) => { - console.log(`error loading script ${url}`, "log-error"); - res() - }; - script.src = url; - document.head.appendChild(script); - }); - return p; - } - - setResolution(width, height) { - // console.log(width, height) - this.canvas.width = width - this.canvas.height = height - this.width = width // is this necessary? - this.height = height // ? - this.sandbox.set('width', width) - this.sandbox.set('height', height) - console.log(this.width) - this.o.forEach((output) => { - output.resize(width, height) - }) - this.s.forEach((source) => { - source.resize(width, height) - }) - this.regl._refresh() - console.log(this.canvas.width) - } - - canvasToImage (callback) { - const a = document.createElement('a') - a.style.display = 'none' - - let d = new Date() - a.download = `hydra-${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}-${d.getHours()}.${d.getMinutes()}.${d.getSeconds()}.png` - document.body.appendChild(a) - var self = this - this.canvas.toBlob( (blob) => { - if(self.imageCallback){ - self.imageCallback(blob) - delete self.imageCallback - } else { - a.href = URL.createObjectURL(blob) - console.log(a.href) - a.click() - } - }, 'image/png') - setTimeout(() => { - document.body.removeChild(a); - window.URL.revokeObjectURL(a.href); - }, 300); - } - - _initAudio () { - const that = this - this.synth.a = new Audio({ - numBins: 4, - // changeListener: ({audio}) => { - // that.a = audio.bins.map((_, index) => - // (scale = 1, offset = 0) => () => (audio.fft[index] * scale + offset) - // ) - // - // if (that.makeGlobal) { - // that.a.forEach((a, index) => { - // const aname = `a${index}` - // window[aname] = a - // }) - // } - // } - }) - } - - // create main output canvas and add to screen - _initCanvas (canvas) { - if (canvas) { - this.canvas = canvas - this.width = canvas.width - this.height = canvas.height - } else { - this.canvas = document.createElement('canvas') - this.canvas.width = this.width - this.canvas.height = this.height - this.canvas.style.width = '100%' - this.canvas.style.height = '100%' - this.canvas.style.imageRendering = 'pixelated' - document.body.appendChild(this.canvas) - } - } - - _initRegl () { - this.regl = require('regl')({ - // profile: true, - canvas: this.canvas, - pixelRatio: 1//, - // extensions: [ - // 'oes_texture_half_float', - // 'oes_texture_half_float_linear' - // ], - // optionalExtensions: [ - // 'oes_texture_float', - // 'oes_texture_float_linear' - //] - }) - - // This clears the color buffer to black and the depth buffer to 1 - this.regl.clear({ - color: [0, 0, 0, 1] - }) - - this.renderAll = this.regl({ - frag: ` - precision ${this.precision} float; - varying vec2 uv; - uniform sampler2D tex0; - uniform sampler2D tex1; - uniform sampler2D tex2; - uniform sampler2D tex3; - - void main () { - vec2 st = vec2(1.0 - uv.x, uv.y); - st*= vec2(2); - vec2 q = floor(st).xy*(vec2(2.0, 1.0)); - int quad = int(q.x) + int(q.y); - st.x += step(1., mod(st.y,2.0)); - st.y += step(1., mod(st.x,2.0)); - st = fract(st); - if(quad==0){ - gl_FragColor = texture2D(tex0, st); - } else if(quad==1){ - gl_FragColor = texture2D(tex1, st); - } else if (quad==2){ - gl_FragColor = texture2D(tex2, st); - } else { - gl_FragColor = texture2D(tex3, st); - } - - } - `, - vert: ` - precision ${this.precision} float; - attribute vec2 position; - varying vec2 uv; - - void main () { - uv = position; - gl_Position = vec4(1.0 - 2.0 * position, 0, 1); - }`, - attributes: { - position: [ - [-2, 0], - [0, -2], - [2, 2] - ] - }, - uniforms: { - tex0: this.regl.prop('tex0'), - tex1: this.regl.prop('tex1'), - tex2: this.regl.prop('tex2'), - tex3: this.regl.prop('tex3') - }, - count: 3, - depth: { enable: false } - }) - - this.renderFbo = this.regl({ - frag: ` - precision ${this.precision} float; - varying vec2 uv; - uniform vec2 resolution; - uniform sampler2D tex0; - - void main () { - gl_FragColor = texture2D(tex0, vec2(1.0 - uv.x, uv.y)); - } - `, - vert: ` - precision ${this.precision} float; - attribute vec2 position; - varying vec2 uv; - - void main () { - uv = position; - gl_Position = vec4(1.0 - 2.0 * position, 0, 1); - }`, - attributes: { - position: [ - [-2, 0], - [0, -2], - [2, 2] - ] - }, - uniforms: { - tex0: this.regl.prop('tex0'), - resolution: this.regl.prop('resolution') - }, - count: 3, - depth: { enable: false } - }) - } - - _initOutputs (numOutputs) { - const self = this - this.o = (Array(numOutputs)).fill().map((el, index) => { - var o = new Output({ - regl: this.regl, - width: this.width, - height: this.height, - precision: this.precision, - label: `o${index}` - }) - // o.render() - o.id = index - self.synth['o'+index] = o - return o - }) - - // set default output - this.output = this.o[0] - } - - _initSources (numSources) { - this.s = [] - for(var i = 0; i < numSources; i++) { - this.createSource(i) - } - } - - createSource (i) { - let s = new Source({regl: this.regl, pb: this.pb, width: this.width, height: this.height, label: `s${i}`}) - this.synth['s' + this.s.length] = s - this.s.push(s) - return s - } - - _generateGlslTransforms () { - var self = this - this.generator = new Generator({ - defaultOutput: this.o[0], - defaultUniforms: this.o[0].uniforms, - extendTransforms: this.extendTransforms, - changeListener: ({type, method, synth}) => { - if (type === 'add') { - self.synth[method] = synth.generators[method] - if(self.sandbox) self.sandbox.add(method) - } else if (type === 'remove') { - // what to do here? dangerously deleting window methods - //delete window[method] - } - // } - } - }) - this.synth.setFunction = this.generator.setFunction.bind(this.generator) - } - - _render (output) { - if (output) { - this.output = output - this.isRenderingAll = false - } else { - this.isRenderingAll = true - } - } - - // dt in ms - tick (dt, uniforms) { - this.sandbox.tick() - if(this.detectAudio === true) this.synth.a.tick() - // let updateInterval = 1000/this.synth.fps // ms - if(this.synth.update) { - try { this.synth.update(dt) } catch (e) { console.log(error) } - } - - this.sandbox.set('time', this.synth.time += dt * 0.001 * this.synth.speed) - this.timeSinceLastUpdate += dt - if(!this.synth.fps || this.timeSinceLastUpdate >= 1000/this.synth.fps) { - // console.log(1000/this.timeSinceLastUpdate) - this.synth.stats.fps = Math.ceil(1000/this.timeSinceLastUpdate) - // console.log(this.synth.speed, this.synth.time) - for (let i = 0; i < this.s.length; i++) { - this.s[i].tick(this.synth.time) - } - // console.log(this.canvas.width, this.canvas.height) - for (let i = 0; i < this.o.length; i++) { - this.o[i].tick({ - time: this.synth.time, - mouse: this.synth.mouse, - bpm: this.synth.bpm, - resolution: [this.canvas.width, this.canvas.height] - }) - } - if (this.isRenderingAll) { - this.renderAll({ - tex0: this.o[0].getCurrent(), - tex1: this.o[1].getCurrent(), - tex2: this.o[2].getCurrent(), - tex3: this.o[3].getCurrent(), - resolution: [this.canvas.width, this.canvas.height] - }) - } else { - - this.renderFbo({ - tex0: this.output.getCurrent(), - resolution: [this.canvas.width, this.canvas.height] - }) - } - this.timeSinceLastUpdate = 0 - } - if(this.saveFrame === true) { - this.canvasToImage() - this.saveFrame = false - } - // this.regl.poll() - } - - -} - -module.exports = HydraRenderer - -},{"./src/eval-sandbox.js":44,"./src/generator-factory.js":47,"./src/hydra-source.js":51,"./src/lib/array-utils.js":52,"./src/lib/audio.js":53,"./src/lib/mouse.js":56,"./src/lib/video-recorder.js":59,"./src/output.js":61,"raf-loop":161,"regl":163}],43:[function(require,module,exports){ -const Synth = require('./hydra-synth.js') -//const ShaderGenerator = require('./shader-generator.js') - -module.exports = Synth - -},{"./hydra-synth.js":42}],44:[function(require,module,exports){ -// handles code evaluation and attaching relevant objects to global and evaluation contexts - -const Sandbox = require('./lib/sandbox.js') -const ArrayUtils = require('./lib/array-utils.js') - -class EvalSandbox { - constructor(parent, makeGlobal, userProps = []) { - this.makeGlobal = makeGlobal - this.sandbox = Sandbox(parent) - this.parent = parent - var properties = Object.keys(parent) - properties.forEach((property) => this.add(property)) - this.userProps = userProps - } - - add(name) { - if(this.makeGlobal) window[name] = this.parent[name] - this.sandbox.addToContext(name, `parent.${name}`) - } - -// sets on window as well as synth object if global (not needed for objects, which can be set directly) - - set(property, value) { - if(this.makeGlobal) { - window[property] = value - } - this.parent[property] = value - } - - tick() { - if(this.makeGlobal) { - this.userProps.forEach((property) => { - this.parent[property] = window[property] - }) - // this.parent.speed = window.speed - } else { - - } - } - - eval(code) { - this.sandbox.eval(code) - } -} - -module.exports = EvalSandbox - -},{"./lib/array-utils.js":52,"./lib/sandbox.js":57}],45:[function(require,module,exports){ -const arrayUtils = require('./lib/array-utils.js') - -// [WIP] how to treat different dimensions (?) -const DEFAULT_CONVERSIONS = { - float: { - 'vec4': { name: 'sum', args: [[1, 1, 1, 1]] }, - 'vec2': { name: 'sum', args: [[1, 1]] } - } -} - -function fillArrayWithDefaults(arr, len) { - // fill the array with default values if it's too short - while (arr.length < len) { - if (arr.length === 3) { // push a 1 as the default for .a in vec4 - arr.push(1.0) - } else { - arr.push(0.0) - } - } - return arr.slice(0, len) -} - -const ensure_decimal_dot = (val) => { - val = val.toString() - if (val.indexOf('.') < 0) { - val += '.' - } - return val -} - - - -module.exports = function formatArguments(transform, startIndex, synthContext) { - const defaultArgs = transform.transform.inputs - const userArgs = transform.userArgs - const { generators } = transform.synth - const { src } = generators // depends on synth having src() function - return defaultArgs.map((input, index) => { - const typedArg = { - value: input.default, - type: input.type, // - isUniform: false, - name: input.name, - vecLen: 0 - // generateGlsl: null // function for creating glsl - } - - if (typedArg.type === 'float') typedArg.value = ensure_decimal_dot(input.default) - if (input.type.startsWith('vec')) { - try { - typedArg.vecLen = Number.parseInt(input.type.substr(3)) - } catch (e) { - console.log(`Error determining length of vector input type ${input.type} (${input.name})`) - } - } - - // if user has input something for this argument - if (userArgs.length > index) { - typedArg.value = userArgs[index] - // do something if a composite or transform - - if (typeof userArgs[index] === 'function') { - // if (typedArg.vecLen > 0) { // expected input is a vector, not a scalar - // typedArg.value = (context, props, batchId) => (fillArrayWithDefaults(userArgs[index](props), typedArg.vecLen)) - // } else { - typedArg.value = (context, props, batchId) => { - try { - return userArgs[index](props) - } catch (e) { - console.log('ERROR', e) - return input.default - } - } - // } - - typedArg.isUniform = true - } else if (userArgs[index].constructor === Array) { - // if (typedArg.vecLen > 0) { // expected input is a vector, not a scalar - // typedArg.isUniform = true - // typedArg.value = fillArrayWithDefaults(typedArg.value, typedArg.vecLen) - // } else { - // console.log("is Array") - typedArg.value = (context, props, batchId) => arrayUtils.getValue(userArgs[index])(props) - typedArg.isUniform = true - // } - } - } - - if (startIndex < 0) { - } else { - if (typedArg.value && typedArg.value.transforms) { - const final_transform = typedArg.value.transforms[typedArg.value.transforms.length - 1] - - if (final_transform.transform.glsl_return_type !== input.type) { - const defaults = DEFAULT_CONVERSIONS[input.type] - if (typeof defaults !== 'undefined') { - const default_def = defaults[final_transform.transform.glsl_return_type] - if (typeof default_def !== 'undefined') { - const { name, args } = default_def - typedArg.value = typedArg.value[name](...args) - } - } - } - - typedArg.isUniform = false - } else if (typedArg.type === 'float' && typeof typedArg.value === 'number') { - typedArg.value = ensure_decimal_dot(typedArg.value) - } else if (typedArg.type.startsWith('vec') && typeof typedArg.value === 'object' && Array.isArray(typedArg.value)) { - typedArg.isUniform = false - typedArg.value = `${typedArg.type}(${typedArg.value.map(ensure_decimal_dot).join(', ')})` - } else if (input.type === 'sampler2D') { - // typedArg.tex = typedArg.value - var x = typedArg.value - typedArg.value = () => (x.getTexture()) - typedArg.isUniform = true - } else { - // if passing in a texture reference, when function asks for vec4, convert to vec4 - if (typedArg.value.getTexture && input.type === 'vec4') { - var x1 = typedArg.value - typedArg.value = src(x1) - typedArg.isUniform = false - } - } - - // add tp uniform array if is a function that will pass in a different value on each render frame, - // or a texture/ external source - - if (typedArg.isUniform) { - typedArg.name += startIndex - // shaderParams.uniforms.push(typedArg) - } - } - return typedArg - }) -} - - -},{"./lib/array-utils.js":52}],46:[function(require,module,exports){ -const formatArguments = require('./format-arguments.js') - -// Add extra functionality to Array.prototype for generating sequences in time -const arrayUtils = require('./lib/array-utils.js') - - - -// converts a tree of javascript functions to a shader -module.exports = function (transforms) { - var shaderParams = { - uniforms: [], // list of uniforms used in shader - glslFunctions: [], // list of functions used in shader - fragColor: '' - } - - var gen = generateGlsl(transforms, shaderParams)('st') - shaderParams.fragColor = gen - // remove uniforms with duplicate names - let uniforms = {} - shaderParams.uniforms.forEach((uniform) => uniforms[uniform.name] = uniform) - shaderParams.uniforms = Object.values(uniforms) - return shaderParams - -} - - -// recursive function for generating shader string from object containing functions and user arguments. Order of functions in string depends on type of function -// to do: improve variable names -function generateGlsl (transforms, shaderParams) { - // transform function that outputs a shader string corresponding to gl_FragColor - var fragColor = () => '' - // var uniforms = [] - // var glslFunctions = [] - transforms.forEach((transform) => { - var inputs = formatArguments(transform, shaderParams.uniforms.length) - inputs.forEach((input) => { - if(input.isUniform) shaderParams.uniforms.push(input) - }) - - // add new glsl function to running list of functions - if(!contains(transform, shaderParams.glslFunctions)) shaderParams.glslFunctions.push(transform) - - // current function for generating frag color shader code - var f0 = fragColor - if (transform.transform.type === 'src') { - fragColor = (uv) => `${shaderString(uv, transform.name, inputs, shaderParams)}` - } else if (transform.transform.type === 'coord') { - fragColor = (uv) => `${f0(`${shaderString(uv, transform.name, inputs, shaderParams)}`)}` - } else if (transform.transform.type === 'color') { - fragColor = (uv) => `${shaderString(`${f0(uv)}`, transform.name, inputs, shaderParams)}` - } else if (transform.transform.type === 'combine') { - // combining two generated shader strings (i.e. for blend, mult, add funtions) - var f1 = inputs[0].value && inputs[0].value.transforms ? - (uv) => `${generateGlsl(inputs[0].value.transforms, shaderParams)(uv)}` : - (inputs[0].isUniform ? () => inputs[0].name : () => inputs[0].value) - fragColor = (uv) => `${shaderString(`${f0(uv)}, ${f1(uv)}`, transform.name, inputs.slice(1), shaderParams)}` - } else if (transform.transform.type === 'combineCoord') { - // combining two generated shader strings (i.e. for modulate functions) - var f1 = inputs[0].value && inputs[0].value.transforms ? - (uv) => `${generateGlsl(inputs[0].value.transforms, shaderParams)(uv)}` : - (inputs[0].isUniform ? () => inputs[0].name : () => inputs[0].value) - fragColor = (uv) => `${f0(`${shaderString(`${uv}, ${f1(uv)}`, transform.name, inputs.slice(1), shaderParams)}`)}` - - - } - }) -// console.log(fragColor) - // break; - return fragColor -} - -// assembles a shader string containing the arguments and the function name, i.e. 'osc(uv, frequency)' -function shaderString (uv, method, inputs, shaderParams) { - const str = inputs.map((input) => { - if (input.isUniform) { - return input.name - } else if (input.value && input.value.transforms) { - // this by definition needs to be a generator, hence we start with 'st' as the initial value for generating the glsl fragment - return `${generateGlsl(input.value.transforms, shaderParams)('st')}` - } - return input.value - }).reduce((p, c) => `${p}, ${c}`, '') - - return `${method}(${uv}${str})` -} - -// merge two arrays and remove duplicates -function mergeArrays (a, b) { - return a.concat(b.filter(function (item) { - return a.indexOf(item) < 0; - })) -} - -// check whether array -function contains(object, arr) { - for(var i = 0; i < arr.length; i++){ - if(object.name == arr[i].name) return true - } - return false -} - - - - -},{"./format-arguments.js":45,"./lib/array-utils.js":52}],47:[function(require,module,exports){ -const GlslSource = require('./glsl-source.js') - -class GeneratorFactory { - constructor ({ - defaultUniforms, - defaultOutput, - extendTransforms = [], - changeListener = (() => {}) - } = {} - ) { - this.defaultOutput = defaultOutput - this.defaultUniforms = defaultUniforms - this.changeListener = changeListener - this.extendTransforms = extendTransforms - this.generators = {} - this.init() - } - init () { - this.glslTransforms = {} - this.generators = Object.entries(this.generators).reduce((prev, [method, transform]) => { - this.changeListener({type: 'remove', synth: this, method}) - return prev - }, {}) - - this.sourceClass = (() => { - return class extends GlslSource { - } - })() - - let functions = require('./glsl/glsl-functions.js')() - - // add user definied transforms - if (Array.isArray(this.extendTransforms)) { - functions.concat(this.extendTransforms) - } else if (typeof this.extendTransforms === 'object' && this.extendTransforms.type) { - functions.push(this.extendTransforms) - } - - return functions.map((transform) => this.setFunction(transform)) - } - - _addMethod (method, transform) { - const self = this - this.glslTransforms[method] = transform - if (transform.type === 'src') { - const func = (...args) => new this.sourceClass({ - name: method, - transform: transform, - userArgs: args, - defaultOutput: this.defaultOutput, - defaultUniforms: this.defaultUniforms, - synth: self - }) - this.generators[method] = func - this.changeListener({type: 'add', synth: this, method}) - return func - } else { - this.sourceClass.prototype[method] = function (...args) { - this.transforms.push({name: method, transform: transform, userArgs: args, synth: self}) - return this - } - } - return undefined - } - - setFunction(obj) { - var processedGlsl = processGlsl(obj) - if(processedGlsl) this._addMethod(obj.name, processedGlsl) - } -} - -const typeLookup = { - 'src': { - returnType: 'vec4', - args: ['vec2 _st'] - }, - 'coord': { - returnType: 'vec2', - args: ['vec2 _st'] - }, - 'color': { - returnType: 'vec4', - args: ['vec4 _c0'] - }, - 'combine': { - returnType: 'vec4', - args: ['vec4 _c0', 'vec4 _c1'] - }, - 'combineCoord': { - returnType: 'vec2', - args: ['vec2 _st', 'vec4 _c0'] - } -} -// expects glsl of format -// { -// name: 'osc', // name that will be used to access function as well as within glsl -// type: 'src', // can be src: vec4(vec2 _st), coord: vec2(vec2 _st), color: vec4(vec4 _c0), combine: vec4(vec4 _c0, vec4 _c1), combineCoord: vec2(vec2 _st, vec4 _c0) -// inputs: [ -// { -// name: 'freq', -// type: 'float', // 'float' //, 'texture', 'vec4' -// default: 0.2 -// }, -// { -// name: 'sync', -// type: 'float', -// default: 0.1 -// }, -// { -// name: 'offset', -// type: 'float', -// default: 0.0 -// } -// ], - // glsl: ` - // vec2 st = _st; - // float r = sin((st.x-offset*2/freq+time*sync)*freq)*0.5 + 0.5; - // float g = sin((st.x+time*sync)*freq)*0.5 + 0.5; - // float b = sin((st.x+offset/freq+time*sync)*freq)*0.5 + 0.5; - // return vec4(r, g, b, 1.0); - // ` -// } - -// // generates glsl function: -// `vec4 osc(vec2 _st, float freq, float sync, float offset){ -// vec2 st = _st; -// float r = sin((st.x-offset*2/freq+time*sync)*freq)*0.5 + 0.5; -// float g = sin((st.x+time*sync)*freq)*0.5 + 0.5; -// float b = sin((st.x+offset/freq+time*sync)*freq)*0.5 + 0.5; -// return vec4(r, g, b, 1.0); -// }` - -function processGlsl(obj) { - let t = typeLookup[obj.type] - if(t) { - let baseArgs = t.args.map((arg) => arg).join(", ") - // @todo: make sure this works for all input types, add validation - let customArgs = obj.inputs.map((input) => `${input.type} ${input.name}`).join(', ') - let args = `${baseArgs}${customArgs.length > 0 ? ', '+ customArgs: ''}` -// console.log('args are ', args) - - let glslFunction = -` - ${t.returnType} ${obj.name}(${args}) { - ${obj.glsl} - } -` - - // add extra input to beginning for backward combatibility @todo update compiler so this is no longer necessary - if(obj.type === 'combine' || obj.type === 'combineCoord') obj.inputs.unshift({ - name: 'color', - type: 'vec4' - }) - return Object.assign({}, obj, { glsl: glslFunction}) - } else { - console.warn(`type ${obj.type} not recognized`, obj) - } - -} - -module.exports = GeneratorFactory - -},{"./glsl-source.js":48,"./glsl/glsl-functions.js":49}],48:[function(require,module,exports){ -const generateGlsl = require('./generate-glsl.js') -// const formatArguments = require('./glsl-utils.js').formatArguments - -// const glslTransforms = require('./glsl/composable-glsl-functions.js') -const utilityGlsl = require('./glsl/utility-functions.js') - -var GlslSource = function (obj) { - this.transforms = [] - this.transforms.push(obj) - this.defaultOutput = obj.defaultOutput - this.synth = obj.synth - this.type = 'GlslSource' - this.defaultUniforms = obj.defaultUniforms - return this -} - -GlslSource.prototype.addTransform = function (obj) { - this.transforms.push(obj) -} - -GlslSource.prototype.out = function (_output) { - var output = _output || this.defaultOutput - var glsl = this.glsl(output) - this.synth.currentFunctions = [] - // output.renderPasses(glsl) - if(output) try{ - output.render(glsl) - } catch (error) { - console.log('shader could not compile', error) - } -} - -GlslSource.prototype.glsl = function () { - //var output = _output || this.defaultOutput - var self = this - // uniforms included in all shaders -// this.defaultUniforms = output.uniforms - var passes = [] - var transforms = [] -// console.log('output', output) - this.transforms.forEach((transform) => { - if(transform.transform.type === 'renderpass'){ - // if (transforms.length > 0) passes.push(this.compile(transforms, output)) - // transforms = [] - // var uniforms = {} - // const inputs = formatArguments(transform, -1) - // inputs.forEach((uniform) => { uniforms[uniform.name] = uniform.value }) - // - // passes.push({ - // frag: transform.transform.frag, - // uniforms: Object.assign({}, self.defaultUniforms, uniforms) - // }) - // transforms.push({name: 'prev', transform: glslTransforms['prev'], synth: this.synth}) - console.warn('no support for renderpass') - } else { - transforms.push(transform) - } - }) - - if (transforms.length > 0) passes.push(this.compile(transforms)) - - return passes -} - -GlslSource.prototype.compile = function (transforms) { - var shaderInfo = generateGlsl(transforms, this.synth) - var uniforms = {} - shaderInfo.uniforms.forEach((uniform) => { uniforms[uniform.name] = uniform.value }) - - var frag = ` - precision ${this.defaultOutput.precision} float; - ${Object.values(shaderInfo.uniforms).map((uniform) => { - let type = uniform.type - switch (uniform.type) { - case 'texture': - type = 'sampler2D' - break - } - return ` - uniform ${type} ${uniform.name};` - }).join('')} - uniform float time; - uniform vec2 resolution; - varying vec2 uv; - uniform sampler2D prevBuffer; - - ${Object.values(utilityGlsl).map((transform) => { - // console.log(transform.glsl) - return ` - ${transform.glsl} - ` - }).join('')} - - ${shaderInfo.glslFunctions.map((transform) => { - return ` - ${transform.transform.glsl} - ` - }).join('')} - - void main () { - vec4 c = vec4(1, 0, 0, 1); - vec2 st = gl_FragCoord.xy/resolution.xy; - gl_FragColor = ${shaderInfo.fragColor}; - } - ` - - return { - frag: frag, - uniforms: Object.assign({}, this.defaultUniforms, uniforms) - } - -} - -module.exports = GlslSource - -},{"./generate-glsl.js":46,"./glsl/utility-functions.js":50}],49:[function(require,module,exports){ -/* -Format for adding functions to hydra. For each entry in this file, hydra automatically generates a glsl function and javascript function with the same name. You can also ass functions dynamically using setFunction(object). - -{ - name: 'osc', // name that will be used to access function in js as well as in glsl - type: 'src', // can be 'src', 'color', 'combine', 'combineCoords'. see below for more info - inputs: [ - { - name: 'freq', - type: 'float', - default: 0.2 - }, - { - name: 'sync', - type: 'float', - default: 0.1 - }, - { - name: 'offset', - type: 'float', - default: 0.0 - } - ], - glsl: ` - vec2 st = _st; - float r = sin((st.x-offset*2/freq+time*sync)*freq)*0.5 + 0.5; - float g = sin((st.x+time*sync)*freq)*0.5 + 0.5; - float b = sin((st.x+offset/freq+time*sync)*freq)*0.5 + 0.5; - return vec4(r, g, b, 1.0); - ` -} - -// The above code generates the glsl function: -`vec4 osc(vec2 _st, float freq, float sync, float offset){ - vec2 st = _st; - float r = sin((st.x-offset*2/freq+time*sync)*freq)*0.5 + 0.5; - float g = sin((st.x+time*sync)*freq)*0.5 + 0.5; - float b = sin((st.x+offset/freq+time*sync)*freq)*0.5 + 0.5; - return vec4(r, g, b, 1.0); -}` - - -Types and default arguments for hydra functions. -The value in the 'type' field lets the parser know which type the function will be returned as well as default arguments. - -const types = { - 'src': { - returnType: 'vec4', - args: ['vec2 _st'] - }, - 'coord': { - returnType: 'vec2', - args: ['vec2 _st'] - }, - 'color': { - returnType: 'vec4', - args: ['vec4 _c0'] - }, - 'combine': { - returnType: 'vec4', - args: ['vec4 _c0', 'vec4 _c1'] - }, - 'combineCoord': { - returnType: 'vec2', - args: ['vec2 _st', 'vec4 _c0'] - } -} - -*/ - -module.exports = () => [ - { - name: 'noise', - type: 'src', - inputs: [ - { - type: 'float', - name: 'scale', - default: 10, - }, -{ - type: 'float', - name: 'offset', - default: 0.1, - } - ], - glsl: -` return vec4(vec3(_noise(vec3(_st*scale, offset*time))), 1.0);` -}, -{ - name: 'voronoi', - type: 'src', - inputs: [ - { - type: 'float', - name: 'scale', - default: 5, - }, -{ - type: 'float', - name: 'speed', - default: 0.3, - }, -{ - type: 'float', - name: 'blending', - default: 0.3, - } - ], - glsl: -` vec3 color = vec3(.0); - // Scale - _st *= scale; - // Tile the space - vec2 i_st = floor(_st); - vec2 f_st = fract(_st); - float m_dist = 10.; // minimun distance - vec2 m_point; // minimum point - for (int j=-1; j<=1; j++ ) { - for (int i=-1; i<=1; i++ ) { - vec2 neighbor = vec2(float(i),float(j)); - vec2 p = i_st + neighbor; - vec2 point = fract(sin(vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3))))*43758.5453); - point = 0.5 + 0.5*sin(time*speed + 6.2831*point); - vec2 diff = neighbor + point - f_st; - float dist = length(diff); - if( dist < m_dist ) { - m_dist = dist; - m_point = point; - } - } - } - // Assign a color using the closest point position - color += dot(m_point,vec2(.3,.6)); - color *= 1.0 - blending*m_dist; - return vec4(color, 1.0);` -}, -{ - name: 'osc', - type: 'src', - inputs: [ - { - type: 'float', - name: 'frequency', - default: 60, - }, -{ - type: 'float', - name: 'sync', - default: 0.1, - }, -{ - type: 'float', - name: 'offset', - default: 0, - } - ], - glsl: -` vec2 st = _st; - float r = sin((st.x-offset/frequency+time*sync)*frequency)*0.5 + 0.5; - float g = sin((st.x+time*sync)*frequency)*0.5 + 0.5; - float b = sin((st.x+offset/frequency+time*sync)*frequency)*0.5 + 0.5; - return vec4(r, g, b, 1.0);` -}, -{ - name: 'shape', - type: 'src', - inputs: [ - { - type: 'float', - name: 'sides', - default: 3, - }, -{ - type: 'float', - name: 'radius', - default: 0.3, - }, -{ - type: 'float', - name: 'smoothing', - default: 0.01, - } - ], - glsl: -` vec2 st = _st * 2. - 1.; - // Angle and radius from the current pixel - float a = atan(st.x,st.y)+3.1416; - float r = (2.*3.1416)/sides; - float d = cos(floor(.5+a/r)*r-a)*length(st); - return vec4(vec3(1.0-smoothstep(radius,radius + smoothing + 0.0000001,d)), 1.0);` -}, -{ - name: 'gradient', - type: 'src', - inputs: [ - { - type: 'float', - name: 'speed', - default: 0, - } - ], - glsl: -` return vec4(_st, sin(time*speed), 1.0);` -}, -{ - name: 'src', - type: 'src', - inputs: [ - { - type: 'sampler2D', - name: 'tex', - default: NaN, - } - ], - glsl: -` // vec2 uv = gl_FragCoord.xy/vec2(1280., 720.); - return texture2D(tex, fract(_st));` -}, -{ - name: 'solid', - type: 'src', - inputs: [ - { - type: 'float', - name: 'r', - default: 0, - }, -{ - type: 'float', - name: 'g', - default: 0, - }, -{ - type: 'float', - name: 'b', - default: 0, - }, -{ - type: 'float', - name: 'a', - default: 1, - } - ], - glsl: -` return vec4(r, g, b, a);` -}, -{ - name: 'rotate', - type: 'coord', - inputs: [ - { - type: 'float', - name: 'angle', - default: 10, - }, -{ - type: 'float', - name: 'speed', - default: 0, - } - ], - glsl: -` vec2 xy = _st - vec2(0.5); - float ang = angle + speed *time; - xy = mat2(cos(ang),-sin(ang), sin(ang),cos(ang))*xy; - xy += 0.5; - return xy;` -}, -{ - name: 'scale', - type: 'coord', - inputs: [ - { - type: 'float', - name: 'amount', - default: 1.5, - }, -{ - type: 'float', - name: 'xMult', - default: 1, - }, -{ - type: 'float', - name: 'yMult', - default: 1, - }, -{ - type: 'float', - name: 'offsetX', - default: 0.5, - }, -{ - type: 'float', - name: 'offsetY', - default: 0.5, - } - ], - glsl: -` vec2 xy = _st - vec2(offsetX, offsetY); - xy*=(1.0/vec2(amount*xMult, amount*yMult)); - xy+=vec2(offsetX, offsetY); - return xy; - ` -}, -{ - name: 'pixelate', - type: 'coord', - inputs: [ - { - type: 'float', - name: 'pixelX', - default: 20, - }, -{ - type: 'float', - name: 'pixelY', - default: 20, - } - ], - glsl: -` vec2 xy = vec2(pixelX, pixelY); - return (floor(_st * xy) + 0.5)/xy;` -}, -{ - name: 'posterize', - type: 'color', - inputs: [ - { - type: 'float', - name: 'bins', - default: 3, - }, -{ - type: 'float', - name: 'gamma', - default: 0.6, - } - ], - glsl: -` vec4 c2 = pow(_c0, vec4(gamma)); - c2 *= vec4(bins); - c2 = floor(c2); - c2/= vec4(bins); - c2 = pow(c2, vec4(1.0/gamma)); - return vec4(c2.xyz, _c0.a);` -}, -{ - name: 'shift', - type: 'color', - inputs: [ - { - type: 'float', - name: 'r', - default: 0.5, - }, -{ - type: 'float', - name: 'g', - default: 0, - }, -{ - type: 'float', - name: 'b', - default: 0, - }, -{ - type: 'float', - name: 'a', - default: 0, - } - ], - glsl: -` vec4 c2 = vec4(_c0); - c2.r = fract(c2.r + r); - c2.g = fract(c2.g + g); - c2.b = fract(c2.b + b); - c2.a = fract(c2.a + a); - return vec4(c2.rgba);` -}, -{ - name: 'repeat', - type: 'coord', - inputs: [ - { - type: 'float', - name: 'repeatX', - default: 3, - }, -{ - type: 'float', - name: 'repeatY', - default: 3, - }, -{ - type: 'float', - name: 'offsetX', - default: 0, - }, -{ - type: 'float', - name: 'offsetY', - default: 0, - } - ], - glsl: -` vec2 st = _st * vec2(repeatX, repeatY); - st.x += step(1., mod(st.y,2.0)) * offsetX; - st.y += step(1., mod(st.x,2.0)) * offsetY; - return fract(st);` -}, -{ - name: 'modulateRepeat', - type: 'combineCoord', - inputs: [ - { - type: 'float', - name: 'repeatX', - default: 3, - }, -{ - type: 'float', - name: 'repeatY', - default: 3, - }, -{ - type: 'float', - name: 'offsetX', - default: 0.5, - }, -{ - type: 'float', - name: 'offsetY', - default: 0.5, - } - ], - glsl: -` vec2 st = _st * vec2(repeatX, repeatY); - st.x += step(1., mod(st.y,2.0)) + _c0.r * offsetX; - st.y += step(1., mod(st.x,2.0)) + _c0.g * offsetY; - return fract(st);` -}, -{ - name: 'repeatX', - type: 'coord', - inputs: [ - { - type: 'float', - name: 'reps', - default: 3, - }, -{ - type: 'float', - name: 'offset', - default: 0, - } - ], - glsl: -` vec2 st = _st * vec2(reps, 1.0); - // float f = mod(_st.y,2.0); - st.y += step(1., mod(st.x,2.0))* offset; - return fract(st);` -}, -{ - name: 'modulateRepeatX', - type: 'combineCoord', - inputs: [ - { - type: 'float', - name: 'reps', - default: 3, - }, -{ - type: 'float', - name: 'offset', - default: 0.5, - } - ], - glsl: -` vec2 st = _st * vec2(reps, 1.0); - // float f = mod(_st.y,2.0); - st.y += step(1., mod(st.x,2.0)) + _c0.r * offset; - return fract(st);` -}, -{ - name: 'repeatY', - type: 'coord', - inputs: [ - { - type: 'float', - name: 'reps', - default: 3, - }, -{ - type: 'float', - name: 'offset', - default: 0, - } - ], - glsl: -` vec2 st = _st * vec2(1.0, reps); - // float f = mod(_st.y,2.0); - st.x += step(1., mod(st.y,2.0))* offset; - return fract(st);` -}, -{ - name: 'modulateRepeatY', - type: 'combineCoord', - inputs: [ - { - type: 'float', - name: 'reps', - default: 3, - }, -{ - type: 'float', - name: 'offset', - default: 0.5, - } - ], - glsl: -` vec2 st = _st * vec2(reps, 1.0); - // float f = mod(_st.y,2.0); - st.x += step(1., mod(st.y,2.0)) + _c0.r * offset; - return fract(st);` -}, -{ - name: 'kaleid', - type: 'coord', - inputs: [ - { - type: 'float', - name: 'nSides', - default: 4, - } - ], - glsl: -` vec2 st = _st; - st -= 0.5; - float r = length(st); - float a = atan(st.y, st.x); - float pi = 2.*3.1416; - a = mod(a,pi/nSides); - a = abs(a-pi/nSides/2.); - return r*vec2(cos(a), sin(a));` -}, -{ - name: 'modulateKaleid', - type: 'combineCoord', - inputs: [ - { - type: 'float', - name: 'nSides', - default: 4, - } - ], - glsl: -` vec2 st = _st - 0.5; - float r = length(st); - float a = atan(st.y, st.x); - float pi = 2.*3.1416; - a = mod(a,pi/nSides); - a = abs(a-pi/nSides/2.); - return (_c0.r+r)*vec2(cos(a), sin(a));` -}, -{ - name: 'scroll', - type: 'coord', - inputs: [ - { - type: 'float', - name: 'scrollX', - default: 0.5, - }, -{ - type: 'float', - name: 'scrollY', - default: 0.5, - }, -{ - type: 'float', - name: 'speedX', - default: 0, - }, -{ - type: 'float', - name: 'speedY', - default: 0, - } - ], - glsl: -` - _st.x += scrollX + time*speedX; - _st.y += scrollY + time*speedY; - return fract(_st);` -}, -{ - name: 'scrollX', - type: 'coord', - inputs: [ - { - type: 'float', - name: 'scrollX', - default: 0.5, - }, -{ - type: 'float', - name: 'speed', - default: 0, - } - ], - glsl: -` _st.x += scrollX + time*speed; - return fract(_st);` -}, -{ - name: 'modulateScrollX', - type: 'combineCoord', - inputs: [ - { - type: 'float', - name: 'scrollX', - default: 0.5, - }, -{ - type: 'float', - name: 'speed', - default: 0, - } - ], - glsl: -` _st.x += _c0.r*scrollX + time*speed; - return fract(_st);` -}, -{ - name: 'scrollY', - type: 'coord', - inputs: [ - { - type: 'float', - name: 'scrollY', - default: 0.5, - }, -{ - type: 'float', - name: 'speed', - default: 0, - } - ], - glsl: -` _st.y += scrollY + time*speed; - return fract(_st);` -}, -{ - name: 'modulateScrollY', - type: 'combineCoord', - inputs: [ - { - type: 'float', - name: 'scrollY', - default: 0.5, - }, -{ - type: 'float', - name: 'speed', - default: 0, - } - ], - glsl: -` _st.y += _c0.r*scrollY + time*speed; - return fract(_st);` -}, -{ - name: 'add', - type: 'combine', - inputs: [ - { - type: 'float', - name: 'amount', - default: 1, - } - ], - glsl: -` return (_c0+_c1)*amount + _c0*(1.0-amount);` -}, -{ - name: 'sub', - type: 'combine', - inputs: [ - { - type: 'float', - name: 'amount', - default: 1, - } - ], - glsl: -` return (_c0-_c1)*amount + _c0*(1.0-amount);` -}, -{ - name: 'layer', - type: 'combine', - inputs: [ - - ], - glsl: -` return vec4(mix(_c0.rgb, _c1.rgb, _c1.a), clamp(_c0.a + _c1.a, 0.0, 1.0));` -}, -{ - name: 'blend', - type: 'combine', - inputs: [ - { - type: 'float', - name: 'amount', - default: 0.5, - } - ], - glsl: -` return _c0*(1.0-amount)+_c1*amount;` -}, -{ - name: 'mult', - type: 'combine', - inputs: [ - { - type: 'float', - name: 'amount', - default: 1, - } - ], - glsl: -` return _c0*(1.0-amount)+(_c0*_c1)*amount;` -}, -{ - name: 'diff', - type: 'combine', - inputs: [ - - ], - glsl: -` return vec4(abs(_c0.rgb-_c1.rgb), max(_c0.a, _c1.a));` -}, -{ - name: 'modulate', - type: 'combineCoord', - inputs: [ - { - type: 'float', - name: 'amount', - default: 0.1, - } - ], - glsl: -` // return fract(st+(_c0.xy-0.5)*amount); - return _st + _c0.xy*amount;` -}, -{ - name: 'modulateScale', - type: 'combineCoord', - inputs: [ - { - type: 'float', - name: 'multiple', - default: 1, - }, -{ - type: 'float', - name: 'offset', - default: 1, - } - ], - glsl: -` vec2 xy = _st - vec2(0.5); - xy*=(1.0/vec2(offset + multiple*_c0.r, offset + multiple*_c0.g)); - xy+=vec2(0.5); - return xy;` -}, -{ - name: 'modulatePixelate', - type: 'combineCoord', - inputs: [ - { - type: 'float', - name: 'multiple', - default: 10, - }, -{ - type: 'float', - name: 'offset', - default: 3, - } - ], - glsl: -` vec2 xy = vec2(offset + _c0.x*multiple, offset + _c0.y*multiple); - return (floor(_st * xy) + 0.5)/xy;` -}, -{ - name: 'modulateRotate', - type: 'combineCoord', - inputs: [ - { - type: 'float', - name: 'multiple', - default: 1, - }, -{ - type: 'float', - name: 'offset', - default: 0, - } - ], - glsl: -` vec2 xy = _st - vec2(0.5); - float angle = offset + _c0.x * multiple; - xy = mat2(cos(angle),-sin(angle), sin(angle),cos(angle))*xy; - xy += 0.5; - return xy;` -}, -{ - name: 'modulateHue', - type: 'combineCoord', - inputs: [ - { - type: 'float', - name: 'amount', - default: 1, - } - ], - glsl: -` return _st + (vec2(_c0.g - _c0.r, _c0.b - _c0.g) * amount * 1.0/resolution);` -}, -{ - name: 'invert', - type: 'color', - inputs: [ - { - type: 'float', - name: 'amount', - default: 1, - } - ], - glsl: -` return vec4((1.0-_c0.rgb)*amount + _c0.rgb*(1.0-amount), _c0.a);` -}, -{ - name: 'contrast', - type: 'color', - inputs: [ - { - type: 'float', - name: 'amount', - default: 1.6, - } - ], - glsl: -` vec4 c = (_c0-vec4(0.5))*vec4(amount) + vec4(0.5); - return vec4(c.rgb, _c0.a);` -}, -{ - name: 'brightness', - type: 'color', - inputs: [ - { - type: 'float', - name: 'amount', - default: 0.4, - } - ], - glsl: -` return vec4(_c0.rgb + vec3(amount), _c0.a);` -}, -{ - name: 'mask', - type: 'combine', - inputs: [ - - ], - glsl: - ` float a = _luminance(_c1.rgb); - return vec4(_c0.rgb*a, a*_c0.a);` -}, - -{ - name: 'luma', - type: 'color', - inputs: [ - { - type: 'float', - name: 'threshold', - default: 0.5, - }, -{ - type: 'float', - name: 'tolerance', - default: 0.1, - } - ], - glsl: -` float a = smoothstep(threshold-(tolerance+0.0000001), threshold+(tolerance+0.0000001), _luminance(_c0.rgb)); - return vec4(_c0.rgb*a, a);` -}, -{ - name: 'thresh', - type: 'color', - inputs: [ - { - type: 'float', - name: 'threshold', - default: 0.5, - }, -{ - type: 'float', - name: 'tolerance', - default: 0.04, - } - ], - glsl: -` return vec4(vec3(smoothstep(threshold-(tolerance+0.0000001), threshold+(tolerance+0.0000001), _luminance(_c0.rgb))), _c0.a);` -}, -{ - name: 'color', - type: 'color', - inputs: [ - { - type: 'float', - name: 'r', - default: 1, - }, -{ - type: 'float', - name: 'g', - default: 1, - }, -{ - type: 'float', - name: 'b', - default: 1, - }, -{ - type: 'float', - name: 'a', - default: 1, - } - ], - glsl: -` vec4 c = vec4(r, g, b, a); - vec4 pos = step(0.0, c); // detect whether negative - // if > 0, return r * _c0 - // if < 0 return (1.0-r) * _c0 - return vec4(mix((1.0-_c0)*abs(c), c*_c0, pos));` -}, -{ - name: 'saturate', - type: 'color', - inputs: [ - { - type: 'float', - name: 'amount', - default: 2, - } - ], - glsl: -` const vec3 W = vec3(0.2125, 0.7154, 0.0721); - vec3 intensity = vec3(dot(_c0.rgb, W)); - return vec4(mix(intensity, _c0.rgb, amount), _c0.a);` -}, -{ - name: 'hue', - type: 'color', - inputs: [ - { - type: 'float', - name: 'hue', - default: 0.4, - } - ], - glsl: -` vec3 c = _rgbToHsv(_c0.rgb); - c.r += hue; - // c.r = fract(c.r); - return vec4(_hsvToRgb(c), _c0.a);` -}, -{ - name: 'colorama', - type: 'color', - inputs: [ - { - type: 'float', - name: 'amount', - default: 0.005, - } - ], - glsl: -` vec3 c = _rgbToHsv(_c0.rgb); - c += vec3(amount); - c = _hsvToRgb(c); - c = fract(c); - return vec4(c, _c0.a);` -}, -{ - name: 'prev', - type: 'src', - inputs: [ - - ], - glsl: -` return texture2D(prevBuffer, fract(_st));` -}, -{ - name: 'sum', - type: 'color', - inputs: [ - { - type: 'vec4', - name: 'scale', - default: 1, - } - ], - glsl: -` vec4 v = _c0 * s; - return v.r + v.g + v.b + v.a; - } - float sum(vec2 _st, vec4 s) { // vec4 is not a typo, because argument type is not overloaded - vec2 v = _st.xy * s.xy; - return v.x + v.y;` -}, -{ - name: 'r', - type: 'color', - inputs: [ - { - type: 'float', - name: 'scale', - default: 1, - }, -{ - type: 'float', - name: 'offset', - default: 0, - } - ], - glsl: -` return vec4(_c0.r * scale + offset);` -}, -{ - name: 'g', - type: 'color', - inputs: [ - { - type: 'float', - name: 'scale', - default: 1, - }, -{ - type: 'float', - name: 'offset', - default: 0, - } - ], - glsl: -` return vec4(_c0.g * scale + offset);` -}, -{ - name: 'b', - type: 'color', - inputs: [ - { - type: 'float', - name: 'scale', - default: 1, - }, -{ - type: 'float', - name: 'offset', - default: 0, - } - ], - glsl: -` return vec4(_c0.b * scale + offset);` -}, -{ - name: 'a', - type: 'color', - inputs: [ - { - type: 'float', - name: 'scale', - default: 1, - }, -{ - type: 'float', - name: 'offset', - default: 0, - } - ], - glsl: -` return vec4(_c0.a * scale + offset);` -} -] - -},{}],50:[function(require,module,exports){ -// functions that are only used within other functions - -module.exports = { - _luminance: { - type: 'util', - glsl: `float _luminance(vec3 rgb){ - const vec3 W = vec3(0.2125, 0.7154, 0.0721); - return dot(rgb, W); - }` - }, - _noise: { - type: 'util', - glsl: ` - // Simplex 3D Noise - // by Ian McEwan, Ashima Arts - vec4 permute(vec4 x){return mod(((x*34.0)+1.0)*x, 289.0);} - vec4 taylorInvSqrt(vec4 r){return 1.79284291400159 - 0.85373472095314 * r;} - - float _noise(vec3 v){ - const vec2 C = vec2(1.0/6.0, 1.0/3.0) ; - const vec4 D = vec4(0.0, 0.5, 1.0, 2.0); - - // First corner - vec3 i = floor(v + dot(v, C.yyy) ); - vec3 x0 = v - i + dot(i, C.xxx) ; - - // Other corners - vec3 g = step(x0.yzx, x0.xyz); - vec3 l = 1.0 - g; - vec3 i1 = min( g.xyz, l.zxy ); - vec3 i2 = max( g.xyz, l.zxy ); - - // x0 = x0 - 0. + 0.0 * C - vec3 x1 = x0 - i1 + 1.0 * C.xxx; - vec3 x2 = x0 - i2 + 2.0 * C.xxx; - vec3 x3 = x0 - 1. + 3.0 * C.xxx; - - // Permutations - i = mod(i, 289.0 ); - vec4 p = permute( permute( permute( - i.z + vec4(0.0, i1.z, i2.z, 1.0 )) - + i.y + vec4(0.0, i1.y, i2.y, 1.0 )) - + i.x + vec4(0.0, i1.x, i2.x, 1.0 )); - - // Gradients - // ( N*N points uniformly over a square, mapped onto an octahedron.) - float n_ = 1.0/7.0; // N=7 - vec3 ns = n_ * D.wyz - D.xzx; - - vec4 j = p - 49.0 * floor(p * ns.z *ns.z); // mod(p,N*N) - - vec4 x_ = floor(j * ns.z); - vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N) - - vec4 x = x_ *ns.x + ns.yyyy; - vec4 y = y_ *ns.x + ns.yyyy; - vec4 h = 1.0 - abs(x) - abs(y); - - vec4 b0 = vec4( x.xy, y.xy ); - vec4 b1 = vec4( x.zw, y.zw ); - - vec4 s0 = floor(b0)*2.0 + 1.0; - vec4 s1 = floor(b1)*2.0 + 1.0; - vec4 sh = -step(h, vec4(0.0)); - - vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ; - vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ; - - vec3 p0 = vec3(a0.xy,h.x); - vec3 p1 = vec3(a0.zw,h.y); - vec3 p2 = vec3(a1.xy,h.z); - vec3 p3 = vec3(a1.zw,h.w); - - //Normalise gradients - vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3))); - p0 *= norm.x; - p1 *= norm.y; - p2 *= norm.z; - p3 *= norm.w; - - // Mix final noise value - vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0); - m = m * m; - return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1), - dot(p2,x2), dot(p3,x3) ) ); - } - ` - }, - - - _rgbToHsv: { - type: 'util', - glsl: `vec3 _rgbToHsv(vec3 c){ - vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); - vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)); - vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); - - float d = q.x - min(q.w, q.y); - float e = 1.0e-10; - return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); - }` - }, - _hsvToRgb: { - type: 'util', - glsl: `vec3 _hsvToRgb(vec3 c){ - vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); - vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); - return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); - }` - } -} - -},{}],51:[function(require,module,exports){ -const Webcam = require('./lib/webcam.js') -const Screen = require('./lib/screenmedia.js') - -class HydraSource { - constructor ({ regl, width, height, pb, label = ""}) { - this.label = label - this.regl = regl - this.src = null - this.dynamic = true - this.width = width - this.height = height - this.tex = this.regl.texture({ - // shape: [width, height] - shape: [ 1, 1 ] - }) - this.pb = pb - } - - init (opts, params) { - if ('src' in opts) { - this.src = opts.src - this.tex = this.regl.texture({ data: this.src, ...params }) - } - if ('dynamic' in opts) this.dynamic = opts.dynamic - } - - initCam (index, params) { - const self = this - Webcam(index) - .then(response => { - self.src = response.video - self.dynamic = true - self.tex = self.regl.texture({ data: self.src, ...params }) - }) - .catch(err => console.log('could not get camera', err)) - } - - initVideo (url = '', params) { - // const self = this - const vid = document.createElement('video') - vid.crossOrigin = 'anonymous' - vid.autoplay = true - vid.loop = true - vid.muted = true // mute in order to load without user interaction - const onload = vid.addEventListener('loadeddata', () => { - this.src = vid - vid.play() - this.tex = this.regl.texture({ data: this.src, ...params}) - this.dynamic = true - }) - vid.src = url - } - - initImage (url = '', params) { - const img = document.createElement('img') - img.crossOrigin = 'anonymous' - img.src = url - img.onload = () => { - this.src = img - this.dynamic = false - this.tex = this.regl.texture({ data: this.src, ...params}) - } - } - - initStream (streamName, params) { - // console.log("initing stream!", streamName) - let self = this - if (streamName && this.pb) { - this.pb.initSource(streamName) - - this.pb.on('got video', function (nick, video) { - if (nick === streamName) { - self.src = video - self.dynamic = true - self.tex = self.regl.texture({ data: self.src, ...params}) - } - }) - } - } - - // index only relevant in atom-hydra + desktop apps - initScreen (index = 0, params) { - const self = this - Screen() - .then(function (response) { - self.src = response.video - self.tex = self.regl.texture({ data: self.src, ...params}) - self.dynamic = true - // console.log("received screen input") - }) - .catch(err => console.log('could not get screen', err)) - } - - resize (width, height) { - this.width = width - this.height = height - } - - clear () { - if (this.src && this.src.srcObject) { - if (this.src.srcObject.getTracks) { - this.src.srcObject.getTracks().forEach(track => track.stop()) - } - } - this.src = null - this.tex = this.regl.texture({ shape: [ 1, 1 ] }) - } - - tick (time) { - // console.log(this.src, this.tex.width, this.tex.height) - if (this.src !== null && this.dynamic === true) { - if (this.src.videoWidth && this.src.videoWidth !== this.tex.width) { - console.log( - this.src.videoWidth, - this.src.videoHeight, - this.tex.width, - this.tex.height - ) - this.tex.resize(this.src.videoWidth, this.src.videoHeight) - } - - if (this.src.width && this.src.width !== this.tex.width) { - this.tex.resize(this.src.width, this.src.height) - } - - this.tex.subimage(this.src) - } - } - - getTexture () { - return this.tex - } -} - -module.exports = HydraSource - -},{"./lib/screenmedia.js":58,"./lib/webcam.js":60}],52:[function(require,module,exports){ -// WIP utils for working with arrays -// Possibly should be integrated with lfo extension, etc. -// to do: transform time rather than array values, similar to working with coordinates in hydra - -var easing = require('./easing-functions.js') - -var map = (num, in_min, in_max, out_min, out_max) => { - return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; -} - -module.exports = { - init: () => { - - Array.prototype.fast = function(speed = 1) { - this._speed = speed - return this - } - - Array.prototype.smooth = function(smooth = 1) { - this._smooth = smooth - return this - } - - Array.prototype.ease = function(ease = 'linear') { - if (typeof ease == 'function') { - this._smooth = 1 - this._ease = ease - } - else if (easing[ease]){ - this._smooth = 1 - this._ease = easing[ease] - } - return this - } - - Array.prototype.offset = function(offset = 0.5) { - this._offset = offset%1.0 - return this - } - - // Array.prototype.bounce = function() { - // this.modifiers.bounce = true - // return this - // } - - Array.prototype.fit = function(low = 0, high =1) { - let lowest = Math.min(...this) - let highest = Math.max(...this) - var newArr = this.map((num) => map(num, lowest, highest, low, high)) - newArr._speed = this._speed - newArr._smooth = this._smooth - newArr._ease = this._ease - return newArr - } - }, - - getValue: (arr = []) => ({time, bpm}) =>{ - let speed = arr._speed ? arr._speed : 1 - let smooth = arr._smooth ? arr._smooth : 0 - let index = time * speed * (bpm / 60) + (arr._offset || 0) - - if (smooth!==0) { - let ease = arr._ease ? arr._ease : easing['linear'] - let _index = index - (smooth / 2) - let currValue = arr[Math.floor(_index % (arr.length))] - let nextValue = arr[Math.floor((_index + 1) % (arr.length))] - let t = Math.min((_index%1)/smooth,1) - return ease(t) * (nextValue - currValue) + currValue - } - else { - return arr[Math.floor(index % (arr.length))] - } - } -} - -},{"./easing-functions.js":54}],53:[function(require,module,exports){ -const Meyda = require('meyda') - -class Audio { - constructor ({ - numBins = 4, - cutoff = 2, - smooth = 0.4, - max = 15, - scale = 10, - isDrawing = false - }) { - this.vol = 0 - this.scale = scale - this.max = max - this.cutoff = cutoff - this.smooth = smooth - this.setBins(numBins) - - // beat detection from: https://github.com/therewasaguy/p5-music-viz/blob/gh-pages/demos/01d_beat_detect_amplitude/sketch.js - this.beat = { - holdFrames: 20, - threshold: 40, - _cutoff: 0, // adaptive based on sound state - decay: 0.98, - _framesSinceBeat: 0 // keeps track of frames - } - - this.onBeat = () => { - // console.log("beat") - } - - this.canvas = document.createElement('canvas') - this.canvas.width = 100 - this.canvas.height = 80 - this.canvas.style.width = "100px" - this.canvas.style.height = "80px" - this.canvas.style.position = 'absolute' - this.canvas.style.right = '0px' - this.canvas.style.bottom = '0px' - document.body.appendChild(this.canvas) - - this.isDrawing = isDrawing - this.ctx = this.canvas.getContext('2d') - this.ctx.fillStyle="#DFFFFF" - this.ctx.strokeStyle="#0ff" - this.ctx.lineWidth=0.5 - if(window.navigator.mediaDevices) { - window.navigator.mediaDevices.getUserMedia({video: false, audio: true}) - .then((stream) => { - // console.log('got mic stream', stream) - this.stream = stream - this.context = new AudioContext() - // this.context = new AudioContext() - let audio_stream = this.context.createMediaStreamSource(stream) - - // console.log(this.context) - this.meyda = Meyda.createMeydaAnalyzer({ - audioContext: this.context, - source: audio_stream, - featureExtractors: [ - 'loudness', - // 'perceptualSpread', - // 'perceptualSharpness', - // 'spectralCentroid' - ] - }) - }) - .catch((err) => console.log('ERROR', err)) - } - } - - detectBeat (level) { - //console.log(level, this.beat._cutoff) - if (level > this.beat._cutoff && level > this.beat.threshold) { - this.onBeat() - this.beat._cutoff = level *1.2 - this.beat._framesSinceBeat = 0 - } else { - if (this.beat._framesSinceBeat <= this.beat.holdFrames){ - this.beat._framesSinceBeat ++; - } else { - this.beat._cutoff *= this.beat.decay - this.beat._cutoff = Math.max( this.beat._cutoff, this.beat.threshold); - } - } - } - - tick() { - if(this.meyda){ - var features = this.meyda.get() - if(features && features !== null){ - this.vol = features.loudness.total - this.detectBeat(this.vol) - // reduce loudness array to number of bins - const reducer = (accumulator, currentValue) => accumulator + currentValue; - let spacing = Math.floor(features.loudness.specific.length/this.bins.length) - this.prevBins = this.bins.slice(0) - this.bins = this.bins.map((bin, index) => { - return features.loudness.specific.slice(index * spacing, (index + 1)*spacing).reduce(reducer) - }).map((bin, index) => { - // map to specified range - - // return (bin * (1.0 - this.smooth) + this.prevBins[index] * this.smooth) - return (bin * (1.0 - this.settings[index].smooth) + this.prevBins[index] * this.settings[index].smooth) - }) - // var y = this.canvas.height - scale*this.settings[index].cutoff - // this.ctx.beginPath() - // this.ctx.moveTo(index*spacing, y) - // this.ctx.lineTo((index+1)*spacing, y) - // this.ctx.stroke() - // - // var yMax = this.canvas.height - scale*(this.settings[index].scale + this.settings[index].cutoff) - this.fft = this.bins.map((bin, index) => ( - // Math.max(0, (bin - this.cutoff) / (this.max - this.cutoff)) - Math.max(0, (bin - this.settings[index].cutoff)/this.settings[index].scale) - )) - if(this.isDrawing) this.draw() - } - } - } - - setCutoff (cutoff) { - this.cutoff = cutoff - this.settings = this.settings.map((el) => { - el.cutoff = cutoff - return el - }) - } - - setSmooth (smooth) { - this.smooth = smooth - this.settings = this.settings.map((el) => { - el.smooth = smooth - return el - }) - } - - setBins (numBins) { - this.bins = Array(numBins).fill(0) - this.prevBins = Array(numBins).fill(0) - this.fft = Array(numBins).fill(0) - this.settings = Array(numBins).fill(0).map(() => ({ - cutoff: this.cutoff, - scale: this.scale, - smooth: this.smooth - })) - // to do: what to do in non-global mode? - this.bins.forEach((bin, index) => { - window['a' + index] = (scale = 1, offset = 0) => () => (a.fft[index] * scale + offset) - }) - // console.log(this.settings) - } - - setScale(scale){ - this.scale = scale - this.settings = this.settings.map((el) => { - el.scale = scale - return el - }) - } - - setMax(max) { - this.max = max - console.log('set max is deprecated') - } - hide() { - this.isDrawing = false - this.canvas.style.display = 'none' - } - - show() { - this.isDrawing = true - this.canvas.style.display = 'block' - - } - - draw () { - this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height) - var spacing = this.canvas.width / this.bins.length - var scale = this.canvas.height / (this.max * 2) - // console.log(this.bins) - this.bins.forEach((bin, index) => { - - var height = bin * scale - - this.ctx.fillRect(index * spacing, this.canvas.height - height, spacing, height) - - // console.log(this.settings[index]) - var y = this.canvas.height - scale*this.settings[index].cutoff - this.ctx.beginPath() - this.ctx.moveTo(index*spacing, y) - this.ctx.lineTo((index+1)*spacing, y) - this.ctx.stroke() - - var yMax = this.canvas.height - scale*(this.settings[index].scale + this.settings[index].cutoff) - this.ctx.beginPath() - this.ctx.moveTo(index*spacing, yMax) - this.ctx.lineTo((index+1)*spacing, yMax) - this.ctx.stroke() - }) - - - /*var y = this.canvas.height - scale*this.cutoff - this.ctx.beginPath() - this.ctx.moveTo(0, y) - this.ctx.lineTo(this.canvas.width, y) - this.ctx.stroke() - var yMax = this.canvas.height - scale*this.max - this.ctx.beginPath() - this.ctx.moveTo(0, yMax) - this.ctx.lineTo(this.canvas.width, yMax) - this.ctx.stroke()*/ - } -} - -module.exports = Audio - -},{"meyda":157}],54:[function(require,module,exports){ -// from https://gist.github.com/gre/1650294 - -module.exports = { - // no easing, no acceleration - linear: function (t) { return t }, - // accelerating from zero velocity - easeInQuad: function (t) { return t*t }, - // decelerating to zero velocity - easeOutQuad: function (t) { return t*(2-t) }, - // acceleration until halfway, then deceleration - easeInOutQuad: function (t) { return t<.5 ? 2*t*t : -1+(4-2*t)*t }, - // accelerating from zero velocity - easeInCubic: function (t) { return t*t*t }, - // decelerating to zero velocity - easeOutCubic: function (t) { return (--t)*t*t+1 }, - // acceleration until halfway, then deceleration - easeInOutCubic: function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1 }, - // accelerating from zero velocity - easeInQuart: function (t) { return t*t*t*t }, - // decelerating to zero velocity - easeOutQuart: function (t) { return 1-(--t)*t*t*t }, - // acceleration until halfway, then deceleration - easeInOutQuart: function (t) { return t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t }, - // accelerating from zero velocity - easeInQuint: function (t) { return t*t*t*t*t }, - // decelerating to zero velocity - easeOutQuint: function (t) { return 1+(--t)*t*t*t*t }, - // acceleration until halfway, then deceleration - easeInOutQuint: function (t) { return t<.5 ? 16*t*t*t*t*t : 1+16*(--t)*t*t*t*t }, - // sin shape - sin: function (t) { return (1 + Math.sin(Math.PI*t-Math.PI/2))/2 } -} - -},{}],55:[function(require,module,exports){ -// https://github.com/mikolalysenko/mouse-event - -'use strict' - -function mouseButtons(ev) { - if(typeof ev === 'object') { - if('buttons' in ev) { - return ev.buttons - } else if('which' in ev) { - var b = ev.which - if(b === 2) { - return 4 - } else if(b === 3) { - return 2 - } else if(b > 0) { - return 1<<(b-1) - } - } else if('button' in ev) { - var b = ev.button - if(b === 1) { - return 4 - } else if(b === 2) { - return 2 - } else if(b >= 0) { - return 1< { - var initialCode = `` - - var sandbox = createSandbox(initialCode) - - var addToContext = (name, object) => { - initialCode += ` - var ${name} = ${object} - ` - sandbox = createSandbox(initialCode) - } - - - return { - addToContext: addToContext, - eval: (code) => sandbox.eval(code) - } - - function createSandbox (initial) { - eval(initial) - // optional params - var localEval = function (code) { - eval(code) - } - - // API/data for end-user - return { - eval: localEval - } - } -} - -},{}],58:[function(require,module,exports){ - -module.exports = function (options) { - return new Promise(function(resolve, reject) { - // async function startCapture(displayMediaOptions) { - navigator.mediaDevices.getDisplayMedia(options).then((stream) => { - const video = document.createElement('video') - video.srcObject = stream - video.addEventListener('loadedmetadata', () => { - video.play() - resolve({video: video}) - }) - }).catch((err) => reject(err)) - }) -} - -},{}],59:[function(require,module,exports){ -class VideoRecorder { - constructor(stream) { - this.mediaSource = new MediaSource() - this.stream = stream - - // testing using a recording as input - this.output = document.createElement('video') - this.output.autoplay = true - this.output.loop = true - - let self = this - this.mediaSource.addEventListener('sourceopen', () => { - console.log('MediaSource opened'); - self.sourceBuffer = self.mediaSource.addSourceBuffer('video/webm; codecs="vp8"'); - console.log('Source buffer: ', sourceBuffer); - }) - } - - start() { - // let options = {mimeType: 'video/webm'}; - -// let options = {mimeType: 'video/webm;codecs=h264'}; - let options = {mimeType: 'video/webm;codecs=vp9'}; - - this.recordedBlobs = [] - try { - this.mediaRecorder = new MediaRecorder(this.stream, options) - } catch (e0) { - console.log('Unable to create MediaRecorder with options Object: ', e0) - try { - options = {mimeType: 'video/webm,codecs=vp9'} - this.mediaRecorder = new MediaRecorder(this.stream, options) - } catch (e1) { - console.log('Unable to create MediaRecorder with options Object: ', e1) - try { - options = 'video/vp8' // Chrome 47 - this.mediaRecorder = new MediaRecorder(this.stream, options) - } catch (e2) { - alert('MediaRecorder is not supported by this browser.\n\n' + - 'Try Firefox 29 or later, or Chrome 47 or later, ' + - 'with Enable experimental Web Platform features enabled from chrome://flags.') - console.error('Exception while creating MediaRecorder:', e2) - return - } - } - } - console.log('Created MediaRecorder', this.mediaRecorder, 'with options', options); - this.mediaRecorder.onstop = this._handleStop.bind(this) - this.mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this) - this.mediaRecorder.start(100) // collect 100ms of data - console.log('MediaRecorder started', this.mediaRecorder) - } - - - stop(){ - this.mediaRecorder.stop() - } - - _handleStop() { - //const superBuffer = new Blob(recordedBlobs, {type: 'video/webm'}) - // const blob = new Blob(this.recordedBlobs, {type: 'video/webm;codecs=h264'}) - const blob = new Blob(this.recordedBlobs, {type: this.mediaRecorder.mimeType}) - const url = window.URL.createObjectURL(blob) - this.output.src = url - - const a = document.createElement('a') - a.style.display = 'none' - a.href = url - let d = new Date() - a.download = `hydra-${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}-${d.getHours()}.${d.getMinutes()}.${d.getSeconds()}.webm` - document.body.appendChild(a) - a.click() - setTimeout(() => { - document.body.removeChild(a); - window.URL.revokeObjectURL(url); - }, 300); - } - - _handleDataAvailable(event) { - if (event.data && event.data.size > 0) { - this.recordedBlobs.push(event.data); - } - } -} - -module.exports = VideoRecorder - -},{}],60:[function(require,module,exports){ -//const enumerateDevices = require('enumerate-devices') - -module.exports = function (deviceId) { - return navigator.mediaDevices.enumerateDevices() - .then(devices => devices.filter(devices => devices.kind === 'videoinput')) - .then(cameras => { - let constraints = { audio: false, video: true} - if (cameras[deviceId]) { - constraints['video'] = { - deviceId: { exact: cameras[deviceId].deviceId } - } - } - // console.log(cameras) - return window.navigator.mediaDevices.getUserMedia(constraints) - }) - .then(stream => { - const video = document.createElement('video') - video.setAttribute('autoplay', '') - video.setAttribute('muted', '') - video.setAttribute('playsinline', '') - // video.src = window.URL.createObjectURL(stream) - video.srcObject = stream - return new Promise((resolve, reject) => { - video.addEventListener('loadedmetadata', () => { - video.play().then(() => resolve({video: video})) - }) - }) - }) - .catch(console.log.bind(console)) -} - -},{}],61:[function(require,module,exports){ -//const transforms = require('./glsl-transforms.js') - -var Output = function ({ regl, precision, label = "", width, height}) { - this.regl = regl - this.precision = precision - this.label = label - this.positionBuffer = this.regl.buffer([ - [-2, 0], - [0, -2], - [2, 2] - ]) - - this.draw = () => {} - this.init() - this.pingPongIndex = 0 - - // for each output, create two fbos for pingponging - this.fbos = (Array(2)).fill().map(() => this.regl.framebuffer({ - color: this.regl.texture({ - mag: 'nearest', - width: width, - height: height, - format: 'rgba' - }), - depthStencil: false - })) - - // array containing render passes -// this.passes = [] -} - -Output.prototype.resize = function(width, height) { - this.fbos.forEach((fbo) => { - fbo.resize(width, height) - }) -// console.log(this) -} - - -Output.prototype.getCurrent = function () { - return this.fbos[this.pingPongIndex] -} - -Output.prototype.getTexture = function () { - var index = this.pingPongIndex ? 0 : 1 - return this.fbos[index] -} - -Output.prototype.init = function () { -// console.log('clearing') - this.transformIndex = 0 - this.fragHeader = ` - precision ${this.precision} float; - - uniform float time; - varying vec2 uv; - ` - - this.fragBody = `` - - this.vert = ` - precision ${this.precision} float; - attribute vec2 position; - varying vec2 uv; - - void main () { - uv = position; - gl_Position = vec4(2.0 * position - 1.0, 0, 1); - }` - - this.attributes = { - position: this.positionBuffer - } - this.uniforms = { - time: this.regl.prop('time'), - resolution: this.regl.prop('resolution') - } - - this.frag = ` - ${this.fragHeader} - - void main () { - vec4 c = vec4(0, 0, 0, 0); - vec2 st = uv; - ${this.fragBody} - gl_FragColor = c; - } - ` - return this -} - - -Output.prototype.render = function (passes) { - let pass = passes[0] - //console.log('pass', pass, this.pingPongIndex) - var self = this - var uniforms = Object.assign(pass.uniforms, { prevBuffer: () => { - //var index = this.pingPongIndex ? 0 : 1 - // var index = self.pingPong[(passIndex+1)%2] - // console.log('ping pong', self.pingPongIndex) - return self.fbos[self.pingPongIndex] - } - }) - - self.draw = self.regl({ - frag: pass.frag, - vert: self.vert, - attributes: self.attributes, - uniforms: uniforms, - count: 3, - framebuffer: () => { - self.pingPongIndex = self.pingPongIndex ? 0 : 1 - return self.fbos[self.pingPongIndex] - } - }) -} - - -Output.prototype.tick = function (props) { -// console.log(props) - this.draw(props) -} - -module.exports = Output - -},{}],62:[function(require,module,exports){ -module.exports = attributeToProperty - -var transform = { - 'class': 'className', - 'for': 'htmlFor', - 'http-equiv': 'httpEquiv' -} - -function attributeToProperty (h) { - return function (tagName, attrs, children) { - for (var attr in attrs) { - if (attr in transform) { - attrs[transform[attr]] = attrs[attr] - delete attrs[attr] - } - } - return h(tagName, attrs, children) - } -} - -},{}],63:[function(require,module,exports){ -var attrToProp = require('hyperscript-attribute-to-property') - -var VAR = 0, TEXT = 1, OPEN = 2, CLOSE = 3, ATTR = 4 -var ATTR_KEY = 5, ATTR_KEY_W = 6 -var ATTR_VALUE_W = 7, ATTR_VALUE = 8 -var ATTR_VALUE_SQ = 9, ATTR_VALUE_DQ = 10 -var ATTR_EQ = 11, ATTR_BREAK = 12 -var COMMENT = 13 - -module.exports = function (h, opts) { - if (!opts) opts = {} - var concat = opts.concat || function (a, b) { - return String(a) + String(b) - } - if (opts.attrToProp !== false) { - h = attrToProp(h) - } - - return function (strings) { - var state = TEXT, reg = '' - var arglen = arguments.length - var parts = [] - - for (var i = 0; i < strings.length; i++) { - if (i < arglen - 1) { - var arg = arguments[i+1] - var p = parse(strings[i]) - var xstate = state - if (xstate === ATTR_VALUE_DQ) xstate = ATTR_VALUE - if (xstate === ATTR_VALUE_SQ) xstate = ATTR_VALUE - if (xstate === ATTR_VALUE_W) xstate = ATTR_VALUE - if (xstate === ATTR) xstate = ATTR_KEY - if (xstate === OPEN) { - if (reg === '/') { - p.push([ OPEN, '/', arg ]) - reg = '' - } else { - p.push([ OPEN, arg ]) - } - } else if (xstate === COMMENT && opts.comments) { - reg += String(arg) - } else if (xstate !== COMMENT) { - p.push([ VAR, xstate, arg ]) - } - parts.push.apply(parts, p) - } else parts.push.apply(parts, parse(strings[i])) - } - - var tree = [null,{},[]] - var stack = [[tree,-1]] - for (var i = 0; i < parts.length; i++) { - var cur = stack[stack.length-1][0] - var p = parts[i], s = p[0] - if (s === OPEN && /^\//.test(p[1])) { - var ix = stack[stack.length-1][1] - if (stack.length > 1) { - stack.pop() - stack[stack.length-1][0][2][ix] = h( - cur[0], cur[1], cur[2].length ? cur[2] : undefined - ) - } - } else if (s === OPEN) { - var c = [p[1],{},[]] - cur[2].push(c) - stack.push([c,cur[2].length-1]) - } else if (s === ATTR_KEY || (s === VAR && p[1] === ATTR_KEY)) { - var key = '' - var copyKey - for (; i < parts.length; i++) { - if (parts[i][0] === ATTR_KEY) { - key = concat(key, parts[i][1]) - } else if (parts[i][0] === VAR && parts[i][1] === ATTR_KEY) { - if (typeof parts[i][2] === 'object' && !key) { - for (copyKey in parts[i][2]) { - if (parts[i][2].hasOwnProperty(copyKey) && !cur[1][copyKey]) { - cur[1][copyKey] = parts[i][2][copyKey] - } - } - } else { - key = concat(key, parts[i][2]) - } - } else break - } - if (parts[i][0] === ATTR_EQ) i++ - var j = i - for (; i < parts.length; i++) { - if (parts[i][0] === ATTR_VALUE || parts[i][0] === ATTR_KEY) { - if (!cur[1][key]) cur[1][key] = strfn(parts[i][1]) - else parts[i][1]==="" || (cur[1][key] = concat(cur[1][key], parts[i][1])); - } else if (parts[i][0] === VAR - && (parts[i][1] === ATTR_VALUE || parts[i][1] === ATTR_KEY)) { - if (!cur[1][key]) cur[1][key] = strfn(parts[i][2]) - else parts[i][2]==="" || (cur[1][key] = concat(cur[1][key], parts[i][2])); - } else { - if (key.length && !cur[1][key] && i === j - && (parts[i][0] === CLOSE || parts[i][0] === ATTR_BREAK)) { - // https://html.spec.whatwg.org/multipage/infrastructure.html#boolean-attributes - // empty string is falsy, not well behaved value in browser - cur[1][key] = key.toLowerCase() - } - if (parts[i][0] === CLOSE) { - i-- - } - break - } - } - } else if (s === ATTR_KEY) { - cur[1][p[1]] = true - } else if (s === VAR && p[1] === ATTR_KEY) { - cur[1][p[2]] = true - } else if (s === CLOSE) { - if (selfClosing(cur[0]) && stack.length) { - var ix = stack[stack.length-1][1] - stack.pop() - stack[stack.length-1][0][2][ix] = h( - cur[0], cur[1], cur[2].length ? cur[2] : undefined - ) - } - } else if (s === VAR && p[1] === TEXT) { - if (p[2] === undefined || p[2] === null) p[2] = '' - else if (!p[2]) p[2] = concat('', p[2]) - if (Array.isArray(p[2][0])) { - cur[2].push.apply(cur[2], p[2]) - } else { - cur[2].push(p[2]) - } - } else if (s === TEXT) { - cur[2].push(p[1]) - } else if (s === ATTR_EQ || s === ATTR_BREAK) { - // no-op - } else { - throw new Error('unhandled: ' + s) - } - } - - if (tree[2].length > 1 && /^\s*$/.test(tree[2][0])) { - tree[2].shift() - } - - if (tree[2].length > 2 - || (tree[2].length === 2 && /\S/.test(tree[2][1]))) { - if (opts.createFragment) return opts.createFragment(tree[2]) - throw new Error( - 'multiple root elements must be wrapped in an enclosing tag' - ) - } - if (Array.isArray(tree[2][0]) && typeof tree[2][0][0] === 'string' - && Array.isArray(tree[2][0][2])) { - tree[2][0] = h(tree[2][0][0], tree[2][0][1], tree[2][0][2]) - } - return tree[2][0] - - function parse (str) { - var res = [] - if (state === ATTR_VALUE_W) state = ATTR - for (var i = 0; i < str.length; i++) { - var c = str.charAt(i) - if (state === TEXT && c === '<') { - if (reg.length) res.push([TEXT, reg]) - reg = '' - state = OPEN - } else if (c === '>' && !quot(state) && state !== COMMENT) { - if (state === OPEN && reg.length) { - res.push([OPEN,reg]) - } else if (state === ATTR_KEY) { - res.push([ATTR_KEY,reg]) - } else if (state === ATTR_VALUE && reg.length) { - res.push([ATTR_VALUE,reg]) - } - res.push([CLOSE]) - reg = '' - state = TEXT - } else if (state === COMMENT && /-$/.test(reg) && c === '-') { - if (opts.comments) { - res.push([ATTR_VALUE,reg.substr(0, reg.length - 1)]) - } - reg = '' - state = TEXT - } else if (state === OPEN && /^!--$/.test(reg)) { - if (opts.comments) { - res.push([OPEN, reg],[ATTR_KEY,'comment'],[ATTR_EQ]) - } - reg = c - state = COMMENT - } else if (state === TEXT || state === COMMENT) { - reg += c - } else if (state === OPEN && c === '/' && reg.length) { - // no-op, self closing tag without a space
- } else if (state === OPEN && /\s/.test(c)) { - if (reg.length) { - res.push([OPEN, reg]) - } - reg = '' - state = ATTR - } else if (state === OPEN) { - reg += c - } else if (state === ATTR && /[^\s"'=/]/.test(c)) { - state = ATTR_KEY - reg = c - } else if (state === ATTR && /\s/.test(c)) { - if (reg.length) res.push([ATTR_KEY,reg]) - res.push([ATTR_BREAK]) - } else if (state === ATTR_KEY && /\s/.test(c)) { - res.push([ATTR_KEY,reg]) - reg = '' - state = ATTR_KEY_W - } else if (state === ATTR_KEY && c === '=') { - res.push([ATTR_KEY,reg],[ATTR_EQ]) - reg = '' - state = ATTR_VALUE_W - } else if (state === ATTR_KEY) { - reg += c - } else if ((state === ATTR_KEY_W || state === ATTR) && c === '=') { - res.push([ATTR_EQ]) - state = ATTR_VALUE_W - } else if ((state === ATTR_KEY_W || state === ATTR) && !/\s/.test(c)) { - res.push([ATTR_BREAK]) - if (/[\w-]/.test(c)) { - reg += c - state = ATTR_KEY - } else state = ATTR - } else if (state === ATTR_VALUE_W && c === '"') { - state = ATTR_VALUE_DQ - } else if (state === ATTR_VALUE_W && c === "'") { - state = ATTR_VALUE_SQ - } else if (state === ATTR_VALUE_DQ && c === '"') { - res.push([ATTR_VALUE,reg],[ATTR_BREAK]) - reg = '' - state = ATTR - } else if (state === ATTR_VALUE_SQ && c === "'") { - res.push([ATTR_VALUE,reg],[ATTR_BREAK]) - reg = '' - state = ATTR - } else if (state === ATTR_VALUE_W && !/\s/.test(c)) { - state = ATTR_VALUE - i-- - } else if (state === ATTR_VALUE && /\s/.test(c)) { - res.push([ATTR_VALUE,reg],[ATTR_BREAK]) - reg = '' - state = ATTR - } else if (state === ATTR_VALUE || state === ATTR_VALUE_SQ - || state === ATTR_VALUE_DQ) { - reg += c - } - } - if (state === TEXT && reg.length) { - res.push([TEXT,reg]) - reg = '' - } else if (state === ATTR_VALUE && reg.length) { - res.push([ATTR_VALUE,reg]) - reg = '' - } else if (state === ATTR_VALUE_DQ && reg.length) { - res.push([ATTR_VALUE,reg]) - reg = '' - } else if (state === ATTR_VALUE_SQ && reg.length) { - res.push([ATTR_VALUE,reg]) - reg = '' - } else if (state === ATTR_KEY) { - res.push([ATTR_KEY,reg]) - reg = '' - } - return res - } - } - - function strfn (x) { - if (typeof x === 'function') return x - else if (typeof x === 'string') return x - else if (x && typeof x === 'object') return x - else if (x === null || x === undefined) return x - else return concat('', x) - } -} - -function quot (state) { - return state === ATTR_VALUE_SQ || state === ATTR_VALUE_DQ -} - -var closeRE = RegExp('^(' + [ - 'area', 'base', 'basefont', 'bgsound', 'br', 'col', 'command', 'embed', - 'frame', 'hr', 'img', 'input', 'isindex', 'keygen', 'link', 'meta', 'param', - 'source', 'track', 'wbr', '!--', - // SVG TAGS - 'animate', 'animateTransform', 'circle', 'cursor', 'desc', 'ellipse', - 'feBlend', 'feColorMatrix', 'feComposite', - 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', - 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', - 'feGaussianBlur', 'feImage', 'feMergeNode', 'feMorphology', - 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', - 'feTurbulence', 'font-face-format', 'font-face-name', 'font-face-uri', - 'glyph', 'glyphRef', 'hkern', 'image', 'line', 'missing-glyph', 'mpath', - 'path', 'polygon', 'polyline', 'rect', 'set', 'stop', 'tref', 'use', 'view', - 'vkern' -].join('|') + ')(?:[\.#][a-zA-Z0-9\u007F-\uFFFF_:-]+)*$') -function selfClosing (tag) { return closeRE.test(tag) } - -},{"hyperscript-attribute-to-property":62}],64:[function(require,module,exports){ -/*jshint node:true */ -/* globals define */ -/* - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. - -*/ - -'use strict'; - -/** -The following batches are equivalent: - -var beautify_js = require('js-beautify'); -var beautify_js = require('js-beautify').js; -var beautify_js = require('js-beautify').js_beautify; - -var beautify_css = require('js-beautify').css; -var beautify_css = require('js-beautify').css_beautify; - -var beautify_html = require('js-beautify').html; -var beautify_html = require('js-beautify').html_beautify; - -All methods returned accept two arguments, the source string and an options object. -**/ - -function get_beautify(js_beautify, css_beautify, html_beautify) { - // the default is js - var beautify = function(src, config) { - return js_beautify.js_beautify(src, config); - }; - - // short aliases - beautify.js = js_beautify.js_beautify; - beautify.css = css_beautify.css_beautify; - beautify.html = html_beautify.html_beautify; - - // legacy aliases - beautify.js_beautify = js_beautify.js_beautify; - beautify.css_beautify = css_beautify.css_beautify; - beautify.html_beautify = html_beautify.html_beautify; - - return beautify; -} - -if (typeof define === "function" && define.amd) { - // Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- ) - define([ - "./lib/beautify", - "./lib/beautify-css", - "./lib/beautify-html" - ], function(js_beautify, css_beautify, html_beautify) { - return get_beautify(js_beautify, css_beautify, html_beautify); - }); -} else { - (function(mod) { - var beautifier = require('./src/index'); - beautifier.js_beautify = beautifier.js; - beautifier.css_beautify = beautifier.css; - beautifier.html_beautify = beautifier.html; - - mod.exports = get_beautify(beautifier, beautifier, beautifier); - - })(module); -} -},{"./src/index":82}],65:[function(require,module,exports){ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -'use strict'; - -function Directives(start_block_pattern, end_block_pattern) { - start_block_pattern = typeof start_block_pattern === 'string' ? start_block_pattern : start_block_pattern.source; - end_block_pattern = typeof end_block_pattern === 'string' ? end_block_pattern : end_block_pattern.source; - this.__directives_block_pattern = new RegExp(start_block_pattern + / beautify( \w+[:]\w+)+ /.source + end_block_pattern, 'g'); - this.__directive_pattern = / (\w+)[:](\w+)/g; - - this.__directives_end_ignore_pattern = new RegExp(start_block_pattern + /\sbeautify\signore:end\s/.source + end_block_pattern, 'g'); -} - -Directives.prototype.get_directives = function(text) { - if (!text.match(this.__directives_block_pattern)) { - return null; - } - - var directives = {}; - this.__directive_pattern.lastIndex = 0; - var directive_match = this.__directive_pattern.exec(text); - - while (directive_match) { - directives[directive_match[1]] = directive_match[2]; - directive_match = this.__directive_pattern.exec(text); - } - - return directives; -}; - -Directives.prototype.readIgnored = function(input) { - return input.readUntilAfter(this.__directives_end_ignore_pattern); -}; - - -module.exports.Directives = Directives; - -},{}],66:[function(require,module,exports){ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -'use strict'; - -var regexp_has_sticky = RegExp.prototype.hasOwnProperty('sticky'); - -function InputScanner(input_string) { - this.__input = input_string || ''; - this.__input_length = this.__input.length; - this.__position = 0; -} - -InputScanner.prototype.restart = function() { - this.__position = 0; -}; - -InputScanner.prototype.back = function() { - if (this.__position > 0) { - this.__position -= 1; - } -}; - -InputScanner.prototype.hasNext = function() { - return this.__position < this.__input_length; -}; - -InputScanner.prototype.next = function() { - var val = null; - if (this.hasNext()) { - val = this.__input.charAt(this.__position); - this.__position += 1; - } - return val; -}; - -InputScanner.prototype.peek = function(index) { - var val = null; - index = index || 0; - index += this.__position; - if (index >= 0 && index < this.__input_length) { - val = this.__input.charAt(index); - } - return val; -}; - -// This is a JavaScript only helper function (not in python) -// Javascript doesn't have a match method -// and not all implementation support "sticky" flag. -// If they do not support sticky then both this.match() and this.test() method -// must get the match and check the index of the match. -// If sticky is supported and set, this method will use it. -// Otherwise it will check that global is set, and fall back to the slower method. -InputScanner.prototype.__match = function(pattern, index) { - pattern.lastIndex = index; - var pattern_match = pattern.exec(this.__input); - - if (pattern_match && !(regexp_has_sticky && pattern.sticky)) { - if (pattern_match.index !== index) { - pattern_match = null; - } - } - - return pattern_match; -}; - -InputScanner.prototype.test = function(pattern, index) { - index = index || 0; - index += this.__position; - - if (index >= 0 && index < this.__input_length) { - return !!this.__match(pattern, index); - } else { - return false; - } -}; - -InputScanner.prototype.testChar = function(pattern, index) { - // test one character regex match - var val = this.peek(index); - pattern.lastIndex = 0; - return val !== null && pattern.test(val); -}; - -InputScanner.prototype.match = function(pattern) { - var pattern_match = this.__match(pattern, this.__position); - if (pattern_match) { - this.__position += pattern_match[0].length; - } else { - pattern_match = null; - } - return pattern_match; -}; - -InputScanner.prototype.read = function(starting_pattern, until_pattern, until_after) { - var val = ''; - var match; - if (starting_pattern) { - match = this.match(starting_pattern); - if (match) { - val += match[0]; - } - } - if (until_pattern && (match || !starting_pattern)) { - val += this.readUntil(until_pattern, until_after); - } - return val; -}; - -InputScanner.prototype.readUntil = function(pattern, until_after) { - var val = ''; - var match_index = this.__position; - pattern.lastIndex = this.__position; - var pattern_match = pattern.exec(this.__input); - if (pattern_match) { - match_index = pattern_match.index; - if (until_after) { - match_index += pattern_match[0].length; - } - } else { - match_index = this.__input_length; - } - - val = this.__input.substring(this.__position, match_index); - this.__position = match_index; - return val; -}; - -InputScanner.prototype.readUntilAfter = function(pattern) { - return this.readUntil(pattern, true); -}; - -InputScanner.prototype.get_regexp = function(pattern, match_from) { - var result = null; - var flags = 'g'; - if (match_from && regexp_has_sticky) { - flags = 'y'; - } - // strings are converted to regexp - if (typeof pattern === "string" && pattern !== '') { - // result = new RegExp(pattern.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), flags); - result = new RegExp(pattern, flags); - } else if (pattern) { - result = new RegExp(pattern.source, flags); - } - return result; -}; - -InputScanner.prototype.get_literal_regexp = function(literal_string) { - return RegExp(literal_string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')); -}; - -/* css beautifier legacy helpers */ -InputScanner.prototype.peekUntilAfter = function(pattern) { - var start = this.__position; - var val = this.readUntilAfter(pattern); - this.__position = start; - return val; -}; - -InputScanner.prototype.lookBack = function(testVal) { - var start = this.__position - 1; - return start >= testVal.length && this.__input.substring(start - testVal.length, start) - .toLowerCase() === testVal; -}; - -module.exports.InputScanner = InputScanner; - -},{}],67:[function(require,module,exports){ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -'use strict'; - -function Options(options, merge_child_field) { - this.raw_options = _mergeOpts(options, merge_child_field); - - // Support passing the source text back with no change - this.disabled = this._get_boolean('disabled'); - - this.eol = this._get_characters('eol', 'auto'); - this.end_with_newline = this._get_boolean('end_with_newline'); - this.indent_size = this._get_number('indent_size', 4); - this.indent_char = this._get_characters('indent_char', ' '); - this.indent_level = this._get_number('indent_level'); - - this.preserve_newlines = this._get_boolean('preserve_newlines', true); - this.max_preserve_newlines = this._get_number('max_preserve_newlines', 32786); - if (!this.preserve_newlines) { - this.max_preserve_newlines = 0; - } - - this.indent_with_tabs = this._get_boolean('indent_with_tabs', this.indent_char === '\t'); - if (this.indent_with_tabs) { - this.indent_char = '\t'; - - // indent_size behavior changed after 1.8.6 - // It used to be that indent_size would be - // set to 1 for indent_with_tabs. That is no longer needed and - // actually doesn't make sense - why not use spaces? Further, - // that might produce unexpected behavior - tabs being used - // for single-column alignment. So, when indent_with_tabs is true - // and indent_size is 1, reset indent_size to 4. - if (this.indent_size === 1) { - this.indent_size = 4; - } - } - - // Backwards compat with 1.3.x - this.wrap_line_length = this._get_number('wrap_line_length', this._get_number('max_char')); - - this.indent_empty_lines = this._get_boolean('indent_empty_lines'); - - // valid templating languages ['django', 'erb', 'handlebars', 'php', 'smarty'] - // For now, 'auto' = all off for javascript, all on for html (and inline javascript). - // other values ignored - this.templating = this._get_selection_list('templating', ['auto', 'none', 'django', 'erb', 'handlebars', 'php', 'smarty'], ['auto']); -} - -Options.prototype._get_array = function(name, default_value) { - var option_value = this.raw_options[name]; - var result = default_value || []; - if (typeof option_value === 'object') { - if (option_value !== null && typeof option_value.concat === 'function') { - result = option_value.concat(); - } - } else if (typeof option_value === 'string') { - result = option_value.split(/[^a-zA-Z0-9_\/\-]+/); - } - return result; -}; - -Options.prototype._get_boolean = function(name, default_value) { - var option_value = this.raw_options[name]; - var result = option_value === undefined ? !!default_value : !!option_value; - return result; -}; - -Options.prototype._get_characters = function(name, default_value) { - var option_value = this.raw_options[name]; - var result = default_value || ''; - if (typeof option_value === 'string') { - result = option_value.replace(/\\r/, '\r').replace(/\\n/, '\n').replace(/\\t/, '\t'); - } - return result; -}; - -Options.prototype._get_number = function(name, default_value) { - var option_value = this.raw_options[name]; - default_value = parseInt(default_value, 10); - if (isNaN(default_value)) { - default_value = 0; - } - var result = parseInt(option_value, 10); - if (isNaN(result)) { - result = default_value; - } - return result; -}; - -Options.prototype._get_selection = function(name, selection_list, default_value) { - var result = this._get_selection_list(name, selection_list, default_value); - if (result.length !== 1) { - throw new Error( - "Invalid Option Value: The option '" + name + "' can only be one of the following values:\n" + - selection_list + "\nYou passed in: '" + this.raw_options[name] + "'"); - } - - return result[0]; -}; - - -Options.prototype._get_selection_list = function(name, selection_list, default_value) { - if (!selection_list || selection_list.length === 0) { - throw new Error("Selection list cannot be empty."); - } - - default_value = default_value || [selection_list[0]]; - if (!this._is_valid_selection(default_value, selection_list)) { - throw new Error("Invalid Default Value!"); - } - - var result = this._get_array(name, default_value); - if (!this._is_valid_selection(result, selection_list)) { - throw new Error( - "Invalid Option Value: The option '" + name + "' can contain only the following values:\n" + - selection_list + "\nYou passed in: '" + this.raw_options[name] + "'"); - } - - return result; -}; - -Options.prototype._is_valid_selection = function(result, selection_list) { - return result.length && selection_list.length && - !result.some(function(item) { return selection_list.indexOf(item) === -1; }); -}; - - -// merges child options up with the parent options object -// Example: obj = {a: 1, b: {a: 2}} -// mergeOpts(obj, 'b') -// -// Returns: {a: 2} -function _mergeOpts(allOptions, childFieldName) { - var finalOpts = {}; - allOptions = _normalizeOpts(allOptions); - var name; - - for (name in allOptions) { - if (name !== childFieldName) { - finalOpts[name] = allOptions[name]; - } - } - - //merge in the per type settings for the childFieldName - if (childFieldName && allOptions[childFieldName]) { - for (name in allOptions[childFieldName]) { - finalOpts[name] = allOptions[childFieldName][name]; - } - } - return finalOpts; -} - -function _normalizeOpts(options) { - var convertedOpts = {}; - var key; - - for (key in options) { - var newKey = key.replace(/-/g, "_"); - convertedOpts[newKey] = options[key]; - } - return convertedOpts; -} - -module.exports.Options = Options; -module.exports.normalizeOpts = _normalizeOpts; -module.exports.mergeOpts = _mergeOpts; - -},{}],68:[function(require,module,exports){ -/*jshint node:true */ -/* - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -'use strict'; - -function OutputLine(parent) { - this.__parent = parent; - this.__character_count = 0; - // use indent_count as a marker for this.__lines that have preserved indentation - this.__indent_count = -1; - this.__alignment_count = 0; - this.__wrap_point_index = 0; - this.__wrap_point_character_count = 0; - this.__wrap_point_indent_count = -1; - this.__wrap_point_alignment_count = 0; - - this.__items = []; -} - -OutputLine.prototype.clone_empty = function() { - var line = new OutputLine(this.__parent); - line.set_indent(this.__indent_count, this.__alignment_count); - return line; -}; - -OutputLine.prototype.item = function(index) { - if (index < 0) { - return this.__items[this.__items.length + index]; - } else { - return this.__items[index]; - } -}; - -OutputLine.prototype.has_match = function(pattern) { - for (var lastCheckedOutput = this.__items.length - 1; lastCheckedOutput >= 0; lastCheckedOutput--) { - if (this.__items[lastCheckedOutput].match(pattern)) { - return true; - } - } - return false; -}; - -OutputLine.prototype.set_indent = function(indent, alignment) { - if (this.is_empty()) { - this.__indent_count = indent || 0; - this.__alignment_count = alignment || 0; - this.__character_count = this.__parent.get_indent_size(this.__indent_count, this.__alignment_count); - } -}; - -OutputLine.prototype._set_wrap_point = function() { - if (this.__parent.wrap_line_length) { - this.__wrap_point_index = this.__items.length; - this.__wrap_point_character_count = this.__character_count; - this.__wrap_point_indent_count = this.__parent.next_line.__indent_count; - this.__wrap_point_alignment_count = this.__parent.next_line.__alignment_count; - } -}; - -OutputLine.prototype._should_wrap = function() { - return this.__wrap_point_index && - this.__character_count > this.__parent.wrap_line_length && - this.__wrap_point_character_count > this.__parent.next_line.__character_count; -}; - -OutputLine.prototype._allow_wrap = function() { - if (this._should_wrap()) { - this.__parent.add_new_line(); - var next = this.__parent.current_line; - next.set_indent(this.__wrap_point_indent_count, this.__wrap_point_alignment_count); - next.__items = this.__items.slice(this.__wrap_point_index); - this.__items = this.__items.slice(0, this.__wrap_point_index); - - next.__character_count += this.__character_count - this.__wrap_point_character_count; - this.__character_count = this.__wrap_point_character_count; - - if (next.__items[0] === " ") { - next.__items.splice(0, 1); - next.__character_count -= 1; - } - return true; - } - return false; -}; - -OutputLine.prototype.is_empty = function() { - return this.__items.length === 0; -}; - -OutputLine.prototype.last = function() { - if (!this.is_empty()) { - return this.__items[this.__items.length - 1]; - } else { - return null; - } -}; - -OutputLine.prototype.push = function(item) { - this.__items.push(item); - var last_newline_index = item.lastIndexOf('\n'); - if (last_newline_index !== -1) { - this.__character_count = item.length - last_newline_index; - } else { - this.__character_count += item.length; - } -}; - -OutputLine.prototype.pop = function() { - var item = null; - if (!this.is_empty()) { - item = this.__items.pop(); - this.__character_count -= item.length; - } - return item; -}; - - -OutputLine.prototype._remove_indent = function() { - if (this.__indent_count > 0) { - this.__indent_count -= 1; - this.__character_count -= this.__parent.indent_size; - } -}; - -OutputLine.prototype._remove_wrap_indent = function() { - if (this.__wrap_point_indent_count > 0) { - this.__wrap_point_indent_count -= 1; - } -}; -OutputLine.prototype.trim = function() { - while (this.last() === ' ') { - this.__items.pop(); - this.__character_count -= 1; - } -}; - -OutputLine.prototype.toString = function() { - var result = ''; - if (this.is_empty()) { - if (this.__parent.indent_empty_lines) { - result = this.__parent.get_indent_string(this.__indent_count); - } - } else { - result = this.__parent.get_indent_string(this.__indent_count, this.__alignment_count); - result += this.__items.join(''); - } - return result; -}; - -function IndentStringCache(options, baseIndentString) { - this.__cache = ['']; - this.__indent_size = options.indent_size; - this.__indent_string = options.indent_char; - if (!options.indent_with_tabs) { - this.__indent_string = new Array(options.indent_size + 1).join(options.indent_char); - } - - // Set to null to continue support for auto detection of base indent - baseIndentString = baseIndentString || ''; - if (options.indent_level > 0) { - baseIndentString = new Array(options.indent_level + 1).join(this.__indent_string); - } - - this.__base_string = baseIndentString; - this.__base_string_length = baseIndentString.length; -} - -IndentStringCache.prototype.get_indent_size = function(indent, column) { - var result = this.__base_string_length; - column = column || 0; - if (indent < 0) { - result = 0; - } - result += indent * this.__indent_size; - result += column; - return result; -}; - -IndentStringCache.prototype.get_indent_string = function(indent_level, column) { - var result = this.__base_string; - column = column || 0; - if (indent_level < 0) { - indent_level = 0; - result = ''; - } - column += indent_level * this.__indent_size; - this.__ensure_cache(column); - result += this.__cache[column]; - return result; -}; - -IndentStringCache.prototype.__ensure_cache = function(column) { - while (column >= this.__cache.length) { - this.__add_column(); - } -}; - -IndentStringCache.prototype.__add_column = function() { - var column = this.__cache.length; - var indent = 0; - var result = ''; - if (this.__indent_size && column >= this.__indent_size) { - indent = Math.floor(column / this.__indent_size); - column -= indent * this.__indent_size; - result = new Array(indent + 1).join(this.__indent_string); - } - if (column) { - result += new Array(column + 1).join(' '); - } - - this.__cache.push(result); -}; - -function Output(options, baseIndentString) { - this.__indent_cache = new IndentStringCache(options, baseIndentString); - this.raw = false; - this._end_with_newline = options.end_with_newline; - this.indent_size = options.indent_size; - this.wrap_line_length = options.wrap_line_length; - this.indent_empty_lines = options.indent_empty_lines; - this.__lines = []; - this.previous_line = null; - this.current_line = null; - this.next_line = new OutputLine(this); - this.space_before_token = false; - this.non_breaking_space = false; - this.previous_token_wrapped = false; - // initialize - this.__add_outputline(); -} - -Output.prototype.__add_outputline = function() { - this.previous_line = this.current_line; - this.current_line = this.next_line.clone_empty(); - this.__lines.push(this.current_line); -}; - -Output.prototype.get_line_number = function() { - return this.__lines.length; -}; - -Output.prototype.get_indent_string = function(indent, column) { - return this.__indent_cache.get_indent_string(indent, column); -}; - -Output.prototype.get_indent_size = function(indent, column) { - return this.__indent_cache.get_indent_size(indent, column); -}; - -Output.prototype.is_empty = function() { - return !this.previous_line && this.current_line.is_empty(); -}; - -Output.prototype.add_new_line = function(force_newline) { - // never newline at the start of file - // otherwise, newline only if we didn't just add one or we're forced - if (this.is_empty() || - (!force_newline && this.just_added_newline())) { - return false; - } - - // if raw output is enabled, don't print additional newlines, - // but still return True as though you had - if (!this.raw) { - this.__add_outputline(); - } - return true; -}; - -Output.prototype.get_code = function(eol) { - this.trim(true); - - // handle some edge cases where the last tokens - // has text that ends with newline(s) - var last_item = this.current_line.pop(); - if (last_item) { - if (last_item[last_item.length - 1] === '\n') { - last_item = last_item.replace(/\n+$/g, ''); - } - this.current_line.push(last_item); - } - - if (this._end_with_newline) { - this.__add_outputline(); - } - - var sweet_code = this.__lines.join('\n'); - - if (eol !== '\n') { - sweet_code = sweet_code.replace(/[\n]/g, eol); - } - return sweet_code; -}; - -Output.prototype.set_wrap_point = function() { - this.current_line._set_wrap_point(); -}; - -Output.prototype.set_indent = function(indent, alignment) { - indent = indent || 0; - alignment = alignment || 0; - - // Next line stores alignment values - this.next_line.set_indent(indent, alignment); - - // Never indent your first output indent at the start of the file - if (this.__lines.length > 1) { - this.current_line.set_indent(indent, alignment); - return true; - } - - this.current_line.set_indent(); - return false; -}; - -Output.prototype.add_raw_token = function(token) { - for (var x = 0; x < token.newlines; x++) { - this.__add_outputline(); - } - this.current_line.set_indent(-1); - this.current_line.push(token.whitespace_before); - this.current_line.push(token.text); - this.space_before_token = false; - this.non_breaking_space = false; - this.previous_token_wrapped = false; -}; - -Output.prototype.add_token = function(printable_token) { - this.__add_space_before_token(); - this.current_line.push(printable_token); - this.space_before_token = false; - this.non_breaking_space = false; - this.previous_token_wrapped = this.current_line._allow_wrap(); -}; - -Output.prototype.__add_space_before_token = function() { - if (this.space_before_token && !this.just_added_newline()) { - if (!this.non_breaking_space) { - this.set_wrap_point(); - } - this.current_line.push(' '); - } -}; - -Output.prototype.remove_indent = function(index) { - var output_length = this.__lines.length; - while (index < output_length) { - this.__lines[index]._remove_indent(); - index++; - } - this.current_line._remove_wrap_indent(); -}; - -Output.prototype.trim = function(eat_newlines) { - eat_newlines = (eat_newlines === undefined) ? false : eat_newlines; - - this.current_line.trim(); - - while (eat_newlines && this.__lines.length > 1 && - this.current_line.is_empty()) { - this.__lines.pop(); - this.current_line = this.__lines[this.__lines.length - 1]; - this.current_line.trim(); - } - - this.previous_line = this.__lines.length > 1 ? - this.__lines[this.__lines.length - 2] : null; -}; - -Output.prototype.just_added_newline = function() { - return this.current_line.is_empty(); -}; - -Output.prototype.just_added_blankline = function() { - return this.is_empty() || - (this.current_line.is_empty() && this.previous_line.is_empty()); -}; - -Output.prototype.ensure_empty_line_above = function(starts_with, ends_with) { - var index = this.__lines.length - 2; - while (index >= 0) { - var potentialEmptyLine = this.__lines[index]; - if (potentialEmptyLine.is_empty()) { - break; - } else if (potentialEmptyLine.item(0).indexOf(starts_with) !== 0 && - potentialEmptyLine.item(-1) !== ends_with) { - this.__lines.splice(index + 1, 0, new OutputLine(this)); - this.previous_line = this.__lines[this.__lines.length - 2]; - break; - } - index--; - } -}; - -module.exports.Output = Output; - -},{}],69:[function(require,module,exports){ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -'use strict'; - -function Pattern(input_scanner, parent) { - this._input = input_scanner; - this._starting_pattern = null; - this._match_pattern = null; - this._until_pattern = null; - this._until_after = false; - - if (parent) { - this._starting_pattern = this._input.get_regexp(parent._starting_pattern, true); - this._match_pattern = this._input.get_regexp(parent._match_pattern, true); - this._until_pattern = this._input.get_regexp(parent._until_pattern); - this._until_after = parent._until_after; - } -} - -Pattern.prototype.read = function() { - var result = this._input.read(this._starting_pattern); - if (!this._starting_pattern || result) { - result += this._input.read(this._match_pattern, this._until_pattern, this._until_after); - } - return result; -}; - -Pattern.prototype.read_match = function() { - return this._input.match(this._match_pattern); -}; - -Pattern.prototype.until_after = function(pattern) { - var result = this._create(); - result._until_after = true; - result._until_pattern = this._input.get_regexp(pattern); - result._update(); - return result; -}; - -Pattern.prototype.until = function(pattern) { - var result = this._create(); - result._until_after = false; - result._until_pattern = this._input.get_regexp(pattern); - result._update(); - return result; -}; - -Pattern.prototype.starting_with = function(pattern) { - var result = this._create(); - result._starting_pattern = this._input.get_regexp(pattern, true); - result._update(); - return result; -}; - -Pattern.prototype.matching = function(pattern) { - var result = this._create(); - result._match_pattern = this._input.get_regexp(pattern, true); - result._update(); - return result; -}; - -Pattern.prototype._create = function() { - return new Pattern(this._input, this); -}; - -Pattern.prototype._update = function() {}; - -module.exports.Pattern = Pattern; - -},{}],70:[function(require,module,exports){ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -'use strict'; - -var Pattern = require('./pattern').Pattern; - - -var template_names = { - django: false, - erb: false, - handlebars: false, - php: false, - smarty: false -}; - -// This lets templates appear anywhere we would do a readUntil -// The cost is higher but it is pay to play. -function TemplatablePattern(input_scanner, parent) { - Pattern.call(this, input_scanner, parent); - this.__template_pattern = null; - this._disabled = Object.assign({}, template_names); - this._excluded = Object.assign({}, template_names); - - if (parent) { - this.__template_pattern = this._input.get_regexp(parent.__template_pattern); - this._excluded = Object.assign(this._excluded, parent._excluded); - this._disabled = Object.assign(this._disabled, parent._disabled); - } - var pattern = new Pattern(input_scanner); - this.__patterns = { - handlebars_comment: pattern.starting_with(/{{!--/).until_after(/--}}/), - handlebars_unescaped: pattern.starting_with(/{{{/).until_after(/}}}/), - handlebars: pattern.starting_with(/{{/).until_after(/}}/), - php: pattern.starting_with(/<\?(?:[= ]|php)/).until_after(/\?>/), - erb: pattern.starting_with(/<%[^%]/).until_after(/[^%]%>/), - // django coflicts with handlebars a bit. - django: pattern.starting_with(/{%/).until_after(/%}/), - django_value: pattern.starting_with(/{{/).until_after(/}}/), - django_comment: pattern.starting_with(/{#/).until_after(/#}/), - smarty: pattern.starting_with(/{(?=[^}{\s\n])/).until_after(/[^\s\n]}/), - smarty_comment: pattern.starting_with(/{\*/).until_after(/\*}/), - smarty_literal: pattern.starting_with(/{literal}/).until_after(/{\/literal}/) - }; -} -TemplatablePattern.prototype = new Pattern(); - -TemplatablePattern.prototype._create = function() { - return new TemplatablePattern(this._input, this); -}; - -TemplatablePattern.prototype._update = function() { - this.__set_templated_pattern(); -}; - -TemplatablePattern.prototype.disable = function(language) { - var result = this._create(); - result._disabled[language] = true; - result._update(); - return result; -}; - -TemplatablePattern.prototype.read_options = function(options) { - var result = this._create(); - for (var language in template_names) { - result._disabled[language] = options.templating.indexOf(language) === -1; - } - result._update(); - return result; -}; - -TemplatablePattern.prototype.exclude = function(language) { - var result = this._create(); - result._excluded[language] = true; - result._update(); - return result; -}; - -TemplatablePattern.prototype.read = function() { - var result = ''; - if (this._match_pattern) { - result = this._input.read(this._starting_pattern); - } else { - result = this._input.read(this._starting_pattern, this.__template_pattern); - } - var next = this._read_template(); - while (next) { - if (this._match_pattern) { - next += this._input.read(this._match_pattern); - } else { - next += this._input.readUntil(this.__template_pattern); - } - result += next; - next = this._read_template(); - } - - if (this._until_after) { - result += this._input.readUntilAfter(this._until_pattern); - } - return result; -}; - -TemplatablePattern.prototype.__set_templated_pattern = function() { - var items = []; - - if (!this._disabled.php) { - items.push(this.__patterns.php._starting_pattern.source); - } - if (!this._disabled.handlebars) { - items.push(this.__patterns.handlebars._starting_pattern.source); - } - if (!this._disabled.erb) { - items.push(this.__patterns.erb._starting_pattern.source); - } - if (!this._disabled.django) { - items.push(this.__patterns.django._starting_pattern.source); - // The starting pattern for django is more complex because it has different - // patterns for value, comment, and other sections - items.push(this.__patterns.django_value._starting_pattern.source); - items.push(this.__patterns.django_comment._starting_pattern.source); - } - if (!this._disabled.smarty) { - items.push(this.__patterns.smarty._starting_pattern.source); - } - - if (this._until_pattern) { - items.push(this._until_pattern.source); - } - this.__template_pattern = this._input.get_regexp('(?:' + items.join('|') + ')'); -}; - -TemplatablePattern.prototype._read_template = function() { - var resulting_string = ''; - var c = this._input.peek(); - if (c === '<') { - var peek1 = this._input.peek(1); - //if we're in a comment, do something special - // We treat all comments as literals, even more than preformatted tags - // we just look for the appropriate close tag - if (!this._disabled.php && !this._excluded.php && peek1 === '?') { - resulting_string = resulting_string || - this.__patterns.php.read(); - } - if (!this._disabled.erb && !this._excluded.erb && peek1 === '%') { - resulting_string = resulting_string || - this.__patterns.erb.read(); - } - } else if (c === '{') { - if (!this._disabled.handlebars && !this._excluded.handlebars) { - resulting_string = resulting_string || - this.__patterns.handlebars_comment.read(); - resulting_string = resulting_string || - this.__patterns.handlebars_unescaped.read(); - resulting_string = resulting_string || - this.__patterns.handlebars.read(); - } - if (!this._disabled.django) { - // django coflicts with handlebars a bit. - if (!this._excluded.django && !this._excluded.handlebars) { - resulting_string = resulting_string || - this.__patterns.django_value.read(); - } - if (!this._excluded.django) { - resulting_string = resulting_string || - this.__patterns.django_comment.read(); - resulting_string = resulting_string || - this.__patterns.django.read(); - } - } - if (!this._disabled.smarty) { - // smarty cannot be enabled with django or handlebars enabled - if (this._disabled.django && this._disabled.handlebars) { - resulting_string = resulting_string || - this.__patterns.smarty_comment.read(); - resulting_string = resulting_string || - this.__patterns.smarty_literal.read(); - resulting_string = resulting_string || - this.__patterns.smarty.read(); - } - } - } - return resulting_string; -}; - - -module.exports.TemplatablePattern = TemplatablePattern; - -},{"./pattern":69}],71:[function(require,module,exports){ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -'use strict'; - -function Token(type, text, newlines, whitespace_before) { - this.type = type; - this.text = text; - - // comments_before are - // comments that have a new line before them - // and may or may not have a newline after - // this is a set of comments before - this.comments_before = null; /* inline comment*/ - - - // this.comments_after = new TokenStream(); // no new line before and newline after - this.newlines = newlines || 0; - this.whitespace_before = whitespace_before || ''; - this.parent = null; - this.next = null; - this.previous = null; - this.opened = null; - this.closed = null; - this.directives = null; -} - - -module.exports.Token = Token; - -},{}],72:[function(require,module,exports){ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -'use strict'; - -var InputScanner = require('../core/inputscanner').InputScanner; -var Token = require('../core/token').Token; -var TokenStream = require('../core/tokenstream').TokenStream; -var WhitespacePattern = require('./whitespacepattern').WhitespacePattern; - -var TOKEN = { - START: 'TK_START', - RAW: 'TK_RAW', - EOF: 'TK_EOF' -}; - -var Tokenizer = function(input_string, options) { - this._input = new InputScanner(input_string); - this._options = options || {}; - this.__tokens = null; - - this._patterns = {}; - this._patterns.whitespace = new WhitespacePattern(this._input); -}; - -Tokenizer.prototype.tokenize = function() { - this._input.restart(); - this.__tokens = new TokenStream(); - - this._reset(); - - var current; - var previous = new Token(TOKEN.START, ''); - var open_token = null; - var open_stack = []; - var comments = new TokenStream(); - - while (previous.type !== TOKEN.EOF) { - current = this._get_next_token(previous, open_token); - while (this._is_comment(current)) { - comments.add(current); - current = this._get_next_token(previous, open_token); - } - - if (!comments.isEmpty()) { - current.comments_before = comments; - comments = new TokenStream(); - } - - current.parent = open_token; - - if (this._is_opening(current)) { - open_stack.push(open_token); - open_token = current; - } else if (open_token && this._is_closing(current, open_token)) { - current.opened = open_token; - open_token.closed = current; - open_token = open_stack.pop(); - current.parent = open_token; - } - - current.previous = previous; - previous.next = current; - - this.__tokens.add(current); - previous = current; - } - - return this.__tokens; -}; - - -Tokenizer.prototype._is_first_token = function() { - return this.__tokens.isEmpty(); -}; - -Tokenizer.prototype._reset = function() {}; - -Tokenizer.prototype._get_next_token = function(previous_token, open_token) { // jshint unused:false - this._readWhitespace(); - var resulting_string = this._input.read(/.+/g); - if (resulting_string) { - return this._create_token(TOKEN.RAW, resulting_string); - } else { - return this._create_token(TOKEN.EOF, ''); - } -}; - -Tokenizer.prototype._is_comment = function(current_token) { // jshint unused:false - return false; -}; - -Tokenizer.prototype._is_opening = function(current_token) { // jshint unused:false - return false; -}; - -Tokenizer.prototype._is_closing = function(current_token, open_token) { // jshint unused:false - return false; -}; - -Tokenizer.prototype._create_token = function(type, text) { - var token = new Token(type, text, - this._patterns.whitespace.newline_count, - this._patterns.whitespace.whitespace_before_token); - return token; -}; - -Tokenizer.prototype._readWhitespace = function() { - return this._patterns.whitespace.read(); -}; - - - -module.exports.Tokenizer = Tokenizer; -module.exports.TOKEN = TOKEN; - -},{"../core/inputscanner":66,"../core/token":71,"../core/tokenstream":73,"./whitespacepattern":74}],73:[function(require,module,exports){ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -'use strict'; - -function TokenStream(parent_token) { - // private - this.__tokens = []; - this.__tokens_length = this.__tokens.length; - this.__position = 0; - this.__parent_token = parent_token; -} - -TokenStream.prototype.restart = function() { - this.__position = 0; -}; - -TokenStream.prototype.isEmpty = function() { - return this.__tokens_length === 0; -}; - -TokenStream.prototype.hasNext = function() { - return this.__position < this.__tokens_length; -}; - -TokenStream.prototype.next = function() { - var val = null; - if (this.hasNext()) { - val = this.__tokens[this.__position]; - this.__position += 1; - } - return val; -}; - -TokenStream.prototype.peek = function(index) { - var val = null; - index = index || 0; - index += this.__position; - if (index >= 0 && index < this.__tokens_length) { - val = this.__tokens[index]; - } - return val; -}; - -TokenStream.prototype.add = function(token) { - if (this.__parent_token) { - token.parent = this.__parent_token; - } - this.__tokens.push(token); - this.__tokens_length += 1; -}; - -module.exports.TokenStream = TokenStream; - -},{}],74:[function(require,module,exports){ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -'use strict'; - -var Pattern = require('../core/pattern').Pattern; - -function WhitespacePattern(input_scanner, parent) { - Pattern.call(this, input_scanner, parent); - if (parent) { - this._line_regexp = this._input.get_regexp(parent._line_regexp); - } else { - this.__set_whitespace_patterns('', ''); - } - - this.newline_count = 0; - this.whitespace_before_token = ''; -} -WhitespacePattern.prototype = new Pattern(); - -WhitespacePattern.prototype.__set_whitespace_patterns = function(whitespace_chars, newline_chars) { - whitespace_chars += '\\t '; - newline_chars += '\\n\\r'; - - this._match_pattern = this._input.get_regexp( - '[' + whitespace_chars + newline_chars + ']+', true); - this._newline_regexp = this._input.get_regexp( - '\\r\\n|[' + newline_chars + ']'); -}; - -WhitespacePattern.prototype.read = function() { - this.newline_count = 0; - this.whitespace_before_token = ''; - - var resulting_string = this._input.read(this._match_pattern); - if (resulting_string === ' ') { - this.whitespace_before_token = ' '; - } else if (resulting_string) { - var matches = this.__split(this._newline_regexp, resulting_string); - this.newline_count = matches.length - 1; - this.whitespace_before_token = matches[this.newline_count]; - } - - return resulting_string; -}; - -WhitespacePattern.prototype.matching = function(whitespace_chars, newline_chars) { - var result = this._create(); - result.__set_whitespace_patterns(whitespace_chars, newline_chars); - result._update(); - return result; -}; - -WhitespacePattern.prototype._create = function() { - return new WhitespacePattern(this._input, this); -}; - -WhitespacePattern.prototype.__split = function(regexp, input_string) { - regexp.lastIndex = 0; - var start_index = 0; - var result = []; - var next_match = regexp.exec(input_string); - while (next_match) { - result.push(input_string.substring(start_index, next_match.index)); - start_index = next_match.index + next_match[0].length; - next_match = regexp.exec(input_string); - } - - if (start_index < input_string.length) { - result.push(input_string.substring(start_index, input_string.length)); - } else { - result.push(''); - } - - return result; -}; - - - -module.exports.WhitespacePattern = WhitespacePattern; - -},{"../core/pattern":69}],75:[function(require,module,exports){ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -'use strict'; - -var Options = require('./options').Options; -var Output = require('../core/output').Output; -var InputScanner = require('../core/inputscanner').InputScanner; -var Directives = require('../core/directives').Directives; - -var directives_core = new Directives(/\/\*/, /\*\//); - -var lineBreak = /\r\n|[\r\n]/; -var allLineBreaks = /\r\n|[\r\n]/g; - -// tokenizer -var whitespaceChar = /\s/; -var whitespacePattern = /(?:\s|\n)+/g; -var block_comment_pattern = /\/\*(?:[\s\S]*?)((?:\*\/)|$)/g; -var comment_pattern = /\/\/(?:[^\n\r\u2028\u2029]*)/g; - -function Beautifier(source_text, options) { - this._source_text = source_text || ''; - // Allow the setting of language/file-type specific options - // with inheritance of overall settings - this._options = new Options(options); - this._ch = null; - this._input = null; - - // https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule - this.NESTED_AT_RULE = { - "@page": true, - "@font-face": true, - "@keyframes": true, - // also in CONDITIONAL_GROUP_RULE below - "@media": true, - "@supports": true, - "@document": true - }; - this.CONDITIONAL_GROUP_RULE = { - "@media": true, - "@supports": true, - "@document": true - }; - -} - -Beautifier.prototype.eatString = function(endChars) { - var result = ''; - this._ch = this._input.next(); - while (this._ch) { - result += this._ch; - if (this._ch === "\\") { - result += this._input.next(); - } else if (endChars.indexOf(this._ch) !== -1 || this._ch === "\n") { - break; - } - this._ch = this._input.next(); - } - return result; -}; - -// Skips any white space in the source text from the current position. -// When allowAtLeastOneNewLine is true, will output new lines for each -// newline character found; if the user has preserve_newlines off, only -// the first newline will be output -Beautifier.prototype.eatWhitespace = function(allowAtLeastOneNewLine) { - var result = whitespaceChar.test(this._input.peek()); - var newline_count = 0; - while (whitespaceChar.test(this._input.peek())) { - this._ch = this._input.next(); - if (allowAtLeastOneNewLine && this._ch === '\n') { - if (newline_count === 0 || newline_count < this._options.max_preserve_newlines) { - newline_count++; - this._output.add_new_line(true); - } - } - } - return result; -}; - -// Nested pseudo-class if we are insideRule -// and the next special character found opens -// a new block -Beautifier.prototype.foundNestedPseudoClass = function() { - var openParen = 0; - var i = 1; - var ch = this._input.peek(i); - while (ch) { - if (ch === "{") { - return true; - } else if (ch === '(') { - // pseudoclasses can contain () - openParen += 1; - } else if (ch === ')') { - if (openParen === 0) { - return false; - } - openParen -= 1; - } else if (ch === ";" || ch === "}") { - return false; - } - i++; - ch = this._input.peek(i); - } - return false; -}; - -Beautifier.prototype.print_string = function(output_string) { - this._output.set_indent(this._indentLevel); - this._output.non_breaking_space = true; - this._output.add_token(output_string); -}; - -Beautifier.prototype.preserveSingleSpace = function(isAfterSpace) { - if (isAfterSpace) { - this._output.space_before_token = true; - } -}; - -Beautifier.prototype.indent = function() { - this._indentLevel++; -}; - -Beautifier.prototype.outdent = function() { - if (this._indentLevel > 0) { - this._indentLevel--; - } -}; - -/*_____________________--------------------_____________________*/ - -Beautifier.prototype.beautify = function() { - if (this._options.disabled) { - return this._source_text; - } - - var source_text = this._source_text; - var eol = this._options.eol; - if (eol === 'auto') { - eol = '\n'; - if (source_text && lineBreak.test(source_text || '')) { - eol = source_text.match(lineBreak)[0]; - } - } - - - // HACK: newline parsing inconsistent. This brute force normalizes the this._input. - source_text = source_text.replace(allLineBreaks, '\n'); - - // reset - var baseIndentString = source_text.match(/^[\t ]*/)[0]; - - this._output = new Output(this._options, baseIndentString); - this._input = new InputScanner(source_text); - this._indentLevel = 0; - this._nestedLevel = 0; - - this._ch = null; - var parenLevel = 0; - - var insideRule = false; - // This is the value side of a property value pair (blue in the following ex) - // label { content: blue } - var insidePropertyValue = false; - var enteringConditionalGroup = false; - var insideAtExtend = false; - var insideAtImport = false; - var topCharacter = this._ch; - var whitespace; - var isAfterSpace; - var previous_ch; - - while (true) { - whitespace = this._input.read(whitespacePattern); - isAfterSpace = whitespace !== ''; - previous_ch = topCharacter; - this._ch = this._input.next(); - if (this._ch === '\\' && this._input.hasNext()) { - this._ch += this._input.next(); - } - topCharacter = this._ch; - - if (!this._ch) { - break; - } else if (this._ch === '/' && this._input.peek() === '*') { - // /* css comment */ - // Always start block comments on a new line. - // This handles scenarios where a block comment immediately - // follows a property definition on the same line or where - // minified code is being beautified. - this._output.add_new_line(); - this._input.back(); - - var comment = this._input.read(block_comment_pattern); - - // Handle ignore directive - var directives = directives_core.get_directives(comment); - if (directives && directives.ignore === 'start') { - comment += directives_core.readIgnored(this._input); - } - - this.print_string(comment); - - // Ensures any new lines following the comment are preserved - this.eatWhitespace(true); - - // Block comments are followed by a new line so they don't - // share a line with other properties - this._output.add_new_line(); - } else if (this._ch === '/' && this._input.peek() === '/') { - // // single line comment - // Preserves the space before a comment - // on the same line as a rule - this._output.space_before_token = true; - this._input.back(); - this.print_string(this._input.read(comment_pattern)); - - // Ensures any new lines following the comment are preserved - this.eatWhitespace(true); - } else if (this._ch === '@') { - this.preserveSingleSpace(isAfterSpace); - - // deal with less propery mixins @{...} - if (this._input.peek() === '{') { - this.print_string(this._ch + this.eatString('}')); - } else { - this.print_string(this._ch); - - // strip trailing space, if present, for hash property checks - var variableOrRule = this._input.peekUntilAfter(/[: ,;{}()[\]\/='"]/g); - - if (variableOrRule.match(/[ :]$/)) { - // we have a variable or pseudo-class, add it and insert one space before continuing - variableOrRule = this.eatString(": ").replace(/\s$/, ''); - this.print_string(variableOrRule); - this._output.space_before_token = true; - } - - variableOrRule = variableOrRule.replace(/\s$/, ''); - - if (variableOrRule === 'extend') { - insideAtExtend = true; - } else if (variableOrRule === 'import') { - insideAtImport = true; - } - - // might be a nesting at-rule - if (variableOrRule in this.NESTED_AT_RULE) { - this._nestedLevel += 1; - if (variableOrRule in this.CONDITIONAL_GROUP_RULE) { - enteringConditionalGroup = true; - } - // might be less variable - } else if (!insideRule && parenLevel === 0 && variableOrRule.indexOf(':') !== -1) { - insidePropertyValue = true; - this.indent(); - } - } - } else if (this._ch === '#' && this._input.peek() === '{') { - this.preserveSingleSpace(isAfterSpace); - this.print_string(this._ch + this.eatString('}')); - } else if (this._ch === '{') { - if (insidePropertyValue) { - insidePropertyValue = false; - this.outdent(); - } - - // when entering conditional groups, only rulesets are allowed - if (enteringConditionalGroup) { - enteringConditionalGroup = false; - insideRule = (this._indentLevel >= this._nestedLevel); - } else { - // otherwise, declarations are also allowed - insideRule = (this._indentLevel >= this._nestedLevel - 1); - } - if (this._options.newline_between_rules && insideRule) { - if (this._output.previous_line && this._output.previous_line.item(-1) !== '{') { - this._output.ensure_empty_line_above('/', ','); - } - } - - this._output.space_before_token = true; - - // The difference in print_string and indent order is necessary to indent the '{' correctly - if (this._options.brace_style === 'expand') { - this._output.add_new_line(); - this.print_string(this._ch); - this.indent(); - this._output.set_indent(this._indentLevel); - } else { - this.indent(); - this.print_string(this._ch); - } - - this.eatWhitespace(true); - this._output.add_new_line(); - } else if (this._ch === '}') { - this.outdent(); - this._output.add_new_line(); - if (previous_ch === '{') { - this._output.trim(true); - } - insideAtImport = false; - insideAtExtend = false; - if (insidePropertyValue) { - this.outdent(); - insidePropertyValue = false; - } - this.print_string(this._ch); - insideRule = false; - if (this._nestedLevel) { - this._nestedLevel--; - } - - this.eatWhitespace(true); - this._output.add_new_line(); - - if (this._options.newline_between_rules && !this._output.just_added_blankline()) { - if (this._input.peek() !== '}') { - this._output.add_new_line(true); - } - } - } else if (this._ch === ":") { - if ((insideRule || enteringConditionalGroup) && !(this._input.lookBack("&") || this.foundNestedPseudoClass()) && !this._input.lookBack("(") && !insideAtExtend && parenLevel === 0) { - // 'property: value' delimiter - // which could be in a conditional group query - this.print_string(':'); - if (!insidePropertyValue) { - insidePropertyValue = true; - this._output.space_before_token = true; - this.eatWhitespace(true); - this.indent(); - } - } else { - // sass/less parent reference don't use a space - // sass nested pseudo-class don't use a space - - // preserve space before pseudoclasses/pseudoelements, as it means "in any child" - if (this._input.lookBack(" ")) { - this._output.space_before_token = true; - } - if (this._input.peek() === ":") { - // pseudo-element - this._ch = this._input.next(); - this.print_string("::"); - } else { - // pseudo-class - this.print_string(':'); - } - } - } else if (this._ch === '"' || this._ch === '\'') { - this.preserveSingleSpace(isAfterSpace); - this.print_string(this._ch + this.eatString(this._ch)); - this.eatWhitespace(true); - } else if (this._ch === ';') { - if (parenLevel === 0) { - if (insidePropertyValue) { - this.outdent(); - insidePropertyValue = false; - } - insideAtExtend = false; - insideAtImport = false; - this.print_string(this._ch); - this.eatWhitespace(true); - - // This maintains single line comments on the same - // line. Block comments are also affected, but - // a new line is always output before one inside - // that section - if (this._input.peek() !== '/') { - this._output.add_new_line(); - } - } else { - this.print_string(this._ch); - this.eatWhitespace(true); - this._output.space_before_token = true; - } - } else if (this._ch === '(') { // may be a url - if (this._input.lookBack("url")) { - this.print_string(this._ch); - this.eatWhitespace(); - parenLevel++; - this.indent(); - this._ch = this._input.next(); - if (this._ch === ')' || this._ch === '"' || this._ch === '\'') { - this._input.back(); - } else if (this._ch) { - this.print_string(this._ch + this.eatString(')')); - if (parenLevel) { - parenLevel--; - this.outdent(); - } - } - } else { - this.preserveSingleSpace(isAfterSpace); - this.print_string(this._ch); - this.eatWhitespace(); - parenLevel++; - this.indent(); - } - } else if (this._ch === ')') { - if (parenLevel) { - parenLevel--; - this.outdent(); - } - this.print_string(this._ch); - } else if (this._ch === ',') { - this.print_string(this._ch); - this.eatWhitespace(true); - if (this._options.selector_separator_newline && !insidePropertyValue && parenLevel === 0 && !insideAtImport && !insideAtExtend) { - this._output.add_new_line(); - } else { - this._output.space_before_token = true; - } - } else if ((this._ch === '>' || this._ch === '+' || this._ch === '~') && !insidePropertyValue && parenLevel === 0) { - //handle combinator spacing - if (this._options.space_around_combinator) { - this._output.space_before_token = true; - this.print_string(this._ch); - this._output.space_before_token = true; - } else { - this.print_string(this._ch); - this.eatWhitespace(); - // squash extra whitespace - if (this._ch && whitespaceChar.test(this._ch)) { - this._ch = ''; - } - } - } else if (this._ch === ']') { - this.print_string(this._ch); - } else if (this._ch === '[') { - this.preserveSingleSpace(isAfterSpace); - this.print_string(this._ch); - } else if (this._ch === '=') { // no whitespace before or after - this.eatWhitespace(); - this.print_string('='); - if (whitespaceChar.test(this._ch)) { - this._ch = ''; - } - } else if (this._ch === '!' && !this._input.lookBack("\\")) { // !important - this.print_string(' '); - this.print_string(this._ch); - } else { - this.preserveSingleSpace(isAfterSpace); - this.print_string(this._ch); - } - } - - var sweetCode = this._output.get_code(eol); - - return sweetCode; -}; - -module.exports.Beautifier = Beautifier; - -},{"../core/directives":65,"../core/inputscanner":66,"../core/output":68,"./options":77}],76:[function(require,module,exports){ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -'use strict'; - -var Beautifier = require('./beautifier').Beautifier, - Options = require('./options').Options; - -function css_beautify(source_text, options) { - var beautifier = new Beautifier(source_text, options); - return beautifier.beautify(); -} - -module.exports = css_beautify; -module.exports.defaultOptions = function() { - return new Options(); -}; - -},{"./beautifier":75,"./options":77}],77:[function(require,module,exports){ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -'use strict'; - -var BaseOptions = require('../core/options').Options; - -function Options(options) { - BaseOptions.call(this, options, 'css'); - - this.selector_separator_newline = this._get_boolean('selector_separator_newline', true); - this.newline_between_rules = this._get_boolean('newline_between_rules', true); - var space_around_selector_separator = this._get_boolean('space_around_selector_separator'); - this.space_around_combinator = this._get_boolean('space_around_combinator') || space_around_selector_separator; - - var brace_style_split = this._get_selection_list('brace_style', ['collapse', 'expand', 'end-expand', 'none', 'preserve-inline']); - this.brace_style = 'collapse'; - for (var bs = 0; bs < brace_style_split.length; bs++) { - if (brace_style_split[bs] !== 'expand') { - // default to collapse, as only collapse|expand is implemented for now - this.brace_style = 'collapse'; - } else { - this.brace_style = brace_style_split[bs]; - } - } -} -Options.prototype = new BaseOptions(); - - - -module.exports.Options = Options; - -},{"../core/options":67}],78:[function(require,module,exports){ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -'use strict'; - -var Options = require('../html/options').Options; -var Output = require('../core/output').Output; -var Tokenizer = require('../html/tokenizer').Tokenizer; -var TOKEN = require('../html/tokenizer').TOKEN; - -var lineBreak = /\r\n|[\r\n]/; -var allLineBreaks = /\r\n|[\r\n]/g; - -var Printer = function(options, base_indent_string) { //handles input/output and some other printing functions - - this.indent_level = 0; - this.alignment_size = 0; - this.max_preserve_newlines = options.max_preserve_newlines; - this.preserve_newlines = options.preserve_newlines; - - this._output = new Output(options, base_indent_string); - -}; - -Printer.prototype.current_line_has_match = function(pattern) { - return this._output.current_line.has_match(pattern); -}; - -Printer.prototype.set_space_before_token = function(value, non_breaking) { - this._output.space_before_token = value; - this._output.non_breaking_space = non_breaking; -}; - -Printer.prototype.set_wrap_point = function() { - this._output.set_indent(this.indent_level, this.alignment_size); - this._output.set_wrap_point(); -}; - - -Printer.prototype.add_raw_token = function(token) { - this._output.add_raw_token(token); -}; - -Printer.prototype.print_preserved_newlines = function(raw_token) { - var newlines = 0; - if (raw_token.type !== TOKEN.TEXT && raw_token.previous.type !== TOKEN.TEXT) { - newlines = raw_token.newlines ? 1 : 0; - } - - if (this.preserve_newlines) { - newlines = raw_token.newlines < this.max_preserve_newlines + 1 ? raw_token.newlines : this.max_preserve_newlines + 1; - } - for (var n = 0; n < newlines; n++) { - this.print_newline(n > 0); - } - - return newlines !== 0; -}; - -Printer.prototype.traverse_whitespace = function(raw_token) { - if (raw_token.whitespace_before || raw_token.newlines) { - if (!this.print_preserved_newlines(raw_token)) { - this._output.space_before_token = true; - } - return true; - } - return false; -}; - -Printer.prototype.previous_token_wrapped = function() { - return this._output.previous_token_wrapped; -}; - -Printer.prototype.print_newline = function(force) { - this._output.add_new_line(force); -}; - -Printer.prototype.print_token = function(token) { - if (token.text) { - this._output.set_indent(this.indent_level, this.alignment_size); - this._output.add_token(token.text); - } -}; - -Printer.prototype.indent = function() { - this.indent_level++; -}; - -Printer.prototype.get_full_indent = function(level) { - level = this.indent_level + (level || 0); - if (level < 1) { - return ''; - } - - return this._output.get_indent_string(level); -}; - -var get_type_attribute = function(start_token) { - var result = null; - var raw_token = start_token.next; - - // Search attributes for a type attribute - while (raw_token.type !== TOKEN.EOF && start_token.closed !== raw_token) { - if (raw_token.type === TOKEN.ATTRIBUTE && raw_token.text === 'type') { - if (raw_token.next && raw_token.next.type === TOKEN.EQUALS && - raw_token.next.next && raw_token.next.next.type === TOKEN.VALUE) { - result = raw_token.next.next.text; - } - break; - } - raw_token = raw_token.next; - } - - return result; -}; - -var get_custom_beautifier_name = function(tag_check, raw_token) { - var typeAttribute = null; - var result = null; - - if (!raw_token.closed) { - return null; - } - - if (tag_check === 'script') { - typeAttribute = 'text/javascript'; - } else if (tag_check === 'style') { - typeAttribute = 'text/css'; - } - - typeAttribute = get_type_attribute(raw_token) || typeAttribute; - - // For script and style tags that have a type attribute, only enable custom beautifiers for matching values - // For those without a type attribute use default; - if (typeAttribute.search('text/css') > -1) { - result = 'css'; - } else if (typeAttribute.search(/module|((text|application|dojo)\/(x-)?(javascript|ecmascript|jscript|livescript|(ld\+)?json|method|aspect))/) > -1) { - result = 'javascript'; - } else if (typeAttribute.search(/(text|application|dojo)\/(x-)?(html)/) > -1) { - result = 'html'; - } else if (typeAttribute.search(/test\/null/) > -1) { - // Test only mime-type for testing the beautifier when null is passed as beautifing function - result = 'null'; - } - - return result; -}; - -function in_array(what, arr) { - return arr.indexOf(what) !== -1; -} - -function TagFrame(parent, parser_token, indent_level) { - this.parent = parent || null; - this.tag = parser_token ? parser_token.tag_name : ''; - this.indent_level = indent_level || 0; - this.parser_token = parser_token || null; -} - -function TagStack(printer) { - this._printer = printer; - this._current_frame = null; -} - -TagStack.prototype.get_parser_token = function() { - return this._current_frame ? this._current_frame.parser_token : null; -}; - -TagStack.prototype.record_tag = function(parser_token) { //function to record a tag and its parent in this.tags Object - var new_frame = new TagFrame(this._current_frame, parser_token, this._printer.indent_level); - this._current_frame = new_frame; -}; - -TagStack.prototype._try_pop_frame = function(frame) { //function to retrieve the opening tag to the corresponding closer - var parser_token = null; - - if (frame) { - parser_token = frame.parser_token; - this._printer.indent_level = frame.indent_level; - this._current_frame = frame.parent; - } - - return parser_token; -}; - -TagStack.prototype._get_frame = function(tag_list, stop_list) { //function to retrieve the opening tag to the corresponding closer - var frame = this._current_frame; - - while (frame) { //till we reach '' (the initial value); - if (tag_list.indexOf(frame.tag) !== -1) { //if this is it use it - break; - } else if (stop_list && stop_list.indexOf(frame.tag) !== -1) { - frame = null; - break; - } - frame = frame.parent; - } - - return frame; -}; - -TagStack.prototype.try_pop = function(tag, stop_list) { //function to retrieve the opening tag to the corresponding closer - var frame = this._get_frame([tag], stop_list); - return this._try_pop_frame(frame); -}; - -TagStack.prototype.indent_to_tag = function(tag_list) { - var frame = this._get_frame(tag_list); - if (frame) { - this._printer.indent_level = frame.indent_level; - } -}; - -function Beautifier(source_text, options, js_beautify, css_beautify) { - //Wrapper function to invoke all the necessary constructors and deal with the output. - this._source_text = source_text || ''; - options = options || {}; - this._js_beautify = js_beautify; - this._css_beautify = css_beautify; - this._tag_stack = null; - - // Allow the setting of language/file-type specific options - // with inheritance of overall settings - var optionHtml = new Options(options, 'html'); - - this._options = optionHtml; - - this._is_wrap_attributes_force = this._options.wrap_attributes.substr(0, 'force'.length) === 'force'; - this._is_wrap_attributes_force_expand_multiline = (this._options.wrap_attributes === 'force-expand-multiline'); - this._is_wrap_attributes_force_aligned = (this._options.wrap_attributes === 'force-aligned'); - this._is_wrap_attributes_aligned_multiple = (this._options.wrap_attributes === 'aligned-multiple'); - this._is_wrap_attributes_preserve = this._options.wrap_attributes.substr(0, 'preserve'.length) === 'preserve'; - this._is_wrap_attributes_preserve_aligned = (this._options.wrap_attributes === 'preserve-aligned'); -} - -Beautifier.prototype.beautify = function() { - - // if disabled, return the input unchanged. - if (this._options.disabled) { - return this._source_text; - } - - var source_text = this._source_text; - var eol = this._options.eol; - if (this._options.eol === 'auto') { - eol = '\n'; - if (source_text && lineBreak.test(source_text)) { - eol = source_text.match(lineBreak)[0]; - } - } - - // HACK: newline parsing inconsistent. This brute force normalizes the input. - source_text = source_text.replace(allLineBreaks, '\n'); - - var baseIndentString = source_text.match(/^[\t ]*/)[0]; - - var last_token = { - text: '', - type: '' - }; - - var last_tag_token = new TagOpenParserToken(); - - var printer = new Printer(this._options, baseIndentString); - var tokens = new Tokenizer(source_text, this._options).tokenize(); - - this._tag_stack = new TagStack(printer); - - var parser_token = null; - var raw_token = tokens.next(); - while (raw_token.type !== TOKEN.EOF) { - - if (raw_token.type === TOKEN.TAG_OPEN || raw_token.type === TOKEN.COMMENT) { - parser_token = this._handle_tag_open(printer, raw_token, last_tag_token, last_token); - last_tag_token = parser_token; - } else if ((raw_token.type === TOKEN.ATTRIBUTE || raw_token.type === TOKEN.EQUALS || raw_token.type === TOKEN.VALUE) || - (raw_token.type === TOKEN.TEXT && !last_tag_token.tag_complete)) { - parser_token = this._handle_inside_tag(printer, raw_token, last_tag_token, tokens); - } else if (raw_token.type === TOKEN.TAG_CLOSE) { - parser_token = this._handle_tag_close(printer, raw_token, last_tag_token); - } else if (raw_token.type === TOKEN.TEXT) { - parser_token = this._handle_text(printer, raw_token, last_tag_token); - } else { - // This should never happen, but if it does. Print the raw token - printer.add_raw_token(raw_token); - } - - last_token = parser_token; - - raw_token = tokens.next(); - } - var sweet_code = printer._output.get_code(eol); - - return sweet_code; -}; - -Beautifier.prototype._handle_tag_close = function(printer, raw_token, last_tag_token) { - var parser_token = { - text: raw_token.text, - type: raw_token.type - }; - printer.alignment_size = 0; - last_tag_token.tag_complete = true; - - printer.set_space_before_token(raw_token.newlines || raw_token.whitespace_before !== '', true); - if (last_tag_token.is_unformatted) { - printer.add_raw_token(raw_token); - } else { - if (last_tag_token.tag_start_char === '<') { - printer.set_space_before_token(raw_token.text[0] === '/', true); // space before />, no space before > - if (this._is_wrap_attributes_force_expand_multiline && last_tag_token.has_wrapped_attrs) { - printer.print_newline(false); - } - } - printer.print_token(raw_token); - - } - - if (last_tag_token.indent_content && - !(last_tag_token.is_unformatted || last_tag_token.is_content_unformatted)) { - printer.indent(); - - // only indent once per opened tag - last_tag_token.indent_content = false; - } - - if (!last_tag_token.is_inline_element && - !(last_tag_token.is_unformatted || last_tag_token.is_content_unformatted)) { - printer.set_wrap_point(); - } - - return parser_token; -}; - -Beautifier.prototype._handle_inside_tag = function(printer, raw_token, last_tag_token, tokens) { - var wrapped = last_tag_token.has_wrapped_attrs; - var parser_token = { - text: raw_token.text, - type: raw_token.type - }; - - printer.set_space_before_token(raw_token.newlines || raw_token.whitespace_before !== '', true); - if (last_tag_token.is_unformatted) { - printer.add_raw_token(raw_token); - } else if (last_tag_token.tag_start_char === '{' && raw_token.type === TOKEN.TEXT) { - // For the insides of handlebars allow newlines or a single space between open and contents - if (printer.print_preserved_newlines(raw_token)) { - raw_token.newlines = 0; - printer.add_raw_token(raw_token); - } else { - printer.print_token(raw_token); - } - } else { - if (raw_token.type === TOKEN.ATTRIBUTE) { - printer.set_space_before_token(true); - last_tag_token.attr_count += 1; - } else if (raw_token.type === TOKEN.EQUALS) { //no space before = - printer.set_space_before_token(false); - } else if (raw_token.type === TOKEN.VALUE && raw_token.previous.type === TOKEN.EQUALS) { //no space before value - printer.set_space_before_token(false); - } - - if (raw_token.type === TOKEN.ATTRIBUTE && last_tag_token.tag_start_char === '<') { - if (this._is_wrap_attributes_preserve || this._is_wrap_attributes_preserve_aligned) { - printer.traverse_whitespace(raw_token); - wrapped = wrapped || raw_token.newlines !== 0; - } - - - if (this._is_wrap_attributes_force) { - var force_attr_wrap = last_tag_token.attr_count > 1; - if (this._is_wrap_attributes_force_expand_multiline && last_tag_token.attr_count === 1) { - var is_only_attribute = true; - var peek_index = 0; - var peek_token; - do { - peek_token = tokens.peek(peek_index); - if (peek_token.type === TOKEN.ATTRIBUTE) { - is_only_attribute = false; - break; - } - peek_index += 1; - } while (peek_index < 4 && peek_token.type !== TOKEN.EOF && peek_token.type !== TOKEN.TAG_CLOSE); - - force_attr_wrap = !is_only_attribute; - } - - if (force_attr_wrap) { - printer.print_newline(false); - wrapped = true; - } - } - } - printer.print_token(raw_token); - wrapped = wrapped || printer.previous_token_wrapped(); - last_tag_token.has_wrapped_attrs = wrapped; - } - return parser_token; -}; - -Beautifier.prototype._handle_text = function(printer, raw_token, last_tag_token) { - var parser_token = { - text: raw_token.text, - type: 'TK_CONTENT' - }; - if (last_tag_token.custom_beautifier_name) { //check if we need to format javascript - this._print_custom_beatifier_text(printer, raw_token, last_tag_token); - } else if (last_tag_token.is_unformatted || last_tag_token.is_content_unformatted) { - printer.add_raw_token(raw_token); - } else { - printer.traverse_whitespace(raw_token); - printer.print_token(raw_token); - } - return parser_token; -}; - -Beautifier.prototype._print_custom_beatifier_text = function(printer, raw_token, last_tag_token) { - var local = this; - if (raw_token.text !== '') { - - var text = raw_token.text, - _beautifier, - script_indent_level = 1, - pre = '', - post = ''; - if (last_tag_token.custom_beautifier_name === 'javascript' && typeof this._js_beautify === 'function') { - _beautifier = this._js_beautify; - } else if (last_tag_token.custom_beautifier_name === 'css' && typeof this._css_beautify === 'function') { - _beautifier = this._css_beautify; - } else if (last_tag_token.custom_beautifier_name === 'html') { - _beautifier = function(html_source, options) { - var beautifier = new Beautifier(html_source, options, local._js_beautify, local._css_beautify); - return beautifier.beautify(); - }; - } - - if (this._options.indent_scripts === "keep") { - script_indent_level = 0; - } else if (this._options.indent_scripts === "separate") { - script_indent_level = -printer.indent_level; - } - - var indentation = printer.get_full_indent(script_indent_level); - - // if there is at least one empty line at the end of this text, strip it - // we'll be adding one back after the text but before the containing tag. - text = text.replace(/\n[ \t]*$/, ''); - - // Handle the case where content is wrapped in a comment or cdata. - if (last_tag_token.custom_beautifier_name !== 'html' && - text[0] === '<' && text.match(/^(|]]>)$/.exec(text); - - // if we start to wrap but don't finish, print raw - if (!matched) { - printer.add_raw_token(raw_token); - return; - } - - pre = indentation + matched[1] + '\n'; - text = matched[4]; - if (matched[5]) { - post = indentation + matched[5]; - } - - // if there is at least one empty line at the end of this text, strip it - // we'll be adding one back after the text but before the containing tag. - text = text.replace(/\n[ \t]*$/, ''); - - if (matched[2] || matched[3].indexOf('\n') !== -1) { - // if the first line of the non-comment text has spaces - // use that as the basis for indenting in null case. - matched = matched[3].match(/[ \t]+$/); - if (matched) { - raw_token.whitespace_before = matched[0]; - } - } - } - - if (text) { - if (_beautifier) { - - // call the Beautifier if avaliable - var Child_options = function() { - this.eol = '\n'; - }; - Child_options.prototype = this._options.raw_options; - var child_options = new Child_options(); - text = _beautifier(indentation + text, child_options); - } else { - // simply indent the string otherwise - var white = raw_token.whitespace_before; - if (white) { - text = text.replace(new RegExp('\n(' + white + ')?', 'g'), '\n'); - } - - text = indentation + text.replace(/\n/g, '\n' + indentation); - } - } - - if (pre) { - if (!text) { - text = pre + post; - } else { - text = pre + text + '\n' + post; - } - } - - printer.print_newline(false); - if (text) { - raw_token.text = text; - raw_token.whitespace_before = ''; - raw_token.newlines = 0; - printer.add_raw_token(raw_token); - printer.print_newline(true); - } - } -}; - -Beautifier.prototype._handle_tag_open = function(printer, raw_token, last_tag_token, last_token) { - var parser_token = this._get_tag_open_token(raw_token); - - if ((last_tag_token.is_unformatted || last_tag_token.is_content_unformatted) && - !last_tag_token.is_empty_element && - raw_token.type === TOKEN.TAG_OPEN && raw_token.text.indexOf(']*)/); - this.tag_check = tag_check_match ? tag_check_match[1] : ''; - } else { - tag_check_match = raw_token.text.match(/^{{(?:[\^]|#\*?)?([^\s}]+)/); - this.tag_check = tag_check_match ? tag_check_match[1] : ''; - - // handle "{{#> myPartial}} - if (raw_token.text === '{{#>' && this.tag_check === '>' && raw_token.next !== null) { - this.tag_check = raw_token.next.text; - } - } - this.tag_check = this.tag_check.toLowerCase(); - - if (raw_token.type === TOKEN.COMMENT) { - this.tag_complete = true; - } - - this.is_start_tag = this.tag_check.charAt(0) !== '/'; - this.tag_name = !this.is_start_tag ? this.tag_check.substr(1) : this.tag_check; - this.is_end_tag = !this.is_start_tag || - (raw_token.closed && raw_token.closed.text === '/>'); - - // handlebars tags that don't start with # or ^ are single_tags, and so also start and end. - this.is_end_tag = this.is_end_tag || - (this.tag_start_char === '{' && (this.text.length < 3 || (/[^#\^]/.test(this.text.charAt(2))))); - } -}; - -Beautifier.prototype._get_tag_open_token = function(raw_token) { //function to get a full tag and parse its type - var parser_token = new TagOpenParserToken(this._tag_stack.get_parser_token(), raw_token); - - parser_token.alignment_size = this._options.wrap_attributes_indent_size; - - parser_token.is_end_tag = parser_token.is_end_tag || - in_array(parser_token.tag_check, this._options.void_elements); - - parser_token.is_empty_element = parser_token.tag_complete || - (parser_token.is_start_tag && parser_token.is_end_tag); - - parser_token.is_unformatted = !parser_token.tag_complete && in_array(parser_token.tag_check, this._options.unformatted); - parser_token.is_content_unformatted = !parser_token.is_empty_element && in_array(parser_token.tag_check, this._options.content_unformatted); - parser_token.is_inline_element = in_array(parser_token.tag_name, this._options.inline) || parser_token.tag_start_char === '{'; - - return parser_token; -}; - -Beautifier.prototype._set_tag_position = function(printer, raw_token, parser_token, last_tag_token, last_token) { - - if (!parser_token.is_empty_element) { - if (parser_token.is_end_tag) { //this tag is a double tag so check for tag-ending - parser_token.start_tag_token = this._tag_stack.try_pop(parser_token.tag_name); //remove it and all ancestors - } else { // it's a start-tag - // check if this tag is starting an element that has optional end element - // and do an ending needed - if (this._do_optional_end_element(parser_token)) { - if (!parser_token.is_inline_element) { - printer.print_newline(false); - } - } - - this._tag_stack.record_tag(parser_token); //push it on the tag stack - - if ((parser_token.tag_name === 'script' || parser_token.tag_name === 'style') && - !(parser_token.is_unformatted || parser_token.is_content_unformatted)) { - parser_token.custom_beautifier_name = get_custom_beautifier_name(parser_token.tag_check, raw_token); - } - } - } - - if (in_array(parser_token.tag_check, this._options.extra_liners)) { //check if this double needs an extra line - printer.print_newline(false); - if (!printer._output.just_added_blankline()) { - printer.print_newline(true); - } - } - - if (parser_token.is_empty_element) { //if this tag name is a single tag type (either in the list or has a closing /) - - // if you hit an else case, reset the indent level if you are inside an: - // 'if', 'unless', or 'each' block. - if (parser_token.tag_start_char === '{' && parser_token.tag_check === 'else') { - this._tag_stack.indent_to_tag(['if', 'unless', 'each']); - parser_token.indent_content = true; - // Don't add a newline if opening {{#if}} tag is on the current line - var foundIfOnCurrentLine = printer.current_line_has_match(/{{#if/); - if (!foundIfOnCurrentLine) { - printer.print_newline(false); - } - } - - // Don't add a newline before elements that should remain where they are. - if (parser_token.tag_name === '!--' && last_token.type === TOKEN.TAG_CLOSE && - last_tag_token.is_end_tag && parser_token.text.indexOf('\n') === -1) { - //Do nothing. Leave comments on same line. - } else { - if (!(parser_token.is_inline_element || parser_token.is_unformatted)) { - printer.print_newline(false); - } - this._calcluate_parent_multiline(printer, parser_token); - } - } else if (parser_token.is_end_tag) { //this tag is a double tag so check for tag-ending - var do_end_expand = false; - - // deciding whether a block is multiline should not be this hard - do_end_expand = parser_token.start_tag_token && parser_token.start_tag_token.multiline_content; - do_end_expand = do_end_expand || (!parser_token.is_inline_element && - !(last_tag_token.is_inline_element || last_tag_token.is_unformatted) && - !(last_token.type === TOKEN.TAG_CLOSE && parser_token.start_tag_token === last_tag_token) && - last_token.type !== 'TK_CONTENT' - ); - - if (parser_token.is_content_unformatted || parser_token.is_unformatted) { - do_end_expand = false; - } - - if (do_end_expand) { - printer.print_newline(false); - } - } else { // it's a start-tag - parser_token.indent_content = !parser_token.custom_beautifier_name; - - if (parser_token.tag_start_char === '<') { - if (parser_token.tag_name === 'html') { - parser_token.indent_content = this._options.indent_inner_html; - } else if (parser_token.tag_name === 'head') { - parser_token.indent_content = this._options.indent_head_inner_html; - } else if (parser_token.tag_name === 'body') { - parser_token.indent_content = this._options.indent_body_inner_html; - } - } - - if (!(parser_token.is_inline_element || parser_token.is_unformatted) && - (last_token.type !== 'TK_CONTENT' || parser_token.is_content_unformatted)) { - printer.print_newline(false); - } - - this._calcluate_parent_multiline(printer, parser_token); - } -}; - -Beautifier.prototype._calcluate_parent_multiline = function(printer, parser_token) { - if (parser_token.parent && printer._output.just_added_newline() && - !((parser_token.is_inline_element || parser_token.is_unformatted) && parser_token.parent.is_inline_element)) { - parser_token.parent.multiline_content = true; - } -}; - -//To be used for

tag special case: -var p_closers = ['address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul']; -var p_parent_excludes = ['a', 'audio', 'del', 'ins', 'map', 'noscript', 'video']; - -Beautifier.prototype._do_optional_end_element = function(parser_token) { - var result = null; - // NOTE: cases of "if there is no more content in the parent element" - // are handled automatically by the beautifier. - // It assumes parent or ancestor close tag closes all children. - // https://www.w3.org/TR/html5/syntax.html#optional-tags - if (parser_token.is_empty_element || !parser_token.is_start_tag || !parser_token.parent) { - return; - - } - - if (parser_token.tag_name === 'body') { - // A head element’s end tag may be omitted if the head element is not immediately followed by a space character or a comment. - result = result || this._tag_stack.try_pop('head'); - - //} else if (parser_token.tag_name === 'body') { - // DONE: A body element’s end tag may be omitted if the body element is not immediately followed by a comment. - - } else if (parser_token.tag_name === 'li') { - // An li element’s end tag may be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element. - result = result || this._tag_stack.try_pop('li', ['ol', 'ul']); - - } else if (parser_token.tag_name === 'dd' || parser_token.tag_name === 'dt') { - // A dd element’s end tag may be omitted if the dd element is immediately followed by another dd element or a dt element, or if there is no more content in the parent element. - // A dt element’s end tag may be omitted if the dt element is immediately followed by another dt element or a dd element. - result = result || this._tag_stack.try_pop('dt', ['dl']); - result = result || this._tag_stack.try_pop('dd', ['dl']); - - - } else if (parser_token.parent.tag_name === 'p' && p_closers.indexOf(parser_token.tag_name) !== -1) { - // IMPORTANT: this else-if works because p_closers has no overlap with any other element we look for in this method - // check for the parent element is an HTML element that is not an ,

- ${this.textEl} -
` - } -} - -},{"./editor/editor.js":138,"choo/component":20,"choo/html":21}],137:[function(require,module,exports){ -const html = require('choo/html') -const Component = require('choo/component') -const HydraSynth = require('hydra-synth') - -module.exports = class Hydra extends Component { - constructor (id, state, emit) { - super(id) - this.local = state.components[id] = {} - state.hydra = this - } - - load (element) { - const hydra = new HydraSynth({ detectAudio: true, canvas: element.querySelector("canvas")}) - console.log(hydra) - this.hydra = hydra - osc().out() - } - - update (center) { - return false - } - - createElement ({ width = window.innerWidth, height = window.innerHeight} = {}) { - - return html`
-
` - } -} - -},{"choo/component":20,"choo/html":21,"hydra-synth":43}],138:[function(require,module,exports){ -/* eslint-disable no-eval */ -var CodeMirror = require('codemirror-minified/lib/codemirror') -require('codemirror-minified/mode/javascript/javascript') -require('codemirror-minified/addon/hint/javascript-hint') -require('codemirror-minified/addon/hint/show-hint') -require('codemirror-minified/addon/selection/mark-selection') -require('codemirror-minified/addon/comment/comment') - -const EventEmitter = require('nanobus') -const keymaps = require('./keymaps.js') -const Mutator = require('./randomizer/Mutator.js'); -const beautify_js = require('js-beautify').js_beautify - -var isShowing = true - - -module.exports = class Editor extends EventEmitter { - constructor(parent) { - super() - console.log("*** Editor class created"); - var self = this - - // var container = document.createElement('div') - // container.setAttribute('id', 'editor-container') - // var el = document.createElement('TEXTAREA') - // document.body.appendChild(container) - // container.appendChild(el) - - this.mutator = new Mutator(this); - - const extraKeys = {} - Object.entries(keymaps).forEach(([key, e]) => extraKeys[key] = () => { - if(e == 'editor:evalBlock') { - this.emit(e, this.getCurrentBlock().text) - } else if (e == 'editor:evalLine') { - this.emit(e, this.getLine()) - } else if (e == 'editor:toggleComment') { - this.cm.toggleComment() - // } else if (e == 'gallery:saveToURL') { - this.emit(e, this) - } else if (e === 'editor:formatCode') { - this.formatCode() - } else { - this.emit(e, this) - } - }) - - const opts = { - theme: 'tomorrow-night-eighties', - value: 'hello', - mode: { name: 'javascript', globalVars: true }, - lineWrapping: true, - styleSelectedText: true, - extraKeys: extraKeys - } - - this.cm = CodeMirror.fromTextArea(parent, opts) - window.cm = this.cm - this.cm.refresh() - - // this.show() - // // // TO DO: add show code param - // let searchParams = new URLSearchParams(window.location.search) - // let showCode = searchParams.get('show-code') - - // if (showCode === "false") { - // this.hide() - // } - } - - clear() { - this.cm.setValue('\n \n // Type some code on a new line (such as "osc().out()"), and press CTRL+shift+enter') - } - - setValue(val) { - this.cm.setValue(val) - } - - getValue() { - return this.cm.getValue() - } - - formatCode() { - const formatted = beautify_js(this.cm.getValue(), { indent_size: 2, "break_chained_methods": true, "indent_with_tabs": true}) - this.cm.setValue(formatted) - } - - // hide() { - // console.log('hiding') - // var l = document.getElementsByClassName('CodeMirror')[0] - // var m = document.getElementById('modal-header') - // l.style.opacity = 0 - // m.style.opacity = 0 - // this.isShowing = false - // } - - // show() { - // var l = document.getElementsByClassName('CodeMirror')[0] - // var m = document.getElementById('modal-header') - // l.style.opacity= 1 - // m.style.opacity = 1 - // l.style.pointerEvents = 'all' - // this.isShowing = true - // } - - toggle() { - if (this.isShowing) { - this.hide() - } else { - this.show() - } - } - - getLine() { - var c = this.cm.getCursor() - var s = this.cm.getLine(c.line) - // this.cm.markText({line: c.line, ch:0}, {line: c.line+1, ch:0}, {className: 'styled-background'}) - this.flashCode({ line: c.line, ch: 0 }, { line: c.line + 1, ch: 0 }) - return s - } - - flashCode(start, end) { - if (!start) start = { line: this.cm.firstLine(), ch: 0 } - if (!end) end = { line: this.cm.lastLine() + 1, ch: 0 } - var marker = this.cm.markText(start, end, { className: 'styled-background' }) - setTimeout(() => marker.clear(), 300) - } - - - getCurrentBlock() { // thanks to graham wakefield + gibber - var editor = this.cm - var pos = editor.getCursor() - var startline = pos.line - var endline = pos.line - while (startline > 0 && editor.getLine(startline) !== '') { - startline-- - } - while (endline < editor.lineCount() && editor.getLine(endline) !== '') { - endline++ - } - var pos1 = { - line: startline, - ch: 0 - } - var pos2 = { - line: endline, - ch: 0 - } - var str = editor.getRange(pos1, pos2) - - this.flashCode(pos1, pos2) - - return { - start: pos1, - end: pos2, - text: str - } - } - -} - - -},{"./keymaps.js":139,"./randomizer/Mutator.js":141,"codemirror-minified/addon/comment/comment":25,"codemirror-minified/addon/hint/javascript-hint":26,"codemirror-minified/addon/hint/show-hint":27,"codemirror-minified/addon/selection/mark-selection":28,"codemirror-minified/lib/codemirror":29,"codemirror-minified/mode/javascript/javascript":30,"js-beautify":64,"nanobus":89}],139:[function(require,module,exports){ -module.exports = { - 'Ctrl-Enter': 'editor:evalLine', - 'Ctrl-/': 'editor:toggleComment', - 'Alt-Enter': 'editor:evalBlock', - 'Shift-Ctrl-Enter': 'editor:evalAll', - 'Shift-Ctrl-G': 'gallery:shareSketch', - 'Shift-Ctrl-F': 'editor:formatCode', - 'Shift-Ctrl-L': 'gallery:saveToURL', - 'Shift-Ctrl-H': 'hideAll', - 'Shift-Ctrl-S': 'screencap' -} -},{}],140:[function(require,module,exports){ -var logElement - -module.exports = { - init: () => { - logElement = document.createElement('div') - logElement.className = "console cm-s-tomorrow-night-eighties" - document.body.appendChild(logElement) - }, - log: (msg, className = "") => { - if(logElement) logElement.innerHTML =` >> ${msg} ` - }, - hide: () => { - if(logElement) logElement.style.display = 'none' - }, - show: () => { - if(logElement) logElement.style.display = 'block' - }, - toggle: () => { - if(logElement.style.display == 'none') { - logElement.style.display = 'block' - } else { - logElement.style.display = 'none' - } - } -} - -},{}],141:[function(require,module,exports){ -const {Parser} = require("acorn"); -const {generate} = require('astring'); -const { defaultTraveler, attachComments, makeTraveler } = require('astravel'); -const {UndoStack} = require('./UndoStack.js'); -const repl = require('./../repl.js') -const glslTransforms = require('hydra-synth/src/glsl/glsl-functions.js')() - -class Mutator { - - constructor(editor) { - this.editor = editor; - this.undoStack = new UndoStack(); - - this.initialVector = []; - - this.funcTab = {}; - this.transMap = {}; - this.scanFuncs(); - this.dumpDict(); - } - - dumpList() { - let gslTab = glslTransforms; - gslTab.forEach (v => { - var argList = ""; - v.inputs.forEach((a) => { - if (argList != "") argList += ", "; - let argL = a.name + ": " + a.type + " {" + a.default + "}"; - argList = argList + argL; - }); - // console.log(v.name + " [" + v.type + "] ("+ argList + ")"); - }); - } - - scanFuncs() { - let gslTab = glslTransforms; - gslTab.forEach (f => { - this.transMap[f.name] = f; - if (this.funcTab[f.type] === undefined) {this.funcTab[f.type] = []} - this.funcTab[f.type].push(f); - }); - } - - dumpDict() { - for(let tn in this.funcTab) - { - this.funcTab[tn].forEach(f => { - var argList = ""; - f.inputs.forEach((a) => { - if (argList != "") argList += ", "; - let argL = a.name + ": " + a.type + " {" + a.default + "}"; - argList = argList + argL; - }); - //console.log(f.name + " [" + f.type + "] ("+ argList + ")"); - }); - } - } - - mutate(options) { - // Get text from CodeMirror. - let text = this.editor.cm.getValue(); - this.undoStack.push({text, lastLitX: this.lastLitX}); - let needToRun = true; - let tryCounter = 5; - while (needToRun && tryCounter-- >= 0) { - // Parse to AST - var comments = []; - let ast = Parser.parse(text, { - locations: true, - onComment: comments} - ); - - // Modify the AST. - this.transform(ast, options); - - // Put the comments back. - attachComments(ast, comments); - - // Generate JS from AST and set back into CodeMirror editor. - let regen = generate(ast, {comments: true}); - - this.editor.cm.setValue(regen); - try { - // Evaluate the updated expression. - repl.eval(regen, (code, error) => { - // If we got an error, keep trying something else. - if (error) { - console.log("Eval error: " + regen); - } - needToRun = error; - }); - } catch (err) { - console.log("Exception caught: " + err); - needToRun = err; - } - } - } - - doUndo() { - // If the current text is unsaved, save it so we can redo if need be. - if (this.undoStack.atTop()) { - let text = this.editor.cm.getValue(); - this.undoStack.push({text, lastLitX: this.lastLitX}); - } - // Then pop-off the info to restore. - if (this.undoStack.canUndo()) { - let {text, lastLitX} = this.undoStack.undo(); - this.setText(text); - this.lastLitX = lastLitX; - } - } - - doRedo() { - if(this.undoStack.canRedo()) { - let {text, lastLitX} = this.undoStack.redo(); - this.setText(text); - this.lastLitX = lastLitX; - } - } - - setText(text) { - this.editor.cm.setValue(text); - repl.eval(text, (code, error) => { - }); - - } - - // The options object contains a flag that controls how the - // Literal to mutate is determined. If reroll is false, we - // pick one at random. If reroll is true, we use the same field - // we did last time. - transform(ast, options) { - // An AST traveler that accumulates a list of Literal nodes. - let traveler = makeTraveler({ - go: function(node, state) { - if (node.type === 'Literal') { - state.literalTab.push(node); - } else if (node.type === 'MemberExpression') { - if (node.property && node.property.type === 'Literal') { - // numeric array subscripts are ineligable - return; - } - } else if (node.type === 'CallExpression') { - if (node.callee && node.callee.property && node.callee.property.name && node.callee.property.name !== 'out') { - state.functionTab.push(node); - } - } - // Call the parent's `go` method - this.super.go.call(this, node, state); - } - }); - - let state = {}; - state.literalTab = []; - state.functionTab = []; - - traveler.go(ast, state); - - this.litCount = state.literalTab.length; - this.funCount = state.functionTab.length; - if (this.litCount !== this.initialVector.length) { - let nextVect = []; - for(let i = 0; i < this.litCount; ++i) { - nextVect.push(state.literalTab[i].value); - } - this.initialVector = nextVect; - } - if (options.changeTransform) { - this.glitchTrans(state, options); - } - else this.glitchLiteral(state, options); - -} - - glitchLiteral(state, options) - { - let litx = 0; - if (options.reroll) { - if (this.lastLitX !== undefined) { - litx = this.lastLitX; - } - } else { - litx = Math.floor(Math.random() * this.litCount); - this.lastLitX = litx; - } - - let modLit = state.literalTab[litx]; - if (modLit) { - // let glitched = this.glitchNumber(modLit.value); - let glitched = this.glitchRelToInit(modLit.value, this.initialVector[litx]); - let was = modLit.raw; - modLit.value = glitched; - modLit.raw = "" + glitched; - console.log("Literal: " + litx + " changed from: " + was + " to: " + glitched); - } - } - - glitchNumber(num) { - if (num === 0) { - num = 1; - } - let range = num * 2; - let rndVal = Math.round(Math.random() * range * 1000) / 1000; - return rndVal; - } - - glitchRelToInit(num, initVal) { - if (initVal === undefined) { - return glitchNumber(num); - } if (initVal === 0) { - initVal = 0.5; - } - - let rndVal = Math.round(Math.random() * initVal * 2 * 1000) / 1000; - return rndVal; -} - glitchTrans(state, options) - { -/* - state.functionTab.forEach((f)=>{ - console.log(f.callee.property.name); - }); -*/ - let funx = Math.floor(Math.random() * this.funCount); - if (state.functionTab[funx] === undefined || state.functionTab[funx].callee === undefined || state.functionTab[funx].callee.property === undefined) { - console.log("No valid functionTab for index: " + funx); - return; - } - let oldName = state.functionTab[funx].callee.property.name; - - if (oldName == undefined) { - console.log("No name for callee"); - return; - } - let ftype = this.transMap[oldName].type; - if (ftype == undefined) { - console.log("ftype undefined for: " + oldName); - return; - } - let others = this.funcTab[ftype]; - if (others == undefined) { - console.log("no funcTab entry for: " + ftype); - return; - } - let changeX = Math.floor(Math.random() * others.length); - let become = others[changeX].name; - - // check blacklisted combinations. - if (oldName === "modulate" && become === "modulateScrollX") - { - console.log("Function: " + funx + " changing from: " + oldName + " can't change to: " + become); - return; - } - - state.functionTab[funx].callee.property.name = become; - console.log("Function: " + funx + " changed from: " + oldName + " to: " + become); - } - -} // End of class Mutator. - -module.exports = Mutator - -},{"./../repl.js":143,"./UndoStack.js":142,"acorn":2,"astravel":3,"astring":6,"hydra-synth/src/glsl/glsl-functions.js":49}],142:[function(require,module,exports){ -// A generalized 'Undo stack' which can keep N levels of revertable state. -class UndoStack { - constructor(limit) { - this.stack = []; - this.index = -1; - this.limit = limit; - } - - atTop() { - return this.index === -1; - } - - canUndo() { - if(this.stack.length === 0) return false; - return this.index === -1 || this.index > 0; - } - - canRedo() { - if(this.stack.length === 0 || this.index === -1) return false; - return this.index < this.stack.length - 1; - } - - push(item) { - if (this.index >= 0) { - while (this.index < this.stack.length) this.stack.pop(); - this.index = -1; - } - if (this.limit && this.stack.length > this.limit) { - this.stack.shift(); - } - this.stack.push(item); - } - - undo() { - if (this.stack.length === 0) return undefined; - if (this.index === -1) { // start one behind the redo buffer - this.index = this.stack.length - 1; - } - if (this.index > 0) this.index--; - let v = this.stack[this.index]; - return v; - } - - redo() { - if (this.stack.length === 0 || this.index === -1) return undefined; - let nextX = this.index + 1; - if (nextX >= this.stack.length) return undefined; - this.index = nextX; - return this.stack[this.index]; - } -}; - - -module.exports = {UndoStack} -},{}],143:[function(require,module,exports){ -const log = require('./log.js').log - -module.exports = { - eval: (arg, callback) => { - var self = this - - // wrap everything in an async function - var jsString = `(async() => { - ${arg} -})().catch(${(err) => log(err.message, "log-error")})` - var isError = false - try { - eval(jsString) - // log(jsString) - log('') - } catch (e) { - isError = true - console.log("logging", e) - // var err = e.constructor('Error in Evaled Script: ' + e.message); - // console.log(err.lineNumber) - log(e.message, "log-error") - //console.log('ERROR', JSON.stringify(e)) - } - // console.log('callback is', callback) - if(callback) callback(jsString, isError) - } -} - -},{"./log.js":140}],144:[function(require,module,exports){ -const html = require('choo/html') -const toolbar = require('./toolbar.js') - -module.exports = function mainView(state, emit) { - return html` -
- -
- ` -} -},{"./toolbar.js":146,"choo/html":21}],145:[function(require,module,exports){ -const html = require('choo/html') -const info = require('./info.js') -const Hydra = require('./Hydra.js') -const Editor = require('./EditorComponent.js') -module.exports = function mainView (state, emit) { - return html` - -
- - ${state.cache(Hydra, 'hydra-canvas').render(state, emit)} - -
- ${info(state, emit)} - ${state.cache(Editor, 'editor').render(state, emit)} - - - ` - - function onclick () { - emit('increment', 1) - } - } -},{"./EditorComponent.js":136,"./Hydra.js":137,"./info.js":144,"choo/html":21}],146:[function(require,module,exports){ -const html = require('choo/html') - -module.exports = function toolbar(state, emit) { - const hidden = state.showInfo ? 'hidden' : '' - - const dispatch = (eventName) => (e) => emit(eventName, e) - - const icon = (id, className, title, event) => html` - ` - - return html`
- ${icon("run", `fa-play-circle ${hidden}`, "Run all code (ctrl+shift+enter)", 'editor:evalAll')} - ${icon("share", `fa-upload ${hidden}`, "upload to gallery", 'gallery:shareSketch')} - ${icon("clear", `fa fa-trash ${hidden}`, "clear all", 'editor:clearAll')} - ${icon("shuffle", `fa-random`, "show random sketch", 'gallery:showExample')} - ${icon("mutator", `fa-dice ${hidden}`, "make random change", 'editor:randomize')} - ${icon("close", state.showInfo? "fa-times" : "fa-question-circle", "", 'toggle info')} -
` -} -},{"choo/html":21}],147:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var objectAssign = require('object-assign'); - -// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js -// original notice: - -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -function compare(a, b) { - if (a === b) { - return 0; - } - - var x = a.length; - var y = b.length; - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } - - if (x < y) { - return -1; - } - if (y < x) { - return 1; - } - return 0; -} -function isBuffer(b) { - if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { - return global.Buffer.isBuffer(b); - } - return !!(b != null && b._isBuffer); -} - -// based on node assert, original notice: -// NB: The URL to the CommonJS spec is kept just for tradition. -// node-assert has evolved a lot since then, both in API and behavior. - -// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 -// -// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! -// -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.com> -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the 'Software'), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -var util = require('util/'); -var hasOwn = Object.prototype.hasOwnProperty; -var pSlice = Array.prototype.slice; -var functionsHaveNames = (function () { - return function foo() {}.name === 'foo'; -}()); -function pToString (obj) { - return Object.prototype.toString.call(obj); -} -function isView(arrbuf) { - if (isBuffer(arrbuf)) { - return false; - } - if (typeof global.ArrayBuffer !== 'function') { - return false; - } - if (typeof ArrayBuffer.isView === 'function') { - return ArrayBuffer.isView(arrbuf); - } - if (!arrbuf) { - return false; - } - if (arrbuf instanceof DataView) { - return true; - } - if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { - return true; - } - return false; -} -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = module.exports = ok; - -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({ message: message, -// actual: actual, -// expected: expected }) - -var regex = /\s*function\s+([^\(\s]*)\s*/; -// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js -function getName(func) { - if (!util.isFunction(func)) { - return; - } - if (functionsHaveNames) { - return func.name; - } - var str = func.toString(); - var match = str.match(regex); - return match && match[1]; -} -assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; - } else { - this.message = getMessage(this); - this.generatedMessage = true; - } - var stackStartFunction = options.stackStartFunction || fail; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; - - // try to strip useless frames - var fn_name = getName(stackStartFunction); - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } - - this.stack = out; - } - } -}; - -// assert.AssertionError instanceof Error -util.inherits(assert.AssertionError, Error); - -function truncate(s, n) { - if (typeof s === 'string') { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } -} -function inspect(something) { - if (functionsHaveNames || !util.isFunction(something)) { - return util.inspect(something); - } - var rawname = getName(something); - var name = rawname ? ': ' + rawname : ''; - return '[Function' + name + ']'; -} -function getMessage(self) { - return truncate(inspect(self.actual), 128) + ' ' + - self.operator + ' ' + - truncate(inspect(self.expected), 128); -} - -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. - -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. - -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} - -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; - -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, !!guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. - -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); -} -assert.ok = ok; - -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); - -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); -}; - -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); - -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } -}; - -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); - -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } -}; - -assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); - } -}; - -function _deepEqual(actual, expected, strict, memos) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - } else if (isBuffer(actual) && isBuffer(expected)) { - return compare(actual, expected) === 0; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if ((actual === null || typeof actual !== 'object') && - (expected === null || typeof expected !== 'object')) { - return strict ? actual === expected : actual == expected; - - // If both values are instances of typed arrays, wrap their underlying - // ArrayBuffers in a Buffer each to increase performance - // This optimization requires the arrays to have the same type as checked by - // Object.prototype.toString (aka pToString). Never perform binary - // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their - // bit patterns are not identical. - } else if (isView(actual) && isView(expected) && - pToString(actual) === pToString(expected) && - !(actual instanceof Float32Array || - actual instanceof Float64Array)) { - return compare(new Uint8Array(actual.buffer), - new Uint8Array(expected.buffer)) === 0; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else if (isBuffer(actual) !== isBuffer(expected)) { - return false; - } else { - memos = memos || {actual: [], expected: []}; - - var actualIndex = memos.actual.indexOf(actual); - if (actualIndex !== -1) { - if (actualIndex === memos.expected.indexOf(expected)) { - return true; - } - } - - memos.actual.push(actual); - memos.expected.push(expected); - - return objEquiv(actual, expected, strict, memos); - } -} - -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv(a, b, strict, actualVisitedObjects) { - if (a === null || a === undefined || b === null || b === undefined) - return false; - // if one is a primitive, the other must be same - if (util.isPrimitive(a) || util.isPrimitive(b)) - return a === b; - if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) - return false; - var aIsArgs = isArguments(a); - var bIsArgs = isArguments(b); - if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) - return false; - if (aIsArgs) { - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b, strict); - } - var ka = objectKeys(a); - var kb = objectKeys(b); - var key, i; - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length !== kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] !== kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) - return false; - } - return true; -} - -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); - -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } -}; - -assert.notDeepStrictEqual = notDeepStrictEqual; -function notDeepStrictEqual(actual, expected, message) { - if (_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); - } -} - - -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); - -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } -}; - -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); - -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } -}; - -function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } - - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } - - try { - if (actual instanceof expected) { - return true; - } - } catch (e) { - // Ignore. The instanceof check doesn't work for arrow functions. - } - - if (Error.isPrototypeOf(expected)) { - return false; - } - - return expected.call({}, actual) === true; -} - -function _tryBlock(block) { - var error; - try { - block(); - } catch (e) { - error = e; - } - return error; -} - -function _throws(shouldThrow, block, expected, message) { - var actual; - - if (typeof block !== 'function') { - throw new TypeError('"block" argument must be a function'); - } - - if (typeof expected === 'string') { - message = expected; - expected = null; - } - - actual = _tryBlock(block); - - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); - - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } - - var userProvidedMessage = typeof message === 'string'; - var isUnwantedException = !shouldThrow && util.isError(actual); - var isUnexpectedException = !shouldThrow && actual && !expected; - - if ((isUnwantedException && - userProvidedMessage && - expectedException(actual, expected)) || - isUnexpectedException) { - fail(actual, expected, 'Got unwanted exception' + message); - } - - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } -} - -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); - -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws(true, block, error, message); -}; - -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { - _throws(false, block, error, message); -}; - -assert.ifError = function(err) { if (err) throw err; }; - -// Expose a strict only variant of assert -function strict(value, message) { - if (!value) fail(value, true, message, '==', strict); -} -assert.strict = objectAssign(strict, assert, { - equal: assert.strictEqual, - deepEqual: assert.deepStrictEqual, - notEqual: assert.notStrictEqual, - notDeepEqual: assert.notDeepStrictEqual -}); -assert.strict.strict = assert.strict; - -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); - } - return keys; -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"object-assign":158,"util/":150}],148:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - -},{}],149:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],150:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":149,"_process":160,"inherits":148}],151:[function(require,module,exports){ +},{}],14:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength @@ -28136,9 +9057,508 @@ function fromByteArray (uint8) { return parts.join('') } -},{}],152:[function(require,module,exports){ +},{}],15:[function(require,module,exports){ -},{}],153:[function(require,module,exports){ +},{}],16:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var R = typeof Reflect === 'object' ? Reflect : null +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + } + +var ReflectOwnKeys +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} + +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} + +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +} + +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; +module.exports.once = once; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } +} + +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); + +EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; + +function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); +}; + +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + checkListener(listener); + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + checkListener(listener); + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +function once(emitter, name) { + return new Promise(function (resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } + + function resolver() { + if (typeof emitter.removeListener === 'function') { + emitter.removeListener('error', errorListener); + } + resolve([].slice.call(arguments)); + }; + + eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); + if (name !== 'error') { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); +} + +function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === 'function') { + eventTargetAgnosticAddListener(emitter, 'error', handler, flags); + } +} + +function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === 'function') { + if (flags.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === 'function') { + // EventTarget does not have `error` event semantics like Node + // EventEmitters, we do not listen for `error` events here. + emitter.addEventListener(name, function wrapListener(arg) { + // IE does not have builtin `{ once: true }` support so we + // have to do it manually. + if (flags.once) { + emitter.removeEventListener(name, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } +} + +},{}],17:[function(require,module,exports){ (function (Buffer){(function (){ /*! * The buffer module from node.js, for the browser. @@ -29919,506 +11339,8812 @@ function numberIsNaN (obj) { } }).call(this)}).call(this,require("buffer").Buffer) -},{"base64-js":151,"buffer":153,"ieee754":155}],154:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - +},{"base64-js":14,"buffer":17,"ieee754":96}],18:[function(require,module,exports){ 'use strict'; -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } +var GetIntrinsic = require('get-intrinsic'); -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; +var callBind = require('./'); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; + +},{"./":19,"get-intrinsic":67}],19:[function(require,module,exports){ +'use strict'; + +var bind = require('function-bind'); +var GetIntrinsic = require('get-intrinsic'); + +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); + +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); +var $max = GetIntrinsic('%Math.max%'); + +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = null; + } +} + +module.exports = function callBind(originalFunction) { + var func = $reflectApply(bind, $call, arguments); + if ($gOPD && $defineProperty) { + var desc = $gOPD(func, 'length'); + if (desc.configurable) { + // original length, plus the receiver, minus any additional arguments (after the receiver) + $defineProperty( + func, + 'length', + { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } + ); + } + } + return func; +}; + +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); } else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; + module.exports.apply = applyBind; } -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} +},{"function-bind":65,"get-intrinsic":67}],20:[function(require,module,exports){ +var EventEmitter = require('events').EventEmitter -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} +var storage = require('./lib/storage') +var logger = require('./lib/logger') +var debug = require('./lib/debug') +var copy = require('./lib/copy') +var help = require('./lib/help') +var perf = require('./lib/perf') +var log = require('./lib/log') +var getAllRoutes = require('wayfarer/get-all-routes') -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; -module.exports.once = once; +module.exports = expose -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; +function expose (opts) { + opts = opts || {} + store.storeName = 'choo-devtools' + return store + function store (state, emitter, app) { + var localEmitter = new EventEmitter() -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -function checkListener(listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } -} - -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + if (typeof window !== 'undefined') { + logger(state, emitter, opts) } - defaultMaxListeners = arg; + + emitter.on('DOMContentLoaded', function () { + if (typeof window === 'undefined') return + window.choo = {} + + window.choo.state = state + window.choo.emit = function () { + emitter.emit.apply(emitter, arguments) + } + window.choo.on = function (eventName, listener) { + emitter.on(eventName, listener) + } + + debug(state, emitter, app, localEmitter) + + log(state, emitter, app, localEmitter) + perf(state, emitter, app, localEmitter) + window.choo.copy = copy + if (app.router && app.router.router) { + window.choo.routes = Object.keys(getAllRoutes(app.router.router)) + } + + storage() + help() + }) } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; - -function _getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; } -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); -}; +},{"./lib/copy":21,"./lib/debug":22,"./lib/help":23,"./lib/log":24,"./lib/logger":25,"./lib/perf":26,"./lib/storage":27,"events":16,"wayfarer/get-all-routes":219}],21:[function(require,module,exports){ +var stateCopy = require('state-copy') +var pluck = require('plucker') -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); +module.exports = copy - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; +function copy (state) { + var isStateString = state && typeof state === 'string' + var isChooPath = isStateString && arguments.length === 1 && state.indexOf('state.') === 0 - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event + if (!state || typeof state === 'function') state = window.choo.state + if (isChooPath) [].push.call(arguments, { state: window.choo.state }) + + stateCopy(isStateString ? pluck.apply(this, arguments) : state) +} + +},{"plucker":153,"state-copy":211}],22:[function(require,module,exports){ +/* eslint-disable node/no-deprecated-api */ +var onChange = require('object-change-callsite') +var nanologger = require('nanologger') +var assert = require('assert') + +var enabledMessage = 'Debugging enabled. To disable run: `choo.debug = false`' +var disabledMessage = 'Debugging disabled. We hope it was helpful! 🙌' + +module.exports = debug + +function debug (state, emitter, app, localEmitter) { + var log = nanologger('choo-devtools') + var enabled = window.localStorage.logLevel === 'debug' + if (enabled) log.info(enabledMessage) + + state = onChange(state, function (attr, value, callsite) { + if (!enabled) return + callsite = callsite.split('\n')[1].replace(/^ +/, '') + log.info('state.' + attr, value, '\n' + callsite) + }) + + app.state = state + + Object.defineProperty(window.choo, 'debug', { + get: function () { + window.localStorage.logLevel = 'debug' + localEmitter.emit('debug', true) + enabled = true + return enabledMessage + }, + set: function (bool) { + assert.equal(typeof bool, 'boolean', 'choo-devtools.debug: bool should be type boolean') + window.localStorage.logLevel = bool ? 'debug' : 'info' + enabled = bool + localEmitter.emit('debug', enabled) + if (enabled) log.info(enabledMessage) + else log.info(disabledMessage) } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event + }) +} + +},{"assert":4,"nanologger":135,"object-change-callsite":146}],23:[function(require,module,exports){ +module.exports = help + +function help () { + Object.defineProperty(window.choo, 'help', { + get: get, + set: noop + }) + + function get () { + setTimeout(function () { + print('copy', 'Serialize the current state to the clipboard.') + print('debug', 'Enable Choo debug mode.') + print('emit', 'Emit an event in the Choo emitter.') + print('help', 'Print usage information.') + print('log', 'Print the last 150 events emitted.') + print('on', 'Listen for an event in the Choo emitter.') + print('once', 'Listen for an event once in the Choo emitter.') + print('perf', 'Print out performance metrics') + print('state', 'Print the Choo state object.') + print('storage', 'Print browser storage information.') + }, 0) + return 'Choo command overview' } +} - var handler = events[type]; +function print (cmd, desc) { + var color = '#cc99cc' + console.log(' %cchoo.' + cmd, 'color: ' + color, '— ' + desc) +} - if (handler === undefined) - return false; +function noop () {} - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } +},{}],24:[function(require,module,exports){ +var removeItems = require('remove-array-items') +var scheduler = require('nanoscheduler')() +var nanologger = require('nanologger') +var _log = nanologger('choo') +var clone = require('clone') - return true; -}; +var MAX_HISTORY_LENGTH = 150 // How many items we should keep around -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; +module.exports = log - checkListener(listener); +function log (state, emitter, app, localEmitter) { + var shouldDebug = window.localStorage.logLevel === 'debug' + var history = [] + var i = 0 + var shouldWarn = true - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); + localEmitter.on('debug', function (bool) { + shouldDebug = bool + }) - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } + window.choo._history = history + window.choo.history = showHistory - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); + Object.defineProperty(window.choo, 'log', { get: showHistory, set: noop }) + Object.defineProperty(window.choo, 'history', { get: showHistory, set: noop }) + + emitter.on('*', function (name, data) { + i += 1 + var entry = new Event(name, data, state) + history.push(entry) + scheduler.push(function () { + var length = history.length + if (length > MAX_HISTORY_LENGTH) { + removeItems(history, 0, length - MAX_HISTORY_LENGTH) + } + }) + }) + + function showHistory () { + setTimeout(function () { + console.table(history) + }, 0) + var events = i === 1 ? 'event' : 'events' + var msg = i + ' ' + events + ' recorded, showing the last ' + MAX_HISTORY_LENGTH + '.' + if (shouldDebug === false) { + msg += ' Enable state capture by calling `choo.debug`.' } else { - existing.push(listener); - } - - // Check for listener leak - m = _getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); + msg += ' Disable state capture by calling `choo.debug = false`.' } + return msg } - return target; + function Event (name, data, state) { + this.name = name + this.data = data === undefined ? '' : data + this.state = shouldDebug + ? tryClone(state) + : '' + } + + function tryClone (state) { + try { + var _state = clone(state) + if (!shouldWarn) shouldWarn = true + return _state + } catch (ex) { + if (shouldWarn) { + _log.warn('Could not clone your app state. Make sure to have a serializable state so it can be cloned') + shouldWarn = false + } + return '' + } + } } -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; +function noop () {} -EventEmitter.prototype.on = EventEmitter.prototype.addListener; +},{"clone":35,"nanologger":135,"nanoscheduler":143,"remove-array-items":28}],25:[function(require,module,exports){ +var scheduler = require('nanoscheduler')() +var nanologger = require('nanologger') +var Hooks = require('choo-hooks') -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; +module.exports = logger -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); +function logger (state, emitter, opts) { + var initialRender = true + var hooks = Hooks(emitter) + var log = nanologger('choo') + + hooks.on('log:debug', logger('debug')) + hooks.on('log:info', logger('info')) + hooks.on('log:warn', logger('warn')) + hooks.on('log:error', logger('error')) + hooks.on('log:fatal', logger('fatal')) + + hooks.on('event', function (eventName, data, timing) { + if (opts.filter && !opts.filter(eventName, data, timing)) return + + if (timing) { + var duration = timing.duration.toFixed() + var level = duration < 50 ? 'info' : 'warn' + if (data !== undefined) logger(level)(eventName, data, duration + 'ms') + else logger(level)(eventName, duration + 'ms') + } else { + if (data !== undefined) logger('info')(eventName, data) + else logger('info')(eventName) + } + }) + + hooks.on('unhandled', function (eventName, data) { + logger('error')('No listeners for ' + eventName) + }) + + hooks.on('DOMContentLoaded', function (timing) { + if (!timing) return logger('info')('DOMContentLoaded') + var level = timing.interactive < 1000 ? 'info' : 'warn' + logger(level)('DOMContentLoaded', timing.interactive + 'ms to interactive') + }) + + hooks.on('render', function (timings) { + if (!timings || !timings.render) return logger('info')('render') + var duration = timings.render.duration.toFixed() + var msg = 'render' + + if (initialRender) { + initialRender = false + msg = 'initial ' + msg + } + + // each frame has 10ms available for userland stuff + var fps = Math.min((600 / duration).toFixed(), 60) + + if (fps === 60) { + logger('info')(msg, fps + 'fps', duration + 'ms') + } else { + var times = { + render: timings.render.duration.toFixed() + 'ms' + } + if (timings.morph) times.morph = timings.morph.duration.toFixed() + 'ms' + logger('warn')(msg, fps + 'fps', duration + 'ms', times) + } + }) + + hooks.on('resource-timing-buffer-full', function () { + logger('error')("The browser's Resource Resource timing buffer is full. Cannot store any more timing information") + }) + + hooks.start() + + function logger (level) { + return function () { + var args = [] + for (var i = 0, len = arguments.length; i < len; i++) { + args.push(arguments[i]) + } + scheduler.push(function () { + log[level].apply(log, args) + }) + } + } +} + +},{"choo-hooks":29,"nanologger":135,"nanoscheduler":143}],26:[function(require,module,exports){ +var onPerformance = require('on-performance') + +var BAR = '█' + +module.exports = perf + +function perf (state, emitter, app, localEmitter) { + var stats = {} + + window.choo.perf = {} + + // Print all events + var all = new Perf(stats, 'all') + Object.defineProperty(window.choo.perf, 'all', { + get: all.get.bind(all), + set: noop + }) + + // Print only Choo core events + var core = new Perf(stats, 'core', function (name) { + return /^choo/.test(name) + }) + Object.defineProperty(window.choo.perf, 'core', { + get: core.get.bind(core), + set: noop + }) + + // Print component data + var components = new Perf(stats, 'components', function (name) { + return !/^choo/.test(name) && !/^bankai/.test(name) + }) + Object.defineProperty(window.choo.perf, 'components', { + get: components.get.bind(components), + set: noop + }) + + // Print choo userland events (event emitter) + var events = new Perf(stats, 'events', function (name) { + return /^choo\.emit/.test(name) + }, function (name) { + return name.replace(/^choo\.emit\('/, '').replace(/'\)$/, '') + }) + Object.defineProperty(window.choo.perf, 'events', { + get: events.get.bind(events), + set: noop + }) + + onPerformance(function (entry) { + if (entry.entryType !== 'measure') return + var name = entry.name.replace(/ .*$/, '') + + if (!stats[name]) { + stats[name] = { + name: name, + count: 0, + entries: [] + } + } + + var stat = stats[name] + stat.count += 1 + stat.entries.push(entry.duration) + }) +} + +// Create a new Perf instance by passing it a filter +function Perf (stats, name, filter, rename) { + this.stats = stats + this.name = name + this.filter = filter || function () { return true } + this.rename = rename || function (name) { return name } +} + +// Compute a table of performance entries based on a filter +Perf.prototype.get = function () { + var filtered = Object.keys(this.stats).filter(this.filter) + var self = this + + var maxTime = 0 + var maxMedian = 0 + var fmt = filtered.map(function (key) { + var stat = self.stats[key] + var totalTime = Number(stat.entries.reduce(function (time, entry) { + return time + entry + }, 0).toFixed(2)) + if (totalTime > maxTime) maxTime = totalTime + + var median = getMedian(stat.entries) + if (median > maxMedian) maxMedian = median + + var name = self.rename(stat.name) + return new PerfEntry(name, totalTime, median, stat.count) + }) + + var barLength = 10 + fmt.forEach(function (entry) { + var totalTime = entry['Total Time (ms)'] + var median = entry['Median (ms)'] + entry[' '] = createBar(totalTime / maxTime * 100 / barLength) + entry[' '] = createBar(median / maxMedian * 100 / barLength) + }) + + function createBar (len) { + var str = '' + for (var i = 0, max = Math.round(len); i < max; i++) { + str += BAR + } + return str + } + + var res = fmt.sort(function (a, b) { + return b['Total Time (ms)'] - a['Total Time (ms)'] + }) + console.table(res) + return "Showing performance events for '" + this.name + "'" +} + +// An entry for the performance timeline. +function PerfEntry (name, totalTime, median, count) { + this.Name = name + this['Total Time (ms)'] = totalTime + this[' '] = 0 + this['Median (ms)'] = median + this[' '] = 0 + this['Total Count'] = count +} + +// Get the median from an array of numbers. +function getMedian (args) { + if (!args.length) return 0 + var numbers = args.slice(0).sort(function (a, b) { return a - b }) + var middle = Math.floor(numbers.length / 2) + var isEven = numbers.length % 2 === 0 + var res = isEven ? (numbers[middle] + numbers[middle - 1]) / 2 : numbers[middle] + return Number(res.toFixed(2)) +} + +// Do nothing. +function noop () {} + +},{"on-performance":149}],27:[function(require,module,exports){ +var pretty = require('prettier-bytes') + +module.exports = storage + +function storage () { + Object.defineProperty(window.choo, 'storage', { + get: get, + set: noop + }) + + function get () { + if (navigator.storage) { + navigator.storage.estimate().then(function (estimate) { + var value = (estimate.usage / estimate.quota).toFixed() + clr('Max storage:', fmt(estimate.quota)) + clr('Storage used:', fmt(estimate.usage) + ' (' + value + '%)') + navigator.storage.persisted().then(function (bool) { + var val = bool ? 'enabled' : 'disabled' + clr('Persistent storage:', val) + }) + }) + return 'Calculating storage quota…' + } else { + var protocol = window.location.protocol + return (/https/.test(protocol)) + ? "The Storage API is unavailable in this browser. We're sorry!" + : 'The Storage API is unavailable. Serving this site over HTTPS might help enable it!' + } + } +} + +function clr (msg, arg) { + var color = '#cc99cc' + console.log('%c' + msg, 'color: ' + color, arg) +} + +function fmt (num) { + return pretty(num).replace(' ', '') +} + +function noop () {} + +},{"prettier-bytes":154}],28:[function(require,module,exports){ +'use strict'; + +/** + * Remove a range of items from an array + * + * @function removeItems + * @param {Array<*>} arr The target array + * @param {number} startIdx The index to begin removing from (inclusive) + * @param {number} removeCount How many items to remove + */ +function removeItems (arr, startIdx, removeCount) { + var i, length = arr.length; + + if (startIdx >= length || removeCount <= 0 || startIdx < 0) { + return + } + + removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount); + + var len = length - removeCount; + + for (i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount]; + } + + arr.length = len; +} + +module.exports = removeItems; + +},{}],29:[function(require,module,exports){ +var onPerformance = require('on-performance') +var scheduler = require('nanoscheduler')() +var assert = require('assert') + +module.exports = ChooHooks + +function ChooHooks (emitter) { + if (!(this instanceof ChooHooks)) return new ChooHooks(emitter) + + assert.equal(typeof emitter, 'object') + + this.hasWindow = typeof window !== 'undefined' + this.hasIdleCallback = this.hasWindow && window.requestIdleCallback + this.hasPerformance = this.hasWindow && + window.performance && + window.performance.getEntriesByName + + this.emitter = emitter + this.listeners = {} + this.buffer = { + render: {}, + events: {} } } -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; +ChooHooks.prototype.on = function (name, handler) { + this.listeners[name] = handler } -EventEmitter.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; +ChooHooks.prototype.start = function () { + var self = this + if (this.hasPerformance) { + window.performance.onresourcetimingbufferfull = function () { + var listener = self.listeners['resource-timing-buffer-full'] + if (listener) listener() + } + } -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; + // TODO also handle log events + onPerformance(function (timing) { + if (!timing) return + if (timing.entryType !== 'measure') return -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; + var eventName = timing.name + if (/choo\.morph/.test(eventName)) { + self.buffer.render.morph = timing + } else if (/choo\.route/.test(eventName)) { + self.buffer.render.route = timing + } else if (/choo\.render/.test(eventName)) { + self.buffer.render.render = timing + } else if (/choo\.emit/.test(eventName) && !/log:/.test(eventName)) { + var eventListener = self.listeners['event'] + if (eventListener) { + var timingName = eventName.match(/choo\.emit\('(.*)'\)/)[1] + if (timingName === 'render' || timingName === 'DOMContentLoaded') return - checkListener(listener); + var traceId = eventName.match(/\[(\d+)\]/)[1] + var data = self.buffer.events[traceId] - events = this._events; - if (events === undefined) - return this; + self.buffer.events[traceId] = null + eventListener(timingName, data, timing) + } + } - list = events[type]; - if (list === undefined) - return this; + var rBuf = self.buffer.render + if (rBuf.render && rBuf.route && rBuf.morph) { + var renderListener = self.listeners['render'] + if (!renderListener) return + var timings = {} + while (self.buffer.render.length) { + var _timing = self.buffer.render.pop() + var name = _timing.name + if (/choo\.render/.test(name)) timings.render = _timing + else if (/choo\.morph/.test(name)) timings.morph = _timing + else timings.route = _timing + } + rBuf.render = rBuf.route = rBuf.morph = void 0 + renderListener(timings) + } + }) - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); + // Check if there's timings without any listeners + // and trigger the DOMContentLoaded event. + // If the timing API is not available, we handle all events here + this.emitter.on('*', function (eventName, data, uuid) { + var logLevel = /^log:(\w{4,5})/.exec(eventName) + + if (!self.hasPerformance && eventName === 'render') { + // Render + var renderListener = self.listeners['render'] + if (renderListener) renderListener() + } else if (eventName === 'DOMContentLoaded') { + // DOMContentLoaded + self._emitLoaded() + } else if (logLevel) { + logLevel = logLevel[1] + // Log:* + var logListener = self.listeners['log:' + logLevel] + if (logListener) { + logListener.apply(null, Array.prototype.slice.call(arguments, 0, arguments.length - 1)) + } + } else if (!self.emitter.listeners(eventName).length) { + // Unhandled + var unhandledListener = self.listeners['unhandled'] + if (unhandledListener) unhandledListener(eventName, data) + } else if (eventName !== 'render') { + // * + if (self.hasPerformance) self.buffer.events[uuid] = data + } + }) +} + +// compute and log time till interactive when DOMContentLoaded event fires +ChooHooks.prototype._emitLoaded = function () { + var self = this + scheduler.push(function clear () { + var listener = self.listeners['DOMContentLoaded'] + var timing = self.hasWindow && window.performance && window.performance.timing + + if (listener && timing) { + listener({ + interactive: timing.domInteractive - timing.navigationStart, + loaded: timing.domContentLoadedEventEnd - timing.navigationStart + }) + } + }) +} + +},{"assert":4,"nanoscheduler":143,"on-performance":149}],30:[function(require,module,exports){ +var assert = require('assert') +var LRU = require('nanolru') + +module.exports = ChooComponentCache + +function ChooComponentCache (state, emit, lru) { + assert.ok(this instanceof ChooComponentCache, 'ChooComponentCache should be created with `new`') + + assert.equal(typeof state, 'object', 'ChooComponentCache: state should be type object') + assert.equal(typeof emit, 'function', 'ChooComponentCache: emit should be type function') + + if (typeof lru === 'number') this.cache = new LRU(lru) + else this.cache = lru || new LRU(100) + this.state = state + this.emit = emit +} + +// Get & create component instances. +ChooComponentCache.prototype.render = function (Component, id) { + assert.equal(typeof Component, 'function', 'ChooComponentCache.render: Component should be type function') + assert.ok(typeof id === 'string' || typeof id === 'number', 'ChooComponentCache.render: id should be type string or type number') + + var el = this.cache.get(id) + if (!el) { + var args = [] + for (var i = 2, len = arguments.length; i < len; i++) { + args.push(arguments[i]) + } + args.unshift(Component, id, this.state, this.emit) + el = newCall.apply(newCall, args) + this.cache.set(id, el) + } + + return el +} + +// Because you can't call `new` and `.apply()` at the same time. This is a mad +// hack, but hey it works so we gonna go for it. Whoop. +function newCall (Cls) { + return new (Cls.bind.apply(Cls, arguments)) // eslint-disable-line +} + +},{"assert":123,"nanolru":136}],31:[function(require,module,exports){ +module.exports = require('nanocomponent') + +},{"nanocomponent":125}],32:[function(require,module,exports){ +module.exports = require('nanohtml') + +},{"nanohtml":130}],33:[function(require,module,exports){ +var scrollToAnchor = require('scroll-to-anchor') +var documentReady = require('document-ready') +var nanotiming = require('nanotiming') +var nanorouter = require('nanorouter') +var nanomorph = require('nanomorph') +var nanoquery = require('nanoquery') +var nanohref = require('nanohref') +var nanoraf = require('nanoraf') +var nanobus = require('nanobus') +var assert = require('assert') + +var Cache = require('./component/cache') + +module.exports = Choo + +var HISTORY_OBJECT = {} + +function Choo (opts) { + var timing = nanotiming('choo.constructor') + if (!(this instanceof Choo)) return new Choo(opts) + opts = opts || {} + + assert.equal(typeof opts, 'object', 'choo: opts should be type object') + + var self = this + + // define events used by choo + this._events = { + DOMCONTENTLOADED: 'DOMContentLoaded', + DOMTITLECHANGE: 'DOMTitleChange', + REPLACESTATE: 'replaceState', + PUSHSTATE: 'pushState', + NAVIGATE: 'navigate', + POPSTATE: 'popState', + RENDER: 'render' + } + + // properties for internal use only + this._historyEnabled = opts.history === undefined ? true : opts.history + this._hrefEnabled = opts.href === undefined ? true : opts.href + this._hashEnabled = opts.hash === undefined ? false : opts.hash + this._hasWindow = typeof window !== 'undefined' + this._cache = opts.cache + this._loaded = false + this._stores = [ondomtitlechange] + this._tree = null + + // state + var _state = { + events: this._events, + components: {} + } + if (this._hasWindow) { + this.state = window.initialState + ? Object.assign({}, window.initialState, _state) + : _state + delete window.initialState + } else { + this.state = _state + } + + // properties that are part of the API + this.router = nanorouter({ curry: true }) + this.emitter = nanobus('choo.emit') + this.emit = this.emitter.emit.bind(this.emitter) + + // listen for title changes; available even when calling .toString() + if (this._hasWindow) this.state.title = document.title + function ondomtitlechange (state) { + self.emitter.prependListener(self._events.DOMTITLECHANGE, function (title) { + assert.equal(typeof title, 'string', 'events.DOMTitleChange: title should be type string') + state.title = title + if (self._hasWindow) document.title = title + }) + } + timing() +} + +Choo.prototype.route = function (route, handler) { + var routeTiming = nanotiming("choo.route('" + route + "')") + assert.equal(typeof route, 'string', 'choo.route: route should be type string') + assert.equal(typeof handler, 'function', 'choo.handler: route should be type function') + this.router.on(route, handler) + routeTiming() +} + +Choo.prototype.use = function (cb) { + assert.equal(typeof cb, 'function', 'choo.use: cb should be type function') + var self = this + this._stores.push(function (state) { + var msg = 'choo.use' + msg = cb.storeName ? msg + '(' + cb.storeName + ')' : msg + var endTiming = nanotiming(msg) + cb(state, self.emitter, self) + endTiming() + }) +} + +Choo.prototype.start = function () { + assert.equal(typeof window, 'object', 'choo.start: window was not found. .start() must be called in a browser, use .toString() if running in Node') + var startTiming = nanotiming('choo.start') + + var self = this + if (this._historyEnabled) { + this.emitter.prependListener(this._events.NAVIGATE, function () { + self._matchRoute(self.state) + if (self._loaded) { + self.emitter.emit(self._events.RENDER) + setTimeout(scrollToAnchor.bind(null, window.location.hash), 0) + } + }) + + this.emitter.prependListener(this._events.POPSTATE, function () { + self.emitter.emit(self._events.NAVIGATE) + }) + + this.emitter.prependListener(this._events.PUSHSTATE, function (href) { + assert.equal(typeof href, 'string', 'events.pushState: href should be type string') + window.history.pushState(HISTORY_OBJECT, null, href) + self.emitter.emit(self._events.NAVIGATE) + }) + + this.emitter.prependListener(this._events.REPLACESTATE, function (href) { + assert.equal(typeof href, 'string', 'events.replaceState: href should be type string') + window.history.replaceState(HISTORY_OBJECT, null, href) + self.emitter.emit(self._events.NAVIGATE) + }) + + window.onpopstate = function () { + self.emitter.emit(self._events.POPSTATE) + } + + if (self._hrefEnabled) { + nanohref(function (location) { + var href = location.href + var hash = location.hash + if (href === window.location.href) { + if (!self._hashEnabled && hash) scrollToAnchor(hash) + return } - } else if (typeof list !== 'function') { - position = -1; + self.emitter.emit(self._events.PUSHSTATE, href) + }) + } + } - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; + this._setCache(this.state) + this._matchRoute(this.state) + this._stores.forEach(function (initStore) { + initStore(self.state) + }) + + this._tree = this._prerender(this.state) + assert.ok(this._tree, 'choo.start: no valid DOM node returned for location ' + this.state.href) + + this.emitter.prependListener(self._events.RENDER, nanoraf(function () { + var renderTiming = nanotiming('choo.render') + var newTree = self._prerender(self.state) + assert.ok(newTree, 'choo.render: no valid DOM node returned for location ' + self.state.href) + + assert.equal(self._tree.nodeName, newTree.nodeName, 'choo.render: The target node <' + + self._tree.nodeName.toLowerCase() + '> is not the same type as the new node <' + + newTree.nodeName.toLowerCase() + '>.') + + var morphTiming = nanotiming('choo.morph') + nanomorph(self._tree, newTree) + morphTiming() + + renderTiming() + })) + + documentReady(function () { + self.emitter.emit(self._events.DOMCONTENTLOADED) + self._loaded = true + }) + + startTiming() + return this._tree +} + +Choo.prototype.mount = function mount (selector) { + var mountTiming = nanotiming("choo.mount('" + selector + "')") + if (typeof window !== 'object') { + assert.ok(typeof selector === 'string', 'choo.mount: selector should be type String') + this.selector = selector + mountTiming() + return this + } + + assert.ok(typeof selector === 'string' || typeof selector === 'object', 'choo.mount: selector should be type String or HTMLElement') + + var self = this + + documentReady(function () { + var renderTiming = nanotiming('choo.render') + var newTree = self.start() + if (typeof selector === 'string') { + self._tree = document.querySelector(selector) + } else { + self._tree = selector + } + + assert.ok(self._tree, 'choo.mount: could not query selector: ' + selector) + assert.equal(self._tree.nodeName, newTree.nodeName, 'choo.mount: The target node <' + + self._tree.nodeName.toLowerCase() + '> is not the same type as the new node <' + + newTree.nodeName.toLowerCase() + '>.') + + var morphTiming = nanotiming('choo.morph') + nanomorph(self._tree, newTree) + morphTiming() + + renderTiming() + }) + mountTiming() +} + +Choo.prototype.toString = function (location, state) { + state = state || {} + state.components = state.components || {} + state.events = Object.assign({}, state.events, this._events) + + assert.notEqual(typeof window, 'object', 'choo.mount: window was found. .toString() must be called in Node, use .start() or .mount() if running in the browser') + assert.equal(typeof location, 'string', 'choo.toString: location should be type string') + assert.equal(typeof state, 'object', 'choo.toString: state should be type object') + + this._setCache(state) + this._matchRoute(state, location) + this.emitter.removeAllListeners() + this._stores.forEach(function (initStore) { + initStore(state) + }) + + var html = this._prerender(state) + assert.ok(html, 'choo.toString: no valid value returned for the route ' + location) + assert(!Array.isArray(html), 'choo.toString: return value was an array for the route ' + location) + return typeof html.outerHTML === 'string' ? html.outerHTML : html.toString() +} + +Choo.prototype._matchRoute = function (state, locationOverride) { + var location, queryString + if (locationOverride) { + location = locationOverride.replace(/\?.+$/, '').replace(/\/$/, '') + if (!this._hashEnabled) location = location.replace(/#.+$/, '') + queryString = locationOverride + } else { + location = window.location.pathname.replace(/\/$/, '') + if (this._hashEnabled) location += window.location.hash.replace(/^#/, '/') + queryString = window.location.search + } + var matched = this.router.match(location) + this._handler = matched.cb + state.href = location + state.query = nanoquery(queryString) + state.route = matched.route + state.params = matched.params +} + +Choo.prototype._prerender = function (state) { + var routeTiming = nanotiming("choo.prerender('" + state.route + "')") + var res = this._handler(state, this.emit) + routeTiming() + return res +} + +Choo.prototype._setCache = function (state) { + var cache = new Cache(state, this.emitter.emit.bind(this.emitter), this._cache) + state.cache = renderComponent + + function renderComponent (Component, id) { + assert.equal(typeof Component, 'function', 'choo.state.cache: Component should be type function') + var args = [] + for (var i = 0, len = arguments.length; i < len; i++) { + args.push(arguments[i]) + } + return cache.render.apply(cache, args) + } + + // When the state gets stringified, make sure `state.cache` isn't + // stringified too. + renderComponent.toJSON = function () { + return null + } +} + +},{"./component/cache":30,"assert":123,"document-ready":43,"nanobus":124,"nanohref":127,"nanomorph":137,"nanoquery":140,"nanoraf":141,"nanorouter":142,"nanotiming":144,"scroll-to-anchor":169}],34:[function(require,module,exports){ +/*! clipboard-copy. MIT License. Feross Aboukhadijeh */ +/* global DOMException */ + +module.exports = clipboardCopy + +function clipboardCopy (text) { + // Use the Async Clipboard API when available. Requires a secure browsing + // context (i.e. HTTPS) + if (navigator.clipboard) { + return navigator.clipboard.writeText(text).catch(function (err) { + throw (err !== undefined ? err : new DOMException('The request is not allowed', 'NotAllowedError')) + }) + } + + // ...Otherwise, use document.execCommand() fallback + + // Put the text to copy into a + var span = document.createElement('span') + span.textContent = text + + // Preserve consecutive spaces and newlines + span.style.whiteSpace = 'pre' + span.style.webkitUserSelect = 'auto' + span.style.userSelect = 'all' + + // Add the to the page + document.body.appendChild(span) + + // Make a selection object representing the range of text selected by the user + var selection = window.getSelection() + var range = window.document.createRange() + selection.removeAllRanges() + range.selectNode(span) + selection.addRange(range) + + // Copy text to the clipboard + var success = false + try { + success = window.document.execCommand('copy') + } catch (err) { + console.log('error', err) + } + + // Cleanup + selection.removeAllRanges() + window.document.body.removeChild(span) + + return success + ? Promise.resolve() + : Promise.reject(new DOMException('The request is not allowed', 'NotAllowedError')) +} + +},{}],35:[function(require,module,exports){ +(function (Buffer){(function (){ +var clone = (function() { +'use strict'; + +function _instanceof(obj, type) { + return type != null && obj instanceof type; +} + +var nativeMap; +try { + nativeMap = Map; +} catch(_) { + // maybe a reference error because no `Map`. Give it a dummy value that no + // value will ever be an instanceof. + nativeMap = function() {}; +} + +var nativeSet; +try { + nativeSet = Set; +} catch(_) { + nativeSet = function() {}; +} + +var nativePromise; +try { + nativePromise = Promise; +} catch(_) { + nativePromise = function() {}; +} + +/** + * Clones (copies) an Object using deep copying. + * + * This function supports circular references by default, but if you are certain + * there are no circular references in your object, you can save some CPU time + * by calling clone(obj, false). + * + * Caution: if `circular` is false and `parent` contains circular references, + * your program may enter an infinite loop and crash. + * + * @param `parent` - the object to be cloned + * @param `circular` - set to true if the object to be cloned may contain + * circular references. (optional - true by default) + * @param `depth` - set to a number if the object is only to be cloned to + * a particular depth. (optional - defaults to Infinity) + * @param `prototype` - sets the prototype to be used when cloning an object. + * (optional - defaults to parent prototype). + * @param `includeNonEnumerable` - set to true if the non-enumerable properties + * should be cloned as well. Non-enumerable properties on the prototype + * chain will be ignored. (optional - false by default) +*/ +function clone(parent, circular, depth, prototype, includeNonEnumerable) { + if (typeof circular === 'object') { + depth = circular.depth; + prototype = circular.prototype; + includeNonEnumerable = circular.includeNonEnumerable; + circular = circular.circular; + } + // maintain two arrays for circular references, where corresponding parents + // and children have the same index + var allParents = []; + var allChildren = []; + + var useBuffer = typeof Buffer != 'undefined'; + + if (typeof circular == 'undefined') + circular = true; + + if (typeof depth == 'undefined') + depth = Infinity; + + // recurse this function so we don't reset allParents and allChildren + function _clone(parent, depth) { + // cloning null always returns null + if (parent === null) + return null; + + if (depth === 0) + return parent; + + var child; + var proto; + if (typeof parent != 'object') { + return parent; + } + + if (_instanceof(parent, nativeMap)) { + child = new nativeMap(); + } else if (_instanceof(parent, nativeSet)) { + child = new nativeSet(); + } else if (_instanceof(parent, nativePromise)) { + child = new nativePromise(function (resolve, reject) { + parent.then(function(value) { + resolve(_clone(value, depth - 1)); + }, function(err) { + reject(_clone(err, depth - 1)); + }); + }); + } else if (clone.__isArray(parent)) { + child = []; + } else if (clone.__isRegExp(parent)) { + child = new RegExp(parent.source, __getRegExpFlags(parent)); + if (parent.lastIndex) child.lastIndex = parent.lastIndex; + } else if (clone.__isDate(parent)) { + child = new Date(parent.getTime()); + } else if (useBuffer && Buffer.isBuffer(parent)) { + if (Buffer.allocUnsafe) { + // Node.js >= 4.5.0 + child = Buffer.allocUnsafe(parent.length); + } else { + // Older Node.js versions + child = new Buffer(parent.length); + } + parent.copy(child); + return child; + } else if (_instanceof(parent, Error)) { + child = Object.create(parent); + } else { + if (typeof prototype == 'undefined') { + proto = Object.getPrototypeOf(parent); + child = Object.create(proto); + } + else { + child = Object.create(prototype); + proto = prototype; + } + } + + if (circular) { + var index = allParents.indexOf(parent); + + if (index != -1) { + return allChildren[index]; + } + allParents.push(parent); + allChildren.push(child); + } + + if (_instanceof(parent, nativeMap)) { + parent.forEach(function(value, key) { + var keyChild = _clone(key, depth - 1); + var valueChild = _clone(value, depth - 1); + child.set(keyChild, valueChild); + }); + } + if (_instanceof(parent, nativeSet)) { + parent.forEach(function(value) { + var entryChild = _clone(value, depth - 1); + child.add(entryChild); + }); + } + + for (var i in parent) { + var attrs; + if (proto) { + attrs = Object.getOwnPropertyDescriptor(proto, i); + } + + if (attrs && attrs.set == null) { + continue; + } + child[i] = _clone(parent[i], depth - 1); + } + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(parent); + for (var i = 0; i < symbols.length; i++) { + // Don't need to worry about cloning a symbol because it is a primitive, + // like a number or string. + var symbol = symbols[i]; + var descriptor = Object.getOwnPropertyDescriptor(parent, symbol); + if (descriptor && !descriptor.enumerable && !includeNonEnumerable) { + continue; + } + child[symbol] = _clone(parent[symbol], depth - 1); + if (!descriptor.enumerable) { + Object.defineProperty(child, symbol, { + enumerable: false + }); + } + } + } + + if (includeNonEnumerable) { + var allPropertyNames = Object.getOwnPropertyNames(parent); + for (var i = 0; i < allPropertyNames.length; i++) { + var propertyName = allPropertyNames[i]; + var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName); + if (descriptor && descriptor.enumerable) { + continue; + } + child[propertyName] = _clone(parent[propertyName], depth - 1); + Object.defineProperty(child, propertyName, { + enumerable: false + }); + } + } + + return child; + } + + return _clone(parent, depth); +} + +/** + * Simple flat clone using prototype, accepts only objects, usefull for property + * override on FLAT configuration object (no nested props). + * + * USE WITH CAUTION! This may not behave as you wish if you do not know how this + * works. + */ +clone.clonePrototype = function clonePrototype(parent) { + if (parent === null) + return null; + + var c = function () {}; + c.prototype = parent; + return new c(); +}; + +// private utility functions + +function __objToStr(o) { + return Object.prototype.toString.call(o); +} +clone.__objToStr = __objToStr; + +function __isDate(o) { + return typeof o === 'object' && __objToStr(o) === '[object Date]'; +} +clone.__isDate = __isDate; + +function __isArray(o) { + return typeof o === 'object' && __objToStr(o) === '[object Array]'; +} +clone.__isArray = __isArray; + +function __isRegExp(o) { + return typeof o === 'object' && __objToStr(o) === '[object RegExp]'; +} +clone.__isRegExp = __isRegExp; + +function __getRegExpFlags(re) { + var flags = ''; + if (re.global) flags += 'g'; + if (re.ignoreCase) flags += 'i'; + if (re.multiline) flags += 'm'; + return flags; +} +clone.__getRegExpFlags = __getRegExpFlags; + +return clone; +})(); + +if (typeof module === 'object' && module.exports) { + module.exports = clone; +} + +}).call(this)}).call(this,require("buffer").Buffer) +},{"buffer":17}],36:[function(require,module,exports){ +(function(r){"object"==typeof exports&&"object"==typeof module?r(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],r):r(CodeMirror)})(function(r){function I(c){c=c.search(w);return-1==c?0:c}function J(c,d,a){return/\bstring\b/.test(c.getTokenTypeAt(l(d.line,0)))&&!/^['"`]/.test(a)}function G(c,d){var a=c.getMode();return!1!==a.useInnerComments&&a.innerMode?c.getModeAt(d):a}var E={},w=/[^\s\u00a0]/,l=r.Pos,K=r.cmpPos;r.commands.toggleComment=function(c){c.toggleComment()}; +r.defineExtension("toggleComment",function(c){c||(c=E);for(var d=Infinity,a=this.listSelections(),b=null,e=a.length-1;0<=e;e--){var g=a[e].from(),f=a[e].to();g.line>=d||(f.line>=d&&(f=l(d,0)),d=g.line,null==b?this.uncomment(g,f,c)?b="un":(this.lineComment(g,f,c),b="line"):"un"==b?this.uncomment(g,f,c):this.lineComment(g,f,c))}});r.defineExtension("lineComment",function(c,d,a){a||(a=E);var b=this,e=G(b,c),g=b.getLine(c.line);if(null!=g&&!J(b,c,g)){var f=a.lineComment||e.lineComment;if(f){var m=Math.min(0!= +d.ch||d.line==c.line?d.line+1:d.line,b.lastLine()+1),u=null==a.padding?" ":a.padding,k=a.commentBlankLines||c.line==d.line;b.operation(function(){if(a.indent){for(var p=null,h=c.line;hq.length)p=q}for(h=c.line;hm||b.operation(function(){if(0!= +a.fullLines){var k=w.test(b.getLine(m));b.replaceRange(u+f,l(m));b.replaceRange(g+u,l(c.line,0));var p=a.blockCommentLead||e.blockCommentLead;if(null!=p)for(var h=c.line+1;h<=m;++h)(h!=m||k)&&b.replaceRange(p+u,l(h,0))}else k=0==K(b.getCursor("to"),d),p=!b.somethingSelected(),b.replaceRange(f,d),k&&b.setSelection(p?d:b.getCursor("from"),d),b.replaceRange(g,c)})}});r.defineExtension("uncomment",function(c,d,a){a||(a=E);var b=this,e=G(b,c),g=Math.min(0!=d.ch||d.line==c.line?d.line:d.line-1,b.lastLine()), +f=Math.min(c.line,g),m=a.lineComment||e.lineComment,u=[],k=null==a.padding?" ":a.padding,p;a:if(m){for(var h=f;h<=g;++h){var q=b.getLine(h),t=q.indexOf(m);-1x||(A.slice(v,v+k.length)==k&&(v+=k.length),p=!0,b.replaceRange("",l(n,x),l(n,v)))}});if(p)return!0}var y=a.blockCommentStart|| +e.blockCommentStart,z=a.blockCommentEnd||e.blockCommentEnd;if(!y||!z)return!1;var H=a.blockCommentLead||e.blockCommentLead,C=b.getLine(f),D=C.indexOf(y);if(-1==D)return!1;var F=g==f?C:b.getLine(g),B=F.indexOf(z,g==f?D+y.length:0);a=l(f,D+1);e=l(g,B+1);if(-1==B||!/comment/.test(b.getTokenTypeAt(a))||!/comment/.test(b.getTokenTypeAt(e))||-1c.ch&&(d.end=c.ch,d.string=d.string.slice(0, +c.ch-d.start)):d={start:c.ch,end:c.ch,string:"",state:d.state,type:"."==d.string?"property":null};for(g=d;"property"==g.type;){g=l(a,r(c.line,g.start));if("."!=g.string)return;g=l(a,r(c.line,g.start));if(!p)var p=[];p.push(g)}return{list:u(d,p,b,e),from:r(c.line,d.start),to:r(c.line,d.end)}}}}function v(a,b){a=a.getTokenAt(b);b.ch==a.start+1&&"."==a.string.charAt(0)?(a.end=a.start,a.string=".",a.type="property"):/^\.[\w$_]*$/.test(a.string)&&(a.type="property",a.start++,a.string=a.string.replace(/\./, +""));return a}function u(a,b,l,e){function c(h){var k;if(k=0==h.lastIndexOf(p,0)){a:if(Array.prototype.indexOf)k=-1!=g.indexOf(h);else{for(k=g.length;k--;)if(g[k]===h){k=!0;break a}k=!1}k=!k}k&&g.push(h)}function d(h){"string"==typeof h?q(w,c):h instanceof Array?q(x,c):h instanceof Function&&q(y,c);if(Object.getOwnPropertyNames&&Object.getPrototypeOf)for(;h;h=Object.getPrototypeOf(h))Object.getOwnPropertyNames(h).forEach(c);else for(var k in h)c(k)}var g=[],p=a.string,n=e&&e.globalScope||window;if(b&& +b.length){a=b.pop();var f;a.type&&0===a.type.indexOf("variable")?(e&&e.additionalContext&&(f=e.additionalContext[a.string]),e&&!1===e.useGlobalScope||(f=f||n[a.string])):"string"==a.type?f="":"atom"==a.type?f=1:"function"==a.type&&(null==n.jQuery||"$"!=a.string&&"jQuery"!=a.string||"function"!=typeof n.jQuery?null!=n._&&"_"==a.string&&"function"==typeof n._&&(f=n._()):f=n.jQuery());for(;null!=f&&b.length;)f=f[b.pop().string];null!=f&&d(f)}else{for(b=a.state.localVars;b;b=b.next)c(b.name);for(f=a.state.context;f;f= +f.prev)for(b=f.vars;b;b=b.next)c(b.name);for(b=a.state.globalVars;b;b=b.next)c(b.name);if(e&&null!=e.additionalContext)for(var z in e.additionalContext)c(z);e&&!1===e.useGlobalScope||d(n);q(l,c)}return g}var r=m.Pos;m.registerHelper("hint","javascript",function(a,b){return t(a,A,function(l,e){return l.getTokenAt(e)},b)});m.registerHelper("hint","coffeescript",function(a,b){return t(a,B,v,b)});var w="charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight toUpperCase toLowerCase split concat match replace search".split(" "), +x="length concat join splice push pop shift unshift slice reverse sort indexOf lastIndexOf every some filter forEach map reduce reduceRight ".split(" "),y=["prototype","apply","call","bind"],A="break case catch class const continue debugger default delete do else export extends false finally for function if in import instanceof new null return super switch this throw true try typeof var void while with yield".split(" "),B="and break catch class continue delete do else extends false finally for if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes".split(" ")}); + +},{"../../lib/codemirror":40}],38:[function(require,module,exports){ +(function(h){"object"==typeof exports&&"object"==typeof module?h(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],h):h(CodeMirror)})(function(h){function B(a,b){this.cm=a;this.options=b;this.widget=null;this.tick=this.debounce=0;this.startPos=this.cm.getCursor("start");this.startLen=this.cm.getLine(this.startPos.line).length-this.cm.getSelection().length;if(this.options.updateOnCursorActivity){var c=this;a.on("cursorActivity",this.activityFunc= +function(){c.cursorActivity()})}}function J(a,b){function c(r,g){var m="string"!=typeof g?function(k){return g(k,b)}:d.hasOwnProperty(g)?d[g]:g;p[r]=m}var d={Up:function(){b.moveFocus(-1)},Down:function(){b.moveFocus(1)},PageUp:function(){b.moveFocus(-b.menuSize()+1,!0)},PageDown:function(){b.moveFocus(b.menuSize()-1,!0)},Home:function(){b.setFocus(0)},End:function(){b.setFocus(b.length-1)},Enter:b.pick,Tab:b.pick,Esc:b.close};/Mac/.test(navigator.platform)&&(d["Ctrl-P"]=function(){b.moveFocus(-1)}, +d["Ctrl-N"]=function(){b.moveFocus(1)});var e=a.options.customKeys,p=e?{}:d;if(e)for(var f in e)e.hasOwnProperty(f)&&c(f,e[f]);if(a=a.options.extraKeys)for(f in a)a.hasOwnProperty(f)&&c(f,a[f]);return p}function C(a,b){for(;b&&b!=a;){if("LI"===b.nodeName.toUpperCase()&&b.parentNode==a)return b;b=b.parentNode}}function D(a,b){this.id="cm-complete-"+Math.floor(Math.random(1E6));this.completion=a;this.data=b;this.picked=!1;var c=this,d=a.cm,e=d.getInputField().ownerDocument,p=e.defaultView||e.parentWindow, +f=this.hints=e.createElement("ul");f.setAttribute("role","listbox");f.setAttribute("aria-expanded","true");f.id=this.id;f.className="CodeMirror-hints "+a.cm.options.theme;this.selectedHint=b.selectedHint||0;for(var r=b.list,g=0;g +f.clientHeight+1:!1;var u;setTimeout(function(){u=d.getScrollInfo()});if(0y&&(f.style.height=y-5+"px",f.style.top=(w=g.bottom-l.top-q)+"px",q=d.getCursor(),b.from.ch!=q.ch&&(g=d.cursorCoords(q),f.style.left=(v=g.left-m)+"px",l=f.getBoundingClientRect()))}q=l.right-k;t&&(q+=d.display.nativeBarWidth);0k&&(f.style.width=k-5+"px",q-=l.right-l.left-k),f.style.left=(v=g.left-q-m)+"px"); +if(t)for(g=f.firstChild;g;g=g.nextSibling)g.style.paddingRight=d.display.nativeBarWidth+"px";d.addKeyMap(this.keyMap=J(a,{moveFocus:function(n,x){c.changeActive(c.selectedHint+n,x)},setFocus:function(n){c.changeActive(n)},menuSize:function(){return c.screenAmount()},length:r.length,close:function(){a.close()},pick:function(){c.pick()},data:b}));if(a.options.closeOnUnfocus){var F;d.on("blur",this.onBlur=function(){F=setTimeout(function(){a.close()},100)});d.on("focus",this.onFocus=function(){clearTimeout(F)})}d.on("scroll", +this.onScroll=function(){var n=d.getScrollInfo(),x=d.getWrapperElement().getBoundingClientRect();u||(u=d.getScrollInfo());var G=w+u.top-n.top,A=G-(p.pageYOffset||(e.documentElement||e.body).scrollTop);E||(A+=f.offsetHeight);if(A<=x.top||A>=x.bottom)return a.close();f.style.top=G+"px";f.style.left=v+u.left-n.left+"px"});h.on(f,"dblclick",function(n){(n=C(f,n.target||n.srcElement))&&null!=n.hintId&&(c.changeActive(n.hintId),c.pick())});h.on(f,"click",function(n){(n=C(f,n.target||n.srcElement))&&null!= +n.hintId&&(c.changeActive(n.hintId),a.options.completeOnSingleClick&&c.pick())});h.on(f,"mousedown",function(){setTimeout(function(){d.focus()},20)});g=this.getSelectedHintRange();0===g.from&&0===g.to||this.scrollToActive();h.signal(b,"select",r[this.selectedHint],f.childNodes[this.selectedHint]);return!0}function K(a,b){if(!a.somethingSelected())return b;a=[];for(var c=0;c=this.data.list.length?a=b?this.data.list.length-1:0:0>a&&(a=b?0:this.data.list.length-1);if(this.selectedHint!=a){if(b=this.hints.childNodes[this.selectedHint])b.className=b.className.replace(" CodeMirror-hint-active",""),b.removeAttribute("aria-selected");b=this.hints.childNodes[this.selectedHint=a];b.className+=" CodeMirror-hint-active";b.setAttribute("aria-selected", +"true");this.completion.cm.getInputField().setAttribute("aria-activedescendant",b.id);this.scrollToActive();h.signal(this.data,"select",this.data.list[this.selectedHint],b)}},scrollToActive:function(){var a=this.getSelectedHintRange(),b=this.hints.childNodes[a.from];a=this.hints.childNodes[a.to];var c=this.hints.firstChild;b.offsetTopthis.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=a.offsetTop+ +a.offsetHeight-this.hints.clientHeight+c.offsetTop)},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1},getSelectedHintRange:function(){var a=this.completion.options.scrollMargin||0;return{from:Math.max(0,this.selectedHint-a),to:Math.min(this.data.list.length-1,this.selectedHint+a)}}};h.registerHelper("hint","auto",{resolve:function(a,b){var c=a.getHelpers(b,"hint"),d;return c.length?(a=function(e,p,f){function r(m){if(m==g.length)return p(null); +H(g[m],e,f,function(k){k&&0,]/,closeOnPick:!0,closeOnUnfocus:!0,updateOnCursorActivity:!0,completeOnSingleClick:!0,container:null,customKeys:null,extraKeys:null,paddingForScrollbar:!0,moveOnOverlap:!0};h.defineOption("hintOptions",null)}); + +},{"../../lib/codemirror":40}],39:[function(require,module,exports){ +(function (global){(function (){ +var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.findInternal=function(a,d,c){a instanceof String&&(a=String(a));for(var e=a.length,f=0;f>>0,$jscomp.propertyToPolyfillSymbol[f]=$jscomp.IS_SYMBOL_NATIVE? +$jscomp.global.Symbol(f):$jscomp.POLYFILL_PREFIX+c+"$"+f),$jscomp.defineProperty(e,$jscomp.propertyToPolyfillSymbol[f],{configurable:!0,writable:!0,value:d})))};$jscomp.polyfill("Array.prototype.find",function(a){return a?a:function(d,c){return $jscomp.findInternal(this,d,c).v}},"es6","es3"); +(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})(function(a){function d(b){b.state.markedSelection&&b.operation(function(){r(b)})}function c(b){b.state.markedSelection&&b.state.markedSelection.length&&b.operation(function(){f(b)})}function e(b,g,h,k){if(0!=p(g,h))for(var l=b.state.markedSelection,n=b.state.markedSelectionStyle,q=g.line;;){var t=q==g.line?g:v(q, +0);q+=u;var w=q>=h.line,x=w?h:v(q,0);t=b.markText(t,x,{className:n});null==k?l.push(t):l.splice(k++,0,t);if(w)break}}function f(b){b=b.state.markedSelection;for(var g=0;g=p(h,l.from))return m(b);for(;0p(g,l.from)&&(l.to.line-g.linep(h,n.to);)k.pop().clear(),n=k[k.length-1].find();0>>0,$jscomp.propertyToPolyfillSymbol[M]= +$jscomp.IS_SYMBOL_NATIVE?$jscomp.global.Symbol(M):$jscomp.POLYFILL_PREFIX+D+"$"+M),$jscomp.defineProperty(v,$jscomp.propertyToPolyfillSymbol[M],{configurable:!0,writable:!0,value:E})))};$jscomp.polyfill("Array.prototype.find",function(y){return y?y:function(E,D){return $jscomp.findInternal(this,E,D).v}},"es6","es3"); +(function(y,E){"object"===typeof exports&&"undefined"!==typeof module?module.exports=E():"function"===typeof define&&define.amd?define(E):(y=y||self,y.CodeMirror=E())})(this,function(){function y(a){return new RegExp("(^|\\s)"+a+"(?:$|\\s)\\s*")}function E(a){for(var b=a.childNodes.length;0f||f>=b)return e+(b- +c);e+=f-c;e+=d-e%d;c=f+1}}function ea(a,b){for(var d=0;d=b)return c+Math.min(g,b-e);e+=f-c;e+=d-e%d;c=f+1;if(e>=b)return c}}function hd(a){for(;tc.length<=a;)tc.push(J(tc)+" ");return tc[a]}function J(a){return a[a.length-1]}function uc(a,b){for(var d=[],c=0;cd?0d?-1:1;;){if(b==d)return b;var e=(b+d)/2;e=0>c?Math.ceil(e):Math.floor(e);if(e==b)return a(e)?b:d;a(e)?d=e:b=e+c}}function zg(a,b,d,c){if(!a)return c(b,d,"ltr",0);for(var e=!1,f=0;fb||b==d&&g.to==b)c(Math.max(g.from,b),Math.min(g.to,d),1==g.level?"rtl":"ltr",f),e=!0}e||c(b,d,"ltr")}function Ib(a,b,d){var c;Jb=null;for(var e=0;eb)return e;f.to==b&&(f.from!=f.to&&"before"== +d?c=e:Jb=e);f.from==b&&(f.from!=f.to&&"before"!=d?c=e:Jb=e)}return null!=c?c:Jb}function Ia(a,b){var d=a.order;null==d&&(d=a.order=Ag(a.text,b));return d}function sa(a,b,d){if(a.removeEventListener)a.removeEventListener(b,d,!1);else if(a.detachEvent)a.detachEvent("on"+b,d);else{var c=(a=a._handlers)&&a[b];c&&(d=ea(c,d),-1b||b>=a.size)throw Error("There is no line "+(b+a.first)+" in the document.");for(;!a.lines;)for(var d=0;;++d){var c=a.children[d],e=c.chunkSize();if(b=a.first&&bB(a,b)?b:a} +function zc(a,b){return 0>B(a,b)?a:b}function C(a,b){if(b.lined)return t(d,w(a,d).text.length);a=w(a,b.line).text.length;d=b.ch;b=null==d||d>a?t(b.line,a):0>d?t(b.line,0):b;return b}function we(a,b){for(var d=[],c=0;cp&&e.splice(m,1,p,e[m+1],u);m+=2;n=Math.min(p,u)}if(q)if(l.opaque)e.splice(r,m-r,p,"overlay "+q),m=r+2;else for(;ra.options.maxHighlightLength&& +Ya(a.doc.mode,c.state),f=xe(a,b,c);e&&(c.state=e);b.stateAfter=c.save(!e);b.styles=f.styles;f.classes?b.styleClasses=f.classes:b.styleClasses&&(b.styleClasses=null);d===a.doc.highlightFrontier&&(a.doc.modeFrontier=Math.max(a.doc.modeFrontier,++a.doc.highlightFrontier))}return b.styles}function Mb(a,b,d){var c=a.doc,e=a.display;if(!c.mode.startState)return new Da(c,!0,b);var f=Dg(a,b,d),g=f>c.first&&w(c,f-1).stateAfter,h=g?Da.fromSaved(c,g,f):new Da(c,ve(c.mode),f);c.iter(f,b,function(k){sd(a,k.text, +h);var l=h.line;k.stateAfter=l==b-1||0==l%5||l>=e.viewFrom&&le;e++){c&&(c[0]=nd(a,d).mode);var f=a.token(b, +d);if(b.pos>b.start)return f}throw Error("Mode "+a.name+" failed to advance stream.");}function Be(a,b,d,c){var e=a.doc,f=e.mode;b=C(e,b);var g=w(e,b.line);d=Mb(a,b.line,d);a=new X(g.text,a.options.tabSize,d);var h;for(c&&(h=[]);(c||a.posa.options.maxHighlightLength){h=!1;g&&sd(a,b,c,m.pos);m.pos=b.length;var p=null}else p=De(td(d,m,c.state,n),f);if(n){var q=n[0].name;q&&(p="m-"+(p?q+" "+ +p:q))}if(!h||l!=p){for(;kg;--b){if(b<=f.first)return f.first;var h=w(f,b-1),k=h.stateAfter;if(k&&(!d||b+(k instanceof Ac?k.lookAhead:0)<=f.modeFrontier))return b;h=va(h.text,null,a.options.tabSize);if(null==e||c>h)e=b-1,c=h}return e}function Eg(a,b){a.modeFrontier=Math.min(a.modeFrontier,b);if(!(a.highlightFrontier< +b-10)){for(var d=a.first,c=b-1;c>d;c--){var e=w(a,c).stateAfter;if(e&&(!(e instanceof Ac)||c+e.lookAhead=a:k.to>a);(g||(g=[])).push(new Bc(l,k.from,m?null:k.to))}}d=g;var n;if(c)for(g=0;g=e:h.to>e)||h.from==e&&"bookmark"==k.type&&(!f||h.marker.insertLeft))l=null==h.from||(k.inclusiveLeft?h.from<=e:h.from< +e),(n||(n=[])).push(new Bc(k,l?null:h.from-e,null==h.to?null:h.to-e));c=1==b.text.length;e=J(b.text).length+(c?a:0);if(d)for(f=0;fB(g.to,e.from)||0k||!d.inclusiveLeft&&!k)&&h.push({from:g.from,to:e.from});(0vd(e,d.marker)))var e=d.marker;return e}function He(a,b,d,c,e){a=w(a,b);if(a=Ja&&a.markedSpans)for(b=0;b=k||0>=h&&0<=k)&&(0>=h&&(f.marker.inclusiveRight&&e.inclusiveLeft?0<=B(g.to,d):0=B(g.from,c):0>B(g.from,c))))return!0}}}function Ea(a){for(var b;b=qb(a,!0);)a=b.find(-1,!0).line;return a}function wd(a,b){a=w(a,b);var d=Ea(a);return a==d?b:N(d)} +function Ie(a,b){if(b>a.lastLine())return b;var d=w(a,b);if(!Oa(a,d))return b;for(;a=qb(d,!1);)d=a.find(1,!0).line;return N(d)+1}function Oa(a,b){var d=Ja&&b.markedSpans;if(d)for(var c,e=0;eb.maxLineLength&&(b.maxLineLength=c,b.maxLine=d)})}function Je(a,b){if(!a||/^\s*$/.test(a))return null;b=b.addModeClass?Gg:Hg;return b[a]||(b[a]=a.replace(/\S+/g,"cm-$&"))}function Ke(a, +b){var d=M("span",null,null,fa?"padding-right: .1px":null);d={pre:M("pre",[d],"CodeMirror-line"),content:d,col:0,pos:0,cm:a,trailingSpace:!1,splitSpaces:a.getOption("lineWrapping")};b.measure={};for(var c=0;c<=(b.rest?b.rest.length:0);c++){var e=c?b.rest[c-1]:b.line,f=void 0;d.pos=0;d.addToken=Ig;var g=a.display.measure;if(null!=zd)g=zd;else{var h=D(g,document.createTextNode("A\u062eA")),k=Ob(h,0,1).getBoundingClientRect();h=Ob(h,1,2).getBoundingClientRect();E(g);g=k&&k.left!=k.right?zd=3>h.right- +k.right:!1}g&&(f=Ia(e,a.doc.direction))&&(d.addToken=Jg(d.addToken,f));d.map=[];var l=b!=a.display.externalMeasured&&N(e);a:{var m=h=k=g=void 0,n=void 0,p=void 0,q=void 0;f=d;l=ze(a,e,l);var r=e.markedSpans,u=e.text,A=0;if(r)for(var Y=u.length,x=0,P=1,K="",Q=0;;){if(Q==x){n=m=h=p="";k=g=null;Q=Infinity;for(var S=[],F=void 0,R=0;Rx||L.collapsed&&H.to==x&&H.from==x)){null!= +H.to&&H.to!=x&&Q>H.to&&(Q=H.to,m="");L.className&&(n+=" "+L.className);L.css&&(p=(p?p+";":"")+L.css);L.startStyle&&H.from==x&&(h+=" "+L.startStyle);L.endStyle&&H.to==Q&&(F||(F=[])).push(L.endStyle,H.to);L.title&&((g||(g={})).title=L.title);if(L.attributes)for(var ha in L.attributes)(g||(g={}))[ha]=L.attributes[ha];L.collapsed&&(!k||0>vd(k.marker,L))&&(k=H)}else H.from>x&&Q>H.from&&(Q=H.from)}if(F)for(R=0;R=Y)break;for(S=Math.min(Y,Q);;){if(K){F=x+K.length;k||(R=F>S?K.slice(0,S-x):K,f.addToken(f,R,q?q+n:n,h,x+R.length==Q?m:"",p,g));if(F>=S){K=K.slice(S-x);x=S;break}x=F;h=""}K=u.slice(A,A=l[P++]);q=Je(l[P++],f.cm.options)}}else for(g=1;g=m.offsetWidth&&2T))),h=Ad?v("span","\u200b"):v("span","\u00a0",null,"display: inline-block; width: 1px; margin-right: -1px"),h.setAttribute("cm-text",""),f.call(e,0,0,k.call(g, +h)));0==c?(b.measure.map=d.map,b.measure.cache={}):((b.measure.maps||(b.measure.maps=[])).push(d.map),(b.measure.caches||(b.measure.caches=[])).push({}))}fa&&(ha=d.content.lastChild,/\bcm-tab\b/.test(ha.className)||ha.querySelector&&ha.querySelector(".cm-tab"))&&(d.content.className="cm-tab-wrap-hack");W(a,"renderLine",a,b.line,d.pre);d.pre.className&&(d.textClass=ed(d.pre.className,d.textClass||""));return d}function Kg(a){var b=v("span","\u2022","cm-invalidchar");b.title="\\u"+a.charCodeAt(0).toString(16); +b.setAttribute("aria-label",b.title);return b}function Ig(a,b,d,c,e,f,g){if(b){if(a.splitSpaces){var h=a.trailingSpace;if(1T?h.appendChild(v("span",[r])):h.appendChild(r);a.map.push(a.pos,a.pos+q,r);a.col+=q;a.pos+=q}if(!p)break;n+=q+1;"\t"==p[0]?(p=a.cm.options.tabSize,p-=a.col%p,q=h.appendChild(v("span",hd(p),"cm-tab")),q.setAttribute("role","presentation"),q.setAttribute("cm-text","\t"),a.col+=p):("\r"==p[0]||"\n"==p[0]?(q=h.appendChild(v("span","\r"==p[0]?"\u240d":"\u2424","cm-invalidchar")),q.setAttribute("cm-text",p[0])):(q=a.cm.options.specialCharPlaceholder(p[0]),q.setAttribute("cm-text",p[0]),G&&9>T? +h.appendChild(v("span",[q])):h.appendChild(q)),a.col+=1);a.map.push(a.pos,a.pos+1,q);a.pos++}}else a.col+=b.length,h=document.createTextNode(k),a.map.push(a.pos,a.pos+b.length,h),G&&9>T&&(m=!0),a.pos+=b.length;a.trailingSpace=32==k.charCodeAt(b.length-1);if(d||c||e||m||f||g){b=d||"";c&&(b+=c);e&&(b+=e);c=v("span",[h],b,f);if(g)for(var u in g)g.hasOwnProperty(u)&&"style"!=u&&"class"!=u&&c.setAttribute(u,g[u]);return a.content.appendChild(c)}a.content.appendChild(h)}}function Jg(a,b){return function(d, +c,e,f,g,h,k){e=e?e+" cm-force-border":"cm-force-border";for(var l=d.pos,m=l+c.length;;){for(var n=void 0,p=0;pl&&n.from<=l);p++);if(n.to>=m)return a(d,c,e,f,g,h,k);a(d,c.slice(0,n.to-l),e,f,null,h,k);f=null;c=c.slice(n.to-l);l=n.to}}}function Le(a,b,d,c){var e=!c&&d.widgetNode;e&&a.map.push(a.pos,a.pos+b,e);!c&&a.cm.display.input.needsContentAttribute&&(e||(e=a.content.appendChild(document.createElement("span"))),e.setAttribute("cm-marker",d.id));e&&(a.cm.display.input.setUneditable(e), +a.content.appendChild(e));a.pos+=b;a.trailingSpace=!1}function Me(a,b,d){for(var c=this.line=b,e;c=qb(c,!1);)c=c.find(1,!0).line,(e||(e=[])).push(c);this.size=(this.rest=e)?N(J(this.rest))-d+1:1;this.node=this.text=null;this.hidden=Oa(a,b)}function Dc(a,b,d){var c=[],e;for(e=b;eT&&(a.node.style.zIndex=2));return a.node}function Oe(a,b){var d=a.display.externalMeasured;return d&&d.line==b.line?(a.display.externalMeasured=null,b.measure=d.measure,d.built):Ke(a,b)}function Bd(a,b){var d=b.bgClass?b.bgClass+" "+ +(b.line.bgClass||""):b.line.bgClass;d&&(d+=" CodeMirror-linebackground");if(b.background)d?b.background.className=d:(b.background.parentNode.removeChild(b.background),b.background=null);else if(d){var c=Qb(b);b.background=c.insertBefore(v("div",null,d),c.firstChild);a.display.input.setUneditable(b.background)}b.line.wrapClass?Qb(b).className=b.line.wrapClass:b.node!=b.text&&(b.node.className="");b.text.className=(b.textClass?b.textClass+" "+(b.line.textClass||""):b.line.textClass)||""}function Pe(a, +b,d,c){b.gutter&&(b.node.removeChild(b.gutter),b.gutter=null);b.gutterBackground&&(b.node.removeChild(b.gutterBackground),b.gutterBackground=null);if(b.line.gutterClass){var e=Qb(b);b.gutterBackground=v("div",null,"CodeMirror-gutter-background "+b.line.gutterClass,"left: "+(a.options.fixedGutter?c.fixedPos:-c.gutterTotalWidth)+"px; width: "+c.gutterTotalWidth+"px");a.display.input.setUneditable(b.gutterBackground);e.insertBefore(b.gutterBackground,b.text)}e=b.line.gutterMarkers;if(a.options.lineNumbers|| +e){var f=Qb(b),g=b.gutter=v("div",null,"CodeMirror-gutter-wrapper","left: "+(a.options.fixedGutter?c.fixedPos:-c.gutterTotalWidth)+"px");g.setAttribute("aria-hidden","true");a.display.input.setUneditable(g);f.insertBefore(g,b.text);b.line.gutterClass&&(g.className+=" "+b.line.gutterClass);!a.options.lineNumbers||e&&e["CodeMirror-linenumbers"]||(b.lineNumber=g.appendChild(v("div",pd(a.options,d),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+c.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+ +a.display.lineNumInnerWidth+"px")));if(e)for(b=0;bd)return{map:a.measure.maps[b],cache:a.measure.caches[b],before:!0}}}function Ed(a,b){if(b>=a.display.viewFrom&&b=a.lineN&&bp;p++){for(;h&&jd(b.line.text.charAt(g.coverStart+h));)--h;for(;g.coverStart+kT&&0==h&&k==g.coverEnd-g.coverStart)var q=c.parentNode.getBoundingClientRect();else{q=Ob(c,h,k).getClientRects();k=Ve;if("left"==m)for(l=0;lT&&((p=!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI)||(null!=Gd?p=Gd:(m=D(a.display.measure,v("span","x")),p=m.getBoundingClientRect(),m=Ob(m,0,1).getBoundingClientRect(),p=Gd=1T)||h||q&&(q.left||q.right)||(q=(q=c.parentNode.getClientRects()[0])?{left:q.left,right:q.left+sb(a.display),top:q.top,bottom:q.bottom}:Ve);c=q.top-b.rect.top;h=q.bottom-b.rect.top;p=(c+h)/2;m=b.view.measure.heights;for(g=0;gb)f=k-h,e=f-1,b>=k&&(g="right");if(null!=e){c=a[l+2];h==k&&d==(c.insertLeft?"left":"right")&&(g=d);if("left"== +d&&0==e)for(;l&&a[l-2]==a[l-3]&&a[l-1].insertLeft;)c=a[(l-=3)+2],g="left";if("right"==d&&e==k-h)for(;l=c.text.length?(l=c.text.length,b="before"):0>=l&&(l=0,b="after");if(!k)return g("before"==b?l-1:l,"before"==b);var m=Ib(k,l,b),n=Jb;m=h(l,m,"before"==b);null!=n&&(m.other=h(l,n,"before"!=b));return m}function af(a,b){var d=0;b=C(a.doc,b);a.options.lineWrapping||(d=sb(a.display)*b.ch);b=w(a.doc,b.line);a=Fa(b)+a.display.lineSpace.offsetTop;return{left:d,right:d, +top:a,bottom:a+b.height}}function Id(a,b,d,c,e){a=t(a,b,d);a.xRel=e;c&&(a.outside=c);return a}function Jd(a,b,d){var c=a.doc;d+=a.display.viewOffset;if(0>d)return Id(c.first,0,null,-1,-1);var e=$a(c,d),f=c.first+c.size-1;if(e>f)return Id(c.first+c.size-1,w(c,f).text.length,null,1,1);0>b&&(b=0);for(var g=w(c,e);;){f=Og(a,g,e,b,d);var h=void 0;var k=f.ch+(0k)&&(!h||0>vd(h,m.marker))&&(h=m.marker)}if(!h)return f;f=h.find(1);if(f.line==e)return f;g=w(c,e=f.line)}}function bf(a,b,d,c){c-=Hd(b);b=b.text.length;var e=Hb(function(f){return ya(a,d,f-1).bottom<=c},b,0);b=Hb(function(f){return ya(a,d,f).top>c},e,b);return{begin:e,end:b}}function cf(a,b,d,c){d||(d=cb(a,b));c=Gc(a,b,ya(a,d,c),"line").top;return bf(a,b,d,c)}function Kd(a,b,d,c){return a.bottom<=d?!1:a.top>d?!0:(c?a.left:a.right)>b}function Og(a,b,d,c,e){e-=Fa(b);var f=cb(a,b),g=Hd(b),h=0, +k=b.text.length,l=!0,m=Ia(b,a.doc.direction);m&&(m=(a.options.lineWrapping?Pg:Qg)(a,b,d,f,m,c,e),h=(l=1!=m.level)?m.from:m.to-1,k=l?m.to:m.from-1);var n=null,p=null;m=Hb(function(r){var u=ya(a,f,r);u.top+=g;u.bottom+=g;if(!Kd(u,c,e,!1))return!1;u.top<=e&&u.left<=c&&(n=r,p=u);return!0},h,k);var q=!1;p?(h=c-p.left=q.bottom?1:0);m=re(b.text,m,1);return Id(d,m,l,q,c-h)}function Qg(a,b,d,c,e,f,g){var h=Hb(function(m){m=e[m];var n=1!=m.level;return Kd(za(a,t(d,n?m.to:m.from,n?"before":"after"),"line",b,c),f,g,!0)},0,e.length-1),k=e[h];if(0g&&(k=e[h-1])}return k}function Pg(a,b,d,c,e,f,g){g=bf(a,b,c,g);d=g.begin;g=g.end;/\s/.test(b.text.charAt(g-1))&&g--;for(var h=b=null, +k=0;k=g||l.to<=d)){var m=ya(a,c,1!=l.level?Math.min(g,l.to)-1:Math.max(d,l.from)).right;m=mm)b=l,h=m}}b||(b=e[e.length-1]);b.fromg&&(b={from:b.from,to:g,level:b.level});return b}function tb(a){if(null!=a.cachedTextHeight)return a.cachedTextHeight;if(null==db){db=v("pre",null,"CodeMirror-line-like");for(var b=0;49>b;++b)db.appendChild(document.createTextNode("x")),db.appendChild(v("br"));db.appendChild(document.createTextNode("x"))}D(a.measure, +db);b=db.offsetHeight/50;3=a.display.viewTo)return null;b-=a.display.viewFrom;if(0>b)return null;a=a.display.view;for(var d=0;db)return d}function ma(a,b,d,c){null==b&&(b=a.doc.first);null==d&&(d=a.doc.first+a.doc.size);c||(c=0);var e=a.display;c&&db)&&(e.updateLineNumbers=b);a.curOp.viewChanged=!0;if(b>=e.viewTo)Ja&&wd(a.doc,b)e.viewFrom?Pa(a):(e.viewFrom+=c,e.viewTo+=c);else if(b<=e.viewFrom&&d>=e.viewTo)Pa(a);else if(b<=e.viewFrom){var f=Ic(a,d,d+c,1);f?(e.view=e.view.slice(f.index),e.viewFrom=f.lineN,e.viewTo+=c):Pa(a)}else if(d>=e.viewTo)(f=Ic(a,b,b,-1))?(e.view=e.view.slice(0,f.index),e.viewTo=f.lineN):Pa(a);else{f=Ic(a,b,b,-1);var g=Ic(a,d,d+c,1);f&&g?(e.view=e.view.slice(0,f.index).concat(Dc(a,f.lineN,g.lineN)).concat(e.view.slice(g.index)),e.viewTo+=c):Pa(a)}if(a=e.externalMeasured)d< +a.lineN?a.lineN+=c:b=e.lineN&&b=c.viewTo||(a=c.view[bb(a,b)],null!=a.node&&(a=a.changes||(a.changes=[]),-1==ea(a,d)&&a.push(d)))}function Pa(a){a.display.viewFrom=a.display.viewTo=a.doc.first;a.display.view=[];a.display.viewOffset=0}function Ic(a,b,d,c){var e=bb(a,b),f=a.display.view;if(!Ja||d==a.doc.first+ +a.doc.size)return{index:e,lineN:d};for(var g=a.display.viewFrom,h=0;hc?0:f.length-1))return null;d+=c*f[e-(0>c?1:0)].size;e+=c}return{index:e,lineN:d}}function ef(a){a=a.display.view;for(var b=0,d=0;d=a.display.viewTo||k.to().liner&&(r=0);r=Math.round(r);A=Math.round(A);h.appendChild(v("div",null,"CodeMirror-selected","position: absolute; left: "+q+"px;\n top: "+r+"px; width: "+(null==u?m-q:u)+"px;\n height: "+(A-r)+"px"))}function e(q,r,u){function A(F,R){return Hc(a,t(q,F),"div",x,R)}function Y(F,R,H){F=cf(a,x,null,F);R="ltr"==R==("after"== +H)?"left":"right";H="after"==H?F.begin:F.end-(/\s/.test(x.text.charAt(F.end-1))?2:1);return A(H,R)[R]}var x=w(g,q),P=x.text.length,K,Q,S=Ia(x,g.direction);zg(S,r||0,null==u?P:u,function(F,R,H,L){var ha="ltr"==H,na=A(F,ha?"left":"right"),ta=A(R-1,ha?"right":"left"),fb=null==r&&0==F,gb=null==u&&R==P,Od=0==L;L=!S||L==S.length-1;3>=ta.top-na.top?(R=(n?fb:gb)&&Od?l:(ha?na:ta).left,c(R,na.top,((n?gb:fb)&&L?m:(ha?ta:na).right)-R,na.bottom)):(ha?(ha=n&&fb&&Od?l:na.left,fb=n?m:Y(F,H,"before"),F=n?l:Y(R,H, +"after"),gb=n&&gb&&L?m:ta.right):(ha=n?Y(F,H,"before"):l,fb=!n&&fb&&Od?m:na.right,F=!n&&gb&&L?l:ta.left,gb=n?Y(R,H,"after"):m),c(ha,na.top,fb-ha,na.bottom),na.bottomJc(na,K))K=na;0>Jc(ta,K)&&(K=ta);if(!Q||0>Jc(na,Q))Q=na;0>Jc(ta,Q)&&(Q=ta)});return{start:K,end:Q}}var f=a.display,g=a.doc,h=document.createDocumentFragment(),k=Se(a.display),l=k.left,m=Math.max(f.sizerWidth,ab(a)-f.sizer.offsetLeft)-k.right,n="ltr"==g.direction; +f=b.from();b=b.to();if(f.line==b.line)e(f.line,f.ch,b.ch);else{var p=w(g,f.line);k=w(g,b.line);k=Ea(p)==Ea(k);f=e(f.line,f.ch,k?p.text.length+1:null).end;b=e(b.line,k?0:null,b.ch).start;k&&(f.topa.options.cursorBlinkRate&&(b.cursorDiv.style.visibility="hidden")}}function gf(a){a.hasFocus()||(a.display.input.focus(),a.state.focused||Qd(a))}function Rd(a){a.state.delayingBlurEvent=!0;setTimeout(function(){a.state.delayingBlurEvent&&(a.state.delayingBlurEvent=!1,a.state.focused&&ub(a))},100)}function Qd(a,b){a.state.delayingBlurEvent&&!a.state.draggingText&&(a.state.delayingBlurEvent= +!1);"nocursor"!=a.options.readOnly&&(a.state.focused||(W(a,"focus",a,b),a.state.focused=!0,Wa(a.display.wrapper,"CodeMirror-focused"),a.curOp||a.display.selForContextMenu==a.doc.sel||(a.display.input.reset(),fa&&setTimeout(function(){return a.display.input.reset(!0)},20)),a.display.input.receivedFocus()),Pd(a))}function ub(a,b){a.state.delayingBlurEvent||(a.state.focused&&(W(a,"blur",a,b),a.state.focused=!1,hb(a.display.wrapper,"CodeMirror-focused")),clearInterval(a.display.blinker),setTimeout(function(){a.state.focused|| +(a.display.shift=!1)},150))}function Kc(a){for(var b=a.display,d=b.lineDiv.offsetTop,c=Math.max(0,b.scroller.getBoundingClientRect().top),e=b.lineDiv.getBoundingClientRect().top,f=0,g=0;gT){k=h.node.offsetTop+h.node.offsetHeight;var m=k-d;d=k}else{var n=h.node.getBoundingClientRect();m=n.bottom-n.top;!k&&h.text.firstChild&&(l=h.text.firstChild.getBoundingClientRect().right-n.left-1)}k=h.line.height- +m;if(.005k)if(ea.display.sizerWidth&&(l=Math.ceil(l/sb(a.display)),l>a.display.maxLineLength&&(a.display.maxLineLength=l,a.display.maxLine=h.line,a.display.maxLineChanged=!0))}}2=e&&(c=$a(b,Fa(w(b,d))-a.wrapper.clientHeight),e=d)}return{from:c,to:Math.max(e,c+1)}}function Sd(a,b){var d=a.display,c=tb(a.display);0>b.top&&(b.top=0);var e=a.curOp&&null!=a.curOp.scrollTop?a.curOp.scrollTop:d.scroller.scrollTop, +f=Dd(a),g={};b.bottom-b.top>f&&(b.bottom=b.top+f);var h=a.doc.height+Cd(d),k=b.toph-c;b.tope+f&&(f=Math.min(b.top,(c?h:b.bottom)-f),f!=e&&(g.scrollTop=f));e=a.options.fixedGutter?0:d.gutters.offsetWidth;f=a.curOp&&null!=a.curOp.scrollLeft?a.curOp.scrollLeft:d.scroller.scrollLeft-e;a=ab(a)-d.gutters.offsetWidth;if(d=b.right-b.left>a)b.right=b.left+a;10>b.left?g.scrollLeft=0:b.lefta+f-3&&(g.scrollLeft= +b.right+(d?0:10)-a);return g}function Mc(a,b){null!=b&&(Nc(a),a.curOp.scrollTop=(null==a.curOp.scrollTop?a.doc.scrollTop:a.curOp.scrollTop)+b)}function vb(a){Nc(a);var b=a.getCursor();a.curOp.scrollToPos={from:b,to:b,margin:a.options.cursorScrollMargin}}function Ub(a,b,d){null==b&&null==d||Nc(a);null!=b&&(a.curOp.scrollLeft=b);null!=d&&(a.curOp.scrollTop=d)}function Nc(a){var b=a.curOp.scrollToPos;if(b){a.curOp.scrollToPos=null;var d=af(a,b.from),c=af(a,b.to);jf(a,d,c,b.margin)}}function jf(a,b,d, +c){b=Sd(a,{left:Math.min(b.left,d.left),top:Math.min(b.top,d.top)-c,right:Math.max(b.right,d.right),bottom:Math.max(b.bottom,d.bottom)+c});Ub(a,b.scrollLeft,b.scrollTop)}function Vb(a,b){2>Math.abs(a.doc.scrollTop-b)||(La||Td(a,{top:b}),kf(a,b,!0),La&&Td(a),Wb(a,100))}function kf(a,b,d){b=Math.max(0,Math.min(a.display.scroller.scrollHeight-a.display.scroller.clientHeight,b));if(a.display.scroller.scrollTop!=b||d)a.doc.scrollTop=b,a.display.scrollbars.setScrollTop(b),a.display.scroller.scrollTop!= +b&&(a.display.scroller.scrollTop=b)}function ib(a,b,d,c){b=Math.max(0,Math.min(b,a.display.scroller.scrollWidth-a.display.scroller.clientWidth));(d?b==a.doc.scrollLeft:2>Math.abs(a.doc.scrollLeft-b))&&!c||(a.doc.scrollLeft=b,lf(a),a.display.scroller.scrollLeft!=b&&(a.display.scroller.scrollLeft=b),a.display.scrollbars.setScrollLeft(b))}function Xb(a){var b=a.display,d=b.gutters.offsetWidth,c=Math.round(a.doc.height+Cd(a.display));return{clientHeight:b.scroller.clientHeight,viewHeight:b.wrapper.clientHeight, +scrollWidth:b.scroller.scrollWidth,clientWidth:b.scroller.clientWidth,viewWidth:b.wrapper.clientWidth,barLeft:a.options.fixedGutter?d:0,docHeight:c,scrollHeight:c+Ga(a)+b.barHeight,nativeBarWidth:b.nativeBarWidth,gutterWidth:d}}function wb(a,b){b||(b=Xb(a));var d=a.display.barWidth,c=a.display.barHeight;mf(a,b);for(b=0;4>b&&d!=a.display.barWidth||c!=a.display.barHeight;b++)d!=a.display.barWidth&&a.options.lineWrapping&&Kc(a),mf(a,Xb(a)),d=a.display.barWidth,c=a.display.barHeight}function mf(a,b){var d= +a.display,c=d.scrollbars.update(b);d.sizer.style.paddingRight=(d.barWidth=c.right)+"px";d.sizer.style.paddingBottom=(d.barHeight=c.bottom)+"px";d.heightForcer.style.borderBottom=c.bottom+"px solid transparent";c.right&&c.bottom?(d.scrollbarFiller.style.display="block",d.scrollbarFiller.style.height=c.bottom+"px",d.scrollbarFiller.style.width=c.right+"px"):d.scrollbarFiller.style.display="";c.bottom&&a.options.coverGutterNextToScrollbar&&a.options.fixedGutter?(d.gutterFiller.style.display="block", +d.gutterFiller.style.height=c.bottom+"px",d.gutterFiller.style.width=b.gutterWidth+"px"):d.gutterFiller.style.display=""}function nf(a){a.display.scrollbars&&(a.display.scrollbars.clear(),a.display.scrollbars.addClass&&hb(a.display.wrapper,a.display.scrollbars.addClass));a.display.scrollbars=new of[a.options.scrollbarStyle](function(b){a.display.wrapper.insertBefore(b,a.display.scrollbarFiller);z(b,"mousedown",function(){a.state.focused&&setTimeout(function(){return a.display.input.focus()},0)}); +b.setAttribute("cm-not-content","true")},function(b,d){"horizontal"==d?ib(a,b):Vb(a,b)},a);a.display.scrollbars.addClass&&Wa(a.display.wrapper,a.display.scrollbars.addClass)}function jb(a){a.curOp={cm:a,viewChanged:!1,startHeight:a.doc.height,forceUpdate:!1,updateInput:0,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++Sg,markArrays:null};a=a.curOp;rb?rb.ops.push(a):a.ownsGroup= +rb={ops:[a],delayedCallbacks:[]}}function kb(a){(a=a.curOp)&&Lg(a,function(b){for(var d=0;d=f.viewTo)||f.maxLineChanged&&e.options.lineWrapping;c.update=c.mustUpdate&&new Oc(e,c.mustUpdate&&{top:c.scrollTop,ensure:c.scrollToPos},c.forceUpdate)}for(d=0;dn;n++){var p=!1;h=za(e, +k);var q=l&&l!=k?za(e,l):h;h={left:Math.min(h.left,q.left),top:Math.min(h.top,q.top)-m,right:Math.max(h.left,q.left),bottom:Math.max(h.bottom,q.bottom)+m};q=Sd(e,h);var r=e.doc.scrollTop,u=e.doc.scrollLeft;null!=q.scrollTop&&(Vb(e,q.scrollTop),1l.top+n.top?k=!0:l.bottom+n.top>(window.innerHeight|| +document.documentElement.clientHeight)&&(k=!1),null==k||Tg||(l=v("div","\u200b",null,"position: absolute;\n top: "+(l.top-m.viewOffset-e.display.lineSpace.offsetTop)+"px;\n height: "+(l.bottom-l.top+Ga(e)+m.barHeight)+"px;\n left: "+l.left+"px; width: "+Math.max(2,l.right-l.left)+"px;"),e.display.lineSpace.appendChild(l),l.scrollIntoView(k),e.display.lineSpace.removeChild(l)))}l=c.maybeHiddenMarkers;k=c.maybeUnhiddenMarkers;if(l)for(m= +0;m=a.display.viewTo)){var d=+new Date+a.options.workTime,c=Mb(a,b.highlightFrontier),e=[];b.iter(c.line,Math.min(b.first+b.size,a.display.viewTo+ +500),function(f){if(c.line>=a.display.viewFrom){var g=f.styles,h=f.text.length>a.options.maxHighlightLength?Ya(b.mode,c.state):null,k=xe(a,f,c,!0);h&&(c.state=h);f.styles=k.styles;h=f.styleClasses;(k=k.classes)?f.styleClasses=k:h&&(f.styleClasses=null);k=!g||g.length!=f.styles.length||h!=k&&(!h||!k||h.bgClass!=k.bgClass||h.textClass!=k.textClass);for(h=0;!k&&hd)return Wb(a,a.options.workDelay),!0});b.highlightFrontier=c.line;b.modeFrontier=Math.max(b.modeFrontier,c.line);e.length&&qa(a,function(){for(var f=0;f=d.viewFrom&&b.visible.to<=d.viewTo&&(null==d.updateLineNumbers||d.updateLineNumbers>=d.viewTo)&&d.renderedView==d.view&&0==ef(a))return!1;qf(a)&& +(Pa(a),b.dims=Fd(a));var e=c.first+c.size,f=Math.max(b.visible.from-a.options.viewportMargin,c.first),g=Math.min(e,b.visible.to+a.options.viewportMargin);d.viewFromf-d.viewFrom&&(f=Math.max(c.first,d.viewFrom));d.viewTo>g&&20>d.viewTo-g&&(g=Math.min(e,d.viewTo));Ja&&(f=wd(a.doc,f),g=Ie(a.doc,g));c=f!=d.viewFrom||g!=d.viewTo||d.lastWrapHeight!=b.wrapperHeight||d.lastWrapWidth!=b.wrapperWidth;e=a.display;0==e.view.length||f>=e.viewTo||g<=e.viewFrom?(e.view=Dc(a,f,g),e.viewFrom=f):(e.viewFrom> +f?e.view=Dc(a,f,e.viewFrom).concat(e.view):e.viewFromg&&(e.view=e.view.slice(0,bb(a,g))));e.viewTo=g;d.viewOffset=Fa(w(a.doc,d.viewFrom));a.display.mover.style.top=d.viewOffset+"px";g=ef(a);if(!c&&0==g&&!b.force&&d.renderedView==d.view&&(null==d.updateLineNumbers||d.updateLineNumbers>=d.viewTo))return!1;a.hasFocus()?f=null:(f=ka())&&ja(a.display.lineDiv,f)?(f={activeElt:f},window.getSelection&& +(e=window.getSelection(),e.anchorNode&&e.extend&&ja(a.display.lineDiv,e.anchorNode)&&(f.anchorNode=e.anchorNode,f.anchorOffset=e.anchorOffset,f.focusNode=e.focusNode,f.focusOffset=e.focusOffset))):f=null;4=a.display.viewFrom&&b.visible.to<=a.display.viewTo)break;if(!Ud(a,b))break;Kc(a);c=Xb(a);Tb(a);wb(a,c);Vd(a,c);b.force=!1}b.signal(a,"update",a);if(a.display.viewFrom!=a.display.reportedViewFrom||a.display.viewTo!=a.display.reportedViewTo)b.signal(a,"viewportChange",a,a.display.viewFrom,a.display.viewTo),a.display.reportedViewFrom=a.display.viewFrom, +a.display.reportedViewTo=a.display.viewTo}function Td(a,b){b=new Oc(a,b);if(Ud(a,b)){Kc(a);pf(a,b);var d=Xb(a);Tb(a);wb(a,d);Vd(a,d);b.finish()}}function Vg(a,b,d){function c(p){var q=p.nextSibling;fa&&xa&&a.display.currentWheelTarget==p?p.style.display="none":p.parentNode.removeChild(p);return q}var e=a.display,f=a.options.lineNumbers,g=e.lineDiv,h=g.firstChild,k=e.view;e=e.viewFrom;for(var l=0;lT&&(this.gutters.style.zIndex=-1,this.scroller.style.paddingRight= +0);fa||La&&Zb||(this.scroller.draggable=!0);a&&(a.appendChild?a.appendChild(this.wrapper):a(this.wrapper));this.reportedViewFrom=this.reportedViewTo=this.viewFrom=this.viewTo=b.first;this.view=[];this.externalMeasured=this.renderedView=null;this.lastWrapHeight=this.lastWrapWidth=this.viewOffset=0;this.updateLineNumbers=null;this.nativeBarWidth=this.barHeight=this.barWidth=0;this.scrollbarsClipped=!1;this.lineNumWidth=this.lineNumInnerWidth=this.lineNumChars=null;this.alignWidgets=!1;this.maxLine= +this.cachedCharWidth=this.cachedTextHeight=this.cachedPaddingH=null;this.maxLineLength=0;this.maxLineChanged=!1;this.wheelDX=this.wheelDY=this.wheelStartX=this.wheelStartY=null;this.shift=!1;this.activeTouch=this.selForContextMenu=null;this.gutterSpecs=Xd(c.gutters,c.lineNumbers);rf(this);d.init(this)}function sf(a){var b=a.wheelDeltaX,d=a.wheelDeltaY;null==b&&a.detail&&a.axis==a.HORIZONTAL_AXIS&&(b=a.detail);null==d&&a.detail&&a.axis==a.VERTICAL_AXIS?d=a.detail:null==d&&(d=a.wheelDelta);return{x:b, +y:d}}function Xg(a){a=sf(a);a.x*=Ma;a.y*=Ma;return a}function tf(a,b){var d=sf(b),c=d.x;d=d.y;var e=Ma;0===b.deltaMode&&(c=b.deltaX,d=b.deltaY,e=1);var f=a.display,g=f.scroller,h=g.scrollWidth>g.clientWidth,k=g.scrollHeight>g.clientHeight;if(c&&h||d&&k){if(d&&xa&&fa){h=b.target;var l=f.view;a:for(;h!=g;h=h.parentNode)for(var m=0;me?k=Math.max(0, +k+e-50):h=Math.min(a.doc.height,h+e+50),Td(a,{top:k,bottom:h})),20>Pc&&0!==b.deltaMode&&(null==f.wheelStartX?(f.wheelStartX=g.scrollLeft,f.wheelStartY=g.scrollTop,f.wheelDX=c,f.wheelDY=d,setTimeout(function(){if(null!=f.wheelStartX){var n=g.scrollLeft-f.wheelStartX,p=g.scrollTop-f.wheelStartY;n=p&&f.wheelDY&&p/f.wheelDY||n&&f.wheelDX&&n/f.wheelDX;f.wheelStartX=f.wheelStartY=null;n&&(Ma=(Ma*Pc+n)/(Pc+1),++Pc)}},200)):(f.wheelDX+=c,f.wheelDY+=d))):(d&&k&&Vb(a,Math.max(0,g.scrollTop+d*e)),ib(a,Math.max(0, +g.scrollLeft+c*e)),(!d||d&&k)&&la(b),f.wheelStartX=null)}}function Ba(a,b,d){a=a&&a.options.selectionsMayTouch;d=b[d];b.sort(function(k,l){return B(k.from(),l.from())});d=ea(b,d);for(var c=1;cB(a,b.from))return a;if(0>=B(a,b.to))return Ra(b);var d=a.line+b.text.length-(b.to.line-b.from.line)-1,c=a.ch;a.line==b.to.line&&(c+=Ra(b).ch-b.to.ch);return t(d,c)}function Yd(a,b){for(var d=[],c=0;cf-(a.cm?a.cm.options.historyEventDelay:500)||"*"==b.origin.charAt(0))){if(e.lastOp==c){Af(e.done);var h=J(e.done)}else e.done.length&&!J(e.done).ranges?h=J(e.done):1e.undoDepth;)e.done.shift(), +e.done[0].ranges||e.done.shift();e.done.push(d);e.generation=++e.maxGeneration;e.lastModTime=e.lastSelTime=f;e.lastOp=e.lastSelOp=c;e.lastOrigin=e.lastSelOrigin=b.origin;k||W(a,"historyAdded")}function Rc(a,b){var d=J(b);d&&d.ranges&&d.equals(a)||b.push(a)}function zf(a,b,d,c){var e=b["spans_"+a.id],f=0;a.iter(Math.max(a.first,d),Math.min(a.first+a.size,c),function(g){g.markedSpans&&((e||(e=b["spans_"+a.id]={}))[f]=g.markedSpans);++f})}function Cf(a,b){var d;if(d=b["spans_"+a.id]){for(var c=[],e= +0;eB(b,a),c!=0>B(d,a)?(a=b,b=d):c!=0>B(b,d)&&(b=d)),new I(a,b)):new I(d||b,b)}function Sc(a,b,d,c,e){null==e&&(e=a.cm&&(a.cm.display.shift||a.extend));da(a,new ua([be(a.sel.primary(), +b,d,e)],0),c)}function Df(a,b,d){for(var c=[],e=a.cm&&(a.cm.display.shift||a.extend),f=0;fB(b.primary().head,a.sel.primary().head)?-1:1);Ff(a,Gf(a,b,c,!0));d&&!1===d.scroll||!a.cm||"nocursor"==a.cm.getOption("readOnly")||vb(a.cm)}function Ff(a,b){b.equals(a.sel)|| +(a.sel=b,a.cm&&(a.cm.curOp.updateInput=1,a.cm.curOp.selectionChanged=!0,se(a.cm)),aa(a,"cursorActivity",a))}function Hf(a){Ff(a,Gf(a,a.sel,null,!1))}function Gf(a,b,d,c){for(var e,f=0;f=b.ch:h.to>b.ch))){if(e&&(W(k,"beforeCursorEnter"),k.explicitlyCleared))if(f.markedSpans){--g;continue}else break;if(k.atomic){if(d){g=k.find(0>c?1:-1);h=void 0;if(0>c?m:l)g=If(a,g,-c,g&&g.line==b.line?f:null);if(g&&g.line==b.line&&(h=B(g,d))&&(0>c?0>h:0c?-1:1);if(0>c?l:m)d=If(a,d,c,d.line==b.line?f:null);return d?zb(a,d,b,c,e):null}}}return b}function Uc(a,b,d,c,e){c=c||1;b=zb(a,b,d,c,e)||!e&&zb(a,b,d,c,!0)||zb(a,b,d,-c,e)||!e&&zb(a,b,d,-c,!0);return b?b:(a.cantEdit=!0,t(a.first,0))}function If(a,b,d,c){return 0>d&&0==b.ch?b.line>a.first?C(a,t(b.line-1)):null:0a.lastLine())){if(b.from.linee&&(b={from:b.from,to:t(e, +w(a,e).text.length),text:[b.text[0]],origin:b.origin});b.removed=Za(a,b.from,b.to);d||(d=Yd(a,b));a.cm?$g(a.cm,b,c):$d(a,b,c);Tc(a,d,Ha);a.cantEdit&&Uc(a,t(a.firstLine(),0))&&(a.cantEdit=!1)}}function $g(a,b,d){var c=a.doc,e=a.display,f=b.from,g=b.to,h=!1,k=f.line;a.options.lineWrapping||(k=N(Ea(w(c,f.line))),c.iter(k,g.line+1,function(l){if(l==e.maxLine)return h=!0}));-1e.maxLineLength&&(e.maxLine=l,e.maxLineLength=m,e.maxLineChanged=!0,h=!1)}),h&&(a.curOp.updateMaxLine=!0));Eg(c,f.line);Wb(a,400);d=b.text.length-(g.line-f.line)-1;b.full?ma(a):f.line!=g.line||1!=b.text.length||wf(a.doc,b)?ma(a,f.line,g.line+1,d):Qa(a,f.line,"text");d=wa(a,"changes");if((c=wa(a,"change"))||d)b={from:f,to:g,text:b.text,removed:b.removed,origin:b.origin},c&&aa(a,"change",a,b),d&&(a.curOp.changeObjs||(a.curOp.changeObjs=[])).push(b);a.display.selForContextMenu=null}function Bb(a,b, +d,c,e){c||(c=d);0>B(c,d)&&(c=[c,d],d=c[0],c=c[1]);"string"==typeof b&&(b=a.splitLines(b));Ab(a,{from:d,to:c,text:b,origin:e})}function Pf(a,b,d,c){d=B(f.from,J(c).to);){var g=c.pop();if(0>B(g.from,f.from)){f.from=g.from;break}}c.push(f)}qa(a,function(){for(var h=c.length-1;0<=h;h--)Bb(a.doc,"",c[h].from,c[h].to,"+delete");vb(a)})}function de(a,b,d){b=re(a.text,b+d,d);return 0>b||b>a.text.length?null:b}function ee(a,b,d){a= +de(a,b.ch,d);return null==a?null:new t(b.line,a,0>d?"after":"before")}function fe(a,b,d,c,e){if(a&&("rtl"==b.doc.direction&&(e=-e),a=Ia(d,b.doc.direction))){a=0>e?J(a):a[0];var f=0>e==(1==a.level)?"after":"before";if(0e?d.text.length-1:0;var k=ya(b,g,h).top;h=Hb(function(l){return ya(b,g,l).top==k},0>e==(1==a.level)?a.from:a.to-1,h);"before"==f&&(h=de(d,h,1))}else h=0>e?a.to:a.from;return new t(c,h,f)}return new t(c,0>e?d.text.length:0,0>e?"before": +"after")}function ih(a,b,d,c){var e=Ia(b,a.doc.direction);if(!e)return ee(b,d,c);d.ch>=b.text.length?(d.ch=b.text.length,d.sticky="before"):0>=d.ch&&(d.ch=0,d.sticky="after");var f=Ib(e,d.ch,d.sticky),g=e[f];if("ltr"==a.doc.direction&&0==g.level%2&&(0d.ch:g.fromc,p=h(d,n?1:-1);if(null!=p&&(n?p<=g.to&&p<=m.end:p>=g.from&&p>=m.begin))return new t(d.line,p,n?"before":"after")}g=function(q,r,u){for(var A=function(K,Q){return Q?new t(d.line,h(K,1),"before"):new t(d.line,K,"after")};0<=q&&qT&&27==a.keyCode&&(a.returnValue=!1);var b=a.keyCode;this.display.shift=16==b||a.shiftKey;var d=cg(this,a);Aa&&(ge=d?b:null,!d&&88==b&&!lh&&(xa?a.metaKey:a.ctrlKey)&&this.replaceSelection("",null,"cut"));La&&!xa&&!d&&46==b&&a.shiftKey&&!a.ctrlKey&&document.execCommand&&document.execCommand("cut");18!=b||/\bCodeMirror-crosshair\b/.test(this.display.lineDiv.className)||mh(this)}}function mh(a){function b(c){18!=c.keyCode&& +c.altKey||(hb(d,"CodeMirror-crosshair"),sa(document,"keyup",b),sa(document,"mouseover",b))}var d=a.display.lineDiv;Wa(d,"CodeMirror-crosshair");z(document,"keyup",b);z(document,"mouseover",b)}function eg(a){16==a.keyCode&&(this.doc.sel.shift=!1);Z(this,a)}function fg(a){if(!(a.target&&a.target!=this.display.input.getField()||Ka(this.display,a)||Z(this,a)||a.ctrlKey&&!a.altKey||xa&&a.metaKey)){var b=a.keyCode,d=a.charCode;if(Aa&&b==ge)ge=null,la(a);else if(!Aa||a.which&&!(10>a.which)||!cg(this,a))if(b= +String.fromCharCode(null==d?b:d),"\b"!=b&&!kh(this,a,b))this.display.input.onKeyPress(a)}}function nh(a,b){var d=+new Date;if(jc&&jc.compare(d,a,b))return kc=jc=null,"triple";if(kc&&kc.compare(d,a,b))return jc=new he(d,a,b),kc=null,"double";kc=new he(d,a,b);jc=null;return"single"}function gg(a){var b=this.display;if(!(Z(this,a)||b.activeTouch&&b.input.supportsTouch()))if(b.input.ensurePolled(),b.shift=a.shiftKey,Ka(b,a))fa||(b.scroller.draggable=!1,setTimeout(function(){return b.scroller.draggable= +!0},100));else if(!Zc(this,a,"gutterClick",!0)){var d=eb(this,a),c=ue(a),e=d?nh(d,c):"single";window.focus();1==c&&this.state.selectingText&&this.state.selectingText(a);if(!d||!oh(this,c,d,e,a))if(1==c)d?ph(this,d,e,a):(a.target||a.srcElement)==b.scroller&&la(a);else if(2==c)d&&Sc(this.doc,d),setTimeout(function(){return b.input.focus()},20);else if(3==c)if(ie)this.display.input.onContextMenu(a);else Rd(this)}}function oh(a,b,d,c,e){var f="Click";"double"==c?f="Double"+f:"triple"==c&&(f="Triple"+ +f);return ic(a,Xf((1==b?"Left":2==b?"Middle":"Right")+f,e),e,function(g){"string"==typeof g&&(g=hc[g]);if(!g)return!1;var h=!1;try{a.isReadOnly()&&(a.state.suppressEdits=!0),h=g(a,d)!=Yc}finally{a.state.suppressEdits=!1}return h})}function ph(a,b,d,c){G?setTimeout(fd(gf,a),0):a.curOp.focus=ka();var e=a.getOption("configureMouse");e=e?e(a,d,c):{};null==e.unit&&(e.unit=(qh?c.shiftKey&&c.metaKey:c.altKey)?"rectangle":"single"==d?"char":"double"==d?"word":"line");if(null==e.extend||a.doc.extend)e.extend= +a.doc.extend||c.shiftKey;null==e.addNew&&(e.addNew=xa?c.metaKey:c.ctrlKey);null==e.moveOnDrag&&(e.moveOnDrag=!(xa?c.altKey:c.ctrlKey));var f=a.doc.sel,g;a.options.dragDrop&&rh&&!a.isReadOnly()&&"single"==d&&-1<(g=f.contains(b))&&(0>B((g=f.ranges[g]).from(),b)||0b.xRel)?sh(a,c,b,e):th(a,c,b,e)}function sh(a,b,d,c){var e=a.display,f=!1,g=ba(a,function(l){fa&&(e.scroller.draggable=!1);a.state.draggingText=!1;a.state.delayingBlurEvent&&(a.hasFocus()?a.state.delayingBlurEvent= +!1:Rd(a));sa(e.wrapper.ownerDocument,"mouseup",g);sa(e.wrapper.ownerDocument,"mousemove",h);sa(e.scroller,"dragstart",k);sa(e.scroller,"drop",g);f||(la(l),c.addNew||Sc(a.doc,d,null,null,c.extend),fa&&!$c||G&&9==T?setTimeout(function(){e.wrapper.ownerDocument.body.focus({preventScroll:!0});e.input.focus()},20):e.input.focus())}),h=function(l){f=f||10<=Math.abs(b.clientX-l.clientX)+Math.abs(b.clientY-l.clientY)},k=function(){return f=!0};fa&&(e.scroller.draggable=!0);a.state.draggingText=g;g.copy=!c.moveOnDrag; +z(e.wrapper.ownerDocument,"mouseup",g);z(e.wrapper.ownerDocument,"mousemove",h);z(e.scroller,"dragstart",k);z(e.scroller,"drop",g);a.state.delayingBlurEvent=!0;setTimeout(function(){return e.input.focus()},20);e.scroller.dragDrop&&e.scroller.dragDrop()}function hg(a,b,d){if("char"==d)return new I(b,b);if("word"==d)return a.findWordAt(b);if("line"==d)return new I(t(b.line,0),C(a.doc,t(b.line+1,0)));a=d(a,b);return new I(a.from,a.to)}function th(a,b,d,c){function e(x){if(0!=B(q,x))if(q=x,"rectangle"== +c.unit){var P=[],K=a.options.tabSize,Q=va(w(k,d.line).text,d.ch,K),S=va(w(k,x.line).text,x.ch,K),F=Math.min(Q,S);Q=Math.max(Q,S);S=Math.min(d.line,x.line);for(var R=Math.min(a.lastLine(),Math.max(d.line,x.line));S<=R;S++){var H=w(k,S).text,L=gd(H,F,K);F==Q?P.push(new I(t(S,L),t(S,L))):H.length>L&&P.push(new I(t(S,L),t(S,gd(H,Q,K))))}P.length||P.push(new I(d,d));da(k,Ba(a,l.ranges.slice(0,n).concat(P),n),{origin:"*mouse",scroll:!1});a.scrollIntoView(x)}else P=p,F=hg(a,x,c.unit),x=P.anchor,0=Q.to||K.liner.bottom?20:0;S&&setTimeout(ba(a,function(){u==P&&(h.scroller.scrollTop+=S,f(x))}),50)}}function g(x){a.state.selectingText=!1;u=Infinity; +x&&(la(x),h.input.focus());sa(h.wrapper.ownerDocument,"mousemove",A);sa(h.wrapper.ownerDocument,"mouseup",Y);k.history.lastSelOrigin=null}G&&Rd(a);var h=a.display,k=a.doc;la(b);var l=k.sel,m=l.ranges;if(c.addNew&&!c.extend){var n=k.sel.contains(d);var p=-1f:0=Math.floor(a.display.gutters.getBoundingClientRect().right))return!1;c&&la(b);c=a.display;var g=c.lineDiv.getBoundingClientRect();if(f>g.bottom||!wa(a,d))return kd(b);f-=g.top-c.viewOffset;for(g=0;g=e)return e=$a(a.doc,f),W(a,d,a,e,a.display.gutterSpecs[g].className,b),kd(b)}}function ig(a,b){var d; +(d=Ka(a.display,b))||(d=wa(a,"gutterContextMenu")?Zc(a,b,"gutterContextMenu",!1):!1);if(!d&&!Z(a,b,"contextmenu")&&!ie)a.display.input.onContextMenu(b)}function jg(a){a.display.wrapper.className=a.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+a.options.theme.replace(/(^|\s)\s*/g," cm-s-");Sb(a)}function vh(a,b,d){!b!=!(d&&d!=Fb)&&(d=a.display.dragFunctions,b=b?z:sa,b(a.display.scroller,"dragstart",d.start),b(a.display.scroller,"dragenter",d.enter),b(a.display.scroller,"dragover",d.over),b(a.display.scroller, +"dragleave",d.leave),b(a.display.scroller,"drop",d.drop))}function wh(a){a.options.lineWrapping?(Wa(a.display.wrapper,"CodeMirror-wrap"),a.display.sizer.style.minWidth="",a.display.sizerWidth=null):(hb(a.display.wrapper,"CodeMirror-wrap"),yd(a));Md(a);ma(a);Sb(a);setTimeout(function(){return wb(a)},100)}function U(a,b){var d=this;if(!(this instanceof U))return new U(a,b);this.options=b=b?Xa(b):{};Xa(kg,b,!1);var c=b.value;"string"==typeof c?c=new oa(c,b.mode,null,b.lineSeparator,b.direction):b.mode&& +(c.modeOption=b.mode);this.doc=c;var e=new U.inputStyles[b.inputStyle](this);a=this.display=new Wg(a,c,e,b);a.wrapper.CodeMirror=this;jg(this);b.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap");nf(this);this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:-1,cutIncoming:-1,selectingText:!1,draggingText:!1,highlight:new Va,keySeq:null,specialChars:null};b.autofocus&&!Zb&&a.input.focus();G&&11>T&&setTimeout(function(){return d.display.input.reset(!0)}, +20);xh(this);lg||(eh(),lg=!0);jb(this);this.curOp.forceUpdate=!0;xf(this,c);b.autofocus&&!Zb||this.hasFocus()?setTimeout(function(){d.hasFocus()&&!d.state.focused&&Qd(d)},20):ub(this);for(var f in ad)if(ad.hasOwnProperty(f))ad[f](this,b[f],Fb);qf(this);b.finishInit&&b.finishInit(this);for(c=0;cT?z(c.scroller,"dblclick",ba(a,function(h){if(!Z(a,h)){var k=eb(a,h);!k||Zc(a,h,"gutterClick",!0)||Ka(a.display,h)||(la(h),h=a.findWordAt(k),Sc(a.doc,h.anchor,h.head))}})):z(c.scroller,"dblclick",function(h){return Z(a,h)||la(h)});z(c.scroller,"contextmenu",function(h){return ig(a, +h)});z(c.input.getField(),"contextmenu",function(h){c.scroller.contains(h.target)||ig(a,h)});var e,f={end:0};z(c.scroller,"touchstart",function(h){var k;if(k=!Z(a,h))1!=h.touches.length?k=!1:(k=h.touches[0],k=1>=k.radiusX&&1>=k.radiusY),k=!k;k&&!Zc(a,h,"gutterClick",!0)&&(c.input.ensurePolled(),clearTimeout(e),k=+new Date,c.activeTouch={start:k,moved:!1,prev:300>=k-f.end?f:null},1==h.touches.length&&(c.activeTouch.left=h.touches[0].pageX,c.activeTouch.top=h.touches[0].pageY))});z(c.scroller,"touchmove", +function(){c.activeTouch&&(c.activeTouch.moved=!0)});z(c.scroller,"touchend",function(h){var k=c.activeTouch;if(k&&!Ka(c,h)&&null!=k.left&&!k.moved&&300>new Date-k.start){var l=a.coordsChar(c.activeTouch,"page");k=!k.prev||d(k,k.prev)?new I(l,l):!k.prev.prev||d(k,k.prev.prev)?a.findWordAt(l):new I(t(l.line,0),C(a.doc,t(l.line+1,0)));a.setSelection(k.anchor,k.head);a.focus();la(h)}b()});z(c.scroller,"touchcancel",b);z(c.scroller,"scroll",function(){c.scroller.clientHeight&&(Vb(a,c.scroller.scrollTop), +ib(a,c.scroller.scrollLeft,!0),W(a,"scroll",a))});z(c.scroller,"mousewheel",function(h){return tf(a,h)});z(c.scroller,"DOMMouseScroll",function(h){return tf(a,h)});z(c.wrapper,"scroll",function(){return c.wrapper.scrollTop=c.wrapper.scrollLeft=0});c.dragFunctions={enter:function(h){Z(a,h)||Kb(h)},over:function(h){if(!Z(a,h)){var k=eb(a,h);if(k){var l=document.createDocumentFragment();Nd(a,k,l);a.display.dragCursor||(a.display.dragCursor=v("div",null,"CodeMirror-cursors CodeMirror-dragcursors"),a.display.lineSpace.insertBefore(a.display.dragCursor, +a.display.cursorDiv));D(a.display.dragCursor,l)}Kb(h)}},start:function(h){if(G&&(!a.state.draggingText||100>+new Date-Uf))Kb(h);else if(!Z(a,h)&&!Ka(a.display,h)&&(h.dataTransfer.setData("Text",a.getSelection()),h.dataTransfer.effectAllowed="copyMove",h.dataTransfer.setDragImage&&!$c)){var k=v("img",null,null,"position: fixed; left: 0; top: 0;");k.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";Aa&&(k.width=k.height=1,a.display.wrapper.appendChild(k),k._top=k.offsetTop); +h.dataTransfer.setDragImage(k,0,0);Aa&&k.parentNode.removeChild(k)}},drop:ba(a,dh),leave:function(h){Z(a,h)||Tf(a)}};var g=c.input.getField();z(g,"keyup",function(h){return eg.call(a,h)});z(g,"keydown",ba(a,dg));z(g,"keypress",ba(a,fg));z(g,"focus",function(h){return Qd(a,h)});z(g,"blur",function(h){return ub(a,h)})}function lc(a,b,d,c){var e=a.doc,f;null==d&&(d="add");"smart"==d&&(e.mode.indent?f=Mb(a,b).state:d="prev");var g=a.options.tabSize,h=w(e,b),k=va(h.text,null,g);h.stateAfter&&(h.stateAfter= +null);var l=h.text.match(/^\s*/)[0];if(!c&&!/\S/.test(h.text)){var m=0;d="not"}else if("smart"==d&&(m=e.mode.indent(f,h.text.slice(l.length),h.text),m==Yc||150e.first?va(w(e,b-1).text,null,g):0:"add"==d?m=k+a.options.indentUnit:"subtract"==d?m=k-a.options.indentUnit:"number"==typeof d&&(m=k+d);m=Math.max(0,m);d="";c=0;if(a.options.indentWithTabs)for(a=Math.floor(m/g);a;--a)c+=g,d+="\t";cg,k=me(b),l=null;if(h&&1g?"cut":"+input")};Ab(a.doc,p);aa(a,"inputRead",a,p)}b&&!h&&mg(a,b);vb(a);2>a.curOp.updateInput&& +(a.curOp.updateInput=m);a.curOp.typing=!0;a.state.pasteIncoming=a.state.cutIncoming=-1}function ng(a,b){var d=a.clipboardData&&a.clipboardData.getData("Text");if(d)return a.preventDefault(),b.isReadOnly()||b.options.disableInput||qa(b,function(){return le(b,d,0,null,"paste")}),!0}function mg(a,b){if(a.options.electricChars&&a.options.smartIndent)for(var d=a.doc.sel,c=d.ranges.length-1;0<=c;c--){var e=d.ranges[c];if(!(100A:56320<=A&&57343>A)?2:1))),-d)}else A=e?ih(a.cm,k,b,d):ee(k,b,d);if(null==A){if(u=!u)u=b.line+l,u=a.first+a.size?u=!1:(b=new t(u,b.ch,b.sticky),u=k=w(a,u));if(u)b=fe(e,a.cm,k,b.line,l);else return!1}else b=A;return!0}var g=b,h=d,k=w(a,b.line),l=e&&"rtl"==a.direction?-d:d;if("char"==c||"codepoint"==c)f();else if("column"== +c)f(!0);else if("word"==c||"group"==c)for(var m=null,n="group"==c,p=a.cm&&a.cm.getHelper(b,"wordChars"),q=!0;!(0>d)||f(!q);q=!1){var r=k.text.charAt(b.ch)||"\n";r=vc(r,p)?"w":n&&"\n"==r?"n":!n||/\s/.test(r)?null:"p";!n||q||r||(r="s");if(m&&m!=r){0>d&&(d=1,f(),b.sticky="after");break}r&&(m=r);if(0d?0>=g:g>=e.height){b.hitSide=!0;break}g+=5*d}return b}function sg(a,b){var d=Ed(a,b.line);if(!d||d.hidden)return null;var c=w(a.doc,b.line);d=Te(d,c,b.line);a=Ia(c,a.doc.direction);c="left";a&&(c=Ib(a,b.ch)%2?"right":"left");b=Ue(d.map,b.ch,c);b.offset="right"==b.collapse?b.end:b.start;return b}function yh(a){for(;a;a=a.parentNode)if(/CodeMirror-gutter-wrapper/.test(a.className))return!0; +return!1}function Gb(a,b){b&&(a.bad=!0);return a}function zh(a,b,d,c,e){function f(q){return function(r){return r.id==q}}function g(){m&&(l+=n,p&&(l+=n),m=p=!1)}function h(q){q&&(g(),l+=q)}function k(q){if(1==q.nodeType){var r=q.getAttribute("cm-text");if(r)h(r);else{r=q.getAttribute("cm-marker");var u;if(r)q=a.findMarks(t(c,0),t(e+1,0),f(+r)),q.length&&(u=q[0].find(0))&&h(Za(a.doc,u.from,u.to).join(n));else if("false"!=q.getAttribute("contenteditable")&&(u=/^(pre|div|p|li|table|br)$/i.test(q.nodeName), +/^br$/i.test(q.nodeName)||0!=q.textContent.length)){u&&g();for(r=0;rq?k.map:l[q],u=0;uq?a.line:a.rest[q]);q=r[u]+p;if(0>p||A!=m)q=r[u+(p?1:0)];return t(n,q)}}}var e=a.text.firstChild,f=!1;if(!b||!ja(e,b))return Gb(t(N(a.line),0),!0); +if(b==e&&(f=!0,b=e.childNodes[d],d=0,!b))return d=a.rest?J(a.rest):a.line,Gb(t(N(d),d.text.length),f);var g=3==b.nodeType?b:null,h=b;g||1!=b.childNodes.length||3!=b.firstChild.nodeType||(g=b.firstChild,d&&(d=g.nodeValue.length));for(;h.parentNode!=e;)h=h.parentNode;var k=a.measure,l=k.maps;if(b=c(g,h,d))return Gb(b,f);e=h.nextSibling;for(g=g?g.nodeValue.length-d:0;e;e=e.nextSibling){if(b=c(e,e.firstChild,0))return Gb(t(b.line,b.ch-g),f);g+=e.textContent.length}for(h=h.previousSibling;h;h=h.previousSibling){if(b= +c(h,h.firstChild,-1))return Gb(t(b.line,b.ch+d),f);d+=h.textContent.length}}var pa=navigator.userAgent,tg=navigator.platform,La=/gecko\/\d/i.test(pa),ug=/MSIE \d/.test(pa),vg=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(pa),cd=/Edge\/(\d+)/.exec(pa),G=ug||vg||cd,T=G&&(ug?document.documentMode||6:+(cd||vg)[1]),fa=!cd&&/WebKit\//.test(pa),Bh=fa&&/Qt\/\d+\.\d+/.test(pa),Ec=!cd&&/Chrome\//.test(pa),Aa=/Opera\//.test(pa),$c=/Apple Computer/.test(navigator.vendor),Ch=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(pa), +Tg=/PhantomJS/.test(pa),mc=$c&&(/Mobile\/\w+/.test(pa)||2lb)),ie=La||G&&9<=T,hb=function(a,b){var d=a.className;if(b=y(b).exec(d)){var c=d.slice(b.index+b[0].length);a.className=d.slice(0,b.index)+ +(c?b[1]+c:"")}};var Ob=document.createRange?function(a,b,d,c){var e=document.createRange();e.setEnd(c||a,d);e.setStart(a,b);return e}:function(a,b,d){var c=document.body.createTextRange();try{c.moveToElementText(a.parentNode)}catch(e){return c}c.collapse(!0);c.moveEnd("character",d);c.moveStart("character",b);return c};var nc=function(a){a.select()};mc?nc=function(a){a.selectionStart=0;a.selectionEnd=a.value.length}:G&&(nc=function(a){try{a.select()}catch(b){}});var Va=function(){this.f=this.id=null; +this.time=0;this.handler=fd(this.onTimeout,this)};Va.prototype.onTimeout=function(a){a.id=0;a.time<=+new Date?a.f():setTimeout(a.handler,a.time-+new Date)};Va.prototype.set=function(a,b){this.f=b;b=+new Date+a;if(!this.id||b=r?"bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN".charAt(r): +1424<=r&&1524>=r?"R":1536<=r&&1785>=r?"nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111".charAt(r-1536):1774<=r&&2220>=r?"r":8192<=r&&8203>=r?"w":8204==r?"b":"L";q.call(p,r)}n=0;for(p=k;nT)return!1;var a=v("div");return"draggable"in a||"dragDrop"in a}(),Ad,zd,me=3!="\n\nb".split(/\n/).length?function(a){for(var b=0,d=[],c=a.length;b<=c;){var e=a.indexOf("\n",b);-1==e&&(e=a.length);var f=a.slice(b,"\r"==a.charAt(e-1)?e-1:e),g=f.indexOf("\r"); +-1!=g?(d.push(f.slice(0,g)),b+=g+1):(d.push(f),b=e+1)}return d}:function(a){return a.split(/\r\n?|\n/)},Eh=window.getSelection?function(a){try{return a.selectionStart!=a.selectionEnd}catch(b){return!1}}:function(a){try{var b=a.ownerDocument.selection.createRange()}catch(d){}return b&&b.parentElement()==a?0!=b.compareEndPoints("StartToEnd",b):!1},lh=function(){var a=v("div");if("oncopy"in a)return!0;a.setAttribute("oncopy","return;");return"function"==typeof a.oncopy}(),Gd=null,ld={},ob={},pb={},X= +function(a,b,d){this.pos=this.start=0;this.string=a;this.tabSize=b||8;this.lineStart=this.lastColumnPos=this.lastColumnValue=0;this.lineOracle=d};X.prototype.eol=function(){return this.pos>=this.string.length};X.prototype.sol=function(){return this.pos==this.lineStart};X.prototype.peek=function(){return this.string.charAt(this.pos)||void 0};X.prototype.next=function(){if(this.posb};X.prototype.eatSpace=function(){for(var a=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>a};X.prototype.skipToEnd=function(){this.pos=this.string.length};X.prototype.skipTo=function(a){a=this.string.indexOf(a,this.pos);if(-1this.maxLookAhead&&(this.maxLookAhead=a);return b};Da.prototype.baseToken=function(a){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=a;)this.baseTokenPos+=2;var b=this.baseTokens[this.baseTokenPos+ +1];return{type:b&&b.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-a}};Da.prototype.nextLine=function(){this.line++;0T&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};mb.prototype.update=function(a){var b=a.scrollWidth>a.clientWidth+1,d=a.scrollHeight>a.clientHeight+1,c=a.nativeBarWidth;d?(this.vert.style.display="block",this.vert.style.bottom=b?c+"px":"0",this.vert.firstChild.style.height=Math.max(0,a.scrollHeight-a.clientHeight+(a.viewHeight- +(b?c:0)))+"px"):(this.vert.scrollTop=0,this.vert.style.display="",this.vert.firstChild.style.height="0");b?(this.horiz.style.display="block",this.horiz.style.right=d?c+"px":"0",this.horiz.style.left=a.barLeft+"px",this.horiz.firstChild.style.width=Math.max(0,a.scrollWidth-a.clientWidth+(a.viewWidth-a.barLeft-(d?c:0)))+"px"):(this.horiz.style.display="",this.horiz.firstChild.style.width="0");!this.checkedZeroWidth&&0=B(a,c.to()))return d}return-1}; +var I=function(a,b){this.anchor=a;this.head=b};I.prototype.from=function(){return zc(this.anchor,this.head)};I.prototype.to=function(){return yc(this.anchor,this.head)};I.prototype.empty=function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch};cc.prototype={chunkSize:function(){return this.lines.length},removeInner:function(a,b){for(var d=a,c=a+b;dthis.size-b&&(1=this.children.length)){var a=this;do{var b=a.children.splice(a.children.length-5,5);b=new dc(b);if(a.parent){a.size-=b.size;a.height-=b.height;var d=ea(a.parent.children,a);a.parent.children.splice(d+1,0,b)}else d=new dc(a.children),d.parent=a,a.children=[d,b],a=d;b.parent=a.parent}while(10< +a.children.length);a.parent.maybeSpill()}},iterN:function(a,b,d){for(var c=0;ca.display.maxLineLength&&(a.display.maxLine=f,a.display.maxLineLength=g,a.display.maxLineChanged=!0);null!=d&&a&&this.collapsed&&ma(a,d,c+1);this.lines.length=0;this.explicitlyCleared=!0;this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,a&&Hf(a.doc));a&&aa(a,"markerCleared",a,this,d, +c);b&&kb(a);this.parent&&this.parent.clear()}};Ta.prototype.find=function(a,b){null==a&&"bookmark"==this.type&&(a=1);for(var d,c,e=0;eB(h.head,h.anchor),a[f]=new I(h?k:g,h?g:k)):a[f]=new I(g,g)}a=new ua(a,this.sel.primIndex)}b= +a;for(a=c.length-1;0<=a;a--)Ab(this,c[a]);b?Ef(this,b):this.cm&&vb(this.cm)}),undo:ca(function(){Vc(this,"undo")}),redo:ca(function(){Vc(this,"redo")}),undoSelection:ca(function(){Vc(this,"undo",!0)}),redoSelection:ca(function(){Vc(this,"redo",!0)}),setExtending:function(a){this.extend=a},getExtending:function(){return this.extend},historySize:function(){for(var a=this.history,b=0,d=0,c=0;c=a.ch)&&b.push(e.marker.parent|| +e.marker)}return b},findMarks:function(a,b,d){a=C(this,a);b=C(this,b);var c=[],e=a.line;this.iter(a.line,b.line+1,function(f){if(f=f.markedSpans)for(var g=0;g=h.to||null==h.from&&e!=a.line||null!=h.from&&e==b.line&&h.from>=b.ch||d&&!d(h.marker)||c.push(h.marker.parent||h.marker)}++e});return c},getAllMarks:function(){var a=[];this.iter(function(b){if(b=b.markedSpans)for(var d=0;da)return b=a,!0;a-=e;++d});return C(this,t(d,b))},indexFromPos:function(a){a=C(this,a);var b=a.ch;if(a.linea.ch)return 0;var d=this.lineSeparator().length;this.iter(this.first,a.line,function(c){b+=c.text.length+d});return b},copy:function(a){var b=new oa(od(this,this.first,this.first+this.size),this.modeOption,this.first,this.lineSep,this.direction);b.scrollTop=this.scrollTop;b.scrollLeft=this.scrollLeft; +b.sel=this.sel;b.extend=!1;a&&(b.history.undoDepth=this.history.undoDepth,b.setHistory(this.getHistory()));return b},linkedDoc:function(a){a||(a={});var b=this.first,d=this.first+this.size;null!=a.from&&a.from>b&&(b=a.from);null!=a.to&&a.toqc;qc++)Ua[qc+48]=Ua[qc+96]=String(qc);for(var dd=65;90>=dd;dd++)Ua[dd]=String.fromCharCode(dd);for(var rc=1;12>=rc;rc++)Ua[rc+111]=Ua[rc+63235]="F"+rc;var gc={basic:{Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto", +Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},pcDefault:{"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev", +"Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},emacsy:{"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars", +"Ctrl-O":"openLine"},macDefault:{"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace", +"Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]}};gc["default"]=xa?gc.macDefault:gc.pcDefault;var hc={selectAll:Jf,singleSelection:function(a){return a.setSelection(a.getCursor("anchor"),a.getCursor("head"),Ha)},killLine:function(a){return Eb(a,function(b){if(b.empty()){var d= +w(a.doc,b.head.line).text.length;return b.head.ch==d&&b.head.linea.doc.first){var g=w(a.doc,e.line-1).text;g&&(e=new t(e.line,1),a.replaceRange(f.charAt(0)+a.doc.lineSeparator()+g.charAt(g.length-1),t(e.line-1,g.length-1),e,"+transpose"))}d.push(new I(e,e))}a.setSelections(d)})},newlineAndIndent:function(a){return qa(a,function(){for(var b=a.listSelections(), +d=b.length-1;0<=d;d--)a.replaceRange(a.doc.lineSeparator(),b[d].anchor,b[d].head,"+input");b=a.listSelections();for(d=0;da&&0==B(b,this.pos)&&d==this.button};var kc,jc,Fb={toString:function(){return"CodeMirror.Init"}}, +kg={},ad={};U.defaults=kg;U.optionHandlers=ad;var ke=[];U.defineInitHook=function(a){return ke.push(a)};var ra=null,O=function(a){this.cm=a;this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null;this.polling=new Va;this.composing=null;this.gracePeriod=!1;this.readDOMTimeout=null};O.prototype.init=function(a){function b(h){for(h=h.target;h;h=h.parentNode){if(h==g)return!0;if(/\bCodeMirror-(?:line)?widget\b/.test(h.className))break}return!1}function d(h){if(b(h)&&!Z(f, +h)){if(f.somethingSelected())ra={lineWise:!1,text:f.getSelections()},"cut"==h.type&&f.replaceSelection("",null,"cut");else if(f.options.lineWiseCopyCut){var k=og(f);ra={lineWise:!0,text:k.text};"cut"==h.type&&f.operation(function(){f.setSelections(k.ranges,0,Ha);f.replaceSelection("",null,"cut")})}else return;if(h.clipboardData){h.clipboardData.clearData();var l=ra.text.join("\n");h.clipboardData.setData("Text",l);if(h.clipboardData.getData("Text")==l){h.preventDefault();return}}var m=qg();h=m.firstChild; +f.display.lineSpace.insertBefore(m,f.display.lineSpace.firstChild);h.value=ra.text.join("\n");var n=ka();nc(h);setTimeout(function(){f.display.lineSpace.removeChild(m);n.focus();n==g&&e.showPrimarySelection()},50)}}var c=this,e=this,f=e.cm,g=e.div=a.lineDiv;g.contentEditable=!0;pg(g,f.options.spellcheck,f.options.autocorrect,f.options.autocapitalize);z(g,"paste",function(h){!b(h)||Z(f,h)||ng(h,f)||11>=T&&setTimeout(ba(f,function(){return c.updateFromDOM()}),20)});z(g,"compositionstart",function(h){c.composing= +{data:h.data,done:!1}});z(g,"compositionupdate",function(h){c.composing||(c.composing={data:h.data,done:!1})});z(g,"compositionend",function(h){c.composing&&(h.data!=c.composing.data&&c.readFromDOMSoon(),c.composing.done=!0)});z(g,"touchstart",function(){return e.forceCompositionEnd()});z(g,"input",function(){c.composing||c.readFromDOMSoon()});z(g,"copy",d);z(g,"cut",d)};O.prototype.screenReaderLabelChanged=function(a){a?this.div.setAttribute("aria-label",a):this.div.removeAttribute("aria-label")}; +O.prototype.prepareSelection=function(){var a=ff(this.cm,!1);a.focus=ka()==this.div;return a};O.prototype.showSelection=function(a,b){a&&this.cm.display.view.length&&((a.focus||b)&&this.showPrimarySelection(),this.showMultipleSelections(a))};O.prototype.getSelection=function(){return this.cm.display.wrapper.ownerDocument.getSelection()};O.prototype.showPrimarySelection=function(){var a=this.getSelection(),b=this.cm,d=b.doc.sel.primary(),c=d.from();d=d.to();if(b.display.viewTo==b.display.viewFrom|| +c.line>=b.display.viewTo||d.line=b.display.viewFrom&&sg(b,c)||{node:e[0].measure.map[2],offset:0},d=d.linea.firstLine()&&(c=t(c.line-1,w(a.doc,c.line-1).length));e.ch==w(a.doc,e.line).text.length&&e.lineb.viewTo-1)return!1;var f;c.line==b.viewFrom||0==(f=bb(a,c.line))?(d=N(b.view[0].line),f=b.view[0].node):(d=N(b.view[f].line),f=b.view[f-1].node.nextSibling);var g=bb(a,e.line);g==b.view.length-1?(e=b.viewTo-1,b=b.lineDiv.lastChild):(e=N(b.view[g+1].line)-1,b=b.view[g+1].node.previousSibling);if(!f)return!1; +b=a.doc.splitLines(zh(a,f,b,d,e));for(f=Za(a.doc,t(d,0),t(e,w(a.doc,e).text.length));1 +c.ch&&k.charCodeAt(k.length-g-1)==l.charCodeAt(l.length-g-1);)h--,g++;b[b.length-1]=k.slice(0,k.length-g).replace(/^\u200b+/,"");b[0]=b[0].slice(h).replace(/\u200b+$/,"");c=t(d,h);d=t(e,f.length?J(f).length-g:0);if(1T&&f.scrollbars.setScrollTop(f.scroller.scrollTop=k),null!=g.selectionStart)){(!G||G&&9>T)&&b();var q=0,r=function(){f.selForContextMenu==e.doc.sel&&0==g.selectionStart&&0q++?f.detectingSelectAll=setTimeout(r,500):(f.selForContextMenu=null,f.input.reset())};f.detectingSelectAll=setTimeout(r,200)}}var c=this,e=c.cm,f=e.display,g=c.textarea;c.contextMenuPending&&c.contextMenuPending();var h=eb(e, +a),k=f.scroller.scrollTop;if(h&&!Aa){e.options.resetSelectionOnContextMenu&&-1==e.doc.sel.contains(h)&&ba(e,da)(e.doc,Na(h),Ha);var l=g.style.cssText,m=c.wrapper.style.cssText;h=c.wrapper.offsetParent.getBoundingClientRect();c.wrapper.style.cssText="position: static";g.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(a.clientY-h.top-5)+"px; left: "+(a.clientX-h.left-5)+"px;\n z-index: 1000; background: "+(G?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; +if(fa)var n=window.scrollY;f.input.focus();fa&&window.scrollTo(null,n);f.input.reset();e.somethingSelected()||(g.value=c.prevInput=" ");c.contextMenuPending=d;f.selForContextMenu=e.doc.sel;clearTimeout(f.detectingSelectAll);G&&9<=T&&b();if(ie){Kb(a);var p=function(){sa(window,"mouseup",p);setTimeout(d,20)};z(window,"mouseup",p)}else setTimeout(d,50)}};V.prototype.readOnlyChanged=function(a){a||this.reset();this.textarea.disabled="nocursor"==a;this.textarea.readOnly=!!a};V.prototype.setUneditable= +function(){};V.prototype.needsContentAttribute=!1;(function(a){function b(c,e,f,g){a.defaults[c]=e;f&&(d[c]=g?function(h,k,l){l!=Fb&&f(h,k,l)}:f)}var d=a.optionHandlers;a.defineOption=b;a.Init=Fb;b("value","",function(c,e){return c.setValue(e)},!0);b("mode",null,function(c,e){c.doc.modeOption=e;Zd(c)},!0);b("indentUnit",2,Zd,!0);b("indentWithTabs",!1);b("smartIndent",!0);b("tabSize",4,function(c){$b(c);Sb(c);ma(c)},!0);b("lineSeparator",null,function(c,e){if(c.doc.lineSep=e){var f=[],g=c.doc.first; +c.doc.iter(function(k){for(var l=0;;){var m=k.text.indexOf(e,l);if(-1==m)break;l=m+e.length;f.push(t(g,m))}g++});for(var h=f.length-1;0<=h;h--)Bb(c.doc,e,f[h],t(f[h].line,f[h].ch+e.length))}});b("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g,function(c,e,f){c.state.specialChars=new RegExp(e.source+(e.test("\t")?"":"|\t"),"g");f!=Fb&&c.refresh()});b("specialCharPlaceholder",Kg,function(c){return c.refresh()},!0);b("electricChars",!0);b("inputStyle", +Zb?"contenteditable":"textarea",function(){throw Error("inputStyle can not (yet) be changed in a running editor");},!0);b("spellcheck",!1,function(c,e){return c.getInputField().spellcheck=e},!0);b("autocorrect",!1,function(c,e){return c.getInputField().autocorrect=e},!0);b("autocapitalize",!1,function(c,e){return c.getInputField().autocapitalize=e},!0);b("rtlMoveVisually",!Dh);b("wholeLineUpdateBefore",!0);b("theme","default",function(c){jg(c);Yb(c)},!0);b("keyMap","default",function(c,e,f){e=Wc(e); +(f=f!=Fb&&Wc(f))&&f.detach&&f.detach(c,e);e.attach&&e.attach(c,f||null)});b("extraKeys",null);b("configureMouse",null);b("lineWrapping",!1,wh,!0);b("gutters",[],function(c,e){c.display.gutterSpecs=Xd(e,c.options.lineNumbers);Yb(c)},!0);b("fixedGutter",!0,function(c,e){c.display.gutters.style.left=e?Ld(c.display)+"px":"0";c.refresh()},!0);b("coverGutterNextToScrollbar",!1,function(c){return wb(c)},!0);b("scrollbarStyle","native",function(c){nf(c);wb(c);c.display.scrollbars.setScrollTop(c.doc.scrollTop); +c.display.scrollbars.setScrollLeft(c.doc.scrollLeft)},!0);b("lineNumbers",!1,function(c,e){c.display.gutterSpecs=Xd(c.options.gutters,e);Yb(c)},!0);b("firstLineNumber",1,Yb,!0);b("lineNumberFormatter",function(c){return c},Yb,!0);b("showCursorWhenSelecting",!1,Tb,!0);b("resetSelectionOnContextMenu",!0);b("lineWiseCopyCut",!0);b("pasteLinesPerSelection",!0);b("selectionsMayTouch",!1);b("readOnly",!1,function(c,e){"nocursor"==e&&(ub(c),c.display.input.blur());c.display.input.readOnlyChanged(e)});b("screenReaderLabel", +null,function(c,e){c.display.input.screenReaderLabelChanged(""===e?null:e)});b("disableInput",!1,function(c,e){e||c.display.input.reset()},!0);b("dragDrop",!0,vh);b("allowDropFileTypes",null);b("cursorBlinkRate",530);b("cursorScrollMargin",0);b("cursorHeight",1,Tb,!0);b("singleCursorHeightPerLine",!0,Tb,!0);b("workTime",100);b("workDelay",100);b("flattenSpans",!0,$b,!0);b("addModeClass",!1,$b,!0);b("pollInterval",100);b("undoDepth",200,function(c,e){return c.doc.history.undoDepth=e});b("historyEventDelay", +1250);b("viewportMargin",10,function(c){return c.refresh()},!0);b("maxHighlightLength",1E4,$b,!0);b("moveInputWithCursor",!0,function(c,e){e||c.display.input.resetPosition()});b("tabindex",null,function(c,e){return c.display.input.getField().tabIndex=e||""});b("autofocus",null);b("direction","ltr",function(c,e){return c.doc.setDirection(e)},!0);b("phrases",null)})(U);(function(a){var b=a.optionHandlers,d=a.helpers={};a.prototype={constructor:a,focus:function(){window.focus();this.display.input.focus()}, +setOption:function(c,e){var f=this.options,g=f[c];if(f[c]!=e||"mode"==c)f[c]=e,b.hasOwnProperty(c)&&ba(this,b[c])(this,e,g),W(this,"optionChange",this,c)},getOption:function(c){return this.options[c]},getDoc:function(){return this.doc},addKeyMap:function(c,e){this.state.keyMaps[e?"push":"unshift"](Wc(c))},removeKeyMap:function(c){for(var e=this.state.keyMaps,f=0;ff&&(lc(this,h.head.line,c,!0),f=h.head.line,g==this.doc.sel.primIndex&&vb(this));else{var k=h.from();h=h.to();var l=Math.max(f,k.line);f=Math.min(this.lastLine(),h.line-(h.ch?0:1))+1;for(h=l;h>1;if((h?e[2*h-1]:0)>=c)g=h;else if(e[2*h+1]f?e:0==f?null:e.slice(0,f-1)},getModeAt:function(c){var e=this.doc.mode;return e.innerMode?a.innerMode(e,this.getTokenAt(c).state).mode:e},getHelper:function(c,e){return this.getHelpers(c, +e)[0]},getHelpers:function(c,e){var f=[];if(!d.hasOwnProperty(e))return f;var g=d[e];c=this.getModeAt(c);if("string"==typeof c[e])g[c[e]]&&f.push(g[c[e]]);else if(c[e])for(var h=0;hh&&(c=h,g=!0);c=w(this.doc,c)}return Gc(this,c,{top:0,left:0},e||"page",f||g).top+(g?this.doc.height-Fa(c):0)},defaultTextHeight:function(){return tb(this.display)},defaultCharWidth:function(){return sb(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(c,e,f,g,h){var k=this.display;c=za(this,C(this.doc,c));var l=c.bottom,m=c.left;e.style.position= +"absolute";e.setAttribute("cm-ignore-events","true");this.display.input.setUneditable(e);k.sizer.appendChild(e);if("over"==g)l=c.top;else if("above"==g||"near"==g){var n=Math.max(k.wrapper.clientHeight,this.doc.height),p=Math.max(k.sizer.clientWidth,k.lineSpace.clientWidth);("above"==g||c.bottom+e.offsetHeight>n)&&c.top>e.offsetHeight?l=c.top-e.offsetHeight:c.bottom+e.offsetHeight<=n&&(l=c.bottom);m+e.offsetWidth>p&&(m=p-e.offsetWidth)}e.style.top=l+"px";e.style.left=e.style.right="";"right"==h?(m= +k.sizer.clientWidth-e.offsetWidth,e.style.right="0px"):("left"==h?m=0:"middle"==h&&(m=(k.sizer.clientWidth-e.offsetWidth)/2),e.style.left=m+"px");f&&(c=Sd(this,{left:m,top:l,right:m+e.offsetWidth,bottom:l+e.offsetHeight}),null!=c.scrollTop&&Vb(this,c.scrollTop),null!=c.scrollLeft&&ib(this,c.scrollLeft))},triggerOnKeyDown:ia(dg),triggerOnKeyPress:ia(fg),triggerOnKeyUp:eg,triggerOnMouseDown:ia(gg),execCommand:function(c){if(hc.hasOwnProperty(c))return hc[c].call(null,this)},triggerElectric:ia(function(c){mg(this, +c)}),findPosH:function(c,e,f,g){var h=1;0>e&&(h=-1,e=-e);c=C(this.doc,c);for(var k=0;kc?g.from():g.to()},oc)}),deleteH:ia(function(c,e){var f=this.doc;this.doc.sel.somethingSelected()?f.replaceSelection("",null,"+delete"):Eb(this,function(g){var h=ne(f,g.head,c,e,!1);return 0>c? +{from:h,to:g.head}:{from:g.head,to:h}})}),findPosV:function(c,e,f,g){var h=1;0>e&&(h=-1,e=-e);var k=C(this.doc,c);for(c=0;cc?m.from():m.to();var n=za(f,m.head,"div");null!=m.goalColumn&&(n.left=m.goalColumn);h.push(n.left);var p=rg(f,n,c,e);"page"==e&& +m==g.sel.primary()&&Mc(f,Hc(f,p,"div").top-n.top);return p},oc);if(h.length)for(var l=0;lea(Gh,sc)&&(U.prototype[sc]=function(a){return function(){return a.apply(this.doc,arguments)}}(oa.prototype[sc]));nb(oa);U.inputStyles={textarea:V,contenteditable:O};U.defineMode=function(a){U.defaults.mode||"null"==a||(U.defaults.mode= +a);Bg.apply(this,arguments)};U.defineMIME=function(a,b){ob[a]=b};U.defineMode("null",function(){return{token:function(a){return a.skipToEnd()}}});U.defineMIME("text/plain","null");U.defineExtension=function(a,b){U.prototype[a]=b};U.defineDocExtension=function(a,b){oa.prototype[a]=b};U.fromTextArea=function(a,b){function d(){a.value=h.getValue()}b=b?Xa(b):{};b.value=a.value;!b.tabindex&&a.tabIndex&&(b.tabindex=a.tabIndex);!b.placeholder&&a.placeholder&&(b.placeholder=a.placeholder);if(null==b.autofocus){var c= +ka();b.autofocus=c==a||null!=a.getAttribute("autofocus")&&c==document.body}if(a.form&&(z(a.form,"submit",d),!b.leaveSubmitMethodAlone)){var e=a.form;var f=e.submit;try{var g=e.submit=function(){d();e.submit=f;e.submit();e.submit=g}}catch(k){}}b.finishInit=function(k){k.save=d;k.getTextArea=function(){return a};k.toTextArea=function(){k.toTextArea=isNaN;d();a.parentNode.removeChild(k.getWrapperElement());a.style.display="";a.form&&(sa(a.form,"submit",d),b.leaveSubmitMethodAlone||"function"!=typeof a.form.submit|| +(a.form.submit=f))}};a.style.display="none";var h=U(function(k){return a.parentNode.insertBefore(k,a.nextSibling)},b);return h};(function(a){a.off=sa;a.on=z;a.wheelEventPixels=Xg;a.Doc=oa;a.splitLines=me;a.countColumn=va;a.findColumn=gd;a.isWordChar=id;a.Pass=Yc;a.signal=W;a.Line=xb;a.changeEnd=Ra;a.scrollbarModel=of;a.Pos=t;a.cmpPos=B;a.modes=ld;a.mimeModes=ob;a.resolveMode=xc;a.getMode=md;a.modeExtensions=pb;a.extendMode=Cg;a.copyState=Ya;a.startState=ve;a.innerMode=nd;a.commands=hc;a.keyMap=gc; +a.keyName=Zf;a.isModifierKey=Wf;a.lookupKey=Db;a.normalizeKeyMap=hh;a.StringStream=X;a.SharedTextMarker=fc;a.TextMarker=Ta;a.LineWidget=ec;a.e_preventDefault=la;a.e_stopPropagation=te;a.e_stop=Kb;a.addClass=Wa;a.contains=ja;a.rmClass=hb;a.keyNames=Ua})(U);U.version="5.65.0";return U}); + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],41:[function(require,module,exports){ +(function(v){"object"==typeof exports&&"object"==typeof module?v(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],v):v(CodeMirror)})(function(v){v.defineMode("javascript",function(Ua,A){var p,w,f;function u(a,b,d){V=a;ca=d;return b}function I(a,b){var d=a.next();if('"'==d||"'"==d)return b.tokenize=Va(d),b.tokenize(a,b);if("."==d&&a.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/))return u("number","number");if("."==d&&a.match(".."))return u("spread","meta"); +if(/[\[\]{}\(\),;:\.]/.test(d))return u(d);if("="==d&&a.eat(">"))return u("=>","operator");if("0"==d&&a.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/))return u("number","number");if(/\d/.test(d))return a.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/),u("number","number");if("/"==d){if(a.eat("*"))return b.tokenize=da,da(a,b);if(a.eat("/"))return a.skipToEnd(),u("comment","comment");if(Aa(a,b,1)){a:for(var e=b=!1;null!=(d=a.next());){if(!b){if("/"==d&&!e)break a;"["==d?e=!0:e&&"]"==d&&(e= +!1)}b=!b&&"\\"==d}a.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);return u("regexp","string-2")}a.eat("=");return u("operator","operator",a.current())}if("`"==d)return b.tokenize=W,W(a,b);if("#"==d&&"!"==a.peek())return a.skipToEnd(),u("meta","meta");if("#"==d&&a.eatWhile(ea))return u("variable","property");if("<"==d&&a.match("!--")||"-"==d&&a.match("->")&&!/\S/.test(a.string.slice(0,a.start)))return a.skipToEnd(),u("comment","comment");if(Ba.test(d))return">"==d&&b.lexical&&">"==b.lexical.type||(a.eat("=")? +"!"!=d&&"="!=d||a.eat("="):/[<>*+\-|&?]/.test(d)&&(a.eat(d),">"==d&&a.eat(d))),"?"==d&&a.eat(".")?u("."):u("operator","operator",a.current());if(ea.test(d)){a.eatWhile(ea);d=a.current();if("."!=b.lastType){if(Ca.propertyIsEnumerable(d))return a=Ca[d],u(a.type,a.style,d);if("async"==d&&a.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/,!1))return u("async","keyword",d)}return u("variable","variable",d)}}function Va(a){return function(b,d){var e=!1,h;if(fa&&"@"==b.peek()&&b.match(Wa))return d.tokenize= +I,u("jsonld-keyword","meta");for(;null!=(h=b.next())&&(h!=a||e);)e=!e&&"\\"==h;e||(d.tokenize=I);return u("string","string")}}function da(a,b){for(var d=!1,e;e=a.next();){if("/"==e&&d){b.tokenize=I;break}d="*"==e}return u("comment","comment")}function W(a,b){for(var d=!1,e;null!=(e=a.next());){if(!d&&("`"==e||"$"==e&&a.eat("{"))){b.tokenize=I;break}d=!d&&"\\"==e}return u("quasi","string-2",a.current())}function pa(a,b){b.fatArrowAt&&(b.fatArrowAt=null);var d=a.string.indexOf("=>",a.start);if(!(0> +d)){if(r){var e=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(a.string.slice(a.start,d));e&&(d=e.index)}e=0;var h=!1;for(--d;0<=d;--d){var m=a.string.charAt(d),y="([{}])".indexOf(m);if(0<=y&&3>y){if(!e){++d;break}if(0==--e){"("==m&&(h=!0);break}}else if(3<=y&&6>y)++e;else if(ea.test(m))h=!0;else if(/["'\/`]/.test(m))for(;;--d){if(0==d)return;if(a.string.charAt(d-1)==m&&"\\"!=a.string.charAt(d-2)){d--;break}}else if(h&&!e){++d;break}}h&&!e&&(b.fatArrowAt=d)}}function Da(a,b,d,e,h,m){this.indented= +a;this.column=b;this.type=d;this.prev=h;this.info=m;null!=e&&(this.align=e)}function Ea(a,b,d,e,h){var m=a.cc;p=a;w=h;f=null;qa=m;X=b;a.lexical.hasOwnProperty("align")||(a.lexical.align=!0);for(;;)if((m.length?m.pop():J?t:x)(d,e)){for(;m.length&&m[m.length-1].lex;)m.pop()();if(f)return f;if(d="variable"==d)a:if(Fa){for(d=a.localVars;d;d=d.next)if(d.name==e){d=!0;break a}for(a=a.context;a;a=a.prev)for(d=a.vars;d;d=d.next)if(d.name==e){d=!0;break a}d=void 0}else d=!1;return d?"variable-2":b}}function k(){for(var a= +arguments.length-1;0<=a;a--)qa.push(arguments[a])}function c(){k.apply(null,arguments);return!0}function ra(a,b){for(;b;b=b.next)if(b.name==a)return!0;return!1}function N(a){var b=p;f="def";if(Fa){if(b.context)if("var"==b.lexical.info&&b.context&&b.context.block){var d=Ga(a,b.context);if(null!=d){b.context=d;return}}else if(!ra(a,b.localVars)){b.localVars=new Y(a,b.localVars);return}A.globalVars&&!ra(a,b.globalVars)&&(b.globalVars=new Y(a,b.globalVars))}}function Ga(a,b){return b?b.block?(a=Ga(a, +b.prev))?a==b.prev?b:new Z(a,b.vars,!0):null:ra(a,b.vars)?b:new Z(b.prev,new Y(a,b.vars),!1):null}function ha(a){return"public"==a||"private"==a||"protected"==a||"abstract"==a||"readonly"==a}function Z(a,b,d){this.prev=a;this.vars=b;this.block=d}function Y(a,b){this.name=a;this.next=b}function O(){p.context=new Z(p.context,p.localVars,!1);p.localVars=Xa}function sa(){p.context=new Z(p.context,p.localVars,!0);p.localVars=null}function C(){p.localVars=p.context.vars;p.context=p.context.prev}function l(a, +b){var d=function(){var e=p,h=e.indented;if("stat"==e.lexical.type)h=e.lexical.indented;else for(var m=e.lexical;m&&")"==m.type&&m.align;m=m.prev)h=m.indented;e.lexical=new Da(h,w.column(),a,null,e.lexical,b)};d.lex=!0;return d}function g(){var a=p;a.lexical.prev&&(")"==a.lexical.type&&(a.indented=a.lexical.indented),a.lexical=a.lexical.prev)}function n(a){function b(d){return d==a?c():";"==a||"}"==d||")"==d||"]"==d?k():c(b)}return b}function x(a,b){return"var"==a?c(l("vardef",b),ta,n(";"),g):"keyword a"== +a?c(l("form"),ua,x,g):"keyword b"==a?c(l("form"),x,g):"keyword d"==a?w.match(/^\s*$/,!1)?c():c(l("stat"),P,n(";"),g):"debugger"==a?c(n(";")):"{"==a?c(l("}"),sa,ia,g,C):";"==a?c():"if"==a?("else"==p.lexical.info&&p.cc[p.cc.length-1]==g&&p.cc.pop()(),c(l("form"),ua,x,g,Ha)):"function"==a?c(G):"for"==a?c(l("form"),sa,Ia,x,C,g):"class"==a||r&&"interface"==b?(f="keyword",c(l("form","class"==a?a:b),Ja,g)):"variable"==a?r&&"declare"==b?(f="keyword",c(x)):r&&("module"==b||"enum"==b||"type"==b)&&w.match(/^\s*\w/, +!1)?(f="keyword","enum"==b?c(Ka):"type"==b?c(La,n("operator"),q,n(";")):c(l("form"),D,n("{"),l("}"),ia,g,g)):r&&"namespace"==b?(f="keyword",c(l("form"),t,x,g)):r&&"abstract"==b?(f="keyword",c(x)):c(l("stat"),Ya):"switch"==a?c(l("form"),ua,n("{"),l("}","switch"),sa,ia,g,g,C):"case"==a?c(t,n(":")):"default"==a?c(n(":")):"catch"==a?c(l("form"),O,Za,x,g,C):"export"==a?c(l("stat"),$a,g):"import"==a?c(l("stat"),ab,g):"async"==a?c(x):"@"==b?c(t,x):k(l("stat"),t,n(";"),g)}function Za(a){if("("==a)return c(K, +n(")"))}function t(a,b){return Ma(a,b,!1)}function B(a,b){return Ma(a,b,!0)}function ua(a){return"("!=a?k():c(l(")"),P,n(")"),g)}function Ma(a,b,d){if(p.fatArrowAt==w.start){var e=d?Na:Oa;if("("==a)return c(O,l(")"),z(K,")"),g,n("=>"),e,C);if("variable"==a)return k(O,D,n("=>"),e,C)}e=d?Q:L;return bb.hasOwnProperty(a)?c(e):"function"==a?c(G,e):"class"==a||r&&"interface"==b?(f="keyword",c(l("form"),cb,g)):"keyword c"==a||"async"==a?c(d?B:t):"("==a?c(l(")"),P,n(")"),g,e):"operator"==a||"spread"==a?c(d? +B:t):"["==a?c(l("]"),db,g,e):"{"==a?aa(ja,"}",null,e):"quasi"==a?k(ka,e):"new"==a?c(eb(d)):c()}function P(a){return a.match(/[;\}\)\],]/)?k():k(t)}function L(a,b){return","==a?c(P):Q(a,b,!1)}function Q(a,b,d){var e=0==d?L:Q,h=0==d?t:B;if("=>"==a)return c(O,d?Na:Oa,C);if("operator"==a)return/\+\+|--/.test(b)||r&&"!"==b?c(e):r&&"<"==b&&w.match(/^([^<>]|<[^<>]*>)*>\s*\(/,!1)?c(l(">"),z(q,">"),g,e):"?"==b?c(t,n(":"),h):c(h);if("quasi"==a)return k(ka,e);if(";"!=a){if("("==a)return aa(B,")","call",e);if("."== +a)return c(fb,e);if("["==a)return c(l("]"),P,n("]"),g,e);if(r&&"as"==b)return f="keyword",c(q,e);if("regexp"==a)return p.lastType=f="operator",w.backUp(w.pos-w.start-1),c(h)}}function ka(a,b){return"quasi"!=a?k():"${"!=b.slice(b.length-2)?c(ka):c(P,gb)}function gb(a){if("}"==a)return f="string-2",p.tokenize=W,c(ka)}function Oa(a){pa(w,p);return k("{"==a?x:t)}function Na(a){pa(w,p);return k("{"==a?x:B)}function eb(a){return function(b){return"."==b?c(a?hb:ib):"variable"==b&&r?c(jb,a?Q:L):k(a?B:t)}} +function ib(a,b){if("target"==b)return f="keyword",c(L)}function hb(a,b){if("target"==b)return f="keyword",c(Q)}function Ya(a){return":"==a?c(g,x):k(L,n(";"),g)}function fb(a){if("variable"==a)return f="property",c()}function ja(a,b){if("async"==a)return f="property",c(ja);if("variable"==a||"keyword"==X){f="property";if("get"==b||"set"==b)return c(kb);var d;r&&p.fatArrowAt==w.start&&(d=w.match(/^\s*:\s*/,!1))&&(p.fatArrowAt=w.pos+d[0].length);return c(M)}if("number"==a||"string"==a)return f=fa?"property": +X+" property",c(M);if("jsonld-keyword"==a)return c(M);if(r&&ha(b))return f="keyword",c(ja);if("["==a)return c(t,R,n("]"),M);if("spread"==a)return c(B,M);if("*"==b)return f="keyword",c(ja);if(":"==a)return k(M)}function kb(a){if("variable"!=a)return k(M);f="property";return c(G)}function M(a){if(":"==a)return c(B);if("("==a)return k(G)}function z(a,b,d){function e(h,m){return(d?-1"),q);if("quasi"==a)return k(ya,E)}function nb(a){if("=>"==a)return c(q)}function wa(a){return a.match(/[\}\)\]]/)?c():","==a||";"==a?c(wa): +k(ba,wa)}function ba(a,b){if("variable"==a||"keyword"==X)return f="property",c(ba);if("?"==b||"number"==a||"string"==a)return c(ba);if(":"==a)return c(q);if("["==a)return c(n("variable"),lb,n("]"),ba);if("("==a)return k(S,ba);if(!a.match(/[;\}\)\],]/))return c()}function ya(a,b){return"quasi"!=a?k():"${"!=b.slice(b.length-2)?c(ya):c(q,ob)}function ob(a){if("}"==a)return f="string-2",p.tokenize=W,c(ya)}function xa(a,b){return"variable"==a&&w.match(/^\s*[?:]/,!1)||"?"==b?c(xa):":"==a?c(q):"spread"== +a?c(xa):k(q)}function E(a,b){if("<"==b)return c(l(">"),z(q,">"),g,E);if("|"==b||"."==a||"&"==b)return c(q);if("["==a)return c(q,n("]"),E);if("extends"==b||"implements"==b)return f="keyword",c(q);if("?"==b)return c(q,n(":"),q)}function jb(a,b){if("<"==b)return c(l(">"),z(q,">"),g,E)}function la(){return k(q,pb)}function pb(a,b){if("="==b)return c(q)}function ta(a,b){return"enum"==b?(f="keyword",c(Ka)):k(D,R,H,qb)}function D(a,b){if(r&&ha(b))return f="keyword",c(D);if("variable"==a)return N(b),c(); +if("spread"==a)return c(D);if("["==a)return aa(rb,"]");if("{"==a)return aa(Qa,"}")}function Qa(a,b){if("variable"==a&&!w.match(/^\s*:/,!1))return N(b),c(H);"variable"==a&&(f="property");return"spread"==a?c(D):"}"==a?k():"["==a?c(t,n("]"),n(":"),Qa):c(n(":"),D,H)}function rb(){return k(D,H)}function H(a,b){if("="==b)return c(B)}function qb(a){if(","==a)return c(ta)}function Ha(a,b){if("keyword b"==a&&"else"==b)return c(l("form","else"),x,g)}function Ia(a,b){if("await"==b)return c(Ia);if("("==a)return c(l(")"), +sb,g)}function sb(a){return"var"==a?c(ta,T):"variable"==a?c(T):k(T)}function T(a,b){return")"==a?c():";"==a?c(T):"in"==b||"of"==b?(f="keyword",c(t,T)):k(t,T)}function G(a,b){if("*"==b)return f="keyword",c(G);if("variable"==a)return N(b),c(G);if("("==a)return c(O,l(")"),z(K,")"),g,Pa,x,C);if(r&&"<"==b)return c(l(">"),z(la,">"),g,G)}function S(a,b){if("*"==b)return f="keyword",c(S);if("variable"==a)return N(b),c(S);if("("==a)return c(O,l(")"),z(K,")"),g,Pa,C);if(r&&"<"==b)return c(l(">"),z(la,">"), +g,S)}function La(a,b){if("keyword"==a||"variable"==a)return f="type",c(La);if("<"==b)return c(l(">"),z(la,">"),g)}function K(a,b){"@"==b&&c(t,K);return"spread"==a?c(K):r&&ha(b)?(f="keyword",c(K)):r&&"this"==a?c(R,H):k(D,R,H)}function cb(a,b){return"variable"==a?Ja(a,b):ma(a,b)}function Ja(a,b){if("variable"==a)return N(b),c(ma)}function ma(a,b){if("<"==b)return c(l(">"),z(la,">"),g,ma);if("extends"==b||"implements"==b||r&&","==a)return"implements"==b&&(f="keyword"),c(r?q:t,ma);if("{"==a)return c(l("}"), +F,g)}function F(a,b){if("async"==a||"variable"==a&&("static"==b||"get"==b||"set"==b||r&&ha(b))&&w.match(/^\s+[\w$\xa1-\uffff]/,!1))return f="keyword",c(F);if("variable"==a||"keyword"==X)return f="property",c(na,F);if("number"==a||"string"==a)return c(na,F);if("["==a)return c(t,R,n("]"),na,F);if("*"==b)return f="keyword",c(F);if(r&&"("==a)return k(S,F);if(";"==a||","==a)return c(F);if("}"==a)return c();if("@"==b)return c(t,F)}function na(a,b){if("!"==b||"?"==b)return c(na);if(":"==a)return c(q,H); +if("="==b)return c(B);a=p.lexical.prev;return k(a&&"interface"==a.info?S:G)}function $a(a,b){return"*"==b?(f="keyword",c(za,n(";"))):"default"==b?(f="keyword",c(t,n(";"))):"{"==a?c(z(Ra,"}"),za,n(";")):k(x)}function Ra(a,b){if("as"==b)return f="keyword",c(n("variable"));if("variable"==a)return k(B,Ra)}function ab(a){return"string"==a?c():"("==a?k(t):"."==a?k(L):k(oa,Sa,za)}function oa(a,b){if("{"==a)return aa(oa,"}");"variable"==a&&N(b);"*"==b&&(f="keyword");return c(tb)}function Sa(a){if(","==a)return c(oa, +Sa)}function tb(a,b){if("as"==b)return f="keyword",c(oa)}function za(a,b){if("from"==b)return f="keyword",c(t)}function db(a){return"]"==a?c():k(z(B,"]"))}function Ka(){return k(l("form"),D,n("{"),l("}"),z(ub,"}"),g,g)}function ub(){return k(D,H)}function Aa(a,b,d){return b.tokenize==I&&/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(b.lastType)||"quasi"==b.lastType&&/\{\s*$/.test(a.string.slice(0,a.pos-(d||0)))}var U=Ua.indentUnit,Ta=A.statementIndent,fa=A.jsonld, +J=A.json||fa,Fa=!1!==A.trackScope,r=A.typescript,ea=A.wordCharacters||/[\w$\xa1-\uffff]/,Ca=function(){function a(va){return{type:va,style:"keyword"}}var b=a("keyword a"),d=a("keyword b"),e=a("keyword c"),h=a("keyword d"),m=a("operator"),y={type:"atom",style:"atom"};return{"if":a("if"),"while":b,"with":b,"else":d,"do":d,"try":d,"finally":d,"return":h,"break":h,"continue":h,"new":a("new"),"delete":e,"void":e,"throw":e,"debugger":a("debugger"),"var":a("var"),"const":a("var"),let:a("var"),"function":a("function"), +"catch":a("catch"),"for":a("for"),"switch":a("switch"),"case":a("case"),"default":a("default"),"in":m,"typeof":m,"instanceof":m,"true":y,"false":y,"null":y,undefined:y,NaN:y,Infinity:y,"this":a("this"),"class":a("class"),"super":a("atom"),yield:e,"export":a("export"),"import":a("import"),"extends":e,await:e}}(),Ba=/[+\-*&%=<>!?|~^@]/,Wa=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,V,ca,bb={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,"this":!0,"import":!0, +"jsonld-keyword":!0};var qa=f=p=null;var X=w=void 0;var Xa=new Y("this",new Y("arguments",null));C.lex=!0;g.lex=!0;return{startState:function(a){a={tokenize:I,lastType:"sof",cc:[],lexical:new Da((a||0)-U,0,"block",!1),localVars:A.localVars,context:A.localVars&&new Z(null,null,!1),indented:a||0};A.globalVars&&"object"==typeof A.globalVars&&(a.globalVars=A.globalVars);return a},token:function(a,b){a.sol()&&(b.lexical.hasOwnProperty("align")||(b.lexical.align=!1),b.indented=a.indentation(),pa(a,b)); +if(b.tokenize!=da&&a.eatSpace())return null;var d=b.tokenize(a,b);if("comment"==V)return d;b.lastType="operator"!=V||"++"!=ca&&"--"!=ca?V:"incdec";return Ea(b,d,V,ca,a)},indent:function(a,b){if(a.tokenize==da||a.tokenize==W)return v.Pass;if(a.tokenize!=I)return 0;var d=b&&b.charAt(0),e=a.lexical,h;if(!/^\s*else\b/.test(b))for(var m=a.cc.length-1;0<=m;--m){var y=a.cc[m];if(y==g)e=e.prev;else if(y!=Ha&&y!=C)break}for(;!("stat"!=e.type&&"form"!=e.type||"}"!=d&&(!(h=a.cc[a.cc.length-1])||h!=L&&h!=Q|| +/^[,\.=+\-*:?[\(]/.test(b)));)e=e.prev;Ta&&")"==e.type&&"stat"==e.prev.type&&(e=e.prev);h=e.type;m=d==h;return"vardef"==h?e.indented+("operator"==a.lastType||","==a.lastType?e.info.length+1:0):"form"==h&&"{"==d?e.indented:"form"==h?e.indented+U:"stat"==h?(d=e.indented,a="operator"==a.lastType||","==a.lastType||Ba.test(b.charAt(0))||/[,.]/.test(b.charAt(0)),d+(a?Ta||U:0)):"switch"!=e.info||m||0==A.doubleIndentSwitch?e.align?e.column+(m?0:1):e.indented+(m?0:U):e.indented+(/^(?:case|default)\b/.test(b)? +U:2*U)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:J?null:"/*",blockCommentEnd:J?null:"*/",blockCommentContinue:J?null:" * ",lineComment:J?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:J?"json":"javascript",jsonldMode:fa,jsonMode:J,expressionAllowed:Aa,skipExpression:function(a){Ea(a,"atom","atom","true",new v.StringStream("",2,null))}}});v.registerHelper("wordChars","javascript",/[\w$]/);v.defineMIME("text/javascript","javascript");v.defineMIME("text/ecmascript", +"javascript");v.defineMIME("application/javascript","javascript");v.defineMIME("application/x-javascript","javascript");v.defineMIME("application/ecmascript","javascript");v.defineMIME("application/json",{name:"javascript",json:!0});v.defineMIME("application/x-json",{name:"javascript",json:!0});v.defineMIME("application/manifest+json",{name:"javascript",json:!0});v.defineMIME("application/ld+json",{name:"javascript",jsonld:!0});v.defineMIME("text/typescript",{name:"javascript",typescript:!0});v.defineMIME("application/typescript", +{name:"javascript",typescript:!0})}); + +},{"../../lib/codemirror":40}],42:[function(require,module,exports){ + +/** + * Expose `Emitter`. + */ + +if (typeof module !== 'undefined') { + module.exports = Emitter; +} + +/** + * Initialize a new `Emitter`. + * + * @api public + */ + +function Emitter(obj) { + if (obj) return mixin(obj); +}; + +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} + +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []) + .push(fn); + return this; +}; + +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.once = function(event, fn){ + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; +}; + +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } + + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + + // Remove event specific arrays for event types that no + // one is subscribed for to avoid memory leak. + if (callbacks.length === 0) { + delete this._callbacks['$' + event]; + } + + return this; +}; + +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + + var args = new Array(arguments.length - 1) + , callbacks = this._callbacks['$' + event]; + + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; +}; + +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; +}; + +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; + +},{}],43:[function(require,module,exports){ +'use strict' + +module.exports = ready + +function ready (callback) { + if (typeof document === 'undefined') { + throw new Error('document-ready only runs in the browser') + } + var state = document.readyState + if (state === 'complete' || state === 'interactive') { + return setTimeout(callback, 0) + } + + document.addEventListener('DOMContentLoaded', function onLoad () { + callback() + }) +} + +},{}],44:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = (() => { + if (typeof self !== "undefined") { + return self; + } + else if (typeof window !== "undefined") { + return window; + } + else { + return Function("return this")(); + } +})(); + +},{}],45:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.installTimerFunctions = exports.transports = exports.Transport = exports.protocol = exports.Socket = void 0; +const socket_js_1 = require("./socket.js"); +Object.defineProperty(exports, "Socket", { enumerable: true, get: function () { return socket_js_1.Socket; } }); +exports.protocol = socket_js_1.Socket.protocol; +var transport_js_1 = require("./transport.js"); +Object.defineProperty(exports, "Transport", { enumerable: true, get: function () { return transport_js_1.Transport; } }); +var index_js_1 = require("./transports/index.js"); +Object.defineProperty(exports, "transports", { enumerable: true, get: function () { return index_js_1.transports; } }); +var util_js_1 = require("./util.js"); +Object.defineProperty(exports, "installTimerFunctions", { enumerable: true, get: function () { return util_js_1.installTimerFunctions; } }); + +},{"./socket.js":46,"./transport.js":47,"./transports/index.js":48,"./util.js":54}],46:[function(require,module,exports){ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Socket = void 0; +const index_js_1 = require("./transports/index.js"); +const util_js_1 = require("./util.js"); +const parseqs_1 = __importDefault(require("parseqs")); +const parseuri_1 = __importDefault(require("parseuri")); +const debug_1 = __importDefault(require("debug")); // debug() +const component_emitter_1 = require("@socket.io/component-emitter"); +const engine_io_parser_1 = require("engine.io-parser"); +const debug = (0, debug_1.default)("engine.io-client:socket"); // debug() +class Socket extends component_emitter_1.Emitter { + /** + * Socket constructor. + * + * @param {String|Object} uri or options + * @param {Object} opts - options + * @api public + */ + constructor(uri, opts = {}) { + super(); + if (uri && "object" === typeof uri) { + opts = uri; + uri = null; + } + if (uri) { + uri = (0, parseuri_1.default)(uri); + opts.hostname = uri.host; + opts.secure = uri.protocol === "https" || uri.protocol === "wss"; + opts.port = uri.port; + if (uri.query) + opts.query = uri.query; + } + else if (opts.host) { + opts.hostname = (0, parseuri_1.default)(opts.host).host; + } + (0, util_js_1.installTimerFunctions)(this, opts); + this.secure = + null != opts.secure + ? opts.secure + : typeof location !== "undefined" && "https:" === location.protocol; + if (opts.hostname && !opts.port) { + // if no port is specified manually, use the protocol default + opts.port = this.secure ? "443" : "80"; + } + this.hostname = + opts.hostname || + (typeof location !== "undefined" ? location.hostname : "localhost"); + this.port = + opts.port || + (typeof location !== "undefined" && location.port + ? location.port + : this.secure + ? "443" + : "80"); + this.transports = opts.transports || ["polling", "websocket"]; + this.readyState = ""; + this.writeBuffer = []; + this.prevBufferLen = 0; + this.opts = Object.assign({ + path: "/engine.io", + agent: false, + withCredentials: false, + upgrade: true, + timestampParam: "t", + rememberUpgrade: false, + rejectUnauthorized: true, + perMessageDeflate: { + threshold: 1024 + }, + transportOptions: {}, + closeOnBeforeunload: true + }, opts); + this.opts.path = this.opts.path.replace(/\/$/, "") + "/"; + if (typeof this.opts.query === "string") { + this.opts.query = parseqs_1.default.decode(this.opts.query); + } + // set on handshake + this.id = null; + this.upgrades = null; + this.pingInterval = null; + this.pingTimeout = null; + // set on heartbeat + this.pingTimeoutTimer = null; + if (typeof addEventListener === "function") { + if (this.opts.closeOnBeforeunload) { + // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener + // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is + // closed/reloaded) + addEventListener("beforeunload", () => { + if (this.transport) { + // silently close the transport + this.transport.removeAllListeners(); + this.transport.close(); + } + }, false); + } + if (this.hostname !== "localhost") { + this.offlineEventListener = () => { + this.onClose("transport close"); + }; + addEventListener("offline", this.offlineEventListener, false); + } + } + this.open(); + } + /** + * Creates transport of the given type. + * + * @param {String} transport name + * @return {Transport} + * @api private + */ + createTransport(name) { + debug('creating transport "%s"', name); + const query = clone(this.opts.query); + // append engine.io protocol identifier + query.EIO = engine_io_parser_1.protocol; + // transport name + query.transport = name; + // session id if we already have one + if (this.id) + query.sid = this.id; + const opts = Object.assign({}, this.opts.transportOptions[name], this.opts, { + query, + socket: this, + hostname: this.hostname, + secure: this.secure, + port: this.port + }); + debug("options: %j", opts); + return new index_js_1.transports[name](opts); + } + /** + * Initializes transport to use and starts probe. + * + * @api private + */ + open() { + let transport; + if (this.opts.rememberUpgrade && + Socket.priorWebsocketSuccess && + this.transports.indexOf("websocket") !== -1) { + transport = "websocket"; + } + else if (0 === this.transports.length) { + // Emit error on next tick so it can be listened to + this.setTimeoutFn(() => { + this.emitReserved("error", "No transports available"); + }, 0); + return; + } + else { + transport = this.transports[0]; + } + this.readyState = "opening"; + // Retry with the next transport if the transport is disabled (jsonp: false) + try { + transport = this.createTransport(transport); + } + catch (e) { + debug("error while creating transport: %s", e); + this.transports.shift(); + this.open(); + return; + } + transport.open(); + this.setTransport(transport); + } + /** + * Sets the current transport. Disables the existing one (if any). + * + * @api private + */ + setTransport(transport) { + debug("setting transport %s", transport.name); + if (this.transport) { + debug("clearing existing transport %s", this.transport.name); + this.transport.removeAllListeners(); + } + // set up transport + this.transport = transport; + // set up transport listeners + transport + .on("drain", this.onDrain.bind(this)) + .on("packet", this.onPacket.bind(this)) + .on("error", this.onError.bind(this)) + .on("close", () => { + this.onClose("transport close"); + }); + } + /** + * Probes a transport. + * + * @param {String} transport name + * @api private + */ + probe(name) { + debug('probing transport "%s"', name); + let transport = this.createTransport(name); + let failed = false; + Socket.priorWebsocketSuccess = false; + const onTransportOpen = () => { + if (failed) + return; + debug('probe transport "%s" opened', name); + transport.send([{ type: "ping", data: "probe" }]); + transport.once("packet", msg => { + if (failed) + return; + if ("pong" === msg.type && "probe" === msg.data) { + debug('probe transport "%s" pong', name); + this.upgrading = true; + this.emitReserved("upgrading", transport); + if (!transport) + return; + Socket.priorWebsocketSuccess = "websocket" === transport.name; + debug('pausing current transport "%s"', this.transport.name); + this.transport.pause(() => { + if (failed) + return; + if ("closed" === this.readyState) + return; + debug("changing transport and sending upgrade packet"); + cleanup(); + this.setTransport(transport); + transport.send([{ type: "upgrade" }]); + this.emitReserved("upgrade", transport); + transport = null; + this.upgrading = false; + this.flush(); + }); + } + else { + debug('probe transport "%s" failed', name); + const err = new Error("probe error"); + // @ts-ignore + err.transport = transport.name; + this.emitReserved("upgradeError", err); + } + }); + }; + function freezeTransport() { + if (failed) + return; + // Any callback called by transport should be ignored since now + failed = true; + cleanup(); + transport.close(); + transport = null; + } + // Handle any error that happens while probing + const onerror = err => { + const error = new Error("probe error: " + err); + // @ts-ignore + error.transport = transport.name; + freezeTransport(); + debug('probe transport "%s" failed because of error: %s', name, err); + this.emitReserved("upgradeError", error); + }; + function onTransportClose() { + onerror("transport closed"); + } + // When the socket is closed while we're probing + function onclose() { + onerror("socket closed"); + } + // When the socket is upgraded while we're probing + function onupgrade(to) { + if (transport && to.name !== transport.name) { + debug('"%s" works - aborting "%s"', to.name, transport.name); + freezeTransport(); + } + } + // Remove all listeners on the transport and on self + const cleanup = () => { + transport.removeListener("open", onTransportOpen); + transport.removeListener("error", onerror); + transport.removeListener("close", onTransportClose); + this.off("close", onclose); + this.off("upgrading", onupgrade); + }; + transport.once("open", onTransportOpen); + transport.once("error", onerror); + transport.once("close", onTransportClose); + this.once("close", onclose); + this.once("upgrading", onupgrade); + transport.open(); + } + /** + * Called when connection is deemed open. + * + * @api private + */ + onOpen() { + debug("socket open"); + this.readyState = "open"; + Socket.priorWebsocketSuccess = "websocket" === this.transport.name; + this.emitReserved("open"); + this.flush(); + // we check for `readyState` in case an `open` + // listener already closed the socket + if ("open" === this.readyState && + this.opts.upgrade && + this.transport.pause) { + debug("starting upgrade probes"); + let i = 0; + const l = this.upgrades.length; + for (; i < l; i++) { + this.probe(this.upgrades[i]); + } + } + } + /** + * Handles a packet. + * + * @api private + */ + onPacket(packet) { + if ("opening" === this.readyState || + "open" === this.readyState || + "closing" === this.readyState) { + debug('socket receive: type "%s", data "%s"', packet.type, packet.data); + this.emitReserved("packet", packet); + // Socket is live - any packet counts + this.emitReserved("heartbeat"); + switch (packet.type) { + case "open": + this.onHandshake(JSON.parse(packet.data)); + break; + case "ping": + this.resetPingTimeout(); + this.sendPacket("pong"); + this.emitReserved("ping"); + this.emitReserved("pong"); + break; + case "error": + const err = new Error("server error"); + // @ts-ignore + err.code = packet.data; + this.onError(err); + break; + case "message": + this.emitReserved("data", packet.data); + this.emitReserved("message", packet.data); + break; + } + } + else { + debug('packet received with socket readyState "%s"', this.readyState); + } + } + /** + * Called upon handshake completion. + * + * @param {Object} data - handshake obj + * @api private + */ + onHandshake(data) { + this.emitReserved("handshake", data); + this.id = data.sid; + this.transport.query.sid = data.sid; + this.upgrades = this.filterUpgrades(data.upgrades); + this.pingInterval = data.pingInterval; + this.pingTimeout = data.pingTimeout; + this.onOpen(); + // In case open handler closes socket + if ("closed" === this.readyState) + return; + this.resetPingTimeout(); + } + /** + * Sets and resets ping timeout timer based on server pings. + * + * @api private + */ + resetPingTimeout() { + this.clearTimeoutFn(this.pingTimeoutTimer); + this.pingTimeoutTimer = this.setTimeoutFn(() => { + this.onClose("ping timeout"); + }, this.pingInterval + this.pingTimeout); + if (this.opts.autoUnref) { + this.pingTimeoutTimer.unref(); + } + } + /** + * Called on `drain` event + * + * @api private + */ + onDrain() { + this.writeBuffer.splice(0, this.prevBufferLen); + // setting prevBufferLen = 0 is very important + // for example, when upgrading, upgrade packet is sent over, + // and a nonzero prevBufferLen could cause problems on `drain` + this.prevBufferLen = 0; + if (0 === this.writeBuffer.length) { + this.emitReserved("drain"); + } + else { + this.flush(); + } + } + /** + * Flush write buffers. + * + * @api private + */ + flush() { + if ("closed" !== this.readyState && + this.transport.writable && + !this.upgrading && + this.writeBuffer.length) { + debug("flushing %d packets in socket", this.writeBuffer.length); + this.transport.send(this.writeBuffer); + // keep track of current length of writeBuffer + // splice writeBuffer and callbackBuffer on `drain` + this.prevBufferLen = this.writeBuffer.length; + this.emitReserved("flush"); + } + } + /** + * Sends a message. + * + * @param {String} message. + * @param {Function} callback function. + * @param {Object} options. + * @return {Socket} for chaining. + * @api public + */ + write(msg, options, fn) { + this.sendPacket("message", msg, options, fn); + return this; + } + send(msg, options, fn) { + this.sendPacket("message", msg, options, fn); + return this; + } + /** + * Sends a packet. + * + * @param {String} packet type. + * @param {String} data. + * @param {Object} options. + * @param {Function} callback function. + * @api private + */ + sendPacket(type, data, options, fn) { + if ("function" === typeof data) { + fn = data; + data = undefined; + } + if ("function" === typeof options) { + fn = options; + options = null; + } + if ("closing" === this.readyState || "closed" === this.readyState) { + return; + } + options = options || {}; + options.compress = false !== options.compress; + const packet = { + type: type, + data: data, + options: options + }; + this.emitReserved("packetCreate", packet); + this.writeBuffer.push(packet); + if (fn) + this.once("flush", fn); + this.flush(); + } + /** + * Closes the connection. + * + * @api public + */ + close() { + const close = () => { + this.onClose("forced close"); + debug("socket closing - telling transport to close"); + this.transport.close(); + }; + const cleanupAndClose = () => { + this.off("upgrade", cleanupAndClose); + this.off("upgradeError", cleanupAndClose); + close(); + }; + const waitForUpgrade = () => { + // wait for upgrade to finish since we can't send packets while pausing a transport + this.once("upgrade", cleanupAndClose); + this.once("upgradeError", cleanupAndClose); + }; + if ("opening" === this.readyState || "open" === this.readyState) { + this.readyState = "closing"; + if (this.writeBuffer.length) { + this.once("drain", () => { + if (this.upgrading) { + waitForUpgrade(); + } + else { + close(); + } + }); + } + else if (this.upgrading) { + waitForUpgrade(); + } + else { + close(); + } + } + return this; + } + /** + * Called upon transport error + * + * @api private + */ + onError(err) { + debug("socket error %j", err); + Socket.priorWebsocketSuccess = false; + this.emitReserved("error", err); + this.onClose("transport error", err); + } + /** + * Called upon transport close. + * + * @api private + */ + onClose(reason, desc) { + if ("opening" === this.readyState || + "open" === this.readyState || + "closing" === this.readyState) { + debug('socket close with reason: "%s"', reason); + // clear timers + this.clearTimeoutFn(this.pingTimeoutTimer); + // stop event from firing again for transport + this.transport.removeAllListeners("close"); + // ensure transport won't stay open + this.transport.close(); + // ignore further transport communication + this.transport.removeAllListeners(); + if (typeof removeEventListener === "function") { + removeEventListener("offline", this.offlineEventListener, false); + } + // set ready state + this.readyState = "closed"; + // clear session id + this.id = null; + // emit close event + this.emitReserved("close", reason, desc); + // clean buffers after, so users can still + // grab the buffers on `close` event + this.writeBuffer = []; + this.prevBufferLen = 0; + } + } + /** + * Filters upgrades, returning only those matching client transports. + * + * @param {Array} server upgrades + * @api private + * + */ + filterUpgrades(upgrades) { + const filteredUpgrades = []; + let i = 0; + const j = upgrades.length; + for (; i < j; i++) { + if (~this.transports.indexOf(upgrades[i])) + filteredUpgrades.push(upgrades[i]); + } + return filteredUpgrades; + } +} +exports.Socket = Socket; +Socket.protocol = engine_io_parser_1.protocol; +function clone(obj) { + const o = {}; + for (let i in obj) { + if (obj.hasOwnProperty(i)) { + o[i] = obj[i]; + } + } + return o; +} + +},{"./transports/index.js":48,"./util.js":54,"@socket.io/component-emitter":2,"debug":55,"engine.io-parser":61,"parseqs":150,"parseuri":151}],47:[function(require,module,exports){ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Transport = void 0; +const engine_io_parser_1 = require("engine.io-parser"); +const component_emitter_1 = require("@socket.io/component-emitter"); +const util_js_1 = require("./util.js"); +const debug_1 = __importDefault(require("debug")); // debug() +const debug = (0, debug_1.default)("engine.io-client:transport"); // debug() +class Transport extends component_emitter_1.Emitter { + /** + * Transport abstract constructor. + * + * @param {Object} options. + * @api private + */ + constructor(opts) { + super(); + this.writable = false; + (0, util_js_1.installTimerFunctions)(this, opts); + this.opts = opts; + this.query = opts.query; + this.readyState = ""; + this.socket = opts.socket; + } + /** + * Emits an error. + * + * @param {String} str + * @return {Transport} for chaining + * @api protected + */ + onError(msg, desc) { + const err = new Error(msg); + // @ts-ignore + err.type = "TransportError"; + // @ts-ignore + err.description = desc; + super.emit("error", err); + return this; + } + /** + * Opens the transport. + * + * @api public + */ + open() { + if ("closed" === this.readyState || "" === this.readyState) { + this.readyState = "opening"; + this.doOpen(); + } + return this; + } + /** + * Closes the transport. + * + * @api public + */ + close() { + if ("opening" === this.readyState || "open" === this.readyState) { + this.doClose(); + this.onClose(); + } + return this; + } + /** + * Sends multiple packets. + * + * @param {Array} packets + * @api public + */ + send(packets) { + if ("open" === this.readyState) { + this.write(packets); + } + else { + // this might happen if the transport was silently closed in the beforeunload event handler + debug("transport is not open, discarding packets"); + } + } + /** + * Called upon open + * + * @api protected + */ + onOpen() { + this.readyState = "open"; + this.writable = true; + super.emit("open"); + } + /** + * Called with data. + * + * @param {String} data + * @api protected + */ + onData(data) { + const packet = (0, engine_io_parser_1.decodePacket)(data, this.socket.binaryType); + this.onPacket(packet); + } + /** + * Called with a decoded packet. + * + * @api protected + */ + onPacket(packet) { + super.emit("packet", packet); + } + /** + * Called upon close. + * + * @api protected + */ + onClose() { + this.readyState = "closed"; + super.emit("close"); + } +} +exports.Transport = Transport; + +},{"./util.js":54,"@socket.io/component-emitter":2,"debug":55,"engine.io-parser":61}],48:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.transports = void 0; +const polling_xhr_js_1 = require("./polling-xhr.js"); +const websocket_js_1 = require("./websocket.js"); +exports.transports = { + websocket: websocket_js_1.WS, + polling: polling_xhr_js_1.XHR +}; + +},{"./polling-xhr.js":49,"./websocket.js":52}],49:[function(require,module,exports){ +"use strict"; +/* global attachEvent */ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Request = exports.XHR = void 0; +const xmlhttprequest_js_1 = __importDefault(require("./xmlhttprequest.js")); +const debug_1 = __importDefault(require("debug")); // debug() +const globalThis_js_1 = __importDefault(require("../globalThis.js")); +const util_js_1 = require("../util.js"); +const component_emitter_1 = require("@socket.io/component-emitter"); +const polling_js_1 = require("./polling.js"); +const debug = (0, debug_1.default)("engine.io-client:polling-xhr"); // debug() +/** + * Empty function + */ +function empty() { } +const hasXHR2 = (function () { + const xhr = new xmlhttprequest_js_1.default({ + xdomain: false + }); + return null != xhr.responseType; +})(); +class XHR extends polling_js_1.Polling { + /** + * XHR Polling constructor. + * + * @param {Object} opts + * @api public + */ + constructor(opts) { + super(opts); + if (typeof location !== "undefined") { + const isSSL = "https:" === location.protocol; + let port = location.port; + // some user agents have empty `location.port` + if (!port) { + port = isSSL ? "443" : "80"; + } + this.xd = + (typeof location !== "undefined" && + opts.hostname !== location.hostname) || + port !== opts.port; + this.xs = opts.secure !== isSSL; + } + /** + * XHR supports binary + */ + const forceBase64 = opts && opts.forceBase64; + this.supportsBinary = hasXHR2 && !forceBase64; + } + /** + * Creates a request. + * + * @param {String} method + * @api private + */ + request(opts = {}) { + Object.assign(opts, { xd: this.xd, xs: this.xs }, this.opts); + return new Request(this.uri(), opts); + } + /** + * Sends data. + * + * @param {String} data to send. + * @param {Function} called upon flush. + * @api private + */ + doWrite(data, fn) { + const req = this.request({ + method: "POST", + data: data + }); + req.on("success", fn); + req.on("error", err => { + this.onError("xhr post error", err); + }); + } + /** + * Starts a poll cycle. + * + * @api private + */ + doPoll() { + debug("xhr poll"); + const req = this.request(); + req.on("data", this.onData.bind(this)); + req.on("error", err => { + this.onError("xhr poll error", err); + }); + this.pollXhr = req; + } +} +exports.XHR = XHR; +class Request extends component_emitter_1.Emitter { + /** + * Request constructor + * + * @param {Object} options + * @api public + */ + constructor(uri, opts) { + super(); + (0, util_js_1.installTimerFunctions)(this, opts); + this.opts = opts; + this.method = opts.method || "GET"; + this.uri = uri; + this.async = false !== opts.async; + this.data = undefined !== opts.data ? opts.data : null; + this.create(); + } + /** + * Creates the XHR object and sends the request. + * + * @api private + */ + create() { + const opts = (0, util_js_1.pick)(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref"); + opts.xdomain = !!this.opts.xd; + opts.xscheme = !!this.opts.xs; + const xhr = (this.xhr = new xmlhttprequest_js_1.default(opts)); + try { + debug("xhr open %s: %s", this.method, this.uri); + xhr.open(this.method, this.uri, this.async); + try { + if (this.opts.extraHeaders) { + xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true); + for (let i in this.opts.extraHeaders) { + if (this.opts.extraHeaders.hasOwnProperty(i)) { + xhr.setRequestHeader(i, this.opts.extraHeaders[i]); + } + } + } + } + catch (e) { } + if ("POST" === this.method) { + try { + xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8"); + } + catch (e) { } + } + try { + xhr.setRequestHeader("Accept", "*/*"); + } + catch (e) { } + // ie6 check + if ("withCredentials" in xhr) { + xhr.withCredentials = this.opts.withCredentials; + } + if (this.opts.requestTimeout) { + xhr.timeout = this.opts.requestTimeout; + } + xhr.onreadystatechange = () => { + if (4 !== xhr.readyState) + return; + if (200 === xhr.status || 1223 === xhr.status) { + this.onLoad(); + } + else { + // make sure the `error` event handler that's user-set + // does not throw in the same tick and gets caught here + this.setTimeoutFn(() => { + this.onError(typeof xhr.status === "number" ? xhr.status : 0); + }, 0); + } + }; + debug("xhr data %s", this.data); + xhr.send(this.data); + } + catch (e) { + // Need to defer since .create() is called directly from the constructor + // and thus the 'error' event can only be only bound *after* this exception + // occurs. Therefore, also, we cannot throw here at all. + this.setTimeoutFn(() => { + this.onError(e); + }, 0); + return; + } + if (typeof document !== "undefined") { + this.index = Request.requestsCount++; + Request.requests[this.index] = this; + } + } + /** + * Called upon successful response. + * + * @api private + */ + onSuccess() { + this.emit("success"); + this.cleanup(); + } + /** + * Called if we have data. + * + * @api private + */ + onData(data) { + this.emit("data", data); + this.onSuccess(); + } + /** + * Called upon error. + * + * @api private + */ + onError(err) { + this.emit("error", err); + this.cleanup(true); + } + /** + * Cleans up house. + * + * @api private + */ + cleanup(fromError) { + if ("undefined" === typeof this.xhr || null === this.xhr) { + return; + } + this.xhr.onreadystatechange = empty; + if (fromError) { + try { + this.xhr.abort(); + } + catch (e) { } + } + if (typeof document !== "undefined") { + delete Request.requests[this.index]; + } + this.xhr = null; + } + /** + * Called upon load. + * + * @api private + */ + onLoad() { + const data = this.xhr.responseText; + if (data !== null) { + this.onData(data); + } + } + /** + * Aborts the request. + * + * @api public + */ + abort() { + this.cleanup(); + } +} +exports.Request = Request; +Request.requestsCount = 0; +Request.requests = {}; +/** + * Aborts pending requests when unloading the window. This is needed to prevent + * memory leaks (e.g. when using IE) and to ensure that no spurious error is + * emitted. + */ +if (typeof document !== "undefined") { + // @ts-ignore + if (typeof attachEvent === "function") { + // @ts-ignore + attachEvent("onunload", unloadHandler); + } + else if (typeof addEventListener === "function") { + const terminationEvent = "onpagehide" in globalThis_js_1.default ? "pagehide" : "unload"; + addEventListener(terminationEvent, unloadHandler, false); + } +} +function unloadHandler() { + for (let i in Request.requests) { + if (Request.requests.hasOwnProperty(i)) { + Request.requests[i].abort(); + } + } +} + +},{"../globalThis.js":44,"../util.js":54,"./polling.js":50,"./xmlhttprequest.js":53,"@socket.io/component-emitter":2,"debug":55}],50:[function(require,module,exports){ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Polling = void 0; +const transport_js_1 = require("../transport.js"); +const debug_1 = __importDefault(require("debug")); // debug() +const yeast_1 = __importDefault(require("yeast")); +const parseqs_1 = __importDefault(require("parseqs")); +const engine_io_parser_1 = require("engine.io-parser"); +const debug = (0, debug_1.default)("engine.io-client:polling"); // debug() +class Polling extends transport_js_1.Transport { + constructor() { + super(...arguments); + this.polling = false; + } + /** + * Transport name. + */ + get name() { + return "polling"; + } + /** + * Opens the socket (triggers polling). We write a PING message to determine + * when the transport is open. + * + * @api private + */ + doOpen() { + this.poll(); + } + /** + * Pauses polling. + * + * @param {Function} callback upon buffers are flushed and transport is paused + * @api private + */ + pause(onPause) { + this.readyState = "pausing"; + const pause = () => { + debug("paused"); + this.readyState = "paused"; + onPause(); + }; + if (this.polling || !this.writable) { + let total = 0; + if (this.polling) { + debug("we are currently polling - waiting to pause"); + total++; + this.once("pollComplete", function () { + debug("pre-pause polling complete"); + --total || pause(); + }); + } + if (!this.writable) { + debug("we are currently writing - waiting to pause"); + total++; + this.once("drain", function () { + debug("pre-pause writing complete"); + --total || pause(); + }); + } + } + else { + pause(); + } + } + /** + * Starts polling cycle. + * + * @api public + */ + poll() { + debug("polling"); + this.polling = true; + this.doPoll(); + this.emit("poll"); + } + /** + * Overloads onData to detect payloads. + * + * @api private + */ + onData(data) { + debug("polling got data %s", data); + const callback = packet => { + // if its the first message we consider the transport open + if ("opening" === this.readyState && packet.type === "open") { + this.onOpen(); + } + // if its a close packet, we close the ongoing requests + if ("close" === packet.type) { + this.onClose(); + return false; + } + // otherwise bypass onData and handle the message + this.onPacket(packet); + }; + // decode payload + (0, engine_io_parser_1.decodePayload)(data, this.socket.binaryType).forEach(callback); + // if an event did not trigger closing + if ("closed" !== this.readyState) { + // if we got data we're not polling + this.polling = false; + this.emit("pollComplete"); + if ("open" === this.readyState) { + this.poll(); + } + else { + debug('ignoring poll - transport state "%s"', this.readyState); + } + } + } + /** + * For polling, send a close packet. + * + * @api private + */ + doClose() { + const close = () => { + debug("writing close packet"); + this.write([{ type: "close" }]); + }; + if ("open" === this.readyState) { + debug("transport open - closing"); + close(); + } + else { + // in case we're trying to close while + // handshaking is in progress (GH-164) + debug("transport not open - deferring close"); + this.once("open", close); + } + } + /** + * Writes a packets payload. + * + * @param {Array} data packets + * @param {Function} drain callback + * @api private + */ + write(packets) { + this.writable = false; + (0, engine_io_parser_1.encodePayload)(packets, data => { + this.doWrite(data, () => { + this.writable = true; + this.emit("drain"); + }); + }); + } + /** + * Generates uri for connection. + * + * @api private + */ + uri() { + let query = this.query || {}; + const schema = this.opts.secure ? "https" : "http"; + let port = ""; + // cache busting is forced + if (false !== this.opts.timestampRequests) { + query[this.opts.timestampParam] = (0, yeast_1.default)(); + } + if (!this.supportsBinary && !query.sid) { + query.b64 = 1; + } + // avoid port if default for schema + if (this.opts.port && + (("https" === schema && Number(this.opts.port) !== 443) || + ("http" === schema && Number(this.opts.port) !== 80))) { + port = ":" + this.opts.port; + } + const encodedQuery = parseqs_1.default.encode(query); + const ipv6 = this.opts.hostname.indexOf(":") !== -1; + return (schema + + "://" + + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + + port + + this.opts.path + + (encodedQuery.length ? "?" + encodedQuery : "")); + } +} +exports.Polling = Polling; + +},{"../transport.js":47,"debug":55,"engine.io-parser":61,"parseqs":150,"yeast":222}],51:[function(require,module,exports){ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultBinaryType = exports.usingBrowserWebSocket = exports.WebSocket = exports.nextTick = void 0; +const globalThis_js_1 = __importDefault(require("../globalThis.js")); +exports.nextTick = (() => { + const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function"; + if (isPromiseAvailable) { + return cb => Promise.resolve().then(cb); + } + else { + return (cb, setTimeoutFn) => setTimeoutFn(cb, 0); + } +})(); +exports.WebSocket = globalThis_js_1.default.WebSocket || globalThis_js_1.default.MozWebSocket; +exports.usingBrowserWebSocket = true; +exports.defaultBinaryType = "arraybuffer"; + +},{"../globalThis.js":44}],52:[function(require,module,exports){ +(function (Buffer){(function (){ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WS = void 0; +const transport_js_1 = require("../transport.js"); +const parseqs_1 = __importDefault(require("parseqs")); +const yeast_1 = __importDefault(require("yeast")); +const util_js_1 = require("../util.js"); +const websocket_constructor_js_1 = require("./websocket-constructor.js"); +const debug_1 = __importDefault(require("debug")); // debug() +const engine_io_parser_1 = require("engine.io-parser"); +const debug = (0, debug_1.default)("engine.io-client:websocket"); // debug() +// detect ReactNative environment +const isReactNative = typeof navigator !== "undefined" && + typeof navigator.product === "string" && + navigator.product.toLowerCase() === "reactnative"; +class WS extends transport_js_1.Transport { + /** + * WebSocket transport constructor. + * + * @api {Object} connection options + * @api public + */ + constructor(opts) { + super(opts); + this.supportsBinary = !opts.forceBase64; + } + /** + * Transport name. + * + * @api public + */ + get name() { + return "websocket"; + } + /** + * Opens socket. + * + * @api private + */ + doOpen() { + if (!this.check()) { + // let probe timeout + return; + } + const uri = this.uri(); + const protocols = this.opts.protocols; + // React Native only supports the 'headers' option, and will print a warning if anything else is passed + const opts = isReactNative + ? {} + : (0, util_js_1.pick)(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity"); + if (this.opts.extraHeaders) { + opts.headers = this.opts.extraHeaders; + } + try { + this.ws = + websocket_constructor_js_1.usingBrowserWebSocket && !isReactNative + ? protocols + ? new websocket_constructor_js_1.WebSocket(uri, protocols) + : new websocket_constructor_js_1.WebSocket(uri) + : new websocket_constructor_js_1.WebSocket(uri, protocols, opts); + } + catch (err) { + return this.emit("error", err); + } + this.ws.binaryType = this.socket.binaryType || websocket_constructor_js_1.defaultBinaryType; + this.addEventListeners(); + } + /** + * Adds event listeners to the socket + * + * @api private + */ + addEventListeners() { + this.ws.onopen = () => { + if (this.opts.autoUnref) { + this.ws._socket.unref(); + } + this.onOpen(); + }; + this.ws.onclose = this.onClose.bind(this); + this.ws.onmessage = ev => this.onData(ev.data); + this.ws.onerror = e => this.onError("websocket error", e); + } + /** + * Writes data to socket. + * + * @param {Array} array of packets. + * @api private + */ + write(packets) { + this.writable = false; + // encodePacket efficient as it uses WS framing + // no need for encodePayload + for (let i = 0; i < packets.length; i++) { + const packet = packets[i]; + const lastPacket = i === packets.length - 1; + (0, engine_io_parser_1.encodePacket)(packet, this.supportsBinary, data => { + // always create a new object (GH-437) + const opts = {}; + if (!websocket_constructor_js_1.usingBrowserWebSocket) { + if (packet.options) { + opts.compress = packet.options.compress; + } + if (this.opts.perMessageDeflate) { + const len = "string" === typeof data ? Buffer.byteLength(data) : data.length; + if (len < this.opts.perMessageDeflate.threshold) { + opts.compress = false; + } + } + } + // Sometimes the websocket has already been closed but the browser didn't + // have a chance of informing us about it yet, in that case send will + // throw an error + try { + if (websocket_constructor_js_1.usingBrowserWebSocket) { + // TypeError is thrown when passing the second argument on Safari + this.ws.send(data); + } + else { + this.ws.send(data, opts); + } + } + catch (e) { + debug("websocket closed before onclose event"); + } + if (lastPacket) { + // fake drain + // defer to next tick to allow Socket to clear writeBuffer + (0, websocket_constructor_js_1.nextTick)(() => { + this.writable = true; + this.emit("drain"); + }, this.setTimeoutFn); + } + }); + } + } + /** + * Closes socket. + * + * @api private + */ + doClose() { + if (typeof this.ws !== "undefined") { + this.ws.close(); + this.ws = null; + } + } + /** + * Generates uri for connection. + * + * @api private + */ + uri() { + let query = this.query || {}; + const schema = this.opts.secure ? "wss" : "ws"; + let port = ""; + // avoid port if default for schema + if (this.opts.port && + (("wss" === schema && Number(this.opts.port) !== 443) || + ("ws" === schema && Number(this.opts.port) !== 80))) { + port = ":" + this.opts.port; + } + // append timestamp to URI + if (this.opts.timestampRequests) { + query[this.opts.timestampParam] = (0, yeast_1.default)(); + } + // communicate binary support capabilities + if (!this.supportsBinary) { + query.b64 = 1; + } + const encodedQuery = parseqs_1.default.encode(query); + const ipv6 = this.opts.hostname.indexOf(":") !== -1; + return (schema + + "://" + + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + + port + + this.opts.path + + (encodedQuery.length ? "?" + encodedQuery : "")); + } + /** + * Feature detection for WebSocket. + * + * @return {Boolean} whether this transport is available. + * @api public + */ + check() { + return (!!websocket_constructor_js_1.WebSocket && + !("__initialize" in websocket_constructor_js_1.WebSocket && this.name === WS.prototype.name)); + } +} +exports.WS = WS; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../transport.js":47,"../util.js":54,"./websocket-constructor.js":51,"buffer":17,"debug":55,"engine.io-parser":61,"parseqs":150,"yeast":222}],53:[function(require,module,exports){ +"use strict"; +// browser shim for xmlhttprequest module +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const has_cors_1 = __importDefault(require("has-cors")); +const globalThis_js_1 = __importDefault(require("../globalThis.js")); +function default_1(opts) { + const xdomain = opts.xdomain; + // XMLHttpRequest can be disabled on IE + try { + if ("undefined" !== typeof XMLHttpRequest && (!xdomain || has_cors_1.default)) { + return new XMLHttpRequest(); + } + } + catch (e) { } + if (!xdomain) { + try { + return new globalThis_js_1.default[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP"); + } + catch (e) { } + } +} +exports.default = default_1; + +},{"../globalThis.js":44,"has-cors":70}],54:[function(require,module,exports){ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.installTimerFunctions = exports.pick = void 0; +const globalThis_js_1 = __importDefault(require("./globalThis.js")); +function pick(obj, ...attr) { + return attr.reduce((acc, k) => { + if (obj.hasOwnProperty(k)) { + acc[k] = obj[k]; + } + return acc; + }, {}); +} +exports.pick = pick; +// Keep a reference to the real timeout functions so they can be used when overridden +const NATIVE_SET_TIMEOUT = setTimeout; +const NATIVE_CLEAR_TIMEOUT = clearTimeout; +function installTimerFunctions(obj, opts) { + if (opts.useNativeTimers) { + obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis_js_1.default); + obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis_js_1.default); + } + else { + obj.setTimeoutFn = setTimeout.bind(globalThis_js_1.default); + obj.clearTimeoutFn = clearTimeout.bind(globalThis_js_1.default); + } +} +exports.installTimerFunctions = installTimerFunctions; + +},{"./globalThis.js":44}],55:[function(require,module,exports){ +(function (process){(function (){ +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ + +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = require('./common')(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; + +}).call(this)}).call(this,require('_process')) +},{"./common":56,"_process":155}],56:[function(require,module,exports){ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require('ms'); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +module.exports = setup; + +},{"ms":57}],57:[function(require,module,exports){ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} + +},{}],58:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ERROR_PACKET = exports.PACKET_TYPES_REVERSE = exports.PACKET_TYPES = void 0; +const PACKET_TYPES = Object.create(null); // no Map = no polyfill +exports.PACKET_TYPES = PACKET_TYPES; +PACKET_TYPES["open"] = "0"; +PACKET_TYPES["close"] = "1"; +PACKET_TYPES["ping"] = "2"; +PACKET_TYPES["pong"] = "3"; +PACKET_TYPES["message"] = "4"; +PACKET_TYPES["upgrade"] = "5"; +PACKET_TYPES["noop"] = "6"; +const PACKET_TYPES_REVERSE = Object.create(null); +exports.PACKET_TYPES_REVERSE = PACKET_TYPES_REVERSE; +Object.keys(PACKET_TYPES).forEach(key => { + PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key; +}); +const ERROR_PACKET = { type: "error", data: "parser error" }; +exports.ERROR_PACKET = ERROR_PACKET; + +},{}],59:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const commons_js_1 = require("./commons.js"); +const base64_arraybuffer_1 = require("base64-arraybuffer"); +const withNativeArrayBuffer = typeof ArrayBuffer === "function"; +const decodePacket = (encodedPacket, binaryType) => { + if (typeof encodedPacket !== "string") { + return { + type: "message", + data: mapBinary(encodedPacket, binaryType) + }; + } + const type = encodedPacket.charAt(0); + if (type === "b") { + return { + type: "message", + data: decodeBase64Packet(encodedPacket.substring(1), binaryType) + }; + } + const packetType = commons_js_1.PACKET_TYPES_REVERSE[type]; + if (!packetType) { + return commons_js_1.ERROR_PACKET; + } + return encodedPacket.length > 1 + ? { + type: commons_js_1.PACKET_TYPES_REVERSE[type], + data: encodedPacket.substring(1) + } + : { + type: commons_js_1.PACKET_TYPES_REVERSE[type] + }; +}; +const decodeBase64Packet = (data, binaryType) => { + if (withNativeArrayBuffer) { + const decoded = (0, base64_arraybuffer_1.decode)(data); + return mapBinary(decoded, binaryType); + } + else { + return { base64: true, data }; // fallback for old browsers + } +}; +const mapBinary = (data, binaryType) => { + switch (binaryType) { + case "blob": + return data instanceof ArrayBuffer ? new Blob([data]) : data; + case "arraybuffer": + default: + return data; // assuming the data is already an ArrayBuffer + } +}; +exports.default = decodePacket; + +},{"./commons.js":58,"base64-arraybuffer":13}],60:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const commons_js_1 = require("./commons.js"); +const withNativeBlob = typeof Blob === "function" || + (typeof Blob !== "undefined" && + Object.prototype.toString.call(Blob) === "[object BlobConstructor]"); +const withNativeArrayBuffer = typeof ArrayBuffer === "function"; +// ArrayBuffer.isView method is not defined in IE10 +const isView = obj => { + return typeof ArrayBuffer.isView === "function" + ? ArrayBuffer.isView(obj) + : obj && obj.buffer instanceof ArrayBuffer; +}; +const encodePacket = ({ type, data }, supportsBinary, callback) => { + if (withNativeBlob && data instanceof Blob) { + if (supportsBinary) { + return callback(data); + } + else { + return encodeBlobAsBase64(data, callback); + } + } + else if (withNativeArrayBuffer && + (data instanceof ArrayBuffer || isView(data))) { + if (supportsBinary) { + return callback(data); + } + else { + return encodeBlobAsBase64(new Blob([data]), callback); + } + } + // plain string + return callback(commons_js_1.PACKET_TYPES[type] + (data || "")); +}; +const encodeBlobAsBase64 = (data, callback) => { + const fileReader = new FileReader(); + fileReader.onload = function () { + const content = fileReader.result.split(",")[1]; + callback("b" + content); + }; + return fileReader.readAsDataURL(data); +}; +exports.default = encodePacket; + +},{"./commons.js":58}],61:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodePayload = exports.decodePacket = exports.encodePayload = exports.encodePacket = exports.protocol = void 0; +const encodePacket_js_1 = require("./encodePacket.js"); +exports.encodePacket = encodePacket_js_1.default; +const decodePacket_js_1 = require("./decodePacket.js"); +exports.decodePacket = decodePacket_js_1.default; +const SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text +const encodePayload = (packets, callback) => { + // some packets may be added to the array while encoding, so the initial length must be saved + const length = packets.length; + const encodedPackets = new Array(length); + let count = 0; + packets.forEach((packet, i) => { + // force base64 encoding for binary packets + (0, encodePacket_js_1.default)(packet, false, encodedPacket => { + encodedPackets[i] = encodedPacket; + if (++count === length) { + callback(encodedPackets.join(SEPARATOR)); + } + }); + }); +}; +exports.encodePayload = encodePayload; +const decodePayload = (encodedPayload, binaryType) => { + const encodedPackets = encodedPayload.split(SEPARATOR); + const packets = []; + for (let i = 0; i < encodedPackets.length; i++) { + const decodedPacket = (0, decodePacket_js_1.default)(encodedPackets[i], binaryType); + packets.push(decodedPacket); + if (decodedPacket.type === "error") { break; + } + } + return packets; +}; +exports.decodePayload = decodePayload; +exports.protocol = 4; + +},{"./decodePacket.js":59,"./encodePacket.js":60}],62:[function(require,module,exports){ +'use strict'; + +/** + * @typedef {{ [key: string]: any }} Extensions + * @typedef {Error} Err + * @property {string} message + */ + +/** + * + * @param {Error} obj + * @param {Extensions} props + * @returns {Error & Extensions} + */ +function assign(obj, props) { + for (const key in props) { + Object.defineProperty(obj, key, { + value: props[key], + enumerable: true, + configurable: true, + }); + } + + return obj; +} + +/** + * + * @param {any} err - An Error + * @param {string|Extensions} code - A string code or props to set on the error + * @param {Extensions} [props] - Props to set on the error + * @returns {Error & Extensions} + */ +function createError(err, code, props) { + if (!err || typeof err === 'string') { + throw new TypeError('Please pass an Error to err-code'); + } + + if (!props) { + props = {}; + } + + if (typeof code === 'object') { + props = code; + code = ''; + } + + if (code) { + props.code = code; + } + + try { + return assign(err, props); + } catch (_) { + props.message = err.message; + props.stack = err.stack; + + const ErrClass = function () {}; + + ErrClass.prototype = Object.create(Object.getPrototypeOf(err)); + + // @ts-ignore + const output = assign(new ErrClass(), props); + + return output; + } +} + +module.exports = createError; + +},{}],63:[function(require,module,exports){ +module.exports = stringify +stringify.default = stringify +stringify.stable = deterministicStringify +stringify.stableStringify = deterministicStringify + +var LIMIT_REPLACE_NODE = '[...]' +var CIRCULAR_REPLACE_NODE = '[Circular]' + +var arr = [] +var replacerStack = [] + +function defaultOptions () { + return { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER + } +} + +// Regular stringify +function stringify (obj, replacer, spacer, options) { + if (typeof options === 'undefined') { + options = defaultOptions() + } + + decirc(obj, '', 0, [], undefined, 0, options) + var res + try { + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer) + } else { + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) + } + } catch (_) { + return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') + } finally { + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } + } + } + return res +} + +function setReplace (replace, val, k, parent) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: replace }) + arr.push([parent, k, val, propertyDescriptor]) + } else { + replacerStack.push([val, k, replace]) + } + } else { + parent[k] = replace + arr.push([parent, k, val]) + } +} + +function decirc (val, k, edgeIndex, stack, parent, depth, options) { + depth += 1 + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent) + return + } + } + + if ( + typeof options.depthLimit !== 'undefined' && + depth > options.depthLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent) + return + } + + if ( + typeof options.edgesLimit !== 'undefined' && + edgeIndex + 1 > options.edgesLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent) + return + } + + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + decirc(val[i], i, i, stack, val, depth, options) + } + } else { + var keys = Object.keys(val) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + decirc(val[key], key, i, stack, val, depth, options) + } + } + stack.pop() + } +} + +// Stable-stringify +function compareFunction (a, b) { + if (a < b) { + return -1 + } + if (a > b) { + return 1 + } + return 0 +} + +function deterministicStringify (obj, replacer, spacer, options) { + if (typeof options === 'undefined') { + options = defaultOptions() + } + + var tmp = deterministicDecirc(obj, '', 0, [], undefined, 0, options) || obj + var res + try { + if (replacerStack.length === 0) { + res = JSON.stringify(tmp, replacer, spacer) + } else { + res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) + } + } catch (_) { + return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') + } finally { + // Ensure that we restore the object as it was. + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } + } + } + return res +} + +function deterministicDecirc (val, k, edgeIndex, stack, parent, depth, options) { + depth += 1 + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent) + return + } + } + try { + if (typeof val.toJSON === 'function') { + return + } + } catch (_) { + return + } + + if ( + typeof options.depthLimit !== 'undefined' && + depth > options.depthLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent) + return + } + + if ( + typeof options.edgesLimit !== 'undefined' && + edgeIndex + 1 > options.edgesLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent) + return + } + + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + deterministicDecirc(val[i], i, i, stack, val, depth, options) + } + } else { + // Create a temporary object in the required way + var tmp = {} + var keys = Object.keys(val).sort(compareFunction) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + deterministicDecirc(val[key], key, i, stack, val, depth, options) + tmp[key] = val[key] + } + if (typeof parent !== 'undefined') { + arr.push([parent, k, val]) + parent[k] = tmp + } else { + return tmp + } + } + stack.pop() + } +} + +// wraps replacer function to handle values we couldn't replace +// and mark them as replaced value +function replaceGetterValues (replacer) { + replacer = + typeof replacer !== 'undefined' + ? replacer + : function (k, v) { + return v + } + return function (key, val) { + if (replacerStack.length > 0) { + for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i] + if (part[1] === key && part[0] === val) { + val = part[2] + replacerStack.splice(i, 1) + break + } + } + } + return replacer.call(this, key, val) + } +} + +},{}],64:[function(require,module,exports){ +'use strict'; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var slice = Array.prototype.slice; +var toStr = Object.prototype.toString; +var funcType = '[object Function]'; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.call(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slice.call(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return this; + } else { + return target.apply( + that, + args.concat(slice.call(arguments)) + ); + } + }; + + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); + } + + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; + +},{}],65:[function(require,module,exports){ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = Function.prototype.bind || implementation; + +},{"./implementation":64}],66:[function(require,module,exports){ +// originally pulled out of simple-peer + +module.exports = function getBrowserRTC () { + if (typeof globalThis === 'undefined') return null + var wrtc = { + RTCPeerConnection: globalThis.RTCPeerConnection || globalThis.mozRTCPeerConnection || + globalThis.webkitRTCPeerConnection, + RTCSessionDescription: globalThis.RTCSessionDescription || + globalThis.mozRTCSessionDescription || globalThis.webkitRTCSessionDescription, + RTCIceCandidate: globalThis.RTCIceCandidate || globalThis.mozRTCIceCandidate || + globalThis.webkitRTCIceCandidate + } + if (!wrtc.RTCPeerConnection) return null + return wrtc +} + +},{}],67:[function(require,module,exports){ +'use strict'; + +var undefined; + +var $SyntaxError = SyntaxError; +var $Function = Function; +var $TypeError = TypeError; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = require('has-symbols')(); + +var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': RangeError, + '%ReferenceError%': ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet +}; + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = require('function-bind'); +var hasOwn = require('has'); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; + +},{"function-bind":65,"has":73,"has-symbols":71}],68:[function(require,module,exports){ +(function (global){(function (){ +var topLevel = typeof global !== 'undefined' ? global : + typeof window !== 'undefined' ? window : {} +var minDoc = require('min-document'); + +var doccy; + +if (typeof document !== 'undefined') { + doccy = document; +} else { + doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; + + if (!doccy) { + doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; + } +} + +module.exports = doccy; + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"min-document":15}],69:[function(require,module,exports){ +(function (global){(function (){ +var win; + +if (typeof window !== "undefined") { + win = window; +} else if (typeof global !== "undefined") { + win = global; +} else if (typeof self !== "undefined"){ + win = self; +} else { + win = {}; +} + +module.exports = win; + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],70:[function(require,module,exports){ + +/** + * Module exports. + * + * Logic borrowed from Modernizr: + * + * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js + */ + +try { + module.exports = typeof XMLHttpRequest !== 'undefined' && + 'withCredentials' in new XMLHttpRequest(); +} catch (err) { + // if XMLHttp support is disabled in IE then it will throw + // when trying to create + module.exports = false; +} + +},{}],71:[function(require,module,exports){ +'use strict'; + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = require('./shams'); + +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; + +},{"./shams":72}],72:[function(require,module,exports){ +'use strict'; + +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; + +},{}],73:[function(require,module,exports){ +'use strict'; + +var bind = require('function-bind'); + +module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); + +},{"function-bind":65}],74:[function(require,module,exports){ +const Output = require('./src/output.js') +const loop = require('raf-loop') +const Source = require('./src/hydra-source.js') +const Mouse = require('./src/lib/mouse.js')() +const Audio = require('./src/lib/audio.js') +const VidRecorder = require('./src/lib/video-recorder.js') +const ArrayUtils = require('./src/lib/array-utils.js') +const Sandbox = require('./src/eval-sandbox.js') + +const Generator = require('./src/generator-factory.js') + +// to do: add ability to pass in certain uniforms and transforms +class HydraRenderer { + + constructor ({ + pb = null, + width = 1280, + height = 720, + numSources = 4, + numOutputs = 4, + makeGlobal = true, + autoLoop = true, + detectAudio = true, + enableStreamCapture = true, + canvas, + precision, + extendTransforms = {} // add your own functions on init + } = {}) { + + ArrayUtils.init() + + this.pb = pb + + this.width = width + this.height = height + this.renderAll = false + this.detectAudio = detectAudio + + this._initCanvas(canvas) + + + // object that contains all properties that will be made available on the global context and during local evaluation + this.synth = { + time: 0, + bpm: 30, + width: this.width, + height: this.height, + fps: undefined, + stats: { + fps: 0 + }, + speed: 1, + mouse: Mouse, + render: this._render.bind(this), + setResolution: this.setResolution.bind(this), + update: (dt) => {},// user defined update function + hush: this.hush.bind(this) + } + + if (makeGlobal) window.loadScript = this.loadScript + + + this.timeSinceLastUpdate = 0 + this._time = 0 // for internal use, only to use for deciding when to render frames + + // only allow valid precision options + let precisionOptions = ['lowp','mediump','highp'] + if(precision && precisionOptions.includes(precision.toLowerCase())) { + this.precision = precision.toLowerCase() + // + // if(!precisionValid){ + // console.warn('[hydra-synth warning]\nConstructor was provided an invalid floating point precision value of "' + precision + '". Using default value of "mediump" instead.') + // } + } else { + let isIOS = + (/iPad|iPhone|iPod/.test(navigator.platform) || + (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) && + !window.MSStream; + this.precision = isIOS ? 'highp' : 'mediump' + } + + + + this.extendTransforms = extendTransforms + + // boolean to store when to save screenshot + this.saveFrame = false + + // if stream capture is enabled, this object contains the capture stream + this.captureStream = null + + this.generator = undefined + + this._initRegl() + this._initOutputs(numOutputs) + this._initSources(numSources) + this._generateGlslTransforms() + + this.synth.screencap = () => { + this.saveFrame = true + } + + if (enableStreamCapture) { + try { + this.captureStream = this.canvas.captureStream(25) + // to do: enable capture stream of specific sources and outputs + this.synth.vidRecorder = new VidRecorder(this.captureStream) + } catch (e) { + console.warn('[hydra-synth warning]\nnew MediaSource() is not currently supported on iOS.') + console.error(e) + } + } + + if(detectAudio) this._initAudio() + + if(autoLoop) loop(this.tick.bind(this)).start() + + // final argument is properties that the user can set, all others are treated as read-only + this.sandbox = new Sandbox(this.synth, makeGlobal, ['speed', 'update', 'bpm', 'fps']) + } + + eval(code) { + this.sandbox.eval(code) + } + + getScreenImage(callback) { + this.imageCallback = callback + this.saveFrame = true + } + + hush() { + this.s.forEach((source) => { + source.clear() + }) + this.o.forEach((output) => { + this.synth.solid(0, 0, 0, 0).out(output) + }) + this.synth.render(this.o[0]) + } + + loadScript(url = "") { + const p = new Promise((res, rej) => { + var script = document.createElement("script"); + script.onload = function () { + console.log(`loaded script ${url}`); + res(); + }; + script.onerror = (err) => { + console.log(`error loading script ${url}`, "log-error"); + res() + }; + script.src = url; + document.head.appendChild(script); + }); + return p; + } + + setResolution(width, height) { + // console.log(width, height) + this.canvas.width = width + this.canvas.height = height + this.width = width // is this necessary? + this.height = height // ? + this.sandbox.set('width', width) + this.sandbox.set('height', height) + console.log(this.width) + this.o.forEach((output) => { + output.resize(width, height) + }) + this.s.forEach((source) => { + source.resize(width, height) + }) + this.regl._refresh() + console.log(this.canvas.width) + } + + canvasToImage (callback) { + const a = document.createElement('a') + a.style.display = 'none' + + let d = new Date() + a.download = `hydra-${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}-${d.getHours()}.${d.getMinutes()}.${d.getSeconds()}.png` + document.body.appendChild(a) + var self = this + this.canvas.toBlob( (blob) => { + if(self.imageCallback){ + self.imageCallback(blob) + delete self.imageCallback + } else { + a.href = URL.createObjectURL(blob) + console.log(a.href) + a.click() + } + }, 'image/png') + setTimeout(() => { + document.body.removeChild(a); + window.URL.revokeObjectURL(a.href); + }, 300); + } + + _initAudio () { + const that = this + this.synth.a = new Audio({ + numBins: 4, + // changeListener: ({audio}) => { + // that.a = audio.bins.map((_, index) => + // (scale = 1, offset = 0) => () => (audio.fft[index] * scale + offset) + // ) + // + // if (that.makeGlobal) { + // that.a.forEach((a, index) => { + // const aname = `a${index}` + // window[aname] = a + // }) + // } + // } + }) + } + + // create main output canvas and add to screen + _initCanvas (canvas) { + if (canvas) { + this.canvas = canvas + this.width = canvas.width + this.height = canvas.height + } else { + this.canvas = document.createElement('canvas') + this.canvas.width = this.width + this.canvas.height = this.height + this.canvas.style.width = '100%' + this.canvas.style.height = '100%' + this.canvas.style.imageRendering = 'pixelated' + document.body.appendChild(this.canvas) + } + } + + _initRegl () { + this.regl = require('regl')({ + // profile: true, + canvas: this.canvas, + pixelRatio: 1//, + // extensions: [ + // 'oes_texture_half_float', + // 'oes_texture_half_float_linear' + // ], + // optionalExtensions: [ + // 'oes_texture_float', + // 'oes_texture_float_linear' + //] + }) + + // This clears the color buffer to black and the depth buffer to 1 + this.regl.clear({ + color: [0, 0, 0, 1] + }) + + this.renderAll = this.regl({ + frag: ` + precision ${this.precision} float; + varying vec2 uv; + uniform sampler2D tex0; + uniform sampler2D tex1; + uniform sampler2D tex2; + uniform sampler2D tex3; + + void main () { + vec2 st = vec2(1.0 - uv.x, uv.y); + st*= vec2(2); + vec2 q = floor(st).xy*(vec2(2.0, 1.0)); + int quad = int(q.x) + int(q.y); + st.x += step(1., mod(st.y,2.0)); + st.y += step(1., mod(st.x,2.0)); + st = fract(st); + if(quad==0){ + gl_FragColor = texture2D(tex0, st); + } else if(quad==1){ + gl_FragColor = texture2D(tex1, st); + } else if (quad==2){ + gl_FragColor = texture2D(tex2, st); + } else { + gl_FragColor = texture2D(tex3, st); + } + + } + `, + vert: ` + precision ${this.precision} float; + attribute vec2 position; + varying vec2 uv; + + void main () { + uv = position; + gl_Position = vec4(1.0 - 2.0 * position, 0, 1); + }`, + attributes: { + position: [ + [-2, 0], + [0, -2], + [2, 2] + ] + }, + uniforms: { + tex0: this.regl.prop('tex0'), + tex1: this.regl.prop('tex1'), + tex2: this.regl.prop('tex2'), + tex3: this.regl.prop('tex3') + }, + count: 3, + depth: { enable: false } + }) + + this.renderFbo = this.regl({ + frag: ` + precision ${this.precision} float; + varying vec2 uv; + uniform vec2 resolution; + uniform sampler2D tex0; + + void main () { + gl_FragColor = texture2D(tex0, vec2(1.0 - uv.x, uv.y)); + } + `, + vert: ` + precision ${this.precision} float; + attribute vec2 position; + varying vec2 uv; + + void main () { + uv = position; + gl_Position = vec4(1.0 - 2.0 * position, 0, 1); + }`, + attributes: { + position: [ + [-2, 0], + [0, -2], + [2, 2] + ] + }, + uniforms: { + tex0: this.regl.prop('tex0'), + resolution: this.regl.prop('resolution') + }, + count: 3, + depth: { enable: false } + }) + } + + _initOutputs (numOutputs) { + const self = this + this.o = (Array(numOutputs)).fill().map((el, index) => { + var o = new Output({ + regl: this.regl, + width: this.width, + height: this.height, + precision: this.precision, + label: `o${index}` + }) + // o.render() + o.id = index + self.synth['o'+index] = o + return o + }) + + // set default output + this.output = this.o[0] + } + + _initSources (numSources) { + this.s = [] + for(var i = 0; i < numSources; i++) { + this.createSource(i) + } + } + + createSource (i) { + let s = new Source({regl: this.regl, pb: this.pb, width: this.width, height: this.height, label: `s${i}`}) + this.synth['s' + this.s.length] = s + this.s.push(s) + return s + } + + _generateGlslTransforms () { + var self = this + this.generator = new Generator({ + defaultOutput: this.o[0], + defaultUniforms: this.o[0].uniforms, + extendTransforms: this.extendTransforms, + changeListener: ({type, method, synth}) => { + if (type === 'add') { + self.synth[method] = synth.generators[method] + if(self.sandbox) self.sandbox.add(method) + } else if (type === 'remove') { + // what to do here? dangerously deleting window methods + //delete window[method] + } + // } + } + }) + this.synth.setFunction = this.generator.setFunction.bind(this.generator) + } + + _render (output) { + if (output) { + this.output = output + this.isRenderingAll = false + } else { + this.isRenderingAll = true + } + } + + // dt in ms + tick (dt, uniforms) { + this.sandbox.tick() + if(this.detectAudio === true) this.synth.a.tick() + // let updateInterval = 1000/this.synth.fps // ms + if(this.synth.update) { + try { this.synth.update(dt) } catch (e) { console.log(error) } + } + + this.sandbox.set('time', this.synth.time += dt * 0.001 * this.synth.speed) + this.timeSinceLastUpdate += dt + if(!this.synth.fps || this.timeSinceLastUpdate >= 1000/this.synth.fps) { + // console.log(1000/this.timeSinceLastUpdate) + this.synth.stats.fps = Math.ceil(1000/this.timeSinceLastUpdate) + // console.log(this.synth.speed, this.synth.time) + for (let i = 0; i < this.s.length; i++) { + this.s[i].tick(this.synth.time) + } + // console.log(this.canvas.width, this.canvas.height) + for (let i = 0; i < this.o.length; i++) { + this.o[i].tick({ + time: this.synth.time, + mouse: this.synth.mouse, + bpm: this.synth.bpm, + resolution: [this.canvas.width, this.canvas.height] + }) + } + if (this.isRenderingAll) { + this.renderAll({ + tex0: this.o[0].getCurrent(), + tex1: this.o[1].getCurrent(), + tex2: this.o[2].getCurrent(), + tex3: this.o[3].getCurrent(), + resolution: [this.canvas.width, this.canvas.height] + }) + } else { + + this.renderFbo({ + tex0: this.output.getCurrent(), + resolution: [this.canvas.width, this.canvas.height] + }) + } + this.timeSinceLastUpdate = 0 + } + if(this.saveFrame === true) { + this.canvasToImage() + this.saveFrame = false + } + // this.regl.poll() + } + + +} + +module.exports = HydraRenderer + +},{"./src/eval-sandbox.js":76,"./src/generator-factory.js":79,"./src/hydra-source.js":83,"./src/lib/array-utils.js":84,"./src/lib/audio.js":85,"./src/lib/mouse.js":88,"./src/lib/video-recorder.js":91,"./src/output.js":93,"raf-loop":162,"regl":165}],75:[function(require,module,exports){ +const Synth = require('./hydra-synth.js') +//const ShaderGenerator = require('./shader-generator.js') + +module.exports = Synth + +},{"./hydra-synth.js":74}],76:[function(require,module,exports){ +// handles code evaluation and attaching relevant objects to global and evaluation contexts + +const Sandbox = require('./lib/sandbox.js') +const ArrayUtils = require('./lib/array-utils.js') + +class EvalSandbox { + constructor(parent, makeGlobal, userProps = []) { + this.makeGlobal = makeGlobal + this.sandbox = Sandbox(parent) + this.parent = parent + var properties = Object.keys(parent) + properties.forEach((property) => this.add(property)) + this.userProps = userProps + } + + add(name) { + if(this.makeGlobal) window[name] = this.parent[name] + this.sandbox.addToContext(name, `parent.${name}`) + } + +// sets on window as well as synth object if global (not needed for objects, which can be set directly) + + set(property, value) { + if(this.makeGlobal) { + window[property] = value + } + this.parent[property] = value + } + + tick() { + if(this.makeGlobal) { + this.userProps.forEach((property) => { + this.parent[property] = window[property] + }) + // this.parent.speed = window.speed + } else { + + } + } + + eval(code) { + this.sandbox.eval(code) + } +} + +module.exports = EvalSandbox + +},{"./lib/array-utils.js":84,"./lib/sandbox.js":89}],77:[function(require,module,exports){ +const arrayUtils = require('./lib/array-utils.js') + +// [WIP] how to treat different dimensions (?) +const DEFAULT_CONVERSIONS = { + float: { + 'vec4': { name: 'sum', args: [[1, 1, 1, 1]] }, + 'vec2': { name: 'sum', args: [[1, 1]] } + } +} + +function fillArrayWithDefaults(arr, len) { + // fill the array with default values if it's too short + while (arr.length < len) { + if (arr.length === 3) { // push a 1 as the default for .a in vec4 + arr.push(1.0) + } else { + arr.push(0.0) + } + } + return arr.slice(0, len) +} + +const ensure_decimal_dot = (val) => { + val = val.toString() + if (val.indexOf('.') < 0) { + val += '.' + } + return val +} + + + +module.exports = function formatArguments(transform, startIndex, synthContext) { + const defaultArgs = transform.transform.inputs + const userArgs = transform.userArgs + const { generators } = transform.synth + const { src } = generators // depends on synth having src() function + return defaultArgs.map((input, index) => { + const typedArg = { + value: input.default, + type: input.type, // + isUniform: false, + name: input.name, + vecLen: 0 + // generateGlsl: null // function for creating glsl + } + + if (typedArg.type === 'float') typedArg.value = ensure_decimal_dot(input.default) + if (input.type.startsWith('vec')) { + try { + typedArg.vecLen = Number.parseInt(input.type.substr(3)) + } catch (e) { + console.log(`Error determining length of vector input type ${input.type} (${input.name})`) + } + } + + // if user has input something for this argument + if (userArgs.length > index) { + typedArg.value = userArgs[index] + // do something if a composite or transform + + if (typeof userArgs[index] === 'function') { + // if (typedArg.vecLen > 0) { // expected input is a vector, not a scalar + // typedArg.value = (context, props, batchId) => (fillArrayWithDefaults(userArgs[index](props), typedArg.vecLen)) + // } else { + typedArg.value = (context, props, batchId) => { + try { + return userArgs[index](props) + } catch (e) { + console.log('ERROR', e) + return input.default + } + } + // } + + typedArg.isUniform = true + } else if (userArgs[index].constructor === Array) { + // if (typedArg.vecLen > 0) { // expected input is a vector, not a scalar + // typedArg.isUniform = true + // typedArg.value = fillArrayWithDefaults(typedArg.value, typedArg.vecLen) + // } else { + // console.log("is Array") + typedArg.value = (context, props, batchId) => arrayUtils.getValue(userArgs[index])(props) + typedArg.isUniform = true + // } + } + } + + if (startIndex < 0) { + } else { + if (typedArg.value && typedArg.value.transforms) { + const final_transform = typedArg.value.transforms[typedArg.value.transforms.length - 1] + + if (final_transform.transform.glsl_return_type !== input.type) { + const defaults = DEFAULT_CONVERSIONS[input.type] + if (typeof defaults !== 'undefined') { + const default_def = defaults[final_transform.transform.glsl_return_type] + if (typeof default_def !== 'undefined') { + const { name, args } = default_def + typedArg.value = typedArg.value[name](...args) + } } } - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); + typedArg.isUniform = false + } else if (typedArg.type === 'float' && typeof typedArg.value === 'number') { + typedArg.value = ensure_decimal_dot(typedArg.value) + } else if (typedArg.type.startsWith('vec') && typeof typedArg.value === 'object' && Array.isArray(typedArg.value)) { + typedArg.isUniform = false + typedArg.value = `${typedArg.type}(${typedArg.value.map(ensure_decimal_dot).join(', ')})` + } else if (input.type === 'sampler2D') { + // typedArg.tex = typedArg.value + var x = typedArg.value + typedArg.value = () => (x.getTexture()) + typedArg.isUniform = true + } else { + // if passing in a texture reference, when function asks for vec4, convert to vec4 + if (typedArg.value.getTexture && input.type === 'vec4') { + var x1 = typedArg.value + typedArg.value = src(x1) + typedArg.isUniform = false } } - return this; - }; + // add tp uniform array if is a function that will pass in a different value on each render frame, + // or a texture/ external source -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); + if (typedArg.isUniform) { + typedArg.name += startIndex + // shaderParams.uniforms.push(typedArg) + } + } + return typedArg + }) } -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; +},{"./lib/array-utils.js":84}],78:[function(require,module,exports){ +const formatArguments = require('./format-arguments.js') -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); +// Add extra functionality to Array.prototype for generating sequences in time +const arrayUtils = require('./lib/array-utils.js') + + + +// converts a tree of javascript functions to a shader +module.exports = function (transforms) { + var shaderParams = { + uniforms: [], // list of uniforms used in shader + glslFunctions: [], // list of functions used in shader + fragColor: '' + } + + var gen = generateGlsl(transforms, shaderParams)('st') + shaderParams.fragColor = gen + // remove uniforms with duplicate names + let uniforms = {} + shaderParams.uniforms.forEach((uniform) => uniforms[uniform.name] = uniform) + shaderParams.uniforms = Object.values(uniforms) + return shaderParams + +} + + +// recursive function for generating shader string from object containing functions and user arguments. Order of functions in string depends on type of function +// to do: improve variable names +function generateGlsl (transforms, shaderParams) { + // transform function that outputs a shader string corresponding to gl_FragColor + var fragColor = () => '' + // var uniforms = [] + // var glslFunctions = [] + transforms.forEach((transform) => { + var inputs = formatArguments(transform, shaderParams.uniforms.length) + inputs.forEach((input) => { + if(input.isUniform) shaderParams.uniforms.push(input) + }) + + // add new glsl function to running list of functions + if(!contains(transform, shaderParams.glslFunctions)) shaderParams.glslFunctions.push(transform) + + // current function for generating frag color shader code + var f0 = fragColor + if (transform.transform.type === 'src') { + fragColor = (uv) => `${shaderString(uv, transform.name, inputs, shaderParams)}` + } else if (transform.transform.type === 'coord') { + fragColor = (uv) => `${f0(`${shaderString(uv, transform.name, inputs, shaderParams)}`)}` + } else if (transform.transform.type === 'color') { + fragColor = (uv) => `${shaderString(`${f0(uv)}`, transform.name, inputs, shaderParams)}` + } else if (transform.transform.type === 'combine') { + // combining two generated shader strings (i.e. for blend, mult, add funtions) + var f1 = inputs[0].value && inputs[0].value.transforms ? + (uv) => `${generateGlsl(inputs[0].value.transforms, shaderParams)(uv)}` : + (inputs[0].isUniform ? () => inputs[0].name : () => inputs[0].value) + fragColor = (uv) => `${shaderString(`${f0(uv)}, ${f1(uv)}`, transform.name, inputs.slice(1), shaderParams)}` + } else if (transform.transform.type === 'combineCoord') { + // combining two generated shader strings (i.e. for modulate functions) + var f1 = inputs[0].value && inputs[0].value.transforms ? + (uv) => `${generateGlsl(inputs[0].value.transforms, shaderParams)(uv)}` : + (inputs[0].isUniform ? () => inputs[0].name : () => inputs[0].value) + fragColor = (uv) => `${f0(`${shaderString(`${uv}, ${f1(uv)}`, transform.name, inputs.slice(1), shaderParams)}`)}` + + + } + }) +// console.log(fragColor) + // break; + return fragColor +} + +// assembles a shader string containing the arguments and the function name, i.e. 'osc(uv, frequency)' +function shaderString (uv, method, inputs, shaderParams) { + const str = inputs.map((input) => { + if (input.isUniform) { + return input.name + } else if (input.value && input.value.transforms) { + // this by definition needs to be a generator, hence we start with 'st' as the initial value for generating the glsl fragment + return `${generateGlsl(input.value.transforms, shaderParams)('st')}` + } + return input.value + }).reduce((p, c) => `${p}, ${c}`, '') + + return `${method}(${uv}${str})` +} + +// merge two arrays and remove duplicates +function mergeArrays (a, b) { + return a.concat(b.filter(function (item) { + return a.indexOf(item) < 0; + })) +} + +// check whether array +function contains(object, arr) { + for(var i = 0; i < arr.length; i++){ + if(object.name == arr[i].name) return true + } + return false +} + + + + +},{"./format-arguments.js":77,"./lib/array-utils.js":84}],79:[function(require,module,exports){ +const GlslSource = require('./glsl-source.js') + +class GeneratorFactory { + constructor ({ + defaultUniforms, + defaultOutput, + extendTransforms = [], + changeListener = (() => {}) + } = {} + ) { + this.defaultOutput = defaultOutput + this.defaultUniforms = defaultUniforms + this.changeListener = changeListener + this.extendTransforms = extendTransforms + this.generators = {} + this.init() + } + init () { + this.glslTransforms = {} + this.generators = Object.entries(this.generators).reduce((prev, [method, transform]) => { + this.changeListener({type: 'remove', synth: this, method}) + return prev + }, {}) + + this.sourceClass = (() => { + return class extends GlslSource { + } + })() + + let functions = require('./glsl/glsl-functions.js')() + + // add user definied transforms + if (Array.isArray(this.extendTransforms)) { + functions.concat(this.extendTransforms) + } else if (typeof this.extendTransforms === 'object' && this.extendTransforms.type) { + functions.push(this.extendTransforms) + } + + return functions.map((transform) => this.setFunction(transform)) + } + + _addMethod (method, transform) { + const self = this + this.glslTransforms[method] = transform + if (transform.type === 'src') { + const func = (...args) => new this.sourceClass({ + name: method, + transform: transform, + userArgs: args, + defaultOutput: this.defaultOutput, + defaultUniforms: this.defaultUniforms, + synth: self + }) + this.generators[method] = func + this.changeListener({type: 'add', synth: this, method}) + return func + } else { + this.sourceClass.prototype[method] = function (...args) { + this.transforms.push({name: method, transform: transform, userArgs: args, synth: self}) + return this + } + } + return undefined + } + + setFunction(obj) { + var processedGlsl = processGlsl(obj) + if(processedGlsl) this._addMethod(obj.name, processedGlsl) + } +} + +const typeLookup = { + 'src': { + returnType: 'vec4', + args: ['vec2 _st'] + }, + 'coord': { + returnType: 'vec2', + args: ['vec2 _st'] + }, + 'color': { + returnType: 'vec4', + args: ['vec4 _c0'] + }, + 'combine': { + returnType: 'vec4', + args: ['vec4 _c0', 'vec4 _c1'] + }, + 'combineCoord': { + returnType: 'vec2', + args: ['vec2 _st', 'vec4 _c0'] + } +} +// expects glsl of format +// { +// name: 'osc', // name that will be used to access function as well as within glsl +// type: 'src', // can be src: vec4(vec2 _st), coord: vec2(vec2 _st), color: vec4(vec4 _c0), combine: vec4(vec4 _c0, vec4 _c1), combineCoord: vec2(vec2 _st, vec4 _c0) +// inputs: [ +// { +// name: 'freq', +// type: 'float', // 'float' //, 'texture', 'vec4' +// default: 0.2 +// }, +// { +// name: 'sync', +// type: 'float', +// default: 0.1 +// }, +// { +// name: 'offset', +// type: 'float', +// default: 0.0 +// } +// ], + // glsl: ` + // vec2 st = _st; + // float r = sin((st.x-offset*2/freq+time*sync)*freq)*0.5 + 0.5; + // float g = sin((st.x+time*sync)*freq)*0.5 + 0.5; + // float b = sin((st.x+offset/freq+time*sync)*freq)*0.5 + 0.5; + // return vec4(r, g, b, 1.0); + // ` +// } + +// // generates glsl function: +// `vec4 osc(vec2 _st, float freq, float sync, float offset){ +// vec2 st = _st; +// float r = sin((st.x-offset*2/freq+time*sync)*freq)*0.5 + 0.5; +// float g = sin((st.x+time*sync)*freq)*0.5 + 0.5; +// float b = sin((st.x+offset/freq+time*sync)*freq)*0.5 + 0.5; +// return vec4(r, g, b, 1.0); +// }` + +function processGlsl(obj) { + let t = typeLookup[obj.type] + if(t) { + let baseArgs = t.args.map((arg) => arg).join(", ") + // @todo: make sure this works for all input types, add validation + let customArgs = obj.inputs.map((input) => `${input.type} ${input.name}`).join(', ') + let args = `${baseArgs}${customArgs.length > 0 ? ', '+ customArgs: ''}` +// console.log('args are ', args) + + let glslFunction = +` + ${t.returnType} ${obj.name}(${args}) { + ${obj.glsl} + } +` + + // add extra input to beginning for backward combatibility @todo update compiler so this is no longer necessary + if(obj.type === 'combine' || obj.type === 'combineCoord') obj.inputs.unshift({ + name: 'color', + type: 'vec4' + }) + return Object.assign({}, obj, { glsl: glslFunction}) } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } + console.warn(`type ${obj.type} not recognized`, obj) } - return 0; } -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; +module.exports = GeneratorFactory -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; +},{"./glsl-source.js":80,"./glsl/glsl-functions.js":81}],80:[function(require,module,exports){ +const generateGlsl = require('./generate-glsl.js') +// const formatArguments = require('./glsl-utils.js').formatArguments + +// const glslTransforms = require('./glsl/composable-glsl-functions.js') +const utilityGlsl = require('./glsl/utility-functions.js') + +var GlslSource = function (obj) { + this.transforms = [] + this.transforms.push(obj) + this.defaultOutput = obj.defaultOutput + this.synth = obj.synth + this.type = 'GlslSource' + this.defaultUniforms = obj.defaultUniforms + return this } -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); +GlslSource.prototype.addTransform = function (obj) { + this.transforms.push(obj) } -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - -function once(emitter, name) { - return new Promise(function (resolve, reject) { - function errorListener(err) { - emitter.removeListener(name, resolver); - reject(err); - } - - function resolver() { - if (typeof emitter.removeListener === 'function') { - emitter.removeListener('error', errorListener); - } - resolve([].slice.call(arguments)); - }; - - eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); - if (name !== 'error') { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); - } - }); -} - -function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === 'function') { - eventTargetAgnosticAddListener(emitter, 'error', handler, flags); +GlslSource.prototype.out = function (_output) { + var output = _output || this.defaultOutput + var glsl = this.glsl(output) + this.synth.currentFunctions = [] + // output.renderPasses(glsl) + if(output) try{ + output.render(glsl) + } catch (error) { + console.log('shader could not compile', error) } } -function eventTargetAgnosticAddListener(emitter, name, listener, flags) { - if (typeof emitter.on === 'function') { - if (flags.once) { - emitter.once(name, listener); +GlslSource.prototype.glsl = function () { + //var output = _output || this.defaultOutput + var self = this + // uniforms included in all shaders +// this.defaultUniforms = output.uniforms + var passes = [] + var transforms = [] +// console.log('output', output) + this.transforms.forEach((transform) => { + if(transform.transform.type === 'renderpass'){ + // if (transforms.length > 0) passes.push(this.compile(transforms, output)) + // transforms = [] + // var uniforms = {} + // const inputs = formatArguments(transform, -1) + // inputs.forEach((uniform) => { uniforms[uniform.name] = uniform.value }) + // + // passes.push({ + // frag: transform.transform.frag, + // uniforms: Object.assign({}, self.defaultUniforms, uniforms) + // }) + // transforms.push({name: 'prev', transform: glslTransforms['prev'], synth: this.synth}) + console.warn('no support for renderpass') } else { - emitter.on(name, listener); + transforms.push(transform) } - } else if (typeof emitter.addEventListener === 'function') { - // EventTarget does not have `error` event semantics like Node - // EventEmitters, we do not listen for `error` events here. - emitter.addEventListener(name, function wrapListener(arg) { - // IE does not have builtin `{ once: true }` support so we - // have to do it manually. - if (flags.once) { - emitter.removeEventListener(name, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + }) + + if (transforms.length > 0) passes.push(this.compile(transforms)) + + return passes +} + +GlslSource.prototype.compile = function (transforms) { + var shaderInfo = generateGlsl(transforms, this.synth) + var uniforms = {} + shaderInfo.uniforms.forEach((uniform) => { uniforms[uniform.name] = uniform.value }) + + var frag = ` + precision ${this.defaultOutput.precision} float; + ${Object.values(shaderInfo.uniforms).map((uniform) => { + let type = uniform.type + switch (uniform.type) { + case 'texture': + type = 'sampler2D' + break + } + return ` + uniform ${type} ${uniform.name};` + }).join('')} + uniform float time; + uniform vec2 resolution; + varying vec2 uv; + uniform sampler2D prevBuffer; + + ${Object.values(utilityGlsl).map((transform) => { + // console.log(transform.glsl) + return ` + ${transform.glsl} + ` + }).join('')} + + ${shaderInfo.glslFunctions.map((transform) => { + return ` + ${transform.transform.glsl} + ` + }).join('')} + + void main () { + vec4 c = vec4(1, 0, 0, 1); + vec2 st = gl_FragCoord.xy/resolution.xy; + gl_FragColor = ${shaderInfo.fragColor}; + } + ` + + return { + frag: frag, + uniforms: Object.assign({}, this.defaultUniforms, uniforms) + } + +} + +module.exports = GlslSource + +},{"./generate-glsl.js":78,"./glsl/utility-functions.js":82}],81:[function(require,module,exports){ +/* +Format for adding functions to hydra. For each entry in this file, hydra automatically generates a glsl function and javascript function with the same name. You can also ass functions dynamically using setFunction(object). + +{ + name: 'osc', // name that will be used to access function in js as well as in glsl + type: 'src', // can be 'src', 'color', 'combine', 'combineCoords'. see below for more info + inputs: [ + { + name: 'freq', + type: 'float', + default: 0.2 + }, + { + name: 'sync', + type: 'float', + default: 0.1 + }, + { + name: 'offset', + type: 'float', + default: 0.0 + } + ], + glsl: ` + vec2 st = _st; + float r = sin((st.x-offset*2/freq+time*sync)*freq)*0.5 + 0.5; + float g = sin((st.x+time*sync)*freq)*0.5 + 0.5; + float b = sin((st.x+offset/freq+time*sync)*freq)*0.5 + 0.5; + return vec4(r, g, b, 1.0); + ` +} + +// The above code generates the glsl function: +`vec4 osc(vec2 _st, float freq, float sync, float offset){ + vec2 st = _st; + float r = sin((st.x-offset*2/freq+time*sync)*freq)*0.5 + 0.5; + float g = sin((st.x+time*sync)*freq)*0.5 + 0.5; + float b = sin((st.x+offset/freq+time*sync)*freq)*0.5 + 0.5; + return vec4(r, g, b, 1.0); +}` + + +Types and default arguments for hydra functions. +The value in the 'type' field lets the parser know which type the function will be returned as well as default arguments. + +const types = { + 'src': { + returnType: 'vec4', + args: ['vec2 _st'] + }, + 'coord': { + returnType: 'vec2', + args: ['vec2 _st'] + }, + 'color': { + returnType: 'vec4', + args: ['vec4 _c0'] + }, + 'combine': { + returnType: 'vec4', + args: ['vec4 _c0', 'vec4 _c1'] + }, + 'combineCoord': { + returnType: 'vec2', + args: ['vec2 _st', 'vec4 _c0'] } } -},{}],155:[function(require,module,exports){ +*/ + +module.exports = () => [ + { + name: 'noise', + type: 'src', + inputs: [ + { + type: 'float', + name: 'scale', + default: 10, + }, +{ + type: 'float', + name: 'offset', + default: 0.1, + } + ], + glsl: +` return vec4(vec3(_noise(vec3(_st*scale, offset*time))), 1.0);` +}, +{ + name: 'voronoi', + type: 'src', + inputs: [ + { + type: 'float', + name: 'scale', + default: 5, + }, +{ + type: 'float', + name: 'speed', + default: 0.3, + }, +{ + type: 'float', + name: 'blending', + default: 0.3, + } + ], + glsl: +` vec3 color = vec3(.0); + // Scale + _st *= scale; + // Tile the space + vec2 i_st = floor(_st); + vec2 f_st = fract(_st); + float m_dist = 10.; // minimun distance + vec2 m_point; // minimum point + for (int j=-1; j<=1; j++ ) { + for (int i=-1; i<=1; i++ ) { + vec2 neighbor = vec2(float(i),float(j)); + vec2 p = i_st + neighbor; + vec2 point = fract(sin(vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3))))*43758.5453); + point = 0.5 + 0.5*sin(time*speed + 6.2831*point); + vec2 diff = neighbor + point - f_st; + float dist = length(diff); + if( dist < m_dist ) { + m_dist = dist; + m_point = point; + } + } + } + // Assign a color using the closest point position + color += dot(m_point,vec2(.3,.6)); + color *= 1.0 - blending*m_dist; + return vec4(color, 1.0);` +}, +{ + name: 'osc', + type: 'src', + inputs: [ + { + type: 'float', + name: 'frequency', + default: 60, + }, +{ + type: 'float', + name: 'sync', + default: 0.1, + }, +{ + type: 'float', + name: 'offset', + default: 0, + } + ], + glsl: +` vec2 st = _st; + float r = sin((st.x-offset/frequency+time*sync)*frequency)*0.5 + 0.5; + float g = sin((st.x+time*sync)*frequency)*0.5 + 0.5; + float b = sin((st.x+offset/frequency+time*sync)*frequency)*0.5 + 0.5; + return vec4(r, g, b, 1.0);` +}, +{ + name: 'shape', + type: 'src', + inputs: [ + { + type: 'float', + name: 'sides', + default: 3, + }, +{ + type: 'float', + name: 'radius', + default: 0.3, + }, +{ + type: 'float', + name: 'smoothing', + default: 0.01, + } + ], + glsl: +` vec2 st = _st * 2. - 1.; + // Angle and radius from the current pixel + float a = atan(st.x,st.y)+3.1416; + float r = (2.*3.1416)/sides; + float d = cos(floor(.5+a/r)*r-a)*length(st); + return vec4(vec3(1.0-smoothstep(radius,radius + smoothing + 0.0000001,d)), 1.0);` +}, +{ + name: 'gradient', + type: 'src', + inputs: [ + { + type: 'float', + name: 'speed', + default: 0, + } + ], + glsl: +` return vec4(_st, sin(time*speed), 1.0);` +}, +{ + name: 'src', + type: 'src', + inputs: [ + { + type: 'sampler2D', + name: 'tex', + default: NaN, + } + ], + glsl: +` // vec2 uv = gl_FragCoord.xy/vec2(1280., 720.); + return texture2D(tex, fract(_st));` +}, +{ + name: 'solid', + type: 'src', + inputs: [ + { + type: 'float', + name: 'r', + default: 0, + }, +{ + type: 'float', + name: 'g', + default: 0, + }, +{ + type: 'float', + name: 'b', + default: 0, + }, +{ + type: 'float', + name: 'a', + default: 1, + } + ], + glsl: +` return vec4(r, g, b, a);` +}, +{ + name: 'rotate', + type: 'coord', + inputs: [ + { + type: 'float', + name: 'angle', + default: 10, + }, +{ + type: 'float', + name: 'speed', + default: 0, + } + ], + glsl: +` vec2 xy = _st - vec2(0.5); + float ang = angle + speed *time; + xy = mat2(cos(ang),-sin(ang), sin(ang),cos(ang))*xy; + xy += 0.5; + return xy;` +}, +{ + name: 'scale', + type: 'coord', + inputs: [ + { + type: 'float', + name: 'amount', + default: 1.5, + }, +{ + type: 'float', + name: 'xMult', + default: 1, + }, +{ + type: 'float', + name: 'yMult', + default: 1, + }, +{ + type: 'float', + name: 'offsetX', + default: 0.5, + }, +{ + type: 'float', + name: 'offsetY', + default: 0.5, + } + ], + glsl: +` vec2 xy = _st - vec2(offsetX, offsetY); + xy*=(1.0/vec2(amount*xMult, amount*yMult)); + xy+=vec2(offsetX, offsetY); + return xy; + ` +}, +{ + name: 'pixelate', + type: 'coord', + inputs: [ + { + type: 'float', + name: 'pixelX', + default: 20, + }, +{ + type: 'float', + name: 'pixelY', + default: 20, + } + ], + glsl: +` vec2 xy = vec2(pixelX, pixelY); + return (floor(_st * xy) + 0.5)/xy;` +}, +{ + name: 'posterize', + type: 'color', + inputs: [ + { + type: 'float', + name: 'bins', + default: 3, + }, +{ + type: 'float', + name: 'gamma', + default: 0.6, + } + ], + glsl: +` vec4 c2 = pow(_c0, vec4(gamma)); + c2 *= vec4(bins); + c2 = floor(c2); + c2/= vec4(bins); + c2 = pow(c2, vec4(1.0/gamma)); + return vec4(c2.xyz, _c0.a);` +}, +{ + name: 'shift', + type: 'color', + inputs: [ + { + type: 'float', + name: 'r', + default: 0.5, + }, +{ + type: 'float', + name: 'g', + default: 0, + }, +{ + type: 'float', + name: 'b', + default: 0, + }, +{ + type: 'float', + name: 'a', + default: 0, + } + ], + glsl: +` vec4 c2 = vec4(_c0); + c2.r = fract(c2.r + r); + c2.g = fract(c2.g + g); + c2.b = fract(c2.b + b); + c2.a = fract(c2.a + a); + return vec4(c2.rgba);` +}, +{ + name: 'repeat', + type: 'coord', + inputs: [ + { + type: 'float', + name: 'repeatX', + default: 3, + }, +{ + type: 'float', + name: 'repeatY', + default: 3, + }, +{ + type: 'float', + name: 'offsetX', + default: 0, + }, +{ + type: 'float', + name: 'offsetY', + default: 0, + } + ], + glsl: +` vec2 st = _st * vec2(repeatX, repeatY); + st.x += step(1., mod(st.y,2.0)) * offsetX; + st.y += step(1., mod(st.x,2.0)) * offsetY; + return fract(st);` +}, +{ + name: 'modulateRepeat', + type: 'combineCoord', + inputs: [ + { + type: 'float', + name: 'repeatX', + default: 3, + }, +{ + type: 'float', + name: 'repeatY', + default: 3, + }, +{ + type: 'float', + name: 'offsetX', + default: 0.5, + }, +{ + type: 'float', + name: 'offsetY', + default: 0.5, + } + ], + glsl: +` vec2 st = _st * vec2(repeatX, repeatY); + st.x += step(1., mod(st.y,2.0)) + _c0.r * offsetX; + st.y += step(1., mod(st.x,2.0)) + _c0.g * offsetY; + return fract(st);` +}, +{ + name: 'repeatX', + type: 'coord', + inputs: [ + { + type: 'float', + name: 'reps', + default: 3, + }, +{ + type: 'float', + name: 'offset', + default: 0, + } + ], + glsl: +` vec2 st = _st * vec2(reps, 1.0); + // float f = mod(_st.y,2.0); + st.y += step(1., mod(st.x,2.0))* offset; + return fract(st);` +}, +{ + name: 'modulateRepeatX', + type: 'combineCoord', + inputs: [ + { + type: 'float', + name: 'reps', + default: 3, + }, +{ + type: 'float', + name: 'offset', + default: 0.5, + } + ], + glsl: +` vec2 st = _st * vec2(reps, 1.0); + // float f = mod(_st.y,2.0); + st.y += step(1., mod(st.x,2.0)) + _c0.r * offset; + return fract(st);` +}, +{ + name: 'repeatY', + type: 'coord', + inputs: [ + { + type: 'float', + name: 'reps', + default: 3, + }, +{ + type: 'float', + name: 'offset', + default: 0, + } + ], + glsl: +` vec2 st = _st * vec2(1.0, reps); + // float f = mod(_st.y,2.0); + st.x += step(1., mod(st.y,2.0))* offset; + return fract(st);` +}, +{ + name: 'modulateRepeatY', + type: 'combineCoord', + inputs: [ + { + type: 'float', + name: 'reps', + default: 3, + }, +{ + type: 'float', + name: 'offset', + default: 0.5, + } + ], + glsl: +` vec2 st = _st * vec2(reps, 1.0); + // float f = mod(_st.y,2.0); + st.x += step(1., mod(st.y,2.0)) + _c0.r * offset; + return fract(st);` +}, +{ + name: 'kaleid', + type: 'coord', + inputs: [ + { + type: 'float', + name: 'nSides', + default: 4, + } + ], + glsl: +` vec2 st = _st; + st -= 0.5; + float r = length(st); + float a = atan(st.y, st.x); + float pi = 2.*3.1416; + a = mod(a,pi/nSides); + a = abs(a-pi/nSides/2.); + return r*vec2(cos(a), sin(a));` +}, +{ + name: 'modulateKaleid', + type: 'combineCoord', + inputs: [ + { + type: 'float', + name: 'nSides', + default: 4, + } + ], + glsl: +` vec2 st = _st - 0.5; + float r = length(st); + float a = atan(st.y, st.x); + float pi = 2.*3.1416; + a = mod(a,pi/nSides); + a = abs(a-pi/nSides/2.); + return (_c0.r+r)*vec2(cos(a), sin(a));` +}, +{ + name: 'scroll', + type: 'coord', + inputs: [ + { + type: 'float', + name: 'scrollX', + default: 0.5, + }, +{ + type: 'float', + name: 'scrollY', + default: 0.5, + }, +{ + type: 'float', + name: 'speedX', + default: 0, + }, +{ + type: 'float', + name: 'speedY', + default: 0, + } + ], + glsl: +` + _st.x += scrollX + time*speedX; + _st.y += scrollY + time*speedY; + return fract(_st);` +}, +{ + name: 'scrollX', + type: 'coord', + inputs: [ + { + type: 'float', + name: 'scrollX', + default: 0.5, + }, +{ + type: 'float', + name: 'speed', + default: 0, + } + ], + glsl: +` _st.x += scrollX + time*speed; + return fract(_st);` +}, +{ + name: 'modulateScrollX', + type: 'combineCoord', + inputs: [ + { + type: 'float', + name: 'scrollX', + default: 0.5, + }, +{ + type: 'float', + name: 'speed', + default: 0, + } + ], + glsl: +` _st.x += _c0.r*scrollX + time*speed; + return fract(_st);` +}, +{ + name: 'scrollY', + type: 'coord', + inputs: [ + { + type: 'float', + name: 'scrollY', + default: 0.5, + }, +{ + type: 'float', + name: 'speed', + default: 0, + } + ], + glsl: +` _st.y += scrollY + time*speed; + return fract(_st);` +}, +{ + name: 'modulateScrollY', + type: 'combineCoord', + inputs: [ + { + type: 'float', + name: 'scrollY', + default: 0.5, + }, +{ + type: 'float', + name: 'speed', + default: 0, + } + ], + glsl: +` _st.y += _c0.r*scrollY + time*speed; + return fract(_st);` +}, +{ + name: 'add', + type: 'combine', + inputs: [ + { + type: 'float', + name: 'amount', + default: 1, + } + ], + glsl: +` return (_c0+_c1)*amount + _c0*(1.0-amount);` +}, +{ + name: 'sub', + type: 'combine', + inputs: [ + { + type: 'float', + name: 'amount', + default: 1, + } + ], + glsl: +` return (_c0-_c1)*amount + _c0*(1.0-amount);` +}, +{ + name: 'layer', + type: 'combine', + inputs: [ + + ], + glsl: +` return vec4(mix(_c0.rgb, _c1.rgb, _c1.a), clamp(_c0.a + _c1.a, 0.0, 1.0));` +}, +{ + name: 'blend', + type: 'combine', + inputs: [ + { + type: 'float', + name: 'amount', + default: 0.5, + } + ], + glsl: +` return _c0*(1.0-amount)+_c1*amount;` +}, +{ + name: 'mult', + type: 'combine', + inputs: [ + { + type: 'float', + name: 'amount', + default: 1, + } + ], + glsl: +` return _c0*(1.0-amount)+(_c0*_c1)*amount;` +}, +{ + name: 'diff', + type: 'combine', + inputs: [ + + ], + glsl: +` return vec4(abs(_c0.rgb-_c1.rgb), max(_c0.a, _c1.a));` +}, +{ + name: 'modulate', + type: 'combineCoord', + inputs: [ + { + type: 'float', + name: 'amount', + default: 0.1, + } + ], + glsl: +` // return fract(st+(_c0.xy-0.5)*amount); + return _st + _c0.xy*amount;` +}, +{ + name: 'modulateScale', + type: 'combineCoord', + inputs: [ + { + type: 'float', + name: 'multiple', + default: 1, + }, +{ + type: 'float', + name: 'offset', + default: 1, + } + ], + glsl: +` vec2 xy = _st - vec2(0.5); + xy*=(1.0/vec2(offset + multiple*_c0.r, offset + multiple*_c0.g)); + xy+=vec2(0.5); + return xy;` +}, +{ + name: 'modulatePixelate', + type: 'combineCoord', + inputs: [ + { + type: 'float', + name: 'multiple', + default: 10, + }, +{ + type: 'float', + name: 'offset', + default: 3, + } + ], + glsl: +` vec2 xy = vec2(offset + _c0.x*multiple, offset + _c0.y*multiple); + return (floor(_st * xy) + 0.5)/xy;` +}, +{ + name: 'modulateRotate', + type: 'combineCoord', + inputs: [ + { + type: 'float', + name: 'multiple', + default: 1, + }, +{ + type: 'float', + name: 'offset', + default: 0, + } + ], + glsl: +` vec2 xy = _st - vec2(0.5); + float angle = offset + _c0.x * multiple; + xy = mat2(cos(angle),-sin(angle), sin(angle),cos(angle))*xy; + xy += 0.5; + return xy;` +}, +{ + name: 'modulateHue', + type: 'combineCoord', + inputs: [ + { + type: 'float', + name: 'amount', + default: 1, + } + ], + glsl: +` return _st + (vec2(_c0.g - _c0.r, _c0.b - _c0.g) * amount * 1.0/resolution);` +}, +{ + name: 'invert', + type: 'color', + inputs: [ + { + type: 'float', + name: 'amount', + default: 1, + } + ], + glsl: +` return vec4((1.0-_c0.rgb)*amount + _c0.rgb*(1.0-amount), _c0.a);` +}, +{ + name: 'contrast', + type: 'color', + inputs: [ + { + type: 'float', + name: 'amount', + default: 1.6, + } + ], + glsl: +` vec4 c = (_c0-vec4(0.5))*vec4(amount) + vec4(0.5); + return vec4(c.rgb, _c0.a);` +}, +{ + name: 'brightness', + type: 'color', + inputs: [ + { + type: 'float', + name: 'amount', + default: 0.4, + } + ], + glsl: +` return vec4(_c0.rgb + vec3(amount), _c0.a);` +}, +{ + name: 'mask', + type: 'combine', + inputs: [ + + ], + glsl: + ` float a = _luminance(_c1.rgb); + return vec4(_c0.rgb*a, a*_c0.a);` +}, + +{ + name: 'luma', + type: 'color', + inputs: [ + { + type: 'float', + name: 'threshold', + default: 0.5, + }, +{ + type: 'float', + name: 'tolerance', + default: 0.1, + } + ], + glsl: +` float a = smoothstep(threshold-(tolerance+0.0000001), threshold+(tolerance+0.0000001), _luminance(_c0.rgb)); + return vec4(_c0.rgb*a, a);` +}, +{ + name: 'thresh', + type: 'color', + inputs: [ + { + type: 'float', + name: 'threshold', + default: 0.5, + }, +{ + type: 'float', + name: 'tolerance', + default: 0.04, + } + ], + glsl: +` return vec4(vec3(smoothstep(threshold-(tolerance+0.0000001), threshold+(tolerance+0.0000001), _luminance(_c0.rgb))), _c0.a);` +}, +{ + name: 'color', + type: 'color', + inputs: [ + { + type: 'float', + name: 'r', + default: 1, + }, +{ + type: 'float', + name: 'g', + default: 1, + }, +{ + type: 'float', + name: 'b', + default: 1, + }, +{ + type: 'float', + name: 'a', + default: 1, + } + ], + glsl: +` vec4 c = vec4(r, g, b, a); + vec4 pos = step(0.0, c); // detect whether negative + // if > 0, return r * _c0 + // if < 0 return (1.0-r) * _c0 + return vec4(mix((1.0-_c0)*abs(c), c*_c0, pos));` +}, +{ + name: 'saturate', + type: 'color', + inputs: [ + { + type: 'float', + name: 'amount', + default: 2, + } + ], + glsl: +` const vec3 W = vec3(0.2125, 0.7154, 0.0721); + vec3 intensity = vec3(dot(_c0.rgb, W)); + return vec4(mix(intensity, _c0.rgb, amount), _c0.a);` +}, +{ + name: 'hue', + type: 'color', + inputs: [ + { + type: 'float', + name: 'hue', + default: 0.4, + } + ], + glsl: +` vec3 c = _rgbToHsv(_c0.rgb); + c.r += hue; + // c.r = fract(c.r); + return vec4(_hsvToRgb(c), _c0.a);` +}, +{ + name: 'colorama', + type: 'color', + inputs: [ + { + type: 'float', + name: 'amount', + default: 0.005, + } + ], + glsl: +` vec3 c = _rgbToHsv(_c0.rgb); + c += vec3(amount); + c = _hsvToRgb(c); + c = fract(c); + return vec4(c, _c0.a);` +}, +{ + name: 'prev', + type: 'src', + inputs: [ + + ], + glsl: +` return texture2D(prevBuffer, fract(_st));` +}, +{ + name: 'sum', + type: 'color', + inputs: [ + { + type: 'vec4', + name: 'scale', + default: 1, + } + ], + glsl: +` vec4 v = _c0 * s; + return v.r + v.g + v.b + v.a; + } + float sum(vec2 _st, vec4 s) { // vec4 is not a typo, because argument type is not overloaded + vec2 v = _st.xy * s.xy; + return v.x + v.y;` +}, +{ + name: 'r', + type: 'color', + inputs: [ + { + type: 'float', + name: 'scale', + default: 1, + }, +{ + type: 'float', + name: 'offset', + default: 0, + } + ], + glsl: +` return vec4(_c0.r * scale + offset);` +}, +{ + name: 'g', + type: 'color', + inputs: [ + { + type: 'float', + name: 'scale', + default: 1, + }, +{ + type: 'float', + name: 'offset', + default: 0, + } + ], + glsl: +` return vec4(_c0.g * scale + offset);` +}, +{ + name: 'b', + type: 'color', + inputs: [ + { + type: 'float', + name: 'scale', + default: 1, + }, +{ + type: 'float', + name: 'offset', + default: 0, + } + ], + glsl: +` return vec4(_c0.b * scale + offset);` +}, +{ + name: 'a', + type: 'color', + inputs: [ + { + type: 'float', + name: 'scale', + default: 1, + }, +{ + type: 'float', + name: 'offset', + default: 0, + } + ], + glsl: +` return vec4(_c0.a * scale + offset);` +} +] + +},{}],82:[function(require,module,exports){ +// functions that are only used within other functions + +module.exports = { + _luminance: { + type: 'util', + glsl: `float _luminance(vec3 rgb){ + const vec3 W = vec3(0.2125, 0.7154, 0.0721); + return dot(rgb, W); + }` + }, + _noise: { + type: 'util', + glsl: ` + // Simplex 3D Noise + // by Ian McEwan, Ashima Arts + vec4 permute(vec4 x){return mod(((x*34.0)+1.0)*x, 289.0);} + vec4 taylorInvSqrt(vec4 r){return 1.79284291400159 - 0.85373472095314 * r;} + + float _noise(vec3 v){ + const vec2 C = vec2(1.0/6.0, 1.0/3.0) ; + const vec4 D = vec4(0.0, 0.5, 1.0, 2.0); + + // First corner + vec3 i = floor(v + dot(v, C.yyy) ); + vec3 x0 = v - i + dot(i, C.xxx) ; + + // Other corners + vec3 g = step(x0.yzx, x0.xyz); + vec3 l = 1.0 - g; + vec3 i1 = min( g.xyz, l.zxy ); + vec3 i2 = max( g.xyz, l.zxy ); + + // x0 = x0 - 0. + 0.0 * C + vec3 x1 = x0 - i1 + 1.0 * C.xxx; + vec3 x2 = x0 - i2 + 2.0 * C.xxx; + vec3 x3 = x0 - 1. + 3.0 * C.xxx; + + // Permutations + i = mod(i, 289.0 ); + vec4 p = permute( permute( permute( + i.z + vec4(0.0, i1.z, i2.z, 1.0 )) + + i.y + vec4(0.0, i1.y, i2.y, 1.0 )) + + i.x + vec4(0.0, i1.x, i2.x, 1.0 )); + + // Gradients + // ( N*N points uniformly over a square, mapped onto an octahedron.) + float n_ = 1.0/7.0; // N=7 + vec3 ns = n_ * D.wyz - D.xzx; + + vec4 j = p - 49.0 * floor(p * ns.z *ns.z); // mod(p,N*N) + + vec4 x_ = floor(j * ns.z); + vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N) + + vec4 x = x_ *ns.x + ns.yyyy; + vec4 y = y_ *ns.x + ns.yyyy; + vec4 h = 1.0 - abs(x) - abs(y); + + vec4 b0 = vec4( x.xy, y.xy ); + vec4 b1 = vec4( x.zw, y.zw ); + + vec4 s0 = floor(b0)*2.0 + 1.0; + vec4 s1 = floor(b1)*2.0 + 1.0; + vec4 sh = -step(h, vec4(0.0)); + + vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ; + vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ; + + vec3 p0 = vec3(a0.xy,h.x); + vec3 p1 = vec3(a0.zw,h.y); + vec3 p2 = vec3(a1.xy,h.z); + vec3 p3 = vec3(a1.zw,h.w); + + //Normalise gradients + vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3))); + p0 *= norm.x; + p1 *= norm.y; + p2 *= norm.z; + p3 *= norm.w; + + // Mix final noise value + vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0); + m = m * m; + return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1), + dot(p2,x2), dot(p3,x3) ) ); + } + ` + }, + + + _rgbToHsv: { + type: 'util', + glsl: `vec3 _rgbToHsv(vec3 c){ + vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); + vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)); + vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); + + float d = q.x - min(q.w, q.y); + float e = 1.0e-10; + return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); + }` + }, + _hsvToRgb: { + type: 'util', + glsl: `vec3 _hsvToRgb(vec3 c){ + vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); + return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); + }` + } +} + +},{}],83:[function(require,module,exports){ +const Webcam = require('./lib/webcam.js') +const Screen = require('./lib/screenmedia.js') + +class HydraSource { + constructor ({ regl, width, height, pb, label = ""}) { + this.label = label + this.regl = regl + this.src = null + this.dynamic = true + this.width = width + this.height = height + this.tex = this.regl.texture({ + // shape: [width, height] + shape: [ 1, 1 ] + }) + this.pb = pb + } + + init (opts, params) { + if ('src' in opts) { + this.src = opts.src + this.tex = this.regl.texture({ data: this.src, ...params }) + } + if ('dynamic' in opts) this.dynamic = opts.dynamic + } + + initCam (index, params) { + const self = this + Webcam(index) + .then(response => { + self.src = response.video + self.dynamic = true + self.tex = self.regl.texture({ data: self.src, ...params }) + }) + .catch(err => console.log('could not get camera', err)) + } + + initVideo (url = '', params) { + // const self = this + const vid = document.createElement('video') + vid.crossOrigin = 'anonymous' + vid.autoplay = true + vid.loop = true + vid.muted = true // mute in order to load without user interaction + const onload = vid.addEventListener('loadeddata', () => { + this.src = vid + vid.play() + this.tex = this.regl.texture({ data: this.src, ...params}) + this.dynamic = true + }) + vid.src = url + } + + initImage (url = '', params) { + const img = document.createElement('img') + img.crossOrigin = 'anonymous' + img.src = url + img.onload = () => { + this.src = img + this.dynamic = false + this.tex = this.regl.texture({ data: this.src, ...params}) + } + } + + initStream (streamName, params) { + // console.log("initing stream!", streamName) + let self = this + if (streamName && this.pb) { + this.pb.initSource(streamName) + + this.pb.on('got video', function (nick, video) { + if (nick === streamName) { + self.src = video + self.dynamic = true + self.tex = self.regl.texture({ data: self.src, ...params}) + } + }) + } + } + + // index only relevant in atom-hydra + desktop apps + initScreen (index = 0, params) { + const self = this + Screen() + .then(function (response) { + self.src = response.video + self.tex = self.regl.texture({ data: self.src, ...params}) + self.dynamic = true + // console.log("received screen input") + }) + .catch(err => console.log('could not get screen', err)) + } + + resize (width, height) { + this.width = width + this.height = height + } + + clear () { + if (this.src && this.src.srcObject) { + if (this.src.srcObject.getTracks) { + this.src.srcObject.getTracks().forEach(track => track.stop()) + } + } + this.src = null + this.tex = this.regl.texture({ shape: [ 1, 1 ] }) + } + + tick (time) { + // console.log(this.src, this.tex.width, this.tex.height) + if (this.src !== null && this.dynamic === true) { + if (this.src.videoWidth && this.src.videoWidth !== this.tex.width) { + console.log( + this.src.videoWidth, + this.src.videoHeight, + this.tex.width, + this.tex.height + ) + this.tex.resize(this.src.videoWidth, this.src.videoHeight) + } + + if (this.src.width && this.src.width !== this.tex.width) { + this.tex.resize(this.src.width, this.src.height) + } + + this.tex.subimage(this.src) + } + } + + getTexture () { + return this.tex + } +} + +module.exports = HydraSource + +},{"./lib/screenmedia.js":90,"./lib/webcam.js":92}],84:[function(require,module,exports){ +// WIP utils for working with arrays +// Possibly should be integrated with lfo extension, etc. +// to do: transform time rather than array values, similar to working with coordinates in hydra + +var easing = require('./easing-functions.js') + +var map = (num, in_min, in_max, out_min, out_max) => { + return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; +} + +module.exports = { + init: () => { + + Array.prototype.fast = function(speed = 1) { + this._speed = speed + return this + } + + Array.prototype.smooth = function(smooth = 1) { + this._smooth = smooth + return this + } + + Array.prototype.ease = function(ease = 'linear') { + if (typeof ease == 'function') { + this._smooth = 1 + this._ease = ease + } + else if (easing[ease]){ + this._smooth = 1 + this._ease = easing[ease] + } + return this + } + + Array.prototype.offset = function(offset = 0.5) { + this._offset = offset%1.0 + return this + } + + // Array.prototype.bounce = function() { + // this.modifiers.bounce = true + // return this + // } + + Array.prototype.fit = function(low = 0, high =1) { + let lowest = Math.min(...this) + let highest = Math.max(...this) + var newArr = this.map((num) => map(num, lowest, highest, low, high)) + newArr._speed = this._speed + newArr._smooth = this._smooth + newArr._ease = this._ease + return newArr + } + }, + + getValue: (arr = []) => ({time, bpm}) =>{ + let speed = arr._speed ? arr._speed : 1 + let smooth = arr._smooth ? arr._smooth : 0 + let index = time * speed * (bpm / 60) + (arr._offset || 0) + + if (smooth!==0) { + let ease = arr._ease ? arr._ease : easing['linear'] + let _index = index - (smooth / 2) + let currValue = arr[Math.floor(_index % (arr.length))] + let nextValue = arr[Math.floor((_index + 1) % (arr.length))] + let t = Math.min((_index%1)/smooth,1) + return ease(t) * (nextValue - currValue) + currValue + } + else { + return arr[Math.floor(index % (arr.length))] + } + } +} + +},{"./easing-functions.js":86}],85:[function(require,module,exports){ +const Meyda = require('meyda') + +class Audio { + constructor ({ + numBins = 4, + cutoff = 2, + smooth = 0.4, + max = 15, + scale = 10, + isDrawing = false + }) { + this.vol = 0 + this.scale = scale + this.max = max + this.cutoff = cutoff + this.smooth = smooth + this.setBins(numBins) + + // beat detection from: https://github.com/therewasaguy/p5-music-viz/blob/gh-pages/demos/01d_beat_detect_amplitude/sketch.js + this.beat = { + holdFrames: 20, + threshold: 40, + _cutoff: 0, // adaptive based on sound state + decay: 0.98, + _framesSinceBeat: 0 // keeps track of frames + } + + this.onBeat = () => { + // console.log("beat") + } + + this.canvas = document.createElement('canvas') + this.canvas.width = 100 + this.canvas.height = 80 + this.canvas.style.width = "100px" + this.canvas.style.height = "80px" + this.canvas.style.position = 'absolute' + this.canvas.style.right = '0px' + this.canvas.style.bottom = '0px' + document.body.appendChild(this.canvas) + + this.isDrawing = isDrawing + this.ctx = this.canvas.getContext('2d') + this.ctx.fillStyle="#DFFFFF" + this.ctx.strokeStyle="#0ff" + this.ctx.lineWidth=0.5 + if(window.navigator.mediaDevices) { + window.navigator.mediaDevices.getUserMedia({video: false, audio: true}) + .then((stream) => { + // console.log('got mic stream', stream) + this.stream = stream + this.context = new AudioContext() + // this.context = new AudioContext() + let audio_stream = this.context.createMediaStreamSource(stream) + + // console.log(this.context) + this.meyda = Meyda.createMeydaAnalyzer({ + audioContext: this.context, + source: audio_stream, + featureExtractors: [ + 'loudness', + // 'perceptualSpread', + // 'perceptualSharpness', + // 'spectralCentroid' + ] + }) + }) + .catch((err) => console.log('ERROR', err)) + } + } + + detectBeat (level) { + //console.log(level, this.beat._cutoff) + if (level > this.beat._cutoff && level > this.beat.threshold) { + this.onBeat() + this.beat._cutoff = level *1.2 + this.beat._framesSinceBeat = 0 + } else { + if (this.beat._framesSinceBeat <= this.beat.holdFrames){ + this.beat._framesSinceBeat ++; + } else { + this.beat._cutoff *= this.beat.decay + this.beat._cutoff = Math.max( this.beat._cutoff, this.beat.threshold); + } + } + } + + tick() { + if(this.meyda){ + var features = this.meyda.get() + if(features && features !== null){ + this.vol = features.loudness.total + this.detectBeat(this.vol) + // reduce loudness array to number of bins + const reducer = (accumulator, currentValue) => accumulator + currentValue; + let spacing = Math.floor(features.loudness.specific.length/this.bins.length) + this.prevBins = this.bins.slice(0) + this.bins = this.bins.map((bin, index) => { + return features.loudness.specific.slice(index * spacing, (index + 1)*spacing).reduce(reducer) + }).map((bin, index) => { + // map to specified range + + // return (bin * (1.0 - this.smooth) + this.prevBins[index] * this.smooth) + return (bin * (1.0 - this.settings[index].smooth) + this.prevBins[index] * this.settings[index].smooth) + }) + // var y = this.canvas.height - scale*this.settings[index].cutoff + // this.ctx.beginPath() + // this.ctx.moveTo(index*spacing, y) + // this.ctx.lineTo((index+1)*spacing, y) + // this.ctx.stroke() + // + // var yMax = this.canvas.height - scale*(this.settings[index].scale + this.settings[index].cutoff) + this.fft = this.bins.map((bin, index) => ( + // Math.max(0, (bin - this.cutoff) / (this.max - this.cutoff)) + Math.max(0, (bin - this.settings[index].cutoff)/this.settings[index].scale) + )) + if(this.isDrawing) this.draw() + } + } + } + + setCutoff (cutoff) { + this.cutoff = cutoff + this.settings = this.settings.map((el) => { + el.cutoff = cutoff + return el + }) + } + + setSmooth (smooth) { + this.smooth = smooth + this.settings = this.settings.map((el) => { + el.smooth = smooth + return el + }) + } + + setBins (numBins) { + this.bins = Array(numBins).fill(0) + this.prevBins = Array(numBins).fill(0) + this.fft = Array(numBins).fill(0) + this.settings = Array(numBins).fill(0).map(() => ({ + cutoff: this.cutoff, + scale: this.scale, + smooth: this.smooth + })) + // to do: what to do in non-global mode? + this.bins.forEach((bin, index) => { + window['a' + index] = (scale = 1, offset = 0) => () => (a.fft[index] * scale + offset) + }) + // console.log(this.settings) + } + + setScale(scale){ + this.scale = scale + this.settings = this.settings.map((el) => { + el.scale = scale + return el + }) + } + + setMax(max) { + this.max = max + console.log('set max is deprecated') + } + hide() { + this.isDrawing = false + this.canvas.style.display = 'none' + } + + show() { + this.isDrawing = true + this.canvas.style.display = 'block' + + } + + draw () { + this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height) + var spacing = this.canvas.width / this.bins.length + var scale = this.canvas.height / (this.max * 2) + // console.log(this.bins) + this.bins.forEach((bin, index) => { + + var height = bin * scale + + this.ctx.fillRect(index * spacing, this.canvas.height - height, spacing, height) + + // console.log(this.settings[index]) + var y = this.canvas.height - scale*this.settings[index].cutoff + this.ctx.beginPath() + this.ctx.moveTo(index*spacing, y) + this.ctx.lineTo((index+1)*spacing, y) + this.ctx.stroke() + + var yMax = this.canvas.height - scale*(this.settings[index].scale + this.settings[index].cutoff) + this.ctx.beginPath() + this.ctx.moveTo(index*spacing, yMax) + this.ctx.lineTo((index+1)*spacing, yMax) + this.ctx.stroke() + }) + + + /*var y = this.canvas.height - scale*this.cutoff + this.ctx.beginPath() + this.ctx.moveTo(0, y) + this.ctx.lineTo(this.canvas.width, y) + this.ctx.stroke() + var yMax = this.canvas.height - scale*this.max + this.ctx.beginPath() + this.ctx.moveTo(0, yMax) + this.ctx.lineTo(this.canvas.width, yMax) + this.ctx.stroke()*/ + } +} + +module.exports = Audio + +},{"meyda":122}],86:[function(require,module,exports){ +// from https://gist.github.com/gre/1650294 + +module.exports = { + // no easing, no acceleration + linear: function (t) { return t }, + // accelerating from zero velocity + easeInQuad: function (t) { return t*t }, + // decelerating to zero velocity + easeOutQuad: function (t) { return t*(2-t) }, + // acceleration until halfway, then deceleration + easeInOutQuad: function (t) { return t<.5 ? 2*t*t : -1+(4-2*t)*t }, + // accelerating from zero velocity + easeInCubic: function (t) { return t*t*t }, + // decelerating to zero velocity + easeOutCubic: function (t) { return (--t)*t*t+1 }, + // acceleration until halfway, then deceleration + easeInOutCubic: function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1 }, + // accelerating from zero velocity + easeInQuart: function (t) { return t*t*t*t }, + // decelerating to zero velocity + easeOutQuart: function (t) { return 1-(--t)*t*t*t }, + // acceleration until halfway, then deceleration + easeInOutQuart: function (t) { return t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t }, + // accelerating from zero velocity + easeInQuint: function (t) { return t*t*t*t*t }, + // decelerating to zero velocity + easeOutQuint: function (t) { return 1+(--t)*t*t*t*t }, + // acceleration until halfway, then deceleration + easeInOutQuint: function (t) { return t<.5 ? 16*t*t*t*t*t : 1+16*(--t)*t*t*t*t }, + // sin shape + sin: function (t) { return (1 + Math.sin(Math.PI*t-Math.PI/2))/2 } +} + +},{}],87:[function(require,module,exports){ +// https://github.com/mikolalysenko/mouse-event + +'use strict' + +function mouseButtons(ev) { + if(typeof ev === 'object') { + if('buttons' in ev) { + return ev.buttons + } else if('which' in ev) { + var b = ev.which + if(b === 2) { + return 4 + } else if(b === 3) { + return 2 + } else if(b > 0) { + return 1<<(b-1) + } + } else if('button' in ev) { + var b = ev.button + if(b === 1) { + return 4 + } else if(b === 2) { + return 2 + } else if(b >= 0) { + return 1< { + var initialCode = `` + + var sandbox = createSandbox(initialCode) + + var addToContext = (name, object) => { + initialCode += ` + var ${name} = ${object} + ` + sandbox = createSandbox(initialCode) + } + + + return { + addToContext: addToContext, + eval: (code) => sandbox.eval(code) + } + + function createSandbox (initial) { + eval(initial) + // optional params + var localEval = function (code) { + eval(code) + } + + // API/data for end-user + return { + eval: localEval + } + } +} + +},{}],90:[function(require,module,exports){ + +module.exports = function (options) { + return new Promise(function(resolve, reject) { + // async function startCapture(displayMediaOptions) { + navigator.mediaDevices.getDisplayMedia(options).then((stream) => { + const video = document.createElement('video') + video.srcObject = stream + video.addEventListener('loadedmetadata', () => { + video.play() + resolve({video: video}) + }) + }).catch((err) => reject(err)) + }) +} + +},{}],91:[function(require,module,exports){ +class VideoRecorder { + constructor(stream) { + this.mediaSource = new MediaSource() + this.stream = stream + + // testing using a recording as input + this.output = document.createElement('video') + this.output.autoplay = true + this.output.loop = true + + let self = this + this.mediaSource.addEventListener('sourceopen', () => { + console.log('MediaSource opened'); + self.sourceBuffer = self.mediaSource.addSourceBuffer('video/webm; codecs="vp8"'); + console.log('Source buffer: ', sourceBuffer); + }) + } + + start() { + // let options = {mimeType: 'video/webm'}; + +// let options = {mimeType: 'video/webm;codecs=h264'}; + let options = {mimeType: 'video/webm;codecs=vp9'}; + + this.recordedBlobs = [] + try { + this.mediaRecorder = new MediaRecorder(this.stream, options) + } catch (e0) { + console.log('Unable to create MediaRecorder with options Object: ', e0) + try { + options = {mimeType: 'video/webm,codecs=vp9'} + this.mediaRecorder = new MediaRecorder(this.stream, options) + } catch (e1) { + console.log('Unable to create MediaRecorder with options Object: ', e1) + try { + options = 'video/vp8' // Chrome 47 + this.mediaRecorder = new MediaRecorder(this.stream, options) + } catch (e2) { + alert('MediaRecorder is not supported by this browser.\n\n' + + 'Try Firefox 29 or later, or Chrome 47 or later, ' + + 'with Enable experimental Web Platform features enabled from chrome://flags.') + console.error('Exception while creating MediaRecorder:', e2) + return + } + } + } + console.log('Created MediaRecorder', this.mediaRecorder, 'with options', options); + this.mediaRecorder.onstop = this._handleStop.bind(this) + this.mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this) + this.mediaRecorder.start(100) // collect 100ms of data + console.log('MediaRecorder started', this.mediaRecorder) + } + + + stop(){ + this.mediaRecorder.stop() + } + + _handleStop() { + //const superBuffer = new Blob(recordedBlobs, {type: 'video/webm'}) + // const blob = new Blob(this.recordedBlobs, {type: 'video/webm;codecs=h264'}) + const blob = new Blob(this.recordedBlobs, {type: this.mediaRecorder.mimeType}) + const url = window.URL.createObjectURL(blob) + this.output.src = url + + const a = document.createElement('a') + a.style.display = 'none' + a.href = url + let d = new Date() + a.download = `hydra-${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}-${d.getHours()}.${d.getMinutes()}.${d.getSeconds()}.webm` + document.body.appendChild(a) + a.click() + setTimeout(() => { + document.body.removeChild(a); + window.URL.revokeObjectURL(url); + }, 300); + } + + _handleDataAvailable(event) { + if (event.data && event.data.size > 0) { + this.recordedBlobs.push(event.data); + } + } +} + +module.exports = VideoRecorder + +},{}],92:[function(require,module,exports){ +//const enumerateDevices = require('enumerate-devices') + +module.exports = function (deviceId) { + return navigator.mediaDevices.enumerateDevices() + .then(devices => devices.filter(devices => devices.kind === 'videoinput')) + .then(cameras => { + let constraints = { audio: false, video: true} + if (cameras[deviceId]) { + constraints['video'] = { + deviceId: { exact: cameras[deviceId].deviceId } + } + } + // console.log(cameras) + return window.navigator.mediaDevices.getUserMedia(constraints) + }) + .then(stream => { + const video = document.createElement('video') + video.setAttribute('autoplay', '') + video.setAttribute('muted', '') + video.setAttribute('playsinline', '') + // video.src = window.URL.createObjectURL(stream) + video.srcObject = stream + return new Promise((resolve, reject) => { + video.addEventListener('loadedmetadata', () => { + video.play().then(() => resolve({video: video})) + }) + }) + }) + .catch(console.log.bind(console)) +} + +},{}],93:[function(require,module,exports){ +//const transforms = require('./glsl-transforms.js') + +var Output = function ({ regl, precision, label = "", width, height}) { + this.regl = regl + this.precision = precision + this.label = label + this.positionBuffer = this.regl.buffer([ + [-2, 0], + [0, -2], + [2, 2] + ]) + + this.draw = () => {} + this.init() + this.pingPongIndex = 0 + + // for each output, create two fbos for pingponging + this.fbos = (Array(2)).fill().map(() => this.regl.framebuffer({ + color: this.regl.texture({ + mag: 'nearest', + width: width, + height: height, + format: 'rgba' + }), + depthStencil: false + })) + + // array containing render passes +// this.passes = [] +} + +Output.prototype.resize = function(width, height) { + this.fbos.forEach((fbo) => { + fbo.resize(width, height) + }) +// console.log(this) +} + + +Output.prototype.getCurrent = function () { + return this.fbos[this.pingPongIndex] +} + +Output.prototype.getTexture = function () { + var index = this.pingPongIndex ? 0 : 1 + return this.fbos[index] +} + +Output.prototype.init = function () { +// console.log('clearing') + this.transformIndex = 0 + this.fragHeader = ` + precision ${this.precision} float; + + uniform float time; + varying vec2 uv; + ` + + this.fragBody = `` + + this.vert = ` + precision ${this.precision} float; + attribute vec2 position; + varying vec2 uv; + + void main () { + uv = position; + gl_Position = vec4(2.0 * position - 1.0, 0, 1); + }` + + this.attributes = { + position: this.positionBuffer + } + this.uniforms = { + time: this.regl.prop('time'), + resolution: this.regl.prop('resolution') + } + + this.frag = ` + ${this.fragHeader} + + void main () { + vec4 c = vec4(0, 0, 0, 0); + vec2 st = uv; + ${this.fragBody} + gl_FragColor = c; + } + ` + return this +} + + +Output.prototype.render = function (passes) { + let pass = passes[0] + //console.log('pass', pass, this.pingPongIndex) + var self = this + var uniforms = Object.assign(pass.uniforms, { prevBuffer: () => { + //var index = this.pingPongIndex ? 0 : 1 + // var index = self.pingPong[(passIndex+1)%2] + // console.log('ping pong', self.pingPongIndex) + return self.fbos[self.pingPongIndex] + } + }) + + self.draw = self.regl({ + frag: pass.frag, + vert: self.vert, + attributes: self.attributes, + uniforms: uniforms, + count: 3, + framebuffer: () => { + self.pingPongIndex = self.pingPongIndex ? 0 : 1 + return self.fbos[self.pingPongIndex] + } + }) +} + + +Output.prototype.tick = function (props) { +// console.log(props) + this.draw(props) +} + +module.exports = Output + +},{}],94:[function(require,module,exports){ +module.exports = attributeToProperty + +var transform = { + 'class': 'className', + 'for': 'htmlFor', + 'http-equiv': 'httpEquiv' +} + +function attributeToProperty (h) { + return function (tagName, attrs, children) { + for (var attr in attrs) { + if (attr in transform) { + attrs[transform[attr]] = attrs[attr] + delete attrs[attr] + } + } + return h(tagName, attrs, children) + } +} + +},{}],95:[function(require,module,exports){ +var attrToProp = require('hyperscript-attribute-to-property') + +var VAR = 0, TEXT = 1, OPEN = 2, CLOSE = 3, ATTR = 4 +var ATTR_KEY = 5, ATTR_KEY_W = 6 +var ATTR_VALUE_W = 7, ATTR_VALUE = 8 +var ATTR_VALUE_SQ = 9, ATTR_VALUE_DQ = 10 +var ATTR_EQ = 11, ATTR_BREAK = 12 +var COMMENT = 13 + +module.exports = function (h, opts) { + if (!opts) opts = {} + var concat = opts.concat || function (a, b) { + return String(a) + String(b) + } + if (opts.attrToProp !== false) { + h = attrToProp(h) + } + + return function (strings) { + var state = TEXT, reg = '' + var arglen = arguments.length + var parts = [] + + for (var i = 0; i < strings.length; i++) { + if (i < arglen - 1) { + var arg = arguments[i+1] + var p = parse(strings[i]) + var xstate = state + if (xstate === ATTR_VALUE_DQ) xstate = ATTR_VALUE + if (xstate === ATTR_VALUE_SQ) xstate = ATTR_VALUE + if (xstate === ATTR_VALUE_W) xstate = ATTR_VALUE + if (xstate === ATTR) xstate = ATTR_KEY + if (xstate === OPEN) { + if (reg === '/') { + p.push([ OPEN, '/', arg ]) + reg = '' + } else { + p.push([ OPEN, arg ]) + } + } else if (xstate === COMMENT && opts.comments) { + reg += String(arg) + } else if (xstate !== COMMENT) { + p.push([ VAR, xstate, arg ]) + } + parts.push.apply(parts, p) + } else parts.push.apply(parts, parse(strings[i])) + } + + var tree = [null,{},[]] + var stack = [[tree,-1]] + for (var i = 0; i < parts.length; i++) { + var cur = stack[stack.length-1][0] + var p = parts[i], s = p[0] + if (s === OPEN && /^\//.test(p[1])) { + var ix = stack[stack.length-1][1] + if (stack.length > 1) { + stack.pop() + stack[stack.length-1][0][2][ix] = h( + cur[0], cur[1], cur[2].length ? cur[2] : undefined + ) + } + } else if (s === OPEN) { + var c = [p[1],{},[]] + cur[2].push(c) + stack.push([c,cur[2].length-1]) + } else if (s === ATTR_KEY || (s === VAR && p[1] === ATTR_KEY)) { + var key = '' + var copyKey + for (; i < parts.length; i++) { + if (parts[i][0] === ATTR_KEY) { + key = concat(key, parts[i][1]) + } else if (parts[i][0] === VAR && parts[i][1] === ATTR_KEY) { + if (typeof parts[i][2] === 'object' && !key) { + for (copyKey in parts[i][2]) { + if (parts[i][2].hasOwnProperty(copyKey) && !cur[1][copyKey]) { + cur[1][copyKey] = parts[i][2][copyKey] + } + } + } else { + key = concat(key, parts[i][2]) + } + } else break + } + if (parts[i][0] === ATTR_EQ) i++ + var j = i + for (; i < parts.length; i++) { + if (parts[i][0] === ATTR_VALUE || parts[i][0] === ATTR_KEY) { + if (!cur[1][key]) cur[1][key] = strfn(parts[i][1]) + else parts[i][1]==="" || (cur[1][key] = concat(cur[1][key], parts[i][1])); + } else if (parts[i][0] === VAR + && (parts[i][1] === ATTR_VALUE || parts[i][1] === ATTR_KEY)) { + if (!cur[1][key]) cur[1][key] = strfn(parts[i][2]) + else parts[i][2]==="" || (cur[1][key] = concat(cur[1][key], parts[i][2])); + } else { + if (key.length && !cur[1][key] && i === j + && (parts[i][0] === CLOSE || parts[i][0] === ATTR_BREAK)) { + // https://html.spec.whatwg.org/multipage/infrastructure.html#boolean-attributes + // empty string is falsy, not well behaved value in browser + cur[1][key] = key.toLowerCase() + } + if (parts[i][0] === CLOSE) { + i-- + } + break + } + } + } else if (s === ATTR_KEY) { + cur[1][p[1]] = true + } else if (s === VAR && p[1] === ATTR_KEY) { + cur[1][p[2]] = true + } else if (s === CLOSE) { + if (selfClosing(cur[0]) && stack.length) { + var ix = stack[stack.length-1][1] + stack.pop() + stack[stack.length-1][0][2][ix] = h( + cur[0], cur[1], cur[2].length ? cur[2] : undefined + ) + } + } else if (s === VAR && p[1] === TEXT) { + if (p[2] === undefined || p[2] === null) p[2] = '' + else if (!p[2]) p[2] = concat('', p[2]) + if (Array.isArray(p[2][0])) { + cur[2].push.apply(cur[2], p[2]) + } else { + cur[2].push(p[2]) + } + } else if (s === TEXT) { + cur[2].push(p[1]) + } else if (s === ATTR_EQ || s === ATTR_BREAK) { + // no-op + } else { + throw new Error('unhandled: ' + s) + } + } + + if (tree[2].length > 1 && /^\s*$/.test(tree[2][0])) { + tree[2].shift() + } + + if (tree[2].length > 2 + || (tree[2].length === 2 && /\S/.test(tree[2][1]))) { + if (opts.createFragment) return opts.createFragment(tree[2]) + throw new Error( + 'multiple root elements must be wrapped in an enclosing tag' + ) + } + if (Array.isArray(tree[2][0]) && typeof tree[2][0][0] === 'string' + && Array.isArray(tree[2][0][2])) { + tree[2][0] = h(tree[2][0][0], tree[2][0][1], tree[2][0][2]) + } + return tree[2][0] + + function parse (str) { + var res = [] + if (state === ATTR_VALUE_W) state = ATTR + for (var i = 0; i < str.length; i++) { + var c = str.charAt(i) + if (state === TEXT && c === '<') { + if (reg.length) res.push([TEXT, reg]) + reg = '' + state = OPEN + } else if (c === '>' && !quot(state) && state !== COMMENT) { + if (state === OPEN && reg.length) { + res.push([OPEN,reg]) + } else if (state === ATTR_KEY) { + res.push([ATTR_KEY,reg]) + } else if (state === ATTR_VALUE && reg.length) { + res.push([ATTR_VALUE,reg]) + } + res.push([CLOSE]) + reg = '' + state = TEXT + } else if (state === COMMENT && /-$/.test(reg) && c === '-') { + if (opts.comments) { + res.push([ATTR_VALUE,reg.substr(0, reg.length - 1)]) + } + reg = '' + state = TEXT + } else if (state === OPEN && /^!--$/.test(reg)) { + if (opts.comments) { + res.push([OPEN, reg],[ATTR_KEY,'comment'],[ATTR_EQ]) + } + reg = c + state = COMMENT + } else if (state === TEXT || state === COMMENT) { + reg += c + } else if (state === OPEN && c === '/' && reg.length) { + // no-op, self closing tag without a space
+ } else if (state === OPEN && /\s/.test(c)) { + if (reg.length) { + res.push([OPEN, reg]) + } + reg = '' + state = ATTR + } else if (state === OPEN) { + reg += c + } else if (state === ATTR && /[^\s"'=/]/.test(c)) { + state = ATTR_KEY + reg = c + } else if (state === ATTR && /\s/.test(c)) { + if (reg.length) res.push([ATTR_KEY,reg]) + res.push([ATTR_BREAK]) + } else if (state === ATTR_KEY && /\s/.test(c)) { + res.push([ATTR_KEY,reg]) + reg = '' + state = ATTR_KEY_W + } else if (state === ATTR_KEY && c === '=') { + res.push([ATTR_KEY,reg],[ATTR_EQ]) + reg = '' + state = ATTR_VALUE_W + } else if (state === ATTR_KEY) { + reg += c + } else if ((state === ATTR_KEY_W || state === ATTR) && c === '=') { + res.push([ATTR_EQ]) + state = ATTR_VALUE_W + } else if ((state === ATTR_KEY_W || state === ATTR) && !/\s/.test(c)) { + res.push([ATTR_BREAK]) + if (/[\w-]/.test(c)) { + reg += c + state = ATTR_KEY + } else state = ATTR + } else if (state === ATTR_VALUE_W && c === '"') { + state = ATTR_VALUE_DQ + } else if (state === ATTR_VALUE_W && c === "'") { + state = ATTR_VALUE_SQ + } else if (state === ATTR_VALUE_DQ && c === '"') { + res.push([ATTR_VALUE,reg],[ATTR_BREAK]) + reg = '' + state = ATTR + } else if (state === ATTR_VALUE_SQ && c === "'") { + res.push([ATTR_VALUE,reg],[ATTR_BREAK]) + reg = '' + state = ATTR + } else if (state === ATTR_VALUE_W && !/\s/.test(c)) { + state = ATTR_VALUE + i-- + } else if (state === ATTR_VALUE && /\s/.test(c)) { + res.push([ATTR_VALUE,reg],[ATTR_BREAK]) + reg = '' + state = ATTR + } else if (state === ATTR_VALUE || state === ATTR_VALUE_SQ + || state === ATTR_VALUE_DQ) { + reg += c + } + } + if (state === TEXT && reg.length) { + res.push([TEXT,reg]) + reg = '' + } else if (state === ATTR_VALUE && reg.length) { + res.push([ATTR_VALUE,reg]) + reg = '' + } else if (state === ATTR_VALUE_DQ && reg.length) { + res.push([ATTR_VALUE,reg]) + reg = '' + } else if (state === ATTR_VALUE_SQ && reg.length) { + res.push([ATTR_VALUE,reg]) + reg = '' + } else if (state === ATTR_KEY) { + res.push([ATTR_KEY,reg]) + reg = '' + } + return res + } + } + + function strfn (x) { + if (typeof x === 'function') return x + else if (typeof x === 'string') return x + else if (x && typeof x === 'object') return x + else if (x === null || x === undefined) return x + else return concat('', x) + } +} + +function quot (state) { + return state === ATTR_VALUE_SQ || state === ATTR_VALUE_DQ +} + +var closeRE = RegExp('^(' + [ + 'area', 'base', 'basefont', 'bgsound', 'br', 'col', 'command', 'embed', + 'frame', 'hr', 'img', 'input', 'isindex', 'keygen', 'link', 'meta', 'param', + 'source', 'track', 'wbr', '!--', + // SVG TAGS + 'animate', 'animateTransform', 'circle', 'cursor', 'desc', 'ellipse', + 'feBlend', 'feColorMatrix', 'feComposite', + 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', + 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', + 'feGaussianBlur', 'feImage', 'feMergeNode', 'feMorphology', + 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', + 'feTurbulence', 'font-face-format', 'font-face-name', 'font-face-uri', + 'glyph', 'glyphRef', 'hkern', 'image', 'line', 'missing-glyph', 'mpath', + 'path', 'polygon', 'polyline', 'rect', 'set', 'stop', 'tref', 'use', 'view', + 'vkern' +].join('|') + ')(?:[\.#][a-zA-Z0-9\u007F-\uFFFF_:-]+)*$') +function selfClosing (tag) { return closeRE.test(tag) } + +},{"hyperscript-attribute-to-property":94}],96:[function(require,module,exports){ /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m @@ -30505,7 +20231,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],156:[function(require,module,exports){ +},{}],97:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { @@ -30534,7 +20260,5857 @@ if (typeof Object.create === 'function') { } } -},{}],157:[function(require,module,exports){ +},{}],98:[function(require,module,exports){ +/*jshint node:true */ +/* globals define */ +/* + The MIT License (MIT) + + Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +*/ + +'use strict'; + +/** +The following batches are equivalent: + +var beautify_js = require('js-beautify'); +var beautify_js = require('js-beautify').js; +var beautify_js = require('js-beautify').js_beautify; + +var beautify_css = require('js-beautify').css; +var beautify_css = require('js-beautify').css_beautify; + +var beautify_html = require('js-beautify').html; +var beautify_html = require('js-beautify').html_beautify; + +All methods returned accept two arguments, the source string and an options object. +**/ + +function get_beautify(js_beautify, css_beautify, html_beautify) { + // the default is js + var beautify = function(src, config) { + return js_beautify.js_beautify(src, config); + }; + + // short aliases + beautify.js = js_beautify.js_beautify; + beautify.css = css_beautify.css_beautify; + beautify.html = html_beautify.html_beautify; + + // legacy aliases + beautify.js_beautify = js_beautify.js_beautify; + beautify.css_beautify = css_beautify.css_beautify; + beautify.html_beautify = html_beautify.html_beautify; + + return beautify; +} + +if (typeof define === "function" && define.amd) { + // Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- ) + define([ + "./lib/beautify", + "./lib/beautify-css", + "./lib/beautify-html" + ], function(js_beautify, css_beautify, html_beautify) { + return get_beautify(js_beautify, css_beautify, html_beautify); + }); +} else { + (function(mod) { + var beautifier = require('./src/index'); + beautifier.js_beautify = beautifier.js; + beautifier.css_beautify = beautifier.css; + beautifier.html_beautify = beautifier.html; + + mod.exports = get_beautify(beautifier, beautifier, beautifier); + + })(module); +} +},{"./src/index":116}],99:[function(require,module,exports){ +/*jshint node:true */ +/* + + The MIT License (MIT) + + Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +'use strict'; + +function Directives(start_block_pattern, end_block_pattern) { + start_block_pattern = typeof start_block_pattern === 'string' ? start_block_pattern : start_block_pattern.source; + end_block_pattern = typeof end_block_pattern === 'string' ? end_block_pattern : end_block_pattern.source; + this.__directives_block_pattern = new RegExp(start_block_pattern + / beautify( \w+[:]\w+)+ /.source + end_block_pattern, 'g'); + this.__directive_pattern = / (\w+)[:](\w+)/g; + + this.__directives_end_ignore_pattern = new RegExp(start_block_pattern + /\sbeautify\signore:end\s/.source + end_block_pattern, 'g'); +} + +Directives.prototype.get_directives = function(text) { + if (!text.match(this.__directives_block_pattern)) { + return null; + } + + var directives = {}; + this.__directive_pattern.lastIndex = 0; + var directive_match = this.__directive_pattern.exec(text); + + while (directive_match) { + directives[directive_match[1]] = directive_match[2]; + directive_match = this.__directive_pattern.exec(text); + } + + return directives; +}; + +Directives.prototype.readIgnored = function(input) { + return input.readUntilAfter(this.__directives_end_ignore_pattern); +}; + + +module.exports.Directives = Directives; + +},{}],100:[function(require,module,exports){ +/*jshint node:true */ +/* + + The MIT License (MIT) + + Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +'use strict'; + +var regexp_has_sticky = RegExp.prototype.hasOwnProperty('sticky'); + +function InputScanner(input_string) { + this.__input = input_string || ''; + this.__input_length = this.__input.length; + this.__position = 0; +} + +InputScanner.prototype.restart = function() { + this.__position = 0; +}; + +InputScanner.prototype.back = function() { + if (this.__position > 0) { + this.__position -= 1; + } +}; + +InputScanner.prototype.hasNext = function() { + return this.__position < this.__input_length; +}; + +InputScanner.prototype.next = function() { + var val = null; + if (this.hasNext()) { + val = this.__input.charAt(this.__position); + this.__position += 1; + } + return val; +}; + +InputScanner.prototype.peek = function(index) { + var val = null; + index = index || 0; + index += this.__position; + if (index >= 0 && index < this.__input_length) { + val = this.__input.charAt(index); + } + return val; +}; + +// This is a JavaScript only helper function (not in python) +// Javascript doesn't have a match method +// and not all implementation support "sticky" flag. +// If they do not support sticky then both this.match() and this.test() method +// must get the match and check the index of the match. +// If sticky is supported and set, this method will use it. +// Otherwise it will check that global is set, and fall back to the slower method. +InputScanner.prototype.__match = function(pattern, index) { + pattern.lastIndex = index; + var pattern_match = pattern.exec(this.__input); + + if (pattern_match && !(regexp_has_sticky && pattern.sticky)) { + if (pattern_match.index !== index) { + pattern_match = null; + } + } + + return pattern_match; +}; + +InputScanner.prototype.test = function(pattern, index) { + index = index || 0; + index += this.__position; + + if (index >= 0 && index < this.__input_length) { + return !!this.__match(pattern, index); + } else { + return false; + } +}; + +InputScanner.prototype.testChar = function(pattern, index) { + // test one character regex match + var val = this.peek(index); + pattern.lastIndex = 0; + return val !== null && pattern.test(val); +}; + +InputScanner.prototype.match = function(pattern) { + var pattern_match = this.__match(pattern, this.__position); + if (pattern_match) { + this.__position += pattern_match[0].length; + } else { + pattern_match = null; + } + return pattern_match; +}; + +InputScanner.prototype.read = function(starting_pattern, until_pattern, until_after) { + var val = ''; + var match; + if (starting_pattern) { + match = this.match(starting_pattern); + if (match) { + val += match[0]; + } + } + if (until_pattern && (match || !starting_pattern)) { + val += this.readUntil(until_pattern, until_after); + } + return val; +}; + +InputScanner.prototype.readUntil = function(pattern, until_after) { + var val = ''; + var match_index = this.__position; + pattern.lastIndex = this.__position; + var pattern_match = pattern.exec(this.__input); + if (pattern_match) { + match_index = pattern_match.index; + if (until_after) { + match_index += pattern_match[0].length; + } + } else { + match_index = this.__input_length; + } + + val = this.__input.substring(this.__position, match_index); + this.__position = match_index; + return val; +}; + +InputScanner.prototype.readUntilAfter = function(pattern) { + return this.readUntil(pattern, true); +}; + +InputScanner.prototype.get_regexp = function(pattern, match_from) { + var result = null; + var flags = 'g'; + if (match_from && regexp_has_sticky) { + flags = 'y'; + } + // strings are converted to regexp + if (typeof pattern === "string" && pattern !== '') { + // result = new RegExp(pattern.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), flags); + result = new RegExp(pattern, flags); + } else if (pattern) { + result = new RegExp(pattern.source, flags); + } + return result; +}; + +InputScanner.prototype.get_literal_regexp = function(literal_string) { + return RegExp(literal_string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')); +}; + +/* css beautifier legacy helpers */ +InputScanner.prototype.peekUntilAfter = function(pattern) { + var start = this.__position; + var val = this.readUntilAfter(pattern); + this.__position = start; + return val; +}; + +InputScanner.prototype.lookBack = function(testVal) { + var start = this.__position - 1; + return start >= testVal.length && this.__input.substring(start - testVal.length, start) + .toLowerCase() === testVal; +}; + +module.exports.InputScanner = InputScanner; + +},{}],101:[function(require,module,exports){ +/*jshint node:true */ +/* + + The MIT License (MIT) + + Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +'use strict'; + +function Options(options, merge_child_field) { + this.raw_options = _mergeOpts(options, merge_child_field); + + // Support passing the source text back with no change + this.disabled = this._get_boolean('disabled'); + + this.eol = this._get_characters('eol', 'auto'); + this.end_with_newline = this._get_boolean('end_with_newline'); + this.indent_size = this._get_number('indent_size', 4); + this.indent_char = this._get_characters('indent_char', ' '); + this.indent_level = this._get_number('indent_level'); + + this.preserve_newlines = this._get_boolean('preserve_newlines', true); + this.max_preserve_newlines = this._get_number('max_preserve_newlines', 32786); + if (!this.preserve_newlines) { + this.max_preserve_newlines = 0; + } + + this.indent_with_tabs = this._get_boolean('indent_with_tabs', this.indent_char === '\t'); + if (this.indent_with_tabs) { + this.indent_char = '\t'; + + // indent_size behavior changed after 1.8.6 + // It used to be that indent_size would be + // set to 1 for indent_with_tabs. That is no longer needed and + // actually doesn't make sense - why not use spaces? Further, + // that might produce unexpected behavior - tabs being used + // for single-column alignment. So, when indent_with_tabs is true + // and indent_size is 1, reset indent_size to 4. + if (this.indent_size === 1) { + this.indent_size = 4; + } + } + + // Backwards compat with 1.3.x + this.wrap_line_length = this._get_number('wrap_line_length', this._get_number('max_char')); + + this.indent_empty_lines = this._get_boolean('indent_empty_lines'); + + // valid templating languages ['django', 'erb', 'handlebars', 'php', 'smarty'] + // For now, 'auto' = all off for javascript, all on for html (and inline javascript). + // other values ignored + this.templating = this._get_selection_list('templating', ['auto', 'none', 'django', 'erb', 'handlebars', 'php', 'smarty'], ['auto']); +} + +Options.prototype._get_array = function(name, default_value) { + var option_value = this.raw_options[name]; + var result = default_value || []; + if (typeof option_value === 'object') { + if (option_value !== null && typeof option_value.concat === 'function') { + result = option_value.concat(); + } + } else if (typeof option_value === 'string') { + result = option_value.split(/[^a-zA-Z0-9_\/\-]+/); + } + return result; +}; + +Options.prototype._get_boolean = function(name, default_value) { + var option_value = this.raw_options[name]; + var result = option_value === undefined ? !!default_value : !!option_value; + return result; +}; + +Options.prototype._get_characters = function(name, default_value) { + var option_value = this.raw_options[name]; + var result = default_value || ''; + if (typeof option_value === 'string') { + result = option_value.replace(/\\r/, '\r').replace(/\\n/, '\n').replace(/\\t/, '\t'); + } + return result; +}; + +Options.prototype._get_number = function(name, default_value) { + var option_value = this.raw_options[name]; + default_value = parseInt(default_value, 10); + if (isNaN(default_value)) { + default_value = 0; + } + var result = parseInt(option_value, 10); + if (isNaN(result)) { + result = default_value; + } + return result; +}; + +Options.prototype._get_selection = function(name, selection_list, default_value) { + var result = this._get_selection_list(name, selection_list, default_value); + if (result.length !== 1) { + throw new Error( + "Invalid Option Value: The option '" + name + "' can only be one of the following values:\n" + + selection_list + "\nYou passed in: '" + this.raw_options[name] + "'"); + } + + return result[0]; +}; + + +Options.prototype._get_selection_list = function(name, selection_list, default_value) { + if (!selection_list || selection_list.length === 0) { + throw new Error("Selection list cannot be empty."); + } + + default_value = default_value || [selection_list[0]]; + if (!this._is_valid_selection(default_value, selection_list)) { + throw new Error("Invalid Default Value!"); + } + + var result = this._get_array(name, default_value); + if (!this._is_valid_selection(result, selection_list)) { + throw new Error( + "Invalid Option Value: The option '" + name + "' can contain only the following values:\n" + + selection_list + "\nYou passed in: '" + this.raw_options[name] + "'"); + } + + return result; +}; + +Options.prototype._is_valid_selection = function(result, selection_list) { + return result.length && selection_list.length && + !result.some(function(item) { return selection_list.indexOf(item) === -1; }); +}; + + +// merges child options up with the parent options object +// Example: obj = {a: 1, b: {a: 2}} +// mergeOpts(obj, 'b') +// +// Returns: {a: 2} +function _mergeOpts(allOptions, childFieldName) { + var finalOpts = {}; + allOptions = _normalizeOpts(allOptions); + var name; + + for (name in allOptions) { + if (name !== childFieldName) { + finalOpts[name] = allOptions[name]; + } + } + + //merge in the per type settings for the childFieldName + if (childFieldName && allOptions[childFieldName]) { + for (name in allOptions[childFieldName]) { + finalOpts[name] = allOptions[childFieldName][name]; + } + } + return finalOpts; +} + +function _normalizeOpts(options) { + var convertedOpts = {}; + var key; + + for (key in options) { + var newKey = key.replace(/-/g, "_"); + convertedOpts[newKey] = options[key]; + } + return convertedOpts; +} + +module.exports.Options = Options; +module.exports.normalizeOpts = _normalizeOpts; +module.exports.mergeOpts = _mergeOpts; + +},{}],102:[function(require,module,exports){ +/*jshint node:true */ +/* + The MIT License (MIT) + + Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +'use strict'; + +function OutputLine(parent) { + this.__parent = parent; + this.__character_count = 0; + // use indent_count as a marker for this.__lines that have preserved indentation + this.__indent_count = -1; + this.__alignment_count = 0; + this.__wrap_point_index = 0; + this.__wrap_point_character_count = 0; + this.__wrap_point_indent_count = -1; + this.__wrap_point_alignment_count = 0; + + this.__items = []; +} + +OutputLine.prototype.clone_empty = function() { + var line = new OutputLine(this.__parent); + line.set_indent(this.__indent_count, this.__alignment_count); + return line; +}; + +OutputLine.prototype.item = function(index) { + if (index < 0) { + return this.__items[this.__items.length + index]; + } else { + return this.__items[index]; + } +}; + +OutputLine.prototype.has_match = function(pattern) { + for (var lastCheckedOutput = this.__items.length - 1; lastCheckedOutput >= 0; lastCheckedOutput--) { + if (this.__items[lastCheckedOutput].match(pattern)) { + return true; + } + } + return false; +}; + +OutputLine.prototype.set_indent = function(indent, alignment) { + if (this.is_empty()) { + this.__indent_count = indent || 0; + this.__alignment_count = alignment || 0; + this.__character_count = this.__parent.get_indent_size(this.__indent_count, this.__alignment_count); + } +}; + +OutputLine.prototype._set_wrap_point = function() { + if (this.__parent.wrap_line_length) { + this.__wrap_point_index = this.__items.length; + this.__wrap_point_character_count = this.__character_count; + this.__wrap_point_indent_count = this.__parent.next_line.__indent_count; + this.__wrap_point_alignment_count = this.__parent.next_line.__alignment_count; + } +}; + +OutputLine.prototype._should_wrap = function() { + return this.__wrap_point_index && + this.__character_count > this.__parent.wrap_line_length && + this.__wrap_point_character_count > this.__parent.next_line.__character_count; +}; + +OutputLine.prototype._allow_wrap = function() { + if (this._should_wrap()) { + this.__parent.add_new_line(); + var next = this.__parent.current_line; + next.set_indent(this.__wrap_point_indent_count, this.__wrap_point_alignment_count); + next.__items = this.__items.slice(this.__wrap_point_index); + this.__items = this.__items.slice(0, this.__wrap_point_index); + + next.__character_count += this.__character_count - this.__wrap_point_character_count; + this.__character_count = this.__wrap_point_character_count; + + if (next.__items[0] === " ") { + next.__items.splice(0, 1); + next.__character_count -= 1; + } + return true; + } + return false; +}; + +OutputLine.prototype.is_empty = function() { + return this.__items.length === 0; +}; + +OutputLine.prototype.last = function() { + if (!this.is_empty()) { + return this.__items[this.__items.length - 1]; + } else { + return null; + } +}; + +OutputLine.prototype.push = function(item) { + this.__items.push(item); + var last_newline_index = item.lastIndexOf('\n'); + if (last_newline_index !== -1) { + this.__character_count = item.length - last_newline_index; + } else { + this.__character_count += item.length; + } +}; + +OutputLine.prototype.pop = function() { + var item = null; + if (!this.is_empty()) { + item = this.__items.pop(); + this.__character_count -= item.length; + } + return item; +}; + + +OutputLine.prototype._remove_indent = function() { + if (this.__indent_count > 0) { + this.__indent_count -= 1; + this.__character_count -= this.__parent.indent_size; + } +}; + +OutputLine.prototype._remove_wrap_indent = function() { + if (this.__wrap_point_indent_count > 0) { + this.__wrap_point_indent_count -= 1; + } +}; +OutputLine.prototype.trim = function() { + while (this.last() === ' ') { + this.__items.pop(); + this.__character_count -= 1; + } +}; + +OutputLine.prototype.toString = function() { + var result = ''; + if (this.is_empty()) { + if (this.__parent.indent_empty_lines) { + result = this.__parent.get_indent_string(this.__indent_count); + } + } else { + result = this.__parent.get_indent_string(this.__indent_count, this.__alignment_count); + result += this.__items.join(''); + } + return result; +}; + +function IndentStringCache(options, baseIndentString) { + this.__cache = ['']; + this.__indent_size = options.indent_size; + this.__indent_string = options.indent_char; + if (!options.indent_with_tabs) { + this.__indent_string = new Array(options.indent_size + 1).join(options.indent_char); + } + + // Set to null to continue support for auto detection of base indent + baseIndentString = baseIndentString || ''; + if (options.indent_level > 0) { + baseIndentString = new Array(options.indent_level + 1).join(this.__indent_string); + } + + this.__base_string = baseIndentString; + this.__base_string_length = baseIndentString.length; +} + +IndentStringCache.prototype.get_indent_size = function(indent, column) { + var result = this.__base_string_length; + column = column || 0; + if (indent < 0) { + result = 0; + } + result += indent * this.__indent_size; + result += column; + return result; +}; + +IndentStringCache.prototype.get_indent_string = function(indent_level, column) { + var result = this.__base_string; + column = column || 0; + if (indent_level < 0) { + indent_level = 0; + result = ''; + } + column += indent_level * this.__indent_size; + this.__ensure_cache(column); + result += this.__cache[column]; + return result; +}; + +IndentStringCache.prototype.__ensure_cache = function(column) { + while (column >= this.__cache.length) { + this.__add_column(); + } +}; + +IndentStringCache.prototype.__add_column = function() { + var column = this.__cache.length; + var indent = 0; + var result = ''; + if (this.__indent_size && column >= this.__indent_size) { + indent = Math.floor(column / this.__indent_size); + column -= indent * this.__indent_size; + result = new Array(indent + 1).join(this.__indent_string); + } + if (column) { + result += new Array(column + 1).join(' '); + } + + this.__cache.push(result); +}; + +function Output(options, baseIndentString) { + this.__indent_cache = new IndentStringCache(options, baseIndentString); + this.raw = false; + this._end_with_newline = options.end_with_newline; + this.indent_size = options.indent_size; + this.wrap_line_length = options.wrap_line_length; + this.indent_empty_lines = options.indent_empty_lines; + this.__lines = []; + this.previous_line = null; + this.current_line = null; + this.next_line = new OutputLine(this); + this.space_before_token = false; + this.non_breaking_space = false; + this.previous_token_wrapped = false; + // initialize + this.__add_outputline(); +} + +Output.prototype.__add_outputline = function() { + this.previous_line = this.current_line; + this.current_line = this.next_line.clone_empty(); + this.__lines.push(this.current_line); +}; + +Output.prototype.get_line_number = function() { + return this.__lines.length; +}; + +Output.prototype.get_indent_string = function(indent, column) { + return this.__indent_cache.get_indent_string(indent, column); +}; + +Output.prototype.get_indent_size = function(indent, column) { + return this.__indent_cache.get_indent_size(indent, column); +}; + +Output.prototype.is_empty = function() { + return !this.previous_line && this.current_line.is_empty(); +}; + +Output.prototype.add_new_line = function(force_newline) { + // never newline at the start of file + // otherwise, newline only if we didn't just add one or we're forced + if (this.is_empty() || + (!force_newline && this.just_added_newline())) { + return false; + } + + // if raw output is enabled, don't print additional newlines, + // but still return True as though you had + if (!this.raw) { + this.__add_outputline(); + } + return true; +}; + +Output.prototype.get_code = function(eol) { + this.trim(true); + + // handle some edge cases where the last tokens + // has text that ends with newline(s) + var last_item = this.current_line.pop(); + if (last_item) { + if (last_item[last_item.length - 1] === '\n') { + last_item = last_item.replace(/\n+$/g, ''); + } + this.current_line.push(last_item); + } + + if (this._end_with_newline) { + this.__add_outputline(); + } + + var sweet_code = this.__lines.join('\n'); + + if (eol !== '\n') { + sweet_code = sweet_code.replace(/[\n]/g, eol); + } + return sweet_code; +}; + +Output.prototype.set_wrap_point = function() { + this.current_line._set_wrap_point(); +}; + +Output.prototype.set_indent = function(indent, alignment) { + indent = indent || 0; + alignment = alignment || 0; + + // Next line stores alignment values + this.next_line.set_indent(indent, alignment); + + // Never indent your first output indent at the start of the file + if (this.__lines.length > 1) { + this.current_line.set_indent(indent, alignment); + return true; + } + + this.current_line.set_indent(); + return false; +}; + +Output.prototype.add_raw_token = function(token) { + for (var x = 0; x < token.newlines; x++) { + this.__add_outputline(); + } + this.current_line.set_indent(-1); + this.current_line.push(token.whitespace_before); + this.current_line.push(token.text); + this.space_before_token = false; + this.non_breaking_space = false; + this.previous_token_wrapped = false; +}; + +Output.prototype.add_token = function(printable_token) { + this.__add_space_before_token(); + this.current_line.push(printable_token); + this.space_before_token = false; + this.non_breaking_space = false; + this.previous_token_wrapped = this.current_line._allow_wrap(); +}; + +Output.prototype.__add_space_before_token = function() { + if (this.space_before_token && !this.just_added_newline()) { + if (!this.non_breaking_space) { + this.set_wrap_point(); + } + this.current_line.push(' '); + } +}; + +Output.prototype.remove_indent = function(index) { + var output_length = this.__lines.length; + while (index < output_length) { + this.__lines[index]._remove_indent(); + index++; + } + this.current_line._remove_wrap_indent(); +}; + +Output.prototype.trim = function(eat_newlines) { + eat_newlines = (eat_newlines === undefined) ? false : eat_newlines; + + this.current_line.trim(); + + while (eat_newlines && this.__lines.length > 1 && + this.current_line.is_empty()) { + this.__lines.pop(); + this.current_line = this.__lines[this.__lines.length - 1]; + this.current_line.trim(); + } + + this.previous_line = this.__lines.length > 1 ? + this.__lines[this.__lines.length - 2] : null; +}; + +Output.prototype.just_added_newline = function() { + return this.current_line.is_empty(); +}; + +Output.prototype.just_added_blankline = function() { + return this.is_empty() || + (this.current_line.is_empty() && this.previous_line.is_empty()); +}; + +Output.prototype.ensure_empty_line_above = function(starts_with, ends_with) { + var index = this.__lines.length - 2; + while (index >= 0) { + var potentialEmptyLine = this.__lines[index]; + if (potentialEmptyLine.is_empty()) { + break; + } else if (potentialEmptyLine.item(0).indexOf(starts_with) !== 0 && + potentialEmptyLine.item(-1) !== ends_with) { + this.__lines.splice(index + 1, 0, new OutputLine(this)); + this.previous_line = this.__lines[this.__lines.length - 2]; + break; + } + index--; + } +}; + +module.exports.Output = Output; + +},{}],103:[function(require,module,exports){ +/*jshint node:true */ +/* + + The MIT License (MIT) + + Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +'use strict'; + +function Pattern(input_scanner, parent) { + this._input = input_scanner; + this._starting_pattern = null; + this._match_pattern = null; + this._until_pattern = null; + this._until_after = false; + + if (parent) { + this._starting_pattern = this._input.get_regexp(parent._starting_pattern, true); + this._match_pattern = this._input.get_regexp(parent._match_pattern, true); + this._until_pattern = this._input.get_regexp(parent._until_pattern); + this._until_after = parent._until_after; + } +} + +Pattern.prototype.read = function() { + var result = this._input.read(this._starting_pattern); + if (!this._starting_pattern || result) { + result += this._input.read(this._match_pattern, this._until_pattern, this._until_after); + } + return result; +}; + +Pattern.prototype.read_match = function() { + return this._input.match(this._match_pattern); +}; + +Pattern.prototype.until_after = function(pattern) { + var result = this._create(); + result._until_after = true; + result._until_pattern = this._input.get_regexp(pattern); + result._update(); + return result; +}; + +Pattern.prototype.until = function(pattern) { + var result = this._create(); + result._until_after = false; + result._until_pattern = this._input.get_regexp(pattern); + result._update(); + return result; +}; + +Pattern.prototype.starting_with = function(pattern) { + var result = this._create(); + result._starting_pattern = this._input.get_regexp(pattern, true); + result._update(); + return result; +}; + +Pattern.prototype.matching = function(pattern) { + var result = this._create(); + result._match_pattern = this._input.get_regexp(pattern, true); + result._update(); + return result; +}; + +Pattern.prototype._create = function() { + return new Pattern(this._input, this); +}; + +Pattern.prototype._update = function() {}; + +module.exports.Pattern = Pattern; + +},{}],104:[function(require,module,exports){ +/*jshint node:true */ +/* + + The MIT License (MIT) + + Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +'use strict'; + +var Pattern = require('./pattern').Pattern; + + +var template_names = { + django: false, + erb: false, + handlebars: false, + php: false, + smarty: false +}; + +// This lets templates appear anywhere we would do a readUntil +// The cost is higher but it is pay to play. +function TemplatablePattern(input_scanner, parent) { + Pattern.call(this, input_scanner, parent); + this.__template_pattern = null; + this._disabled = Object.assign({}, template_names); + this._excluded = Object.assign({}, template_names); + + if (parent) { + this.__template_pattern = this._input.get_regexp(parent.__template_pattern); + this._excluded = Object.assign(this._excluded, parent._excluded); + this._disabled = Object.assign(this._disabled, parent._disabled); + } + var pattern = new Pattern(input_scanner); + this.__patterns = { + handlebars_comment: pattern.starting_with(/{{!--/).until_after(/--}}/), + handlebars_unescaped: pattern.starting_with(/{{{/).until_after(/}}}/), + handlebars: pattern.starting_with(/{{/).until_after(/}}/), + php: pattern.starting_with(/<\?(?:[= ]|php)/).until_after(/\?>/), + erb: pattern.starting_with(/<%[^%]/).until_after(/[^%]%>/), + // django coflicts with handlebars a bit. + django: pattern.starting_with(/{%/).until_after(/%}/), + django_value: pattern.starting_with(/{{/).until_after(/}}/), + django_comment: pattern.starting_with(/{#/).until_after(/#}/), + smarty: pattern.starting_with(/{(?=[^}{\s\n])/).until_after(/[^\s\n]}/), + smarty_comment: pattern.starting_with(/{\*/).until_after(/\*}/), + smarty_literal: pattern.starting_with(/{literal}/).until_after(/{\/literal}/) + }; +} +TemplatablePattern.prototype = new Pattern(); + +TemplatablePattern.prototype._create = function() { + return new TemplatablePattern(this._input, this); +}; + +TemplatablePattern.prototype._update = function() { + this.__set_templated_pattern(); +}; + +TemplatablePattern.prototype.disable = function(language) { + var result = this._create(); + result._disabled[language] = true; + result._update(); + return result; +}; + +TemplatablePattern.prototype.read_options = function(options) { + var result = this._create(); + for (var language in template_names) { + result._disabled[language] = options.templating.indexOf(language) === -1; + } + result._update(); + return result; +}; + +TemplatablePattern.prototype.exclude = function(language) { + var result = this._create(); + result._excluded[language] = true; + result._update(); + return result; +}; + +TemplatablePattern.prototype.read = function() { + var result = ''; + if (this._match_pattern) { + result = this._input.read(this._starting_pattern); + } else { + result = this._input.read(this._starting_pattern, this.__template_pattern); + } + var next = this._read_template(); + while (next) { + if (this._match_pattern) { + next += this._input.read(this._match_pattern); + } else { + next += this._input.readUntil(this.__template_pattern); + } + result += next; + next = this._read_template(); + } + + if (this._until_after) { + result += this._input.readUntilAfter(this._until_pattern); + } + return result; +}; + +TemplatablePattern.prototype.__set_templated_pattern = function() { + var items = []; + + if (!this._disabled.php) { + items.push(this.__patterns.php._starting_pattern.source); + } + if (!this._disabled.handlebars) { + items.push(this.__patterns.handlebars._starting_pattern.source); + } + if (!this._disabled.erb) { + items.push(this.__patterns.erb._starting_pattern.source); + } + if (!this._disabled.django) { + items.push(this.__patterns.django._starting_pattern.source); + // The starting pattern for django is more complex because it has different + // patterns for value, comment, and other sections + items.push(this.__patterns.django_value._starting_pattern.source); + items.push(this.__patterns.django_comment._starting_pattern.source); + } + if (!this._disabled.smarty) { + items.push(this.__patterns.smarty._starting_pattern.source); + } + + if (this._until_pattern) { + items.push(this._until_pattern.source); + } + this.__template_pattern = this._input.get_regexp('(?:' + items.join('|') + ')'); +}; + +TemplatablePattern.prototype._read_template = function() { + var resulting_string = ''; + var c = this._input.peek(); + if (c === '<') { + var peek1 = this._input.peek(1); + //if we're in a comment, do something special + // We treat all comments as literals, even more than preformatted tags + // we just look for the appropriate close tag + if (!this._disabled.php && !this._excluded.php && peek1 === '?') { + resulting_string = resulting_string || + this.__patterns.php.read(); + } + if (!this._disabled.erb && !this._excluded.erb && peek1 === '%') { + resulting_string = resulting_string || + this.__patterns.erb.read(); + } + } else if (c === '{') { + if (!this._disabled.handlebars && !this._excluded.handlebars) { + resulting_string = resulting_string || + this.__patterns.handlebars_comment.read(); + resulting_string = resulting_string || + this.__patterns.handlebars_unescaped.read(); + resulting_string = resulting_string || + this.__patterns.handlebars.read(); + } + if (!this._disabled.django) { + // django coflicts with handlebars a bit. + if (!this._excluded.django && !this._excluded.handlebars) { + resulting_string = resulting_string || + this.__patterns.django_value.read(); + } + if (!this._excluded.django) { + resulting_string = resulting_string || + this.__patterns.django_comment.read(); + resulting_string = resulting_string || + this.__patterns.django.read(); + } + } + if (!this._disabled.smarty) { + // smarty cannot be enabled with django or handlebars enabled + if (this._disabled.django && this._disabled.handlebars) { + resulting_string = resulting_string || + this.__patterns.smarty_comment.read(); + resulting_string = resulting_string || + this.__patterns.smarty_literal.read(); + resulting_string = resulting_string || + this.__patterns.smarty.read(); + } + } + } + return resulting_string; +}; + + +module.exports.TemplatablePattern = TemplatablePattern; + +},{"./pattern":103}],105:[function(require,module,exports){ +/*jshint node:true */ +/* + + The MIT License (MIT) + + Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +'use strict'; + +function Token(type, text, newlines, whitespace_before) { + this.type = type; + this.text = text; + + // comments_before are + // comments that have a new line before them + // and may or may not have a newline after + // this is a set of comments before + this.comments_before = null; /* inline comment*/ + + + // this.comments_after = new TokenStream(); // no new line before and newline after + this.newlines = newlines || 0; + this.whitespace_before = whitespace_before || ''; + this.parent = null; + this.next = null; + this.previous = null; + this.opened = null; + this.closed = null; + this.directives = null; +} + + +module.exports.Token = Token; + +},{}],106:[function(require,module,exports){ +/*jshint node:true */ +/* + + The MIT License (MIT) + + Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +'use strict'; + +var InputScanner = require('../core/inputscanner').InputScanner; +var Token = require('../core/token').Token; +var TokenStream = require('../core/tokenstream').TokenStream; +var WhitespacePattern = require('./whitespacepattern').WhitespacePattern; + +var TOKEN = { + START: 'TK_START', + RAW: 'TK_RAW', + EOF: 'TK_EOF' +}; + +var Tokenizer = function(input_string, options) { + this._input = new InputScanner(input_string); + this._options = options || {}; + this.__tokens = null; + + this._patterns = {}; + this._patterns.whitespace = new WhitespacePattern(this._input); +}; + +Tokenizer.prototype.tokenize = function() { + this._input.restart(); + this.__tokens = new TokenStream(); + + this._reset(); + + var current; + var previous = new Token(TOKEN.START, ''); + var open_token = null; + var open_stack = []; + var comments = new TokenStream(); + + while (previous.type !== TOKEN.EOF) { + current = this._get_next_token(previous, open_token); + while (this._is_comment(current)) { + comments.add(current); + current = this._get_next_token(previous, open_token); + } + + if (!comments.isEmpty()) { + current.comments_before = comments; + comments = new TokenStream(); + } + + current.parent = open_token; + + if (this._is_opening(current)) { + open_stack.push(open_token); + open_token = current; + } else if (open_token && this._is_closing(current, open_token)) { + current.opened = open_token; + open_token.closed = current; + open_token = open_stack.pop(); + current.parent = open_token; + } + + current.previous = previous; + previous.next = current; + + this.__tokens.add(current); + previous = current; + } + + return this.__tokens; +}; + + +Tokenizer.prototype._is_first_token = function() { + return this.__tokens.isEmpty(); +}; + +Tokenizer.prototype._reset = function() {}; + +Tokenizer.prototype._get_next_token = function(previous_token, open_token) { // jshint unused:false + this._readWhitespace(); + var resulting_string = this._input.read(/.+/g); + if (resulting_string) { + return this._create_token(TOKEN.RAW, resulting_string); + } else { + return this._create_token(TOKEN.EOF, ''); + } +}; + +Tokenizer.prototype._is_comment = function(current_token) { // jshint unused:false + return false; +}; + +Tokenizer.prototype._is_opening = function(current_token) { // jshint unused:false + return false; +}; + +Tokenizer.prototype._is_closing = function(current_token, open_token) { // jshint unused:false + return false; +}; + +Tokenizer.prototype._create_token = function(type, text) { + var token = new Token(type, text, + this._patterns.whitespace.newline_count, + this._patterns.whitespace.whitespace_before_token); + return token; +}; + +Tokenizer.prototype._readWhitespace = function() { + return this._patterns.whitespace.read(); +}; + + + +module.exports.Tokenizer = Tokenizer; +module.exports.TOKEN = TOKEN; + +},{"../core/inputscanner":100,"../core/token":105,"../core/tokenstream":107,"./whitespacepattern":108}],107:[function(require,module,exports){ +/*jshint node:true */ +/* + + The MIT License (MIT) + + Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +'use strict'; + +function TokenStream(parent_token) { + // private + this.__tokens = []; + this.__tokens_length = this.__tokens.length; + this.__position = 0; + this.__parent_token = parent_token; +} + +TokenStream.prototype.restart = function() { + this.__position = 0; +}; + +TokenStream.prototype.isEmpty = function() { + return this.__tokens_length === 0; +}; + +TokenStream.prototype.hasNext = function() { + return this.__position < this.__tokens_length; +}; + +TokenStream.prototype.next = function() { + var val = null; + if (this.hasNext()) { + val = this.__tokens[this.__position]; + this.__position += 1; + } + return val; +}; + +TokenStream.prototype.peek = function(index) { + var val = null; + index = index || 0; + index += this.__position; + if (index >= 0 && index < this.__tokens_length) { + val = this.__tokens[index]; + } + return val; +}; + +TokenStream.prototype.add = function(token) { + if (this.__parent_token) { + token.parent = this.__parent_token; + } + this.__tokens.push(token); + this.__tokens_length += 1; +}; + +module.exports.TokenStream = TokenStream; + +},{}],108:[function(require,module,exports){ +/*jshint node:true */ +/* + + The MIT License (MIT) + + Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +'use strict'; + +var Pattern = require('../core/pattern').Pattern; + +function WhitespacePattern(input_scanner, parent) { + Pattern.call(this, input_scanner, parent); + if (parent) { + this._line_regexp = this._input.get_regexp(parent._line_regexp); + } else { + this.__set_whitespace_patterns('', ''); + } + + this.newline_count = 0; + this.whitespace_before_token = ''; +} +WhitespacePattern.prototype = new Pattern(); + +WhitespacePattern.prototype.__set_whitespace_patterns = function(whitespace_chars, newline_chars) { + whitespace_chars += '\\t '; + newline_chars += '\\n\\r'; + + this._match_pattern = this._input.get_regexp( + '[' + whitespace_chars + newline_chars + ']+', true); + this._newline_regexp = this._input.get_regexp( + '\\r\\n|[' + newline_chars + ']'); +}; + +WhitespacePattern.prototype.read = function() { + this.newline_count = 0; + this.whitespace_before_token = ''; + + var resulting_string = this._input.read(this._match_pattern); + if (resulting_string === ' ') { + this.whitespace_before_token = ' '; + } else if (resulting_string) { + var matches = this.__split(this._newline_regexp, resulting_string); + this.newline_count = matches.length - 1; + this.whitespace_before_token = matches[this.newline_count]; + } + + return resulting_string; +}; + +WhitespacePattern.prototype.matching = function(whitespace_chars, newline_chars) { + var result = this._create(); + result.__set_whitespace_patterns(whitespace_chars, newline_chars); + result._update(); + return result; +}; + +WhitespacePattern.prototype._create = function() { + return new WhitespacePattern(this._input, this); +}; + +WhitespacePattern.prototype.__split = function(regexp, input_string) { + regexp.lastIndex = 0; + var start_index = 0; + var result = []; + var next_match = regexp.exec(input_string); + while (next_match) { + result.push(input_string.substring(start_index, next_match.index)); + start_index = next_match.index + next_match[0].length; + next_match = regexp.exec(input_string); + } + + if (start_index < input_string.length) { + result.push(input_string.substring(start_index, input_string.length)); + } else { + result.push(''); + } + + return result; +}; + + + +module.exports.WhitespacePattern = WhitespacePattern; + +},{"../core/pattern":103}],109:[function(require,module,exports){ +/*jshint node:true */ +/* + + The MIT License (MIT) + + Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +'use strict'; + +var Options = require('./options').Options; +var Output = require('../core/output').Output; +var InputScanner = require('../core/inputscanner').InputScanner; +var Directives = require('../core/directives').Directives; + +var directives_core = new Directives(/\/\*/, /\*\//); + +var lineBreak = /\r\n|[\r\n]/; +var allLineBreaks = /\r\n|[\r\n]/g; + +// tokenizer +var whitespaceChar = /\s/; +var whitespacePattern = /(?:\s|\n)+/g; +var block_comment_pattern = /\/\*(?:[\s\S]*?)((?:\*\/)|$)/g; +var comment_pattern = /\/\/(?:[^\n\r\u2028\u2029]*)/g; + +function Beautifier(source_text, options) { + this._source_text = source_text || ''; + // Allow the setting of language/file-type specific options + // with inheritance of overall settings + this._options = new Options(options); + this._ch = null; + this._input = null; + + // https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule + this.NESTED_AT_RULE = { + "@page": true, + "@font-face": true, + "@keyframes": true, + // also in CONDITIONAL_GROUP_RULE below + "@media": true, + "@supports": true, + "@document": true + }; + this.CONDITIONAL_GROUP_RULE = { + "@media": true, + "@supports": true, + "@document": true + }; + +} + +Beautifier.prototype.eatString = function(endChars) { + var result = ''; + this._ch = this._input.next(); + while (this._ch) { + result += this._ch; + if (this._ch === "\\") { + result += this._input.next(); + } else if (endChars.indexOf(this._ch) !== -1 || this._ch === "\n") { + break; + } + this._ch = this._input.next(); + } + return result; +}; + +// Skips any white space in the source text from the current position. +// When allowAtLeastOneNewLine is true, will output new lines for each +// newline character found; if the user has preserve_newlines off, only +// the first newline will be output +Beautifier.prototype.eatWhitespace = function(allowAtLeastOneNewLine) { + var result = whitespaceChar.test(this._input.peek()); + var newline_count = 0; + while (whitespaceChar.test(this._input.peek())) { + this._ch = this._input.next(); + if (allowAtLeastOneNewLine && this._ch === '\n') { + if (newline_count === 0 || newline_count < this._options.max_preserve_newlines) { + newline_count++; + this._output.add_new_line(true); + } + } + } + return result; +}; + +// Nested pseudo-class if we are insideRule +// and the next special character found opens +// a new block +Beautifier.prototype.foundNestedPseudoClass = function() { + var openParen = 0; + var i = 1; + var ch = this._input.peek(i); + while (ch) { + if (ch === "{") { + return true; + } else if (ch === '(') { + // pseudoclasses can contain () + openParen += 1; + } else if (ch === ')') { + if (openParen === 0) { + return false; + } + openParen -= 1; + } else if (ch === ";" || ch === "}") { + return false; + } + i++; + ch = this._input.peek(i); + } + return false; +}; + +Beautifier.prototype.print_string = function(output_string) { + this._output.set_indent(this._indentLevel); + this._output.non_breaking_space = true; + this._output.add_token(output_string); +}; + +Beautifier.prototype.preserveSingleSpace = function(isAfterSpace) { + if (isAfterSpace) { + this._output.space_before_token = true; + } +}; + +Beautifier.prototype.indent = function() { + this._indentLevel++; +}; + +Beautifier.prototype.outdent = function() { + if (this._indentLevel > 0) { + this._indentLevel--; + } +}; + +/*_____________________--------------------_____________________*/ + +Beautifier.prototype.beautify = function() { + if (this._options.disabled) { + return this._source_text; + } + + var source_text = this._source_text; + var eol = this._options.eol; + if (eol === 'auto') { + eol = '\n'; + if (source_text && lineBreak.test(source_text || '')) { + eol = source_text.match(lineBreak)[0]; + } + } + + + // HACK: newline parsing inconsistent. This brute force normalizes the this._input. + source_text = source_text.replace(allLineBreaks, '\n'); + + // reset + var baseIndentString = source_text.match(/^[\t ]*/)[0]; + + this._output = new Output(this._options, baseIndentString); + this._input = new InputScanner(source_text); + this._indentLevel = 0; + this._nestedLevel = 0; + + this._ch = null; + var parenLevel = 0; + + var insideRule = false; + // This is the value side of a property value pair (blue in the following ex) + // label { content: blue } + var insidePropertyValue = false; + var enteringConditionalGroup = false; + var insideAtExtend = false; + var insideAtImport = false; + var topCharacter = this._ch; + var whitespace; + var isAfterSpace; + var previous_ch; + + while (true) { + whitespace = this._input.read(whitespacePattern); + isAfterSpace = whitespace !== ''; + previous_ch = topCharacter; + this._ch = this._input.next(); + if (this._ch === '\\' && this._input.hasNext()) { + this._ch += this._input.next(); + } + topCharacter = this._ch; + + if (!this._ch) { + break; + } else if (this._ch === '/' && this._input.peek() === '*') { + // /* css comment */ + // Always start block comments on a new line. + // This handles scenarios where a block comment immediately + // follows a property definition on the same line or where + // minified code is being beautified. + this._output.add_new_line(); + this._input.back(); + + var comment = this._input.read(block_comment_pattern); + + // Handle ignore directive + var directives = directives_core.get_directives(comment); + if (directives && directives.ignore === 'start') { + comment += directives_core.readIgnored(this._input); + } + + this.print_string(comment); + + // Ensures any new lines following the comment are preserved + this.eatWhitespace(true); + + // Block comments are followed by a new line so they don't + // share a line with other properties + this._output.add_new_line(); + } else if (this._ch === '/' && this._input.peek() === '/') { + // // single line comment + // Preserves the space before a comment + // on the same line as a rule + this._output.space_before_token = true; + this._input.back(); + this.print_string(this._input.read(comment_pattern)); + + // Ensures any new lines following the comment are preserved + this.eatWhitespace(true); + } else if (this._ch === '@') { + this.preserveSingleSpace(isAfterSpace); + + // deal with less propery mixins @{...} + if (this._input.peek() === '{') { + this.print_string(this._ch + this.eatString('}')); + } else { + this.print_string(this._ch); + + // strip trailing space, if present, for hash property checks + var variableOrRule = this._input.peekUntilAfter(/[: ,;{}()[\]\/='"]/g); + + if (variableOrRule.match(/[ :]$/)) { + // we have a variable or pseudo-class, add it and insert one space before continuing + variableOrRule = this.eatString(": ").replace(/\s$/, ''); + this.print_string(variableOrRule); + this._output.space_before_token = true; + } + + variableOrRule = variableOrRule.replace(/\s$/, ''); + + if (variableOrRule === 'extend') { + insideAtExtend = true; + } else if (variableOrRule === 'import') { + insideAtImport = true; + } + + // might be a nesting at-rule + if (variableOrRule in this.NESTED_AT_RULE) { + this._nestedLevel += 1; + if (variableOrRule in this.CONDITIONAL_GROUP_RULE) { + enteringConditionalGroup = true; + } + // might be less variable + } else if (!insideRule && parenLevel === 0 && variableOrRule.indexOf(':') !== -1) { + insidePropertyValue = true; + this.indent(); + } + } + } else if (this._ch === '#' && this._input.peek() === '{') { + this.preserveSingleSpace(isAfterSpace); + this.print_string(this._ch + this.eatString('}')); + } else if (this._ch === '{') { + if (insidePropertyValue) { + insidePropertyValue = false; + this.outdent(); + } + + // when entering conditional groups, only rulesets are allowed + if (enteringConditionalGroup) { + enteringConditionalGroup = false; + insideRule = (this._indentLevel >= this._nestedLevel); + } else { + // otherwise, declarations are also allowed + insideRule = (this._indentLevel >= this._nestedLevel - 1); + } + if (this._options.newline_between_rules && insideRule) { + if (this._output.previous_line && this._output.previous_line.item(-1) !== '{') { + this._output.ensure_empty_line_above('/', ','); + } + } + + this._output.space_before_token = true; + + // The difference in print_string and indent order is necessary to indent the '{' correctly + if (this._options.brace_style === 'expand') { + this._output.add_new_line(); + this.print_string(this._ch); + this.indent(); + this._output.set_indent(this._indentLevel); + } else { + this.indent(); + this.print_string(this._ch); + } + + this.eatWhitespace(true); + this._output.add_new_line(); + } else if (this._ch === '}') { + this.outdent(); + this._output.add_new_line(); + if (previous_ch === '{') { + this._output.trim(true); + } + insideAtImport = false; + insideAtExtend = false; + if (insidePropertyValue) { + this.outdent(); + insidePropertyValue = false; + } + this.print_string(this._ch); + insideRule = false; + if (this._nestedLevel) { + this._nestedLevel--; + } + + this.eatWhitespace(true); + this._output.add_new_line(); + + if (this._options.newline_between_rules && !this._output.just_added_blankline()) { + if (this._input.peek() !== '}') { + this._output.add_new_line(true); + } + } + } else if (this._ch === ":") { + if ((insideRule || enteringConditionalGroup) && !(this._input.lookBack("&") || this.foundNestedPseudoClass()) && !this._input.lookBack("(") && !insideAtExtend && parenLevel === 0) { + // 'property: value' delimiter + // which could be in a conditional group query + this.print_string(':'); + if (!insidePropertyValue) { + insidePropertyValue = true; + this._output.space_before_token = true; + this.eatWhitespace(true); + this.indent(); + } + } else { + // sass/less parent reference don't use a space + // sass nested pseudo-class don't use a space + + // preserve space before pseudoclasses/pseudoelements, as it means "in any child" + if (this._input.lookBack(" ")) { + this._output.space_before_token = true; + } + if (this._input.peek() === ":") { + // pseudo-element + this._ch = this._input.next(); + this.print_string("::"); + } else { + // pseudo-class + this.print_string(':'); + } + } + } else if (this._ch === '"' || this._ch === '\'') { + this.preserveSingleSpace(isAfterSpace); + this.print_string(this._ch + this.eatString(this._ch)); + this.eatWhitespace(true); + } else if (this._ch === ';') { + if (parenLevel === 0) { + if (insidePropertyValue) { + this.outdent(); + insidePropertyValue = false; + } + insideAtExtend = false; + insideAtImport = false; + this.print_string(this._ch); + this.eatWhitespace(true); + + // This maintains single line comments on the same + // line. Block comments are also affected, but + // a new line is always output before one inside + // that section + if (this._input.peek() !== '/') { + this._output.add_new_line(); + } + } else { + this.print_string(this._ch); + this.eatWhitespace(true); + this._output.space_before_token = true; + } + } else if (this._ch === '(') { // may be a url + if (this._input.lookBack("url")) { + this.print_string(this._ch); + this.eatWhitespace(); + parenLevel++; + this.indent(); + this._ch = this._input.next(); + if (this._ch === ')' || this._ch === '"' || this._ch === '\'') { + this._input.back(); + } else if (this._ch) { + this.print_string(this._ch + this.eatString(')')); + if (parenLevel) { + parenLevel--; + this.outdent(); + } + } + } else { + this.preserveSingleSpace(isAfterSpace); + this.print_string(this._ch); + this.eatWhitespace(); + parenLevel++; + this.indent(); + } + } else if (this._ch === ')') { + if (parenLevel) { + parenLevel--; + this.outdent(); + } + this.print_string(this._ch); + } else if (this._ch === ',') { + this.print_string(this._ch); + this.eatWhitespace(true); + if (this._options.selector_separator_newline && !insidePropertyValue && parenLevel === 0 && !insideAtImport && !insideAtExtend) { + this._output.add_new_line(); + } else { + this._output.space_before_token = true; + } + } else if ((this._ch === '>' || this._ch === '+' || this._ch === '~') && !insidePropertyValue && parenLevel === 0) { + //handle combinator spacing + if (this._options.space_around_combinator) { + this._output.space_before_token = true; + this.print_string(this._ch); + this._output.space_before_token = true; + } else { + this.print_string(this._ch); + this.eatWhitespace(); + // squash extra whitespace + if (this._ch && whitespaceChar.test(this._ch)) { + this._ch = ''; + } + } + } else if (this._ch === ']') { + this.print_string(this._ch); + } else if (this._ch === '[') { + this.preserveSingleSpace(isAfterSpace); + this.print_string(this._ch); + } else if (this._ch === '=') { // no whitespace before or after + this.eatWhitespace(); + this.print_string('='); + if (whitespaceChar.test(this._ch)) { + this._ch = ''; + } + } else if (this._ch === '!' && !this._input.lookBack("\\")) { // !important + this.print_string(' '); + this.print_string(this._ch); + } else { + this.preserveSingleSpace(isAfterSpace); + this.print_string(this._ch); + } + } + + var sweetCode = this._output.get_code(eol); + + return sweetCode; +}; + +module.exports.Beautifier = Beautifier; + +},{"../core/directives":99,"../core/inputscanner":100,"../core/output":102,"./options":111}],110:[function(require,module,exports){ +/*jshint node:true */ +/* + + The MIT License (MIT) + + Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +'use strict'; + +var Beautifier = require('./beautifier').Beautifier, + Options = require('./options').Options; + +function css_beautify(source_text, options) { + var beautifier = new Beautifier(source_text, options); + return beautifier.beautify(); +} + +module.exports = css_beautify; +module.exports.defaultOptions = function() { + return new Options(); +}; + +},{"./beautifier":109,"./options":111}],111:[function(require,module,exports){ +/*jshint node:true */ +/* + + The MIT License (MIT) + + Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +'use strict'; + +var BaseOptions = require('../core/options').Options; + +function Options(options) { + BaseOptions.call(this, options, 'css'); + + this.selector_separator_newline = this._get_boolean('selector_separator_newline', true); + this.newline_between_rules = this._get_boolean('newline_between_rules', true); + var space_around_selector_separator = this._get_boolean('space_around_selector_separator'); + this.space_around_combinator = this._get_boolean('space_around_combinator') || space_around_selector_separator; + + var brace_style_split = this._get_selection_list('brace_style', ['collapse', 'expand', 'end-expand', 'none', 'preserve-inline']); + this.brace_style = 'collapse'; + for (var bs = 0; bs < brace_style_split.length; bs++) { + if (brace_style_split[bs] !== 'expand') { + // default to collapse, as only collapse|expand is implemented for now + this.brace_style = 'collapse'; + } else { + this.brace_style = brace_style_split[bs]; + } + } +} +Options.prototype = new BaseOptions(); + + + +module.exports.Options = Options; + +},{"../core/options":101}],112:[function(require,module,exports){ +/*jshint node:true */ +/* + + The MIT License (MIT) + + Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +'use strict'; + +var Options = require('../html/options').Options; +var Output = require('../core/output').Output; +var Tokenizer = require('../html/tokenizer').Tokenizer; +var TOKEN = require('../html/tokenizer').TOKEN; + +var lineBreak = /\r\n|[\r\n]/; +var allLineBreaks = /\r\n|[\r\n]/g; + +var Printer = function(options, base_indent_string) { //handles input/output and some other printing functions + + this.indent_level = 0; + this.alignment_size = 0; + this.max_preserve_newlines = options.max_preserve_newlines; + this.preserve_newlines = options.preserve_newlines; + + this._output = new Output(options, base_indent_string); + +}; + +Printer.prototype.current_line_has_match = function(pattern) { + return this._output.current_line.has_match(pattern); +}; + +Printer.prototype.set_space_before_token = function(value, non_breaking) { + this._output.space_before_token = value; + this._output.non_breaking_space = non_breaking; +}; + +Printer.prototype.set_wrap_point = function() { + this._output.set_indent(this.indent_level, this.alignment_size); + this._output.set_wrap_point(); +}; + + +Printer.prototype.add_raw_token = function(token) { + this._output.add_raw_token(token); +}; + +Printer.prototype.print_preserved_newlines = function(raw_token) { + var newlines = 0; + if (raw_token.type !== TOKEN.TEXT && raw_token.previous.type !== TOKEN.TEXT) { + newlines = raw_token.newlines ? 1 : 0; + } + + if (this.preserve_newlines) { + newlines = raw_token.newlines < this.max_preserve_newlines + 1 ? raw_token.newlines : this.max_preserve_newlines + 1; + } + for (var n = 0; n < newlines; n++) { + this.print_newline(n > 0); + } + + return newlines !== 0; +}; + +Printer.prototype.traverse_whitespace = function(raw_token) { + if (raw_token.whitespace_before || raw_token.newlines) { + if (!this.print_preserved_newlines(raw_token)) { + this._output.space_before_token = true; + } + return true; + } + return false; +}; + +Printer.prototype.previous_token_wrapped = function() { + return this._output.previous_token_wrapped; +}; + +Printer.prototype.print_newline = function(force) { + this._output.add_new_line(force); +}; + +Printer.prototype.print_token = function(token) { + if (token.text) { + this._output.set_indent(this.indent_level, this.alignment_size); + this._output.add_token(token.text); + } +}; + +Printer.prototype.indent = function() { + this.indent_level++; +}; + +Printer.prototype.get_full_indent = function(level) { + level = this.indent_level + (level || 0); + if (level < 1) { + return ''; + } + + return this._output.get_indent_string(level); +}; + +var get_type_attribute = function(start_token) { + var result = null; + var raw_token = start_token.next; + + // Search attributes for a type attribute + while (raw_token.type !== TOKEN.EOF && start_token.closed !== raw_token) { + if (raw_token.type === TOKEN.ATTRIBUTE && raw_token.text === 'type') { + if (raw_token.next && raw_token.next.type === TOKEN.EQUALS && + raw_token.next.next && raw_token.next.next.type === TOKEN.VALUE) { + result = raw_token.next.next.text; + } + break; + } + raw_token = raw_token.next; + } + + return result; +}; + +var get_custom_beautifier_name = function(tag_check, raw_token) { + var typeAttribute = null; + var result = null; + + if (!raw_token.closed) { + return null; + } + + if (tag_check === 'script') { + typeAttribute = 'text/javascript'; + } else if (tag_check === 'style') { + typeAttribute = 'text/css'; + } + + typeAttribute = get_type_attribute(raw_token) || typeAttribute; + + // For script and style tags that have a type attribute, only enable custom beautifiers for matching values + // For those without a type attribute use default; + if (typeAttribute.search('text/css') > -1) { + result = 'css'; + } else if (typeAttribute.search(/module|((text|application|dojo)\/(x-)?(javascript|ecmascript|jscript|livescript|(ld\+)?json|method|aspect))/) > -1) { + result = 'javascript'; + } else if (typeAttribute.search(/(text|application|dojo)\/(x-)?(html)/) > -1) { + result = 'html'; + } else if (typeAttribute.search(/test\/null/) > -1) { + // Test only mime-type for testing the beautifier when null is passed as beautifing function + result = 'null'; + } + + return result; +}; + +function in_array(what, arr) { + return arr.indexOf(what) !== -1; +} + +function TagFrame(parent, parser_token, indent_level) { + this.parent = parent || null; + this.tag = parser_token ? parser_token.tag_name : ''; + this.indent_level = indent_level || 0; + this.parser_token = parser_token || null; +} + +function TagStack(printer) { + this._printer = printer; + this._current_frame = null; +} + +TagStack.prototype.get_parser_token = function() { + return this._current_frame ? this._current_frame.parser_token : null; +}; + +TagStack.prototype.record_tag = function(parser_token) { //function to record a tag and its parent in this.tags Object + var new_frame = new TagFrame(this._current_frame, parser_token, this._printer.indent_level); + this._current_frame = new_frame; +}; + +TagStack.prototype._try_pop_frame = function(frame) { //function to retrieve the opening tag to the corresponding closer + var parser_token = null; + + if (frame) { + parser_token = frame.parser_token; + this._printer.indent_level = frame.indent_level; + this._current_frame = frame.parent; + } + + return parser_token; +}; + +TagStack.prototype._get_frame = function(tag_list, stop_list) { //function to retrieve the opening tag to the corresponding closer + var frame = this._current_frame; + + while (frame) { //till we reach '' (the initial value); + if (tag_list.indexOf(frame.tag) !== -1) { //if this is it use it + break; + } else if (stop_list && stop_list.indexOf(frame.tag) !== -1) { + frame = null; + break; + } + frame = frame.parent; + } + + return frame; +}; + +TagStack.prototype.try_pop = function(tag, stop_list) { //function to retrieve the opening tag to the corresponding closer + var frame = this._get_frame([tag], stop_list); + return this._try_pop_frame(frame); +}; + +TagStack.prototype.indent_to_tag = function(tag_list) { + var frame = this._get_frame(tag_list); + if (frame) { + this._printer.indent_level = frame.indent_level; + } +}; + +function Beautifier(source_text, options, js_beautify, css_beautify) { + //Wrapper function to invoke all the necessary constructors and deal with the output. + this._source_text = source_text || ''; + options = options || {}; + this._js_beautify = js_beautify; + this._css_beautify = css_beautify; + this._tag_stack = null; + + // Allow the setting of language/file-type specific options + // with inheritance of overall settings + var optionHtml = new Options(options, 'html'); + + this._options = optionHtml; + + this._is_wrap_attributes_force = this._options.wrap_attributes.substr(0, 'force'.length) === 'force'; + this._is_wrap_attributes_force_expand_multiline = (this._options.wrap_attributes === 'force-expand-multiline'); + this._is_wrap_attributes_force_aligned = (this._options.wrap_attributes === 'force-aligned'); + this._is_wrap_attributes_aligned_multiple = (this._options.wrap_attributes === 'aligned-multiple'); + this._is_wrap_attributes_preserve = this._options.wrap_attributes.substr(0, 'preserve'.length) === 'preserve'; + this._is_wrap_attributes_preserve_aligned = (this._options.wrap_attributes === 'preserve-aligned'); +} + +Beautifier.prototype.beautify = function() { + + // if disabled, return the input unchanged. + if (this._options.disabled) { + return this._source_text; + } + + var source_text = this._source_text; + var eol = this._options.eol; + if (this._options.eol === 'auto') { + eol = '\n'; + if (source_text && lineBreak.test(source_text)) { + eol = source_text.match(lineBreak)[0]; + } + } + + // HACK: newline parsing inconsistent. This brute force normalizes the input. + source_text = source_text.replace(allLineBreaks, '\n'); + + var baseIndentString = source_text.match(/^[\t ]*/)[0]; + + var last_token = { + text: '', + type: '' + }; + + var last_tag_token = new TagOpenParserToken(); + + var printer = new Printer(this._options, baseIndentString); + var tokens = new Tokenizer(source_text, this._options).tokenize(); + + this._tag_stack = new TagStack(printer); + + var parser_token = null; + var raw_token = tokens.next(); + while (raw_token.type !== TOKEN.EOF) { + + if (raw_token.type === TOKEN.TAG_OPEN || raw_token.type === TOKEN.COMMENT) { + parser_token = this._handle_tag_open(printer, raw_token, last_tag_token, last_token); + last_tag_token = parser_token; + } else if ((raw_token.type === TOKEN.ATTRIBUTE || raw_token.type === TOKEN.EQUALS || raw_token.type === TOKEN.VALUE) || + (raw_token.type === TOKEN.TEXT && !last_tag_token.tag_complete)) { + parser_token = this._handle_inside_tag(printer, raw_token, last_tag_token, tokens); + } else if (raw_token.type === TOKEN.TAG_CLOSE) { + parser_token = this._handle_tag_close(printer, raw_token, last_tag_token); + } else if (raw_token.type === TOKEN.TEXT) { + parser_token = this._handle_text(printer, raw_token, last_tag_token); + } else { + // This should never happen, but if it does. Print the raw token + printer.add_raw_token(raw_token); + } + + last_token = parser_token; + + raw_token = tokens.next(); + } + var sweet_code = printer._output.get_code(eol); + + return sweet_code; +}; + +Beautifier.prototype._handle_tag_close = function(printer, raw_token, last_tag_token) { + var parser_token = { + text: raw_token.text, + type: raw_token.type + }; + printer.alignment_size = 0; + last_tag_token.tag_complete = true; + + printer.set_space_before_token(raw_token.newlines || raw_token.whitespace_before !== '', true); + if (last_tag_token.is_unformatted) { + printer.add_raw_token(raw_token); + } else { + if (last_tag_token.tag_start_char === '<') { + printer.set_space_before_token(raw_token.text[0] === '/', true); // space before />, no space before > + if (this._is_wrap_attributes_force_expand_multiline && last_tag_token.has_wrapped_attrs) { + printer.print_newline(false); + } + } + printer.print_token(raw_token); + + } + + if (last_tag_token.indent_content && + !(last_tag_token.is_unformatted || last_tag_token.is_content_unformatted)) { + printer.indent(); + + // only indent once per opened tag + last_tag_token.indent_content = false; + } + + if (!last_tag_token.is_inline_element && + !(last_tag_token.is_unformatted || last_tag_token.is_content_unformatted)) { + printer.set_wrap_point(); + } + + return parser_token; +}; + +Beautifier.prototype._handle_inside_tag = function(printer, raw_token, last_tag_token, tokens) { + var wrapped = last_tag_token.has_wrapped_attrs; + var parser_token = { + text: raw_token.text, + type: raw_token.type + }; + + printer.set_space_before_token(raw_token.newlines || raw_token.whitespace_before !== '', true); + if (last_tag_token.is_unformatted) { + printer.add_raw_token(raw_token); + } else if (last_tag_token.tag_start_char === '{' && raw_token.type === TOKEN.TEXT) { + // For the insides of handlebars allow newlines or a single space between open and contents + if (printer.print_preserved_newlines(raw_token)) { + raw_token.newlines = 0; + printer.add_raw_token(raw_token); + } else { + printer.print_token(raw_token); + } + } else { + if (raw_token.type === TOKEN.ATTRIBUTE) { + printer.set_space_before_token(true); + last_tag_token.attr_count += 1; + } else if (raw_token.type === TOKEN.EQUALS) { //no space before = + printer.set_space_before_token(false); + } else if (raw_token.type === TOKEN.VALUE && raw_token.previous.type === TOKEN.EQUALS) { //no space before value + printer.set_space_before_token(false); + } + + if (raw_token.type === TOKEN.ATTRIBUTE && last_tag_token.tag_start_char === '<') { + if (this._is_wrap_attributes_preserve || this._is_wrap_attributes_preserve_aligned) { + printer.traverse_whitespace(raw_token); + wrapped = wrapped || raw_token.newlines !== 0; + } + + + if (this._is_wrap_attributes_force) { + var force_attr_wrap = last_tag_token.attr_count > 1; + if (this._is_wrap_attributes_force_expand_multiline && last_tag_token.attr_count === 1) { + var is_only_attribute = true; + var peek_index = 0; + var peek_token; + do { + peek_token = tokens.peek(peek_index); + if (peek_token.type === TOKEN.ATTRIBUTE) { + is_only_attribute = false; + break; + } + peek_index += 1; + } while (peek_index < 4 && peek_token.type !== TOKEN.EOF && peek_token.type !== TOKEN.TAG_CLOSE); + + force_attr_wrap = !is_only_attribute; + } + + if (force_attr_wrap) { + printer.print_newline(false); + wrapped = true; + } + } + } + printer.print_token(raw_token); + wrapped = wrapped || printer.previous_token_wrapped(); + last_tag_token.has_wrapped_attrs = wrapped; + } + return parser_token; +}; + +Beautifier.prototype._handle_text = function(printer, raw_token, last_tag_token) { + var parser_token = { + text: raw_token.text, + type: 'TK_CONTENT' + }; + if (last_tag_token.custom_beautifier_name) { //check if we need to format javascript + this._print_custom_beatifier_text(printer, raw_token, last_tag_token); + } else if (last_tag_token.is_unformatted || last_tag_token.is_content_unformatted) { + printer.add_raw_token(raw_token); + } else { + printer.traverse_whitespace(raw_token); + printer.print_token(raw_token); + } + return parser_token; +}; + +Beautifier.prototype._print_custom_beatifier_text = function(printer, raw_token, last_tag_token) { + var local = this; + if (raw_token.text !== '') { + + var text = raw_token.text, + _beautifier, + script_indent_level = 1, + pre = '', + post = ''; + if (last_tag_token.custom_beautifier_name === 'javascript' && typeof this._js_beautify === 'function') { + _beautifier = this._js_beautify; + } else if (last_tag_token.custom_beautifier_name === 'css' && typeof this._css_beautify === 'function') { + _beautifier = this._css_beautify; + } else if (last_tag_token.custom_beautifier_name === 'html') { + _beautifier = function(html_source, options) { + var beautifier = new Beautifier(html_source, options, local._js_beautify, local._css_beautify); + return beautifier.beautify(); + }; + } + + if (this._options.indent_scripts === "keep") { + script_indent_level = 0; + } else if (this._options.indent_scripts === "separate") { + script_indent_level = -printer.indent_level; + } + + var indentation = printer.get_full_indent(script_indent_level); + + // if there is at least one empty line at the end of this text, strip it + // we'll be adding one back after the text but before the containing tag. + text = text.replace(/\n[ \t]*$/, ''); + + // Handle the case where content is wrapped in a comment or cdata. + if (last_tag_token.custom_beautifier_name !== 'html' && + text[0] === '<' && text.match(/^(|]]>)$/.exec(text); + + // if we start to wrap but don't finish, print raw + if (!matched) { + printer.add_raw_token(raw_token); + return; + } + + pre = indentation + matched[1] + '\n'; + text = matched[4]; + if (matched[5]) { + post = indentation + matched[5]; + } + + // if there is at least one empty line at the end of this text, strip it + // we'll be adding one back after the text but before the containing tag. + text = text.replace(/\n[ \t]*$/, ''); + + if (matched[2] || matched[3].indexOf('\n') !== -1) { + // if the first line of the non-comment text has spaces + // use that as the basis for indenting in null case. + matched = matched[3].match(/[ \t]+$/); + if (matched) { + raw_token.whitespace_before = matched[0]; + } + } + } + + if (text) { + if (_beautifier) { + + // call the Beautifier if avaliable + var Child_options = function() { + this.eol = '\n'; + }; + Child_options.prototype = this._options.raw_options; + var child_options = new Child_options(); + text = _beautifier(indentation + text, child_options); + } else { + // simply indent the string otherwise + var white = raw_token.whitespace_before; + if (white) { + text = text.replace(new RegExp('\n(' + white + ')?', 'g'), '\n'); + } + + text = indentation + text.replace(/\n/g, '\n' + indentation); + } + } + + if (pre) { + if (!text) { + text = pre + post; + } else { + text = pre + text + '\n' + post; + } + } + + printer.print_newline(false); + if (text) { + raw_token.text = text; + raw_token.whitespace_before = ''; + raw_token.newlines = 0; + printer.add_raw_token(raw_token); + printer.print_newline(true); + } + } +}; + +Beautifier.prototype._handle_tag_open = function(printer, raw_token, last_tag_token, last_token) { + var parser_token = this._get_tag_open_token(raw_token); + + if ((last_tag_token.is_unformatted || last_tag_token.is_content_unformatted) && + !last_tag_token.is_empty_element && + raw_token.type === TOKEN.TAG_OPEN && raw_token.text.indexOf(']*)/); + this.tag_check = tag_check_match ? tag_check_match[1] : ''; + } else { + tag_check_match = raw_token.text.match(/^{{(?:[\^]|#\*?)?([^\s}]+)/); + this.tag_check = tag_check_match ? tag_check_match[1] : ''; + + // handle "{{#> myPartial}} + if (raw_token.text === '{{#>' && this.tag_check === '>' && raw_token.next !== null) { + this.tag_check = raw_token.next.text; + } + } + this.tag_check = this.tag_check.toLowerCase(); + + if (raw_token.type === TOKEN.COMMENT) { + this.tag_complete = true; + } + + this.is_start_tag = this.tag_check.charAt(0) !== '/'; + this.tag_name = !this.is_start_tag ? this.tag_check.substr(1) : this.tag_check; + this.is_end_tag = !this.is_start_tag || + (raw_token.closed && raw_token.closed.text === '/>'); + + // handlebars tags that don't start with # or ^ are single_tags, and so also start and end. + this.is_end_tag = this.is_end_tag || + (this.tag_start_char === '{' && (this.text.length < 3 || (/[^#\^]/.test(this.text.charAt(2))))); + } +}; + +Beautifier.prototype._get_tag_open_token = function(raw_token) { //function to get a full tag and parse its type + var parser_token = new TagOpenParserToken(this._tag_stack.get_parser_token(), raw_token); + + parser_token.alignment_size = this._options.wrap_attributes_indent_size; + + parser_token.is_end_tag = parser_token.is_end_tag || + in_array(parser_token.tag_check, this._options.void_elements); + + parser_token.is_empty_element = parser_token.tag_complete || + (parser_token.is_start_tag && parser_token.is_end_tag); + + parser_token.is_unformatted = !parser_token.tag_complete && in_array(parser_token.tag_check, this._options.unformatted); + parser_token.is_content_unformatted = !parser_token.is_empty_element && in_array(parser_token.tag_check, this._options.content_unformatted); + parser_token.is_inline_element = in_array(parser_token.tag_name, this._options.inline) || parser_token.tag_start_char === '{'; + + return parser_token; +}; + +Beautifier.prototype._set_tag_position = function(printer, raw_token, parser_token, last_tag_token, last_token) { + + if (!parser_token.is_empty_element) { + if (parser_token.is_end_tag) { //this tag is a double tag so check for tag-ending + parser_token.start_tag_token = this._tag_stack.try_pop(parser_token.tag_name); //remove it and all ancestors + } else { // it's a start-tag + // check if this tag is starting an element that has optional end element + // and do an ending needed + if (this._do_optional_end_element(parser_token)) { + if (!parser_token.is_inline_element) { + printer.print_newline(false); + } + } + + this._tag_stack.record_tag(parser_token); //push it on the tag stack + + if ((parser_token.tag_name === 'script' || parser_token.tag_name === 'style') && + !(parser_token.is_unformatted || parser_token.is_content_unformatted)) { + parser_token.custom_beautifier_name = get_custom_beautifier_name(parser_token.tag_check, raw_token); + } + } + } + + if (in_array(parser_token.tag_check, this._options.extra_liners)) { //check if this double needs an extra line + printer.print_newline(false); + if (!printer._output.just_added_blankline()) { + printer.print_newline(true); + } + } + + if (parser_token.is_empty_element) { //if this tag name is a single tag type (either in the list or has a closing /) + + // if you hit an else case, reset the indent level if you are inside an: + // 'if', 'unless', or 'each' block. + if (parser_token.tag_start_char === '{' && parser_token.tag_check === 'else') { + this._tag_stack.indent_to_tag(['if', 'unless', 'each']); + parser_token.indent_content = true; + // Don't add a newline if opening {{#if}} tag is on the current line + var foundIfOnCurrentLine = printer.current_line_has_match(/{{#if/); + if (!foundIfOnCurrentLine) { + printer.print_newline(false); + } + } + + // Don't add a newline before elements that should remain where they are. + if (parser_token.tag_name === '!--' && last_token.type === TOKEN.TAG_CLOSE && + last_tag_token.is_end_tag && parser_token.text.indexOf('\n') === -1) { + //Do nothing. Leave comments on same line. + } else { + if (!(parser_token.is_inline_element || parser_token.is_unformatted)) { + printer.print_newline(false); + } + this._calcluate_parent_multiline(printer, parser_token); + } + } else if (parser_token.is_end_tag) { //this tag is a double tag so check for tag-ending + var do_end_expand = false; + + // deciding whether a block is multiline should not be this hard + do_end_expand = parser_token.start_tag_token && parser_token.start_tag_token.multiline_content; + do_end_expand = do_end_expand || (!parser_token.is_inline_element && + !(last_tag_token.is_inline_element || last_tag_token.is_unformatted) && + !(last_token.type === TOKEN.TAG_CLOSE && parser_token.start_tag_token === last_tag_token) && + last_token.type !== 'TK_CONTENT' + ); + + if (parser_token.is_content_unformatted || parser_token.is_unformatted) { + do_end_expand = false; + } + + if (do_end_expand) { + printer.print_newline(false); + } + } else { // it's a start-tag + parser_token.indent_content = !parser_token.custom_beautifier_name; + + if (parser_token.tag_start_char === '<') { + if (parser_token.tag_name === 'html') { + parser_token.indent_content = this._options.indent_inner_html; + } else if (parser_token.tag_name === 'head') { + parser_token.indent_content = this._options.indent_head_inner_html; + } else if (parser_token.tag_name === 'body') { + parser_token.indent_content = this._options.indent_body_inner_html; + } + } + + if (!(parser_token.is_inline_element || parser_token.is_unformatted) && + (last_token.type !== 'TK_CONTENT' || parser_token.is_content_unformatted)) { + printer.print_newline(false); + } + + this._calcluate_parent_multiline(printer, parser_token); + } +}; + +Beautifier.prototype._calcluate_parent_multiline = function(printer, parser_token) { + if (parser_token.parent && printer._output.just_added_newline() && + !((parser_token.is_inline_element || parser_token.is_unformatted) && parser_token.parent.is_inline_element)) { + parser_token.parent.multiline_content = true; + } +}; + +//To be used for

tag special case: +var p_closers = ['address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul']; +var p_parent_excludes = ['a', 'audio', 'del', 'ins', 'map', 'noscript', 'video']; + +Beautifier.prototype._do_optional_end_element = function(parser_token) { + var result = null; + // NOTE: cases of "if there is no more content in the parent element" + // are handled automatically by the beautifier. + // It assumes parent or ancestor close tag closes all children. + // https://www.w3.org/TR/html5/syntax.html#optional-tags + if (parser_token.is_empty_element || !parser_token.is_start_tag || !parser_token.parent) { + return; + + } + + if (parser_token.tag_name === 'body') { + // A head element’s end tag may be omitted if the head element is not immediately followed by a space character or a comment. + result = result || this._tag_stack.try_pop('head'); + + //} else if (parser_token.tag_name === 'body') { + // DONE: A body element’s end tag may be omitted if the body element is not immediately followed by a comment. + + } else if (parser_token.tag_name === 'li') { + // An li element’s end tag may be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element. + result = result || this._tag_stack.try_pop('li', ['ol', 'ul']); + + } else if (parser_token.tag_name === 'dd' || parser_token.tag_name === 'dt') { + // A dd element’s end tag may be omitted if the dd element is immediately followed by another dd element or a dt element, or if there is no more content in the parent element. + // A dt element’s end tag may be omitted if the dt element is immediately followed by another dt element or a dd element. + result = result || this._tag_stack.try_pop('dt', ['dl']); + result = result || this._tag_stack.try_pop('dd', ['dl']); + + + } else if (parser_token.parent.tag_name === 'p' && p_closers.indexOf(parser_token.tag_name) !== -1) { + // IMPORTANT: this else-if works because p_closers has no overlap with any other element we look for in this method + // check for the parent element is an HTML element that is not an ,

+ ${this.textEl} +
` + } +} + +},{"./editor/editor.js":231,"choo/component":31,"choo/html":32}],230:[function(require,module,exports){ +const html = require('choo/html') +const Component = require('choo/component') +const HydraSynth = require('hydra-synth') +const P5 = require('./../lib/p5-wrapper.js') +const PatchBay = require('./../lib/patch-bay/pb-live.js') + + + +module.exports = class Hydra extends Component { + constructor (id, state, emit) { + super(id) + this.local = state.components[id] = {} + state.hydra = this + } + + load (element) { + let isIOS = + (/iPad|iPhone|iPod/.test(navigator.platform) || + (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) && + !window.MSStream; + let precisionValue = isIOS ? 'highp' : 'mediump' + + const pb = new PatchBay() + + const hydra = new HydraSynth({ pb: pb, detectAudio: true, canvas: element.querySelector("canvas"), precision: precisionValue}) + console.log(hydra) + this.hydra = hydra + osc().out() + + pb.init(hydra.captureStream, { + server: window.location.origin, + room: 'iclc' + }) + + window.P5 = P5 + window.pb = pb + + } + + update (center) { + return false + } + + createElement ({ width = window.innerWidth, height = window.innerHeight} = {}) { + + return html`
+
` + } +} + +},{"./../lib/p5-wrapper.js":225,"./../lib/patch-bay/pb-live.js":226,"choo/component":31,"choo/html":32,"hydra-synth":75}],231:[function(require,module,exports){ +/* eslint-disable no-eval */ +var CodeMirror = require('codemirror-minified/lib/codemirror') +require('codemirror-minified/mode/javascript/javascript') +require('codemirror-minified/addon/hint/javascript-hint') +require('codemirror-minified/addon/hint/show-hint') +require('codemirror-minified/addon/selection/mark-selection') +require('codemirror-minified/addon/comment/comment') + +const EventEmitter = require('nanobus') +const keymaps = require('./keymaps.js') +const Mutator = require('./randomizer/Mutator.js'); +const beautify_js = require('js-beautify').js_beautify + +var isShowing = true + + +module.exports = class Editor extends EventEmitter { + constructor(parent) { + super() + console.log("*** Editor class created"); + var self = this + + // var container = document.createElement('div') + // container.setAttribute('id', 'editor-container') + // var el = document.createElement('TEXTAREA') + // document.body.appendChild(container) + // container.appendChild(el) + + this.mutator = new Mutator(this); + + const extraKeys = {} + Object.entries(keymaps).forEach(([key, e]) => extraKeys[key] = () => { + if(e == 'editor:evalBlock') { + this.emit(e, this.getCurrentBlock().text) + } else if (e == 'editor:evalLine') { + this.emit(e, this.getLine()) + } else if (e == 'editor:toggleComment') { + this.cm.toggleComment() + // } else if (e == 'gallery:saveToURL') { + this.emit(e, this) + } else if (e === 'editor:formatCode') { + this.formatCode() + } else { + this.emit(e, this) + } + }) + + const opts = { + theme: 'tomorrow-night-eighties', + value: 'hello', + mode: { name: 'javascript', globalVars: true }, + lineWrapping: true, + styleSelectedText: true, + extraKeys: extraKeys + } + + this.cm = CodeMirror.fromTextArea(parent, opts) + window.cm = this.cm + this.cm.refresh() + + // this.show() + // // // TO DO: add show code param + // let searchParams = new URLSearchParams(window.location.search) + // let showCode = searchParams.get('show-code') + + // if (showCode === "false") { + // this.hide() + // } + } + + clear() { + this.cm.setValue('\n \n // Type some code on a new line (such as "osc().out()"), and press CTRL+shift+enter') + } + + setValue(val) { + this.cm.setValue(val) + } + + getValue() { + return this.cm.getValue() + } + + formatCode() { + const formatted = beautify_js(this.cm.getValue(), { indent_size: 2, "break_chained_methods": true, "indent_with_tabs": true}) + this.cm.setValue(formatted) + } + + // hide() { + // console.log('hiding') + // var l = document.getElementsByClassName('CodeMirror')[0] + // var m = document.getElementById('modal-header') + // l.style.opacity = 0 + // m.style.opacity = 0 + // this.isShowing = false + // } + + // show() { + // var l = document.getElementsByClassName('CodeMirror')[0] + // var m = document.getElementById('modal-header') + // l.style.opacity= 1 + // m.style.opacity = 1 + // l.style.pointerEvents = 'all' + // this.isShowing = true + // } + + toggle() { + if (this.isShowing) { + this.hide() + } else { + this.show() + } + } + + getLine() { + var c = this.cm.getCursor() + var s = this.cm.getLine(c.line) + // this.cm.markText({line: c.line, ch:0}, {line: c.line+1, ch:0}, {className: 'styled-background'}) + this.flashCode({ line: c.line, ch: 0 }, { line: c.line + 1, ch: 0 }) + return s + } + + flashCode(start, end) { + if (!start) start = { line: this.cm.firstLine(), ch: 0 } + if (!end) end = { line: this.cm.lastLine() + 1, ch: 0 } + var marker = this.cm.markText(start, end, { className: 'styled-background' }) + setTimeout(() => marker.clear(), 300) + } + + + getCurrentBlock() { // thanks to graham wakefield + gibber + var editor = this.cm + var pos = editor.getCursor() + var startline = pos.line + var endline = pos.line + while (startline > 0 && editor.getLine(startline) !== '') { + startline-- + } + while (endline < editor.lineCount() && editor.getLine(endline) !== '') { + endline++ + } + var pos1 = { + line: startline, + ch: 0 + } + var pos2 = { + line: endline, + ch: 0 + } + var str = editor.getRange(pos1, pos2) + + this.flashCode(pos1, pos2) + + return { + start: pos1, + end: pos2, + text: str + } + } + +} + + +},{"./keymaps.js":232,"./randomizer/Mutator.js":234,"codemirror-minified/addon/comment/comment":36,"codemirror-minified/addon/hint/javascript-hint":37,"codemirror-minified/addon/hint/show-hint":38,"codemirror-minified/addon/selection/mark-selection":39,"codemirror-minified/lib/codemirror":40,"codemirror-minified/mode/javascript/javascript":41,"js-beautify":98,"nanobus":124}],232:[function(require,module,exports){ +module.exports = { + 'Ctrl-Enter': 'editor:evalLine', + 'Ctrl-/': 'editor:toggleComment', + 'Alt-Enter': 'editor:evalBlock', + 'Shift-Ctrl-Enter': 'editor:evalAll', + 'Shift-Ctrl-G': 'gallery:shareSketch', + 'Shift-Ctrl-F': 'editor:formatCode', + 'Shift-Ctrl-L': 'gallery:saveToURL', + 'Shift-Ctrl-H': 'hideAll', + 'Shift-Ctrl-S': 'screencap' +} +},{}],233:[function(require,module,exports){ +var logElement + +module.exports = { + init: () => { + logElement = document.createElement('div') + logElement.className = "console cm-s-tomorrow-night-eighties" + document.body.appendChild(logElement) + }, + log: (msg, className = "") => { + if(logElement) logElement.innerHTML =` >> ${msg} ` + }, + hide: () => { + if(logElement) logElement.style.display = 'none' + }, + show: () => { + if(logElement) logElement.style.display = 'block' + }, + toggle: () => { + if(logElement.style.display == 'none') { + logElement.style.display = 'block' + } else { + logElement.style.display = 'none' + } + } +} + +},{}],234:[function(require,module,exports){ +const {Parser} = require("acorn"); +const {generate} = require('astring'); +const { defaultTraveler, attachComments, makeTraveler } = require('astravel'); +const {UndoStack} = require('./UndoStack.js'); +const repl = require('./../repl.js') +const glslTransforms = require('hydra-synth/src/glsl/glsl-functions.js')() + +class Mutator { + + constructor(editor) { + this.editor = editor; + this.undoStack = new UndoStack(); + + this.initialVector = []; + + this.funcTab = {}; + this.transMap = {}; + this.scanFuncs(); + this.dumpDict(); + } + + dumpList() { + let gslTab = glslTransforms; + gslTab.forEach (v => { + var argList = ""; + v.inputs.forEach((a) => { + if (argList != "") argList += ", "; + let argL = a.name + ": " + a.type + " {" + a.default + "}"; + argList = argList + argL; + }); + // console.log(v.name + " [" + v.type + "] ("+ argList + ")"); + }); + } + + scanFuncs() { + let gslTab = glslTransforms; + gslTab.forEach (f => { + this.transMap[f.name] = f; + if (this.funcTab[f.type] === undefined) {this.funcTab[f.type] = []} + this.funcTab[f.type].push(f); + }); + } + + dumpDict() { + for(let tn in this.funcTab) + { + this.funcTab[tn].forEach(f => { + var argList = ""; + f.inputs.forEach((a) => { + if (argList != "") argList += ", "; + let argL = a.name + ": " + a.type + " {" + a.default + "}"; + argList = argList + argL; + }); + //console.log(f.name + " [" + f.type + "] ("+ argList + ")"); + }); + } + } + + mutate(options) { + // Get text from CodeMirror. + let text = this.editor.cm.getValue(); + this.undoStack.push({text, lastLitX: this.lastLitX}); + let needToRun = true; + let tryCounter = 5; + while (needToRun && tryCounter-- >= 0) { + // Parse to AST + var comments = []; + let ast = Parser.parse(text, { + locations: true, + onComment: comments} + ); + + // Modify the AST. + this.transform(ast, options); + + // Put the comments back. + attachComments(ast, comments); + + // Generate JS from AST and set back into CodeMirror editor. + let regen = generate(ast, {comments: true}); + + this.editor.cm.setValue(regen); + try { + // Evaluate the updated expression. + repl.eval(regen, (code, error) => { + // If we got an error, keep trying something else. + if (error) { + console.log("Eval error: " + regen); + } + needToRun = error; + }); + } catch (err) { + console.log("Exception caught: " + err); + needToRun = err; + } + } + } + + doUndo() { + // If the current text is unsaved, save it so we can redo if need be. + if (this.undoStack.atTop()) { + let text = this.editor.cm.getValue(); + this.undoStack.push({text, lastLitX: this.lastLitX}); + } + // Then pop-off the info to restore. + if (this.undoStack.canUndo()) { + let {text, lastLitX} = this.undoStack.undo(); + this.setText(text); + this.lastLitX = lastLitX; + } + } + + doRedo() { + if(this.undoStack.canRedo()) { + let {text, lastLitX} = this.undoStack.redo(); + this.setText(text); + this.lastLitX = lastLitX; + } + } + + setText(text) { + this.editor.cm.setValue(text); + repl.eval(text, (code, error) => { + }); + + } + + // The options object contains a flag that controls how the + // Literal to mutate is determined. If reroll is false, we + // pick one at random. If reroll is true, we use the same field + // we did last time. + transform(ast, options) { + // An AST traveler that accumulates a list of Literal nodes. + let traveler = makeTraveler({ + go: function(node, state) { + if (node.type === 'Literal') { + state.literalTab.push(node); + } else if (node.type === 'MemberExpression') { + if (node.property && node.property.type === 'Literal') { + // numeric array subscripts are ineligable + return; + } + } else if (node.type === 'CallExpression') { + if (node.callee && node.callee.property && node.callee.property.name && node.callee.property.name !== 'out') { + state.functionTab.push(node); + } + } + // Call the parent's `go` method + this.super.go.call(this, node, state); + } + }); + + let state = {}; + state.literalTab = []; + state.functionTab = []; + + traveler.go(ast, state); + + this.litCount = state.literalTab.length; + this.funCount = state.functionTab.length; + if (this.litCount !== this.initialVector.length) { + let nextVect = []; + for(let i = 0; i < this.litCount; ++i) { + nextVect.push(state.literalTab[i].value); + } + this.initialVector = nextVect; + } + if (options.changeTransform) { + this.glitchTrans(state, options); + } + else this.glitchLiteral(state, options); + +} + + glitchLiteral(state, options) + { + let litx = 0; + if (options.reroll) { + if (this.lastLitX !== undefined) { + litx = this.lastLitX; + } + } else { + litx = Math.floor(Math.random() * this.litCount); + this.lastLitX = litx; + } + + let modLit = state.literalTab[litx]; + if (modLit) { + // let glitched = this.glitchNumber(modLit.value); + let glitched = this.glitchRelToInit(modLit.value, this.initialVector[litx]); + let was = modLit.raw; + modLit.value = glitched; + modLit.raw = "" + glitched; + console.log("Literal: " + litx + " changed from: " + was + " to: " + glitched); + } + } + + glitchNumber(num) { + if (num === 0) { + num = 1; + } + let range = num * 2; + let rndVal = Math.round(Math.random() * range * 1000) / 1000; + return rndVal; + } + + glitchRelToInit(num, initVal) { + if (initVal === undefined) { + return glitchNumber(num); + } if (initVal === 0) { + initVal = 0.5; + } + + let rndVal = Math.round(Math.random() * initVal * 2 * 1000) / 1000; + return rndVal; +} + glitchTrans(state, options) + { +/* + state.functionTab.forEach((f)=>{ + console.log(f.callee.property.name); + }); +*/ + let funx = Math.floor(Math.random() * this.funCount); + if (state.functionTab[funx] === undefined || state.functionTab[funx].callee === undefined || state.functionTab[funx].callee.property === undefined) { + console.log("No valid functionTab for index: " + funx); + return; + } + let oldName = state.functionTab[funx].callee.property.name; + + if (oldName == undefined) { + console.log("No name for callee"); + return; + } + let ftype = this.transMap[oldName].type; + if (ftype == undefined) { + console.log("ftype undefined for: " + oldName); + return; + } + let others = this.funcTab[ftype]; + if (others == undefined) { + console.log("no funcTab entry for: " + ftype); + return; + } + let changeX = Math.floor(Math.random() * others.length); + let become = others[changeX].name; + + // check blacklisted combinations. + if (oldName === "modulate" && become === "modulateScrollX") + { + console.log("Function: " + funx + " changing from: " + oldName + " can't change to: " + become); + return; + } + + state.functionTab[funx].callee.property.name = become; + console.log("Function: " + funx + " changed from: " + oldName + " to: " + become); + } + +} // End of class Mutator. + +module.exports = Mutator + +},{"./../repl.js":236,"./UndoStack.js":235,"acorn":3,"astravel":8,"astring":11,"hydra-synth/src/glsl/glsl-functions.js":81}],235:[function(require,module,exports){ +// A generalized 'Undo stack' which can keep N levels of revertable state. +class UndoStack { + constructor(limit) { + this.stack = []; + this.index = -1; + this.limit = limit; + } + + atTop() { + return this.index === -1; + } + + canUndo() { + if(this.stack.length === 0) return false; + return this.index === -1 || this.index > 0; + } + + canRedo() { + if(this.stack.length === 0 || this.index === -1) return false; + return this.index < this.stack.length - 1; + } + + push(item) { + if (this.index >= 0) { + while (this.index < this.stack.length) this.stack.pop(); + this.index = -1; + } + if (this.limit && this.stack.length > this.limit) { + this.stack.shift(); + } + this.stack.push(item); + } + + undo() { + if (this.stack.length === 0) return undefined; + if (this.index === -1) { // start one behind the redo buffer + this.index = this.stack.length - 1; + } + if (this.index > 0) this.index--; + let v = this.stack[this.index]; + return v; + } + + redo() { + if (this.stack.length === 0 || this.index === -1) return undefined; + let nextX = this.index + 1; + if (nextX >= this.stack.length) return undefined; + this.index = nextX; + return this.stack[this.index]; + } +}; + + +module.exports = {UndoStack} +},{}],236:[function(require,module,exports){ +const log = require('./log.js').log + +module.exports = { + eval: (arg, callback) => { + var self = this + + // wrap everything in an async function + var jsString = `(async() => { + ${arg} +})().catch(${(err) => log(err.message, "log-error")})` + var isError = false + try { + eval(jsString) + // log(jsString) + log('') + } catch (e) { + isError = true + console.log("logging", e) + // var err = e.constructor('Error in Evaled Script: ' + e.message); + // console.log(err.lineNumber) + log(e.message, "log-error") + //console.log('ERROR', JSON.stringify(e)) + } + // console.log('callback is', callback) + if(callback) callback(jsString, isError) + } +} + +},{"./log.js":233}],237:[function(require,module,exports){ +const html = require('choo/html') +const toolbar = require('./toolbar.js') + +module.exports = function mainView(state, emit) { + return html` +
+ +
+ ` +} +},{"./toolbar.js":239,"choo/html":32}],238:[function(require,module,exports){ +const html = require('choo/html') +const info = require('./info.js') +const Hydra = require('./Hydra.js') +const Editor = require('./EditorComponent.js') + +module.exports = function mainView(state, emit) { + return html` + +
+ ${state.cache(Hydra, 'hydra-canvas').render(state, emit)} + +
+ ${info(state, emit)} + ${state.cache(Editor, 'editor').render(state, emit)} + + ` +} +},{"./EditorComponent.js":229,"./Hydra.js":230,"./info.js":237,"choo/html":32}],239:[function(require,module,exports){ +const html = require('choo/html') + +module.exports = function toolbar(state, emit) { + const hidden = state.showInfo ? 'hidden' : '' + + const dispatch = (eventName) => (e) => emit(eventName, e) + + const icon = (id, className, title, event) => html` + ` + + return html`
+ ${icon("run", `fa-play-circle ${hidden}`, "Run all code (ctrl+shift+enter)", 'editor:evalAll')} + ${icon("share", `fa-upload ${hidden}`, "upload to gallery", 'gallery:shareSketch')} + ${icon("clear", `fa fa-trash ${hidden}`, "clear all", 'editor:clearAll')} + ${icon("shuffle", `fa-random`, "show random sketch", 'gallery:showExample')} + ${icon("mutator", `fa-dice ${hidden}`, "make random change", 'editor:randomize')} + ${icon("close", state.showInfo? "fa-times" : "fa-question-circle", "", 'toggle info')} +
` +} +},{"choo/html":32}]},{},[1]); diff --git a/frontend/web-editor/src/older/patch-bay/pb-live.js b/frontend/web-editor/src/older/patch-bay/pb-live.js deleted file mode 100755 index 312cff1..0000000 --- a/frontend/web-editor/src/older/patch-bay/pb-live.js +++ /dev/null @@ -1,138 +0,0 @@ -/* globals sessionStorage */ -// Extends rtc-patch-bay to include support for nicknames and persistent session storage - -var PatchBay = require('./rtc-patch-bay.js') -//var PatchBay = require('./../../../../rtc-patch-bay') -var inherits = require('inherits') - -var PBLive = function () { - this.session = {} - - // lookup tables for converting id to nickname - this.nickFromId = {} - this.idFromNick = {} - - this.loadFromStorage() -} -// inherits from PatchBay module -inherits(PBLive, PatchBay) - -PBLive.prototype.init = function (stream, opts) { - this.settings = { - server: opts.server || 'https://patch-bay.glitch.me/', - room: opts.room || 'patch-bay', - stream: stream - } - - this.makeGlobal = opts.makeGlobal || true - this.setPageTitle = opts.setTitle || true - - if (this.session.id) this.settings.id = this.session.id - - PatchBay.call(this, this.settings) - - if (this.makeGlobal) window.pb = this - - this.on('ready', () => { - if (!this.nick) { - if (this.session.nick) { - this.setName(this.session.nick) - } else { - this.session.id = this.id - this.setName(this.session.id) - } - } - console.log('connected to server ' + this.settings.server + ' with name ' + this.settings.id) - }) - // received a broadcast - this.on('broadcast', this._processBroadcast.bind(this)) - this.on('new peer', this.handleNewPeer.bind(this)) - - window.onbeforeunload = () => { - this.session.id = window.pb.id - this.session.nick = this.nick - sessionStorage.setItem('pb', JSON.stringify(this.session)) - } - - var self = this - this.on('stream', function (id, stream) { - console.log('got stream!', id, stream) - const video = document.createElement('video') - if ('srcObject' in video) { - video.srcObject = stream - } else { - // Avoid using this in new browsers, as it is going away. - video.src = window.URL.createObjectURL(stream) - } - // video.src = window.URL.createObjectURL(stream) - video.addEventListener('loadedmetadata', () => { - // console.log("loaded meta22") - video.play() - self.video = video - self.emit('got video', self.nickFromId[id], video) - }) - }) -} - -PBLive.prototype.loadFromStorage = function () { - if (sessionStorage.getItem('pb') !== null) { - this.session = JSON.parse(sessionStorage.getItem('pb')) - } -} - -PBLive.prototype.initSource = function (nick, callback) { - this.initConnectionFromId(this.idFromNick[nick], callback) -// this.peers[this.idFromNick[nick]].streamCallback = callback -} - -// default nickname is just peer id. -// to do: save nickname information between sessions -PBLive.prototype.handleNewPeer = function (peer) { - // console.log("new peer", peer) - this.nickFromId[peer] = peer - this.idFromNick[peer] = peer - // console.log("THIS IS THE PEER", peer) - // to do: only send to new peer, not to all - if (this.nick) { - this.broadcast({ - type: 'update-nick', - id: this.id, - nick: this.nick - }) - } -} - -PBLive.prototype.list = function () { - var l = Object.keys(this.idFromNick) - //console.log(l) - return Object.keys(this.idFromNick) -} - -// choose an identifying name -PBLive.prototype.setName = function (nick) { - this.broadcast({ - type: 'update-nick', - id: this.id, - nick: nick, - previous: this.nick - }) - this.nick = nick - if (this.setPageTitle) document.title = nick -} - -PBLive.prototype._processBroadcast = function (data) { - if (data.type === 'update-nick') { - if (data.previous !== data.nick) { - delete this.idFromNick[this.nickFromId[data.id]] - this.nickFromId[data.id] = data.nick - this.idFromNick[data.nick] = data.id - if (data.previous) { - //console.log(data.previous + ' changed to ' + data.nick) - } else { - //console.log('connected to ' + data.nick) - } - } - } -} -// PBExtended.prototype. -module.exports = PBLive diff --git a/frontend/web-editor/src/older/patch-bay/rtc-patch-bay.js b/frontend/web-editor/src/older/patch-bay/rtc-patch-bay.js deleted file mode 100644 index fba8ae9..0000000 --- a/frontend/web-editor/src/older/patch-bay/rtc-patch-bay.js +++ /dev/null @@ -1,251 +0,0 @@ -// Module for handling connections to multiple peers. - - -var io = require('socket.io-client') -var SimplePeer = require('simple-peer') -var extend = Object.assign -var events = require('events').EventEmitter -var inherits = require('inherits') -const shortid = require('shortid') - -var PatchBay = function (options) { -// connect to websocket signalling server. To DO: error validation - this.signaller = io(options.server) - - //assign unique id to this peer, or use id passed in - - this.id = options.id || shortid.generate() - - this.stream = options.stream || null - - //options to be sent to simple peer - this._peerOptions = options.peerOptions || {} - this._room = options.room - - - this.settings['shareMediaWhenRequested'] = true - this.settings['shareMediaWhenInitiating'] = false - this.settings['requestMediaWhenInitiating'] = true - this.settings['autoconnect'] = false - - //object containing ALL peers in room - this.peers = {} - - //object containing peers connected via webrtc - this.rtcPeers = {} - - // Handle events from signalling server - this.signaller.on('ready', this._readyForSignalling.bind(this)) -// this.signaller.on('peers', ) -// this.signaller.on('signal', this._handleSignal.bind(this)) - this.signaller.on('message', this._handleMessage.bind(this)) - // Received message via websockets to all peers in room - this.signaller.on('broadcast', this._receivedBroadcast.bind(this)) - - // emit 'join' event to signalling server - this.signaller.emit('join', this._room, {uuid: this.id}) - - this.signaller.on('new peer', this._newPeer.bind(this)) -} -// inherits from events module in order to trigger events -inherits(PatchBay, events) - -// send data to all connected peers via data channels -PatchBay.prototype.sendToAll = function (data) { - Object.keys(this.rtcPeers).forEach(function (id) { - this.rtcPeers[id].send(data) - }, this) -} - -// sends to peer specified b -PatchBay.prototype.sendToPeer = function (peerId, data) { - if (peerId in this.rtcPeers) { - this.rtcPeers[peerId].send(data) - } -} - -PatchBay.prototype.reinitAll = function(){ - Object.keys(this.rtcPeers).forEach(function (id) { - this.reinitPeer(id) - }.bind(this)) -// this._connectToPeers.bind(this) -} - -PatchBay.prototype.initRtcPeer = function(id, opts) { - this.emit('new peer', {id: id}) - var newOptions = opts - // console.log() - if(this.iceServers) { - opts['config'] = { - iceServers: this.iceServers - } - } - - if(opts.initiator === true) { - if (this.stream != null) { - if(this.settings.shareMediaWhenInitiating === true){ - newOptions.stream = this.stream - } - } - if(this.settings.requestMediaWhenInitiating === true){ - newOptions.offerConstraints = { - offerToReceiveVideo: true, - offerToReceiveAudio: true - } - } - } else { - if(this.settings.shareMediaWhenRequested === true){ - if (this.stream != null) { - newOptions.stream = this.stream - } - } - } - var options = extend(this._peerOptions, newOptions) -//console.log("OPTIONS", options) - this.rtcPeers[id] = new SimplePeer(options) - this._attachPeerEvents(this.rtcPeers[id], id) -} - -PatchBay.prototype.reinitRtcConnection = function(id, opts){ - // Because renegotiation is not implemeneted in SimplePeer, reinitiate connection when configuration has changed - this.rtcPeers[id]._destroy(null, function(e){ - this.initRtcPeer(id, { - stream: this.stream, - initiator: true - }) - }.bind(this)) -} -// //new peer connected to signalling server -PatchBay.prototype._newPeer = function (peer){ - // this.connectedIds.push(peer) - - - // Configuration for specified peer. - // Individual configuration controls whether will receive media from - // and/or send media to a specific peer. - - this.peers[peer] = { - rtcPeer: null - } - - this.emit('new peer', peer) - // this.emit('updated peer list', this.connectedIds) -} -// // Once the new peer receives a list of connected peers from the server, -// // creates new simple peer object for each connected peer. -PatchBay.prototype._readyForSignalling = function ({ peers, servers }) { -// console.log("received peer list", _t, this.peers) - - peers.forEach((peer) => { - this._newPeer(peer) - }) - - // if received ice and turn server information from signalling server, use in establishing - if(servers) { - this.iceServers = servers - } -// this.peers = peers - this.emit('ready') -} - -// Init connection to RECEIVE video -PatchBay.prototype.initConnectionFromId = function(id, callback){ -// console.log("initianing connection") - if(id in this.rtcPeers){ - console.log("Already connected to..", id, this.rtcPeers) - //if this peer was originally only sending a stream (not receiving), recreate connecting but this time two-way - if(this.rtcPeers[id].initiator===false){ - this.reinitRtcConnection(id) - } else { - //already connected, do nothing - - } - } else { - this.initRtcPeer(id, { - initiator: true - }) - } -} - - -// receive signal from signalling server, forward to simple-peer -PatchBay.prototype._handleMessage = function (data) { - // if there is currently no peer object for a peer id, that peer is initiating a new connection. - - if (data.type === 'signal'){ - this._handleSignal(data) - } else { - this.emit('message', data) - } -} -// receive signal from signalling server, forward to simple-peer -PatchBay.prototype._handleSignal = function (data) { - // if there is currently no peer object for a peer id, that peer is initiating a new connection. - if (!this.rtcPeers[data.id]) { - // this.emit('new peer', data) - // var options = extend({stream: this.stream}, this._peerOptions) - // this.rtcPeers[data.id] = new SimplePeer(options) - // this._attachPeerEvents(this.rtcPeers[data.id], data.id) - - this.initRtcPeer(data.id, {initiator: false}) - } - this.rtcPeers[data.id].signal(data.message) -} -// sendToAll send through rtc connections, whereas broadcast -// send through the signalling server. Useful in cases where -// not all peers are connected via webrtc with other peers -PatchBay.prototype._receivedBroadcast = function(data) { - //console.log("RECEIVED BROADCAST", data) - this.emit('broadcast', data) -} - -//sends via signalling server -PatchBay.prototype.broadcast = function (data) { - this.signaller.emit('broadcast', data) -} -// handle events for each connected peer -PatchBay.prototype._attachPeerEvents = function (p, _id) { - p.on('signal', function (id, signal) { - // console.log('signal', id, signal) - // console.log("peer signal sending over sockets", id, signal) - // this.signaller.emit('signal', {id: id, signal: signal}) - this.signaller.emit('message', {id: id, message: signal, type: 'signal'}) - }.bind(this, _id)) - - p.on('stream', function (id, stream) { - this.rtcPeers[id].stream = stream - // console.log('E: stream', id, stream) - // console.log("received a stream", stream) - this.emit('stream', id, stream) - }.bind(this, _id)) - - p.on('connect', function (id) { - // console.log("connected to ", id) - this.emit('connect', id) - }.bind(this, _id)) - - p.on('data', function (id, data) { -// console.log('data', id) - this.emit('data', {id: id, data: JSON.parse(data)}) - }.bind(this, _id)) - - p.on('close', function (id) { - //console.log('CLOSED') - delete (this.rtcPeers[id]) - this.emit('close', id) - }.bind(this, _id)) - - p.on('error', function(e){ - console.warn("simple peer error", e) - }) -} - -PatchBay.prototype._destroy = function () { - Object.values(this.rtcPeers).forEach( function (peer) { - peer.destroy() - }) - this.signaller.close() -} - - -module.exports = PatchBay diff --git a/frontend/web-editor/src/views/Hydra.js b/frontend/web-editor/src/views/Hydra.js index 50050ec..b4b4b7a 100644 --- a/frontend/web-editor/src/views/Hydra.js +++ b/frontend/web-editor/src/views/Hydra.js @@ -1,6 +1,10 @@ const html = require('choo/html') const Component = require('choo/component') const HydraSynth = require('hydra-synth') +const P5 = require('./../lib/p5-wrapper.js') +const PatchBay = require('./../lib/patch-bay/pb-live.js') + + module.exports = class Hydra extends Component { constructor (id, state, emit) { @@ -10,10 +14,27 @@ module.exports = class Hydra extends Component { } load (element) { - const hydra = new HydraSynth({ detectAudio: true, canvas: element.querySelector("canvas")}) + let isIOS = + (/iPad|iPhone|iPod/.test(navigator.platform) || + (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) && + !window.MSStream; + let precisionValue = isIOS ? 'highp' : 'mediump' + + const pb = new PatchBay() + + const hydra = new HydraSynth({ pb: pb, detectAudio: true, canvas: element.querySelector("canvas"), precision: precisionValue}) console.log(hydra) this.hydra = hydra osc().out() + + pb.init(hydra.captureStream, { + server: window.location.origin, + room: 'iclc' + }) + + window.P5 = P5 + window.pb = pb + } update (center) { diff --git a/frontend/web-editor/src/views/main.js b/frontend/web-editor/src/views/main.js index 2340054..159526e 100644 --- a/frontend/web-editor/src/views/main.js +++ b/frontend/web-editor/src/views/main.js @@ -2,22 +2,17 @@ const html = require('choo/html') const info = require('./info.js') const Hydra = require('./Hydra.js') const Editor = require('./EditorComponent.js') -module.exports = function mainView (state, emit) { - return html` - + +module.exports = function mainView(state, emit) { + return html` +
- - ${state.cache(Hydra, 'hydra-canvas').render(state, emit)} - -
+ ${state.cache(Hydra, 'hydra-canvas').render(state, emit)} + + ${info(state, emit)} ${state.cache(Editor, 'editor').render(state, emit)} - ` - - function onclick () { - emit('increment', 1) - } - } \ No newline at end of file +} \ No newline at end of file