Пример #1
0
  isFn(node) {
    if (!isString(node['!type'])) {
      return false
    }

    return Parser.MATCHES.fn.test(node['!type'])
  }
Пример #2
0
  fnArgs(node) {
    if (!isString(node['!type'])) {
      return []
    }

    const args = node['!type'].match(Parser.MATCHES.args)

    if (!Array.isArray(args) || !args.length) {
      return ''
    }

    return args.pop().split(',').map(function (arg) {
      const t = arg.match(Parser.MATCHES.arg)

      if (!Array.isArray(t) || !t.length) {
        return null
      }

      const type = t.pop()

      if (this.define[type] && this.define[type]['!type']) {
        return this.typeFn(this.define[type]['!type'])
      }

      if (type && Parser.MATCHES.arrArg.test(type)) {
        return 'Array'.concat(type)
      }

      return type
    }, this).filter(function (type) {
      return !!type
    })
  }
Пример #3
0
  lineno(node) {
    if (!isString(node['!span'])) {
      return null
    }

    return Number(node['!span'].match(Parser.MATCHES.lineno).pop()) + 1
  }
Пример #4
0
module.exports = function escapeHTML(value) {
  if (!isString(value)) {
    return value;
  }

  return value.replace(escapeRegex, match => escapeMap[match]);
};
Пример #5
0
    return Parser.DEFAULT_TYPES.some(function (dt) {
      if (isString(dt)) {
        return type === dt
      }

      return dt.test(type)
    })
Пример #6
0
module.exports = function withGlobal(globalName, valueThunk) {
	var isNonEmptyString = isString(globalName) && globalName.length > 0;
	if (!isNonEmptyString && !isSymbol(globalName)) {
		throw new TypeError('global name must be a non-empty string or a Symbol');
	}

	return this.use(withOverride, getGlobal, globalName, valueThunk).extend('with global: ' + inspect(globalName));
};
Пример #7
0
 prepend: function(el){
     if (!this.view) throw new Error(NO_VIEW_ERROR_MSG);
     if (isString(el)){
         // This is an HTML tag or a Text node
         el = domify(el);
     }
     prepend(this.view, el);
     return this;
 },
Пример #8
0
 return formatted.map((val) => {
   // Only if this is a string (not a nested array, which would have already been padded)
   if (isString(val) && val.length < maxLength) {
     // Depending on symbol position, pad after symbol or at index 0
     return padAfterSymbol ?
       val.replace(opts.symbol, opts.symbol + (new Array(maxLength - val.length + 1).join(' '))) :
       (new Array(maxLength - val.length + 1).join(' ')) + val;
   }
   return val;
 });
Пример #9
0
 function parseKeys (key) {
   if (isString(key)) {
     var keys = key.split('.').map(function (key) {
       if (isNumber(key)) return parseInt(key)
       return key
     })
     return keys
   }
   return key
 }
Пример #10
0
 prependTo: function(elOrSelector){
     if (!this.view) throw new Error(NO_VIEW_ERROR_MSG);
     var el = elOrSelector;
     if (isString(el)){ el = select(el) }
     if (el && el._isSpookyElement){ el = el.view; }
     prepend(el, this.view);
     // dispatch
     this.onPrepended.dispatch(this);
     return this;
 },
      return Object.keys(reporters).map((reporter) => {
        debug('adding reporter %j %j', reporter, reporters[reporter]);
        const r = reporters[reporter];

        if (isString(r)) {
          return [reporter, r, null];
        }

        return [reporter, r.stdout, r.options];
      });
Пример #12
0
var SpookyElement = function(elOrData, parentOrData){
    
    // Create an instance if calling without new
    if (!(this instanceof SpookyElement)){
        return new SpookyElement(elOrData, parentOrData);
    }

    if (elOrData){
        // If the passed elemen is already an instance of spooky element, return the passed element
        if (elOrData._isSpookyElement){
            return elOrData;
        } else if (elOrData.jquery){
            // If a jquery object then extract th dom element
            if (elOrData.length){
                elOrData = elOrData[0];
            } else {
                return this;
            }
        }
    }

    // Parent (context) object could be a jQuery element
    if (parentOrData && parentOrData.jquery){
        parentOrData = (parentOrData.length) ? parentOrData[0] : null;
    }

    this._view = null;
    this.onAppended = new Signal();
    this.onPrepended = new Signal();

    if (isFunction(elOrData)){
        // THis must be a template
        this.template = elOrData;
        var dom = domify( this._render(parentOrData) );
        this.view = dom;
    } else if (isString(elOrData)){
        if (elOrData.indexOf('<') === 0){
            // This is a tag
            this.view = domify(elOrData);
        } else {
            // This is a selector
            this.select(elOrData, parentOrData);
        }
    } else if (isElement(elOrData)){
        this.view = elOrData;
    } else if (this.template){
        this.view = domify( this._render(elOrData) );
    }

    // Set this to identify spooky elements
    this._isSpookyElement = true;

}
Пример #13
0
 function normaliseUnit(unitString) {
   var unit;
   if (isString(unitString)) {
     unitString = unitString.trim().toLowerCase();
     if (unitString.length > 2 && unitString.endsWith('s')) {
       unitString = unitString.slice(0, -1);
     }
     unit = commonData.fullKeys.find(function(element) {
       return unitString === element.alias || unitString === element.full;
     });
   }
   return unit && unit.full;
 }
Пример #14
0
  returns(node) {
    if (!isString(node['!type'])) {
      return null
    }

    const ret = node['!type'].match(Parser.MATCHES.ret)

    if (!ret || !Array.isArray(ret)) {
      return 'void'
    }

    return this.type({
      '!type': ret[1],
    })
  }
Пример #15
0
  actionDefs.forEach(actionDef => {
    let magicAction = null

    if (isString(actionDef)) {
      magicAction = createMagicAction(actionDef)
    } else if (isPlainObject(actionDef)) {
      magicAction = createMagicAction(actionDef.type, actionDef.payload, actionDef.meta)
    }

    if (magicAction) {
      const funcName = typeNameToFuncName(magicAction.type)
      actions[funcName] = magicAction
      types[magicAction.type] = magicAction.type
    }
  })
Пример #16
0
    Object.keys(reporters).forEach(function(reporter) {
      debug("adding reporter %j %j", reporter, reporters[reporter]);

      var stdout;
      var options;
      if (isString(reporters[reporter])) {
        stdout = reporters[reporter];
        options = null;
      } else {
        stdout = reporters[reporter].stdout;
        options = reporters[reporter].options;
      }

      setup.push([ reporter, stdout, options ]);
    });
Пример #17
0
  addr(node) {
    if (!isString(node['!span'])) {
      return null
    }

    const pos = node['!span'].match(Parser.MATCHES.pos)

    const end = pos.pop()
    const start = pos.pop()

    const blob = this.ctx.content.slice(start, end)
    const regexp = blob.split(/\n/).shift().replace(Parser.MATCHES.addr, '\\$&')
    const str = new RegExp(regexp).toString()

    return str
  }
function normalizeSourceMapPath(option) {
  if (!option) { return function () {}; }
  if (option === true) { option = '{{dir}}/{{name}}.map'; }

  if (typeof option === 'function') { return option; }
  if (isString(option)) {
    return function (filepath) {
      var dirname = path.dirname(filepath);
      var filename = path.basename(filepath);
      var replacement = option
        .replace(/\{\{dir\}\}/g, dirname)
        .replace(/\{\{name\}\}/g, filename);
      return path.normalize(replacement);
    };
  }
  return function () {};
}
Пример #19
0
  type(node) {
    if (!isString(node['!type'])) {
      return null
    }

    if (this.isFn(node)) {
      return this.typeFn(node)
    }

    const clean = node['!type'].replace(/^\+/, '')
    const mapped = Parser.TYPE_MAPPING[clean]

    if (mapped) {
      return mapped
    }

    return this.ctx.preserveType ? node['!type'] : clean
  }
Пример #20
0
function propString(prop) {
  if (isString(prop)) {
    return inspect(String(prop), { quoteStyle: 'double' });
  }
  if (isNumber(prop)) {
    return `{${inspect(Number(prop))}}`;
  }
  if (isBoolean(prop)) {
    return `{${inspect(booleanValue(prop))}}`;
  }
  if (isCallable(prop)) {
    return `{${inspect(prop)}}`;
  }
  if (typeof prop === 'object') {
    return '{{...}}';
  }
  return `{[${typeof prop}]}`;
}
Пример #21
0
export function isHashSelector(input) {

    function hasWhiteSpace(input) {
        /**
         * @see {@link http://stackoverflow.com/a/6623252/1063035}
         */
        return input === input.replace(/\s/g,'');
    }

    if (isNotSet(input)) {
        throw new ReferenceError(STRINGS.ERRORS.MISSING_REQUIRED_INPUT);
    }

    if (!isString(input)) {
        throw new TypeError(STRINGS.ERRORS.INPUT_NOT_STRING_TYPE);
    }

    return input.charAt(0) === '#' && !hasWhiteSpace(input);
}
Пример #22
0
  return function respond(ctx, status, payload) {
    ctx.status = status;
    if (status === NO_CONTENT) {
      ctx.body = null;
      return ctx;
    }

    if (payload === undefined) {
      return ctx;
    }

    if (opts.autoMessage && isString(payload)) {
      payload = {
        message: payload
      };
    }

    ctx.body = payload;
    return ctx;
  };
function normalizeFilter(filter) {
  // If it's a string, it must be a glob type thing
  if (isString(filter)) {
    return minimatch.filter(filter);
  }
  // If it's a function, pass it directly to the .filter function
  if (typeof filter === 'function') {
    return filter;
  }
  // If it's an array (of strings), then return a filtering function that only
  // returns the files given in the array
  if (Array.isArray(filter)) {
    return function (file) {
      return filter.some(function (pattern) {
        return minimatch(file, pattern);
      });
    };
  }
  return function () { return true; };
}
Пример #24
0
  onNode(name, node, parent) {
    let _node = node
    if (!_node) {
      return false
    }

    if (isString(_node)) {
      _node = this.walk(node, parent)
    }

    if (!isObject(_node)) {
      return false
    }

    if (!this.isDefaultType(_node['!type'])) {
      return false
    }

    const tag = {
      id: uuid.v1(),
      name,
      addr: this.addr(_node),
      kind: this.kind(_node),
      type: this.type(_node),
      lineno: this.lineno(_node),
      namespace: this.namespace(_node, parent),
      parent: parent ? parent.id : undefined,
      origin: {
        '!span': _node['!span'],
        '!type': _node['!type'],
        '!data': _node['!data'],
      },
    }

    if (_node['!type'] || _node['!span']) {
      this.push(tag)
    }

    this.fromTree(_node, tag)
    return true
  }
Пример #25
0
MochaWrapper.prototype.extend = function extend(description, descriptor) {
	checkThis(this);
	if (!isString(description) || description.length === 0) {
		throw new TypeError('a non-empty description string is required');
	}
	var newWrappers = [];
	if (descriptor) {
		forEach(supportedMethods, function (methodName) {
			if (methodName in descriptor) {
				if (!isArray(descriptor[methodName])) {
					descriptor[methodName] = [descriptor[methodName]];
				}
				forEach(descriptor[methodName], function (method) {
					if (!isCallable(method)) {
						throw new TypeError('wrapper method "' + method + '" must be a function, or array of functions, if present');
					}
				});
			}
		});
		newWrappers = [descriptor];
	}
	return setThisDescription(concatThisWrappers(this, newWrappers), description);
};
Пример #26
0
module.exports = function(opts, selector) {
  if (isString(opts)) {
    return module.exports({}, opts);
  }

  if (!isObject(opts)) {
    return module.exports({}, selector);
  }

  var parser = sax.createStream(Boolean(opts.strict), defaults(opts, {
    trim: true,
    normalize: true,
    lowercase: true,
    xmlns: false,
    position: true
  }));

  var stream = new XMLStream(defaults({
    parser: parser
  }, opts), selector);

  return combine(parser, stream);
};
module.exports = function normalizeOptions(options) {
  options = assign({
    filter: '**/*.js',// string, function, array of strings
    preserveComments: false, // boolean, 'all', 'some', function
    removeOriginal: false, // boolean
    concat: false, // boolean, string
    // TODO inSourceMap: false, // boolean, string ({{dir}}/{{name}}), function
    sourceMap: false, // boolean, string ({{dir}}/{{name}}), function
    output: {}
  }, options);

  options.fromString = true;
  options.order = normalizeOrder(options.order);
  options.filter = normalizeFilter(options.filter);
  options.sourceMap = normalizeSourceMapPath(options.sourceMap);
  // TODO make getMinPath configurable
  options.getMinPath = getMinPath;

  if (options.concat) {
    if (!isString(options.concat)) {
      throw new Error('uglify: options.concat must be falsy or a string');
    }
    options.getMinPath = function () { return options.concat; };
  }

  // https://github.com/terinjokes/gulp-uglify/blob/master/index.js
  if (options.preserveComments === 'all' || options.preserveComments === true) {
    options.output.comments = true;
  } else if (options.preserveComments === 'some') {
    // preserve comments with directives or that start with a bang (!)
    options.output.comments = /^!|@preserve|@license|@cc_on/i;
  } else if (typeof options.preserveComments === 'function') {
    options.output.comments = options.preserveComments;
  }

  return options;
};
!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,g.SpookyEl=f()}}(function(){var define;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module){var select=require("queried"),style=require("dom-css"),domify=require("domify"),on=require("dom-events").on,off=require("dom-events").off,once=require("dom-events").once,append=require("insert").append,prepend=require("insert").prepend,remove=require("insert").remove,mixes=require("mixes"),Signal=require("signals").Signal,atts=require("atts"),elementClass=require("element-class"),NO_VIEW_ERROR_MSG="The view is not defined in this SpookyElement",isUndefined=require("is-undefined"),isString=require("is-string"),isFunction=require("is-function"),isElement=require("is-element"),isObject=require("is-object"),SpookyElement=function(e,i){if(!(this instanceof SpookyElement))return new SpookyElement(e,i);if(e){if(e._isSpookyElement)return e;if(e.jquery){if(!e.length)return this;e=e[0]}}if(i&&i.jquery&&(i=i.length?i[0]:null),this._view=null,this.onAppended=new Signal,this.onPrepended=new Signal,isFunction(e)){this.template=e;var t=domify(this._render(i));this.view=t}else isString(e)?0===e.indexOf("<")?this.view=domify(e):this.select(e,i):isElement(e)?this.view=e:this.template&&(this.view=domify(this._render(e)));this._isSpookyElement=!0};SpookyElement.prototype=Object.create(Array.prototype),mixes(SpookyElement,{view:{set:function(e){this._view=e,null===e?this.length=0:(this[0]=this._view,this.length=1)},get:function(){return this._view}},select:function(e,i){return i&&i._isSpookyElement&&(i=i.view),this.view=select(e,i),this},getElement:function(e){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);return e?select(e,this.view):this.view},findElement:function(e){return this.getElement(e)},find:function(e){var i=this.getElement(e);return i?new SpookyElement(i):null},findAll:function(e){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);var i=select.all(e,this.view),t=[];if(i)for(var n=0,r=i.length;r>n;n+=1){var s=i[n];t.push(SpookyElement(s))}return t},appendTo:function(e){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);var i=e;return isString(i)&&(i=select(i)),i&&i._isSpookyElement&&(i=i.view),append(i,this.view),this.onAppended.dispatch(this),this},prependTo:function(e){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);var i=e;return isString(i)&&(i=select(i)),i&&i._isSpookyElement&&(i=i.view),prepend(i,this.view),this.onPrepended.dispatch(this),this},append:function(e){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);return isString(e)&&(e=domify(e)),append(this.view,e),this},prepend:function(e){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);return isString(e)&&(e=domify(e)),prepend(this.view,e),this},_render:function(e){return this.template&&isFunction(this.template)?this.template(e).replace(/^\s+|\s+$/g,""):this},on:function(e,i){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);return on(this.view,e,i),this},off:function(e,i){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);return off(this.view,e,i),this},once:function(e,i){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);return once(this.view,e,i),this},css:function(e,i){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);return i?style(this.view,e,i):style(this.view,e),this},attr:function(e,i){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);return 2==arguments.length?(atts.attr(this.view,e,i),this):1==arguments.length?atts.attr(this.view,e):this},addClass:function(e){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);return elementClass(this.view).add(e),this},removeClass:function(e){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);return elementClass(this.view).remove(e),this},hasClass:function(e){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);return elementClass(this.view).has(e)},getWidth:function(){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);return this.view.offsetWidth},getHeight:function(){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);return this.view.offsetHeight},html:function(e){if(!this.view)throw new Error(NO_VIEW_ERROR_MSG);return isUndefined(e)?this.view.innerHTML:(this.view.innerHTML=e,this)},animateIn:function(e,i){return i&&i(),this},animateOut:function(e,i){return i&&i(),this},resize:function(e,i){return this.width=e,this.height=i,this.css({width:e,height:i}),this},destroy:function(){this.removeAddedSignals(),this.view&&this.remove(),this.view=null},remove:function(){return this.view&&remove(this.view),this.view=null,this},addSignal:function(e,i,t,n){if(!e)throw new Error("Signal was not provided");if(!i)throw new Error("handler funciton was not provided");this._addedSignals||(this._addedSignals=[]),isObject(t)&&(i=i.bind(t));var r={signal:e,handler:i};this.removeSignal(e,i),n===!0?r.signal.addOnce(r.handler):r.signal.add(r.handler),this._addedSignals.push(r)},addSignalOnce:function(e,i,t){this.addSignal(e,i,t,!0)},removeSignal:function(e,i){this._addedSignals&&this._addedSignals.length&&this._addedSignals.some(function(t,n){return t.signal==e&&t.handler==i?(t.signal.remove(t.handler),this._addedSignals.splice(n,1),!0):void 0}.bind(this))},removeAddedSignals:function(){this._addedSignals&&this._addedSignals.length&&(this._addedSignals.forEach(function(e){e.signal.remove(e.handler)}),this._addedSignals=[])}}),module.exports=SpookyElement},{atts:6,"dom-css":7,"dom-events":8,domify:9,"element-class":10,insert:17,"is-element":22,"is-function":23,"is-object":24,"is-string":25,"is-undefined":26,mixes:27,queried:36,signals:43}],2:[function(require,module){var IS_UNITLESS={animationIterationCount:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridColumn:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,stopOpacity:!0,strokeDashoffset:!0,strokeOpacity:!0,strokeWidth:!0};module.exports=function(name,value){return"number"!=typeof value||IS_UNITLESS[name]?value:value+"px"}},{}],3:[function(require,module){"use strict";function flatten(array){if(!Array.isArray(array))throw new TypeError("Expected value to be an array");return flattenFrom(array)}function flattenFrom(array){return flattenDown(array,[])}function flattenDepth(array,depth){if(!Array.isArray(array))throw new TypeError("Expected value to be an array");return flattenFromDepth(array,depth)}function flattenFromDepth(array,depth){if("number"!=typeof depth)throw new TypeError("Expected the depth to be a number");return flattenDownDepth(array,[],depth)}function flattenDown(array,result){for(var i=0;i<array.length;i++){var value=array[i];Array.isArray(value)?flattenDown(value,result):result.push(value)}return result}function flattenDownDepth(array,result,depth){depth--;for(var i=0;i<array.length;i++){var value=array[i];depth>-1&&Array.isArray(value)?flattenDownDepth(value,result,depth):result.push(value)}return result}module.exports=flatten,module.exports.from=flattenFrom,module.exports.depth=flattenDepth,module.exports.fromDepth=flattenFromDepth},{}],4:[function(require,module){"use strict";module.exports=function(arr){if(!Array.isArray(arr))throw new TypeError("array-unique expects an array.");for(var len=arr.length,i=-1;i++<len;)for(var j=i+1;j<arr.length;++j)arr[i]===arr[j]&&arr.splice(j--,1);return arr}},{}],5:[function(require,module){"use strict";var flatten=require("array-flatten");module.exports=function(arr){return flatten(Array.isArray(arr)?arr:[arr]).filter(Boolean)}},{"array-flatten":3}],6:[function(require,module){!function(root,name,make){"undefined"!=typeof module&&module.exports?module.exports=make():root[name]=make()}(this,"atts",function(){function api(e){return this instanceof api?void((this.length=null==e?0:1)&&(this[0]=e)):new api(e)}function anyAttr(e,fn,scope){var a,o=e.attributes,l=o&&o.length,i=0;if("function"!=typeof fn)return+l||0;for(scope=scope||e;l>i;)if(fn.call(scope,(a=o[i++]).value,a.name,a))return i;return 0}function copy(v,k){this[k]=v}function getAtts(e){var o={};return anyAttr(e,copy,o),o}function setAtts(e,o){for(var n in o)owns.call(o,n)&&attr(e,n,o[n]);return o}function atts(e,o){return void 0===o?getAtts(e):setAtts(e,o)}function normalize(v){return null==v?void 0:""+v}function attr(e,k,v){return void 0===v?normalize(e[getAttr](k)):("boolean"==typeof v?toggleAttr(e,k,v):null===v?e[remAttr](k):e[setAttr](k,v=""+v),v)}function removeAttr(e,keys){keys="string"==typeof keys?keys.match(ssv):[].concat(keys);for(var i=keys&&keys.length;i--;)e[remAttr](keys[i])}function toggleAttr(e,k,force){"boolean"==typeof force||(force=null==e[getAttr](k)||e[k]===!1);var opposite=!force;return force?e[setAttr](k,""):e[remAttr](k),e[k]===opposite?e[k]=force:force}function supportAttr(e,n){if(n in e)return!0;if("class"===n)return"className"in e;for(var p in e)if(n.toLowerCase()===p.toLowerCase())return!0;return!1}function isAttr(e,n){return null!=e[getAttr](n)}function each(stack,fn){for(var l=stack.length,i=0;l>i;i++)fn(stack[i]);return stack}var ssv=/\S+/g,effin=api.prototype,setAttr="setAttribute",getAttr="getAttribute",remAttr="removeAttribute",owns={}.hasOwnProperty;return api.attr=attr,api.atts=atts,api.isAttr=isAttr,api.supportAttr=supportAttr,api.anyAttr=anyAttr,api.removeAttr=removeAttr,api.toggleAttr=toggleAttr,effin.atts=function(o){return void 0===o?atts(this[0]):each(this,function(e){atts(e,o)})},effin.attr=function(k,v){return void 0===v?attr(this[0],k):each(this,function(e){var x="function"==typeof v?v.call(e):v;void 0===x||attr(e,k,x)})},effin.removeAttr=function(keys){return each(this,function(e){removeAttr(e,keys)})},effin.toggleAttr=function(k,force){return each(this,function(e){toggleAttr(e,k,force)})},api})},{}],7:[function(require,module){function style(element,property,value){var camel=cache[property];if("undefined"==typeof camel&&(camel=detect(property)),camel){if(void 0===value)return element.style[camel];element.style[camel]=addPxToStyle(camel,value)}}function each(element,properties){for(var k in properties)properties.hasOwnProperty(k)&&style(element,k,properties[k])}function detect(cssProp){var camel=toCamelCase(cssProp),result=prefix(camel);return cache[camel]=cache[cssProp]=cache[result]=result,result}function set(){2===arguments.length?"string"==typeof arguments[1]?arguments[0].style.cssText=arguments[1]:each(arguments[0],arguments[1]):style(arguments[0],arguments[1],arguments[2])}var prefix=require("prefix-style"),toCamelCase=require("to-camel-case"),cache={"float":"cssFloat"},addPxToStyle=require("add-px-to-style");module.exports=set,module.exports.set=set,module.exports.get=function(element,properties){return Array.isArray(properties)?properties.reduce(function(obj,prop){return obj[prop]=style(element,prop||""),obj},{}):style(element,properties||"")}},{"add-px-to-style":2,"prefix-style":35,"to-camel-case":50}],8:[function(require,module){var synth=require("synthetic-dom-events"),on=function(element,name,fn,capture){return element.addEventListener(name,fn,capture||!1)},off=function(element,name,fn,capture){return element.removeEventListener(name,fn,capture||!1)},once=function(element,name,fn,capture){function tmp(ev){off(element,name,tmp,capture),fn(ev)}on(element,name,tmp,capture)},emit=function(element,name,opt){var ev=synth(name,opt);element.dispatchEvent(ev)};document.addEventListener||(on=function(element,name,fn){return element.attachEvent("on"+name,fn)}),document.removeEventListener||(off=function(element,name,fn){return element.detachEvent("on"+name,fn)}),document.dispatchEvent||(emit=function(element,name,opt){var ev=synth(name,opt);return element.fireEvent("on"+ev.type,ev)}),module.exports={on:on,off:off,once:once,emit:emit}},{"synthetic-dom-events":46}],9:[function(require,module){function parse(html,doc){if("string"!=typeof html)throw new TypeError("String expected");doc||(doc=document);var m=/<([\w:]+)/.exec(html);if(!m)return doc.createTextNode(html);html=html.replace(/^\s+|\s+$/g,"");var tag=m[1];if("body"==tag){var el=doc.createElement("html");return el.innerHTML=html,el.removeChild(el.lastChild)}var wrap=map[tag]||map._default,depth=wrap[0],prefix=wrap[1],suffix=wrap[2],el=doc.createElement("div");for(el.innerHTML=prefix+html+suffix;depth--;)el=el.lastChild;if(el.firstChild==el.lastChild)return el.removeChild(el.firstChild);for(var fragment=doc.createDocumentFragment();el.firstChild;)fragment.appendChild(el.removeChild(el.firstChild));return fragment}module.exports=parse;var bugTestDiv,innerHTMLBug=!1;"undefined"!=typeof document&&(bugTestDiv=document.createElement("div"),bugTestDiv.innerHTML='  <link/><table></table><a href="/a">a</a><input type="checkbox"/>',innerHTMLBug=!bugTestDiv.getElementsByTagName("link").length,bugTestDiv=void 0);var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:innerHTMLBug?[1,"X<div>","</div>"]:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"],map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"],map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"],map.polyline=map.ellipse=map.polygon=map.circle=map.text=map.line=map.path=map.rect=map.g=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"]},{}],10:[function(require,module){function indexOf(arr,prop){if(arr.indexOf)return arr.indexOf(prop);for(var i=0,len=arr.length;len>i;i++)if(arr[i]===prop)return i;return-1}function ElementClass(opts){if(!(this instanceof ElementClass))return new ElementClass(opts);opts||(opts={}),opts.nodeType&&(opts={el:opts}),this.opts=opts,this.el=opts.el||document.body,"object"!=typeof this.el&&(this.el=document.querySelector(this.el))}module.exports=function(opts){return new ElementClass(opts)},ElementClass.prototype.add=function(className){var el=this.el;if(el){if(""===el.className)return el.className=className;var classes=el.className.split(" ");return indexOf(classes,className)>-1?classes:(classes.push(className),el.className=classes.join(" "),classes)}},ElementClass.prototype.remove=function(className){var el=this.el;if(el&&""!==el.className){var classes=el.className.split(" "),idx=indexOf(classes,className);return idx>-1&&classes.splice(idx,1),el.className=classes.join(" "),classes}},ElementClass.prototype.has=function(className){var el=this.el;if(el){var classes=el.className.split(" ");return indexOf(classes,className)>-1}},ElementClass.prototype.toggle=function(className){var el=this.el;el&&(this.has(className)?this.remove(className):this.add(className))}},{}],11:[function(require,module){var hasDom=require("has-dom");module.exports=hasDom()?document:null},{"has-dom":13}],12:[function(require,module){var counter=Date.now()%1e9;module.exports=function(){return(1e9*Math.random()>>>0)+counter++}},{}],13:[function(require,module){"use strict";module.exports=function(){return"undefined"!=typeof window&&"undefined"!=typeof document&&"function"==typeof document.createElement}},{}],14:[function(require,module){function after(sibling,first){var node=mutation(toArray(arguments,1)),parent=sibling.parentNode,child=sibling.nextSibling;return parent.insertBefore(node,child),first}var toArray=require("to-array"),mutation=require("./mutation");module.exports=after},{"./mutation":18,"to-array":49}],15:[function(require,module){function append(parent,first){var node=mutation(toArray(arguments,1));return parent.appendChild(node),first}var toArray=require("to-array"),mutation=require("./mutation");module.exports=append},{"./mutation":18,"to-array":49}],16:[function(require,module){function before(sibling,first){var node=mutation(toArray(arguments,1)),parent=sibling.parentNode;return parent.insertBefore(node,sibling),first}var toArray=require("to-array"),mutation=require("./mutation");module.exports=before},{"./mutation":18,"to-array":49}],17:[function(require,module){var mutation=require("./mutation"),prepend=require("./prepend"),append=require("./append"),after=require("./after"),before=require("./before"),remove=require("./remove"),replace=require("./replace");module.exports={prepend:prepend,append:append,after:after,before:before,remove:remove,replace:replace,mutation:mutation}},{"./after":14,"./append":15,"./before":16,"./mutation":18,"./prepend":19,"./remove":20,"./replace":21}],18:[function(require,module){function mutation(list){if(list=list.map(replaceStringWithTextNode),1===list.length)return list[0];var frag=document.createDocumentFragment();return list.forEach(appendToFragment,frag),frag}function replaceStringWithTextNode(string){return"string"==typeof string?document.createTextNode(string):string&&string.view&&string.view.nodeType?string.view:string}function appendToFragment(elem){this.appendChild(elem)}module.exports=mutation},{}],19:[function(require,module){function prepend(parent,first){var node=mutation(toArray(arguments,1));return parent.insertBefore(node,parent.firstChild),first}var toArray=require("to-array"),mutation=require("./mutation");module.exports=prepend},{"./mutation":18,"to-array":49}],20:[function(require,module){function remove(first){var list=toArray(arguments);return list.map(function(elem){return elem&&elem.view&&elem.view.nodeType?elem.view:elem}).forEach(removeFromParent),first}function removeFromParent(elem){elem.parentNode&&elem.parentNode.removeChild(elem)}{var toArray=require("to-array");require("./mutation")}module.exports=remove},{"./mutation":18,"to-array":49}],21:[function(require,module){function replace(target,first){var node=mutation(toArray(arguments,1)),parent=target.parentNode;return parent.replaceChild(node,target),first}var toArray=require("to-array"),mutation=require("./mutation");module.exports=replace},{"./mutation":18,"to-array":49}],22:[function(require,module,exports){!function(root){function isElement(value){return value&&1===value.nodeType&&value&&"object"==typeof value&&Object.prototype.toString.call(value).indexOf("Element")>-1}"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=isElement),exports.isElement=isElement):"function"==typeof define&&define.amd?define([],function(){return isElement}):root.isElement=isElement}(this)},{}],23:[function(require,module){function isFunction(fn){var string=toString.call(fn);return"[object Function]"===string||"function"==typeof fn&&"[object RegExp]"!==string||"undefined"!=typeof window&&(fn===window.setTimeout||fn===window.alert||fn===window.confirm||fn===window.prompt)}module.exports=isFunction;var toString=Object.prototype.toString},{}],24:[function(require,module){"use strict";module.exports=function(x){return"object"==typeof x&&null!==x}},{}],25:[function(require,module){"use strict";var strValue=String.prototype.valueOf,tryStringObject=function(value){try{return strValue.call(value),!0}catch(e){return!1}},toStr=Object.prototype.toString,strClass="[object String]",hasToStringTag="function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag;module.exports=function(value){return"string"==typeof value?!0:"object"!=typeof value?!1:hasToStringTag?tryStringObject(value):toStr.call(value)===strClass}},{}],26:[function(require,module){"use strict";var u=void 0;module.exports=function(input){return input===u}},{}],27:[function(require,module){function mix(obj,entries){for(var k in entries)if(entries.hasOwnProperty(k)){var f=entries[k];if("function"==typeof f)obj[k]=f;else if(f&&"object"==typeof f){var def=xtend(defaults,f);Object.defineProperty(obj,k,def)}}}var xtend=require("xtend"),defaults={enumerable:!0,configurable:!0};module.exports=function(ctor,entries){mix(ctor.prototype,entries)},module.exports.mix=mix},{xtend:53}],28:[function(require,module){var isString=require("./is-string"),isArray=require("./is-array"),isFn=require("./is-fn");module.exports=function(a){return isArray(a)||a&&!isString(a)&&!a.nodeType&&("undefined"!=typeof window?a!=window:!0)&&!isFn(a)&&"number"==typeof a.length}},{"./is-array":29,"./is-fn":30,"./is-string":31}],29:[function(require,module){module.exports=function(a){return a instanceof Array}},{}],30:[function(require,module){module.exports=function(a){return!(!a||!a.apply)}},{}],31:[function(require,module){module.exports=function(a){return"string"==typeof a||a instanceof String}},{}],32:[function(require,module){var parse=require("./parse"),stringify=require("./stringify");parse.parse=parse,parse.stringify=stringify,module.exports=parse},{"./parse":33,"./stringify":34}],33:[function(require,module){module.exports=function(str,bracket){function replaceToken(token){var refId=res.push(token.slice(1,-1));return"\\"+refId}if("string"!=typeof str)return[str];var prevStr,res=[];bracket=bracket||"()";for(var pRE=new RegExp(["\\",bracket[0],"[^\\",bracket[0],"\\",bracket[1],"]*\\",bracket[1]].join(""));str!=prevStr;)prevStr=str,str=str.replace(pRE,replaceToken);return res.unshift(str),res}},{}],34:[function(require,module){module.exports=function(str,refs,bracket){function replaceRef(token){return bracket[0]+refs[token.slice(1)]+bracket[1]}var prevStr;if(!str)return"";for("string"!=typeof str&&(bracket=refs,refs=str,str=refs[0]),bracket=bracket||"()";str!=prevStr;)prevStr=str,str=str.replace(/\\[0-9]+/,replaceRef);return str}},{}],35:[function(require,module){var div=null,prefixes=["Webkit","Moz","O","ms"];module.exports=function(prop){div||(div=document.createElement("div"));var style=div.style;if(prop in style)return prop;for(var titleCase=prop.charAt(0).toUpperCase()+prop.slice(1),i=prefixes.length;i>=0;i--){var name=prefixes[i]+titleCase;if(name in style)return name}return!1}},{}],36:[function(require,module){var doc=require("get-doc"),q=require("./lib/");try{doc.querySelector(":scope")}catch(e){q.registerFilter("scope",require("./lib/pseudos/scope"))}try{doc.querySelector(":has")}catch(e){q.registerFilter("has",require("./lib/pseudos/has")),q.registerFilter("not",require("./lib/pseudos/not"))}try{doc.querySelector(":root")}catch(e){q.registerFilter("root",require("./lib/pseudos/root"))}try{doc.querySelector(":matches")}catch(e){q.registerFilter("matches",require("./lib/pseudos/matches"))}q.matches=require("./lib/pseudos/matches"),module.exports=q},{"./lib/":37,"./lib/pseudos/has":38,"./lib/pseudos/matches":39,"./lib/pseudos/not":40,"./lib/pseudos/root":41,"./lib/pseudos/scope":42,"get-doc":11}],37:[function(require,module){function queryMultiple(selector,el){return selector?isString(selector)?(pseudos.scope&&(selector=selector.replace(/^\s*:scope/,"")),el=el?isArrayLike(el)?arrayify(el):el.querySelector?[el]:[querySingle.document]:[querySingle.document],qPseudos(el,selector)):isArray(selector)?unique(arrayify(selector.map(function(sel){return queryMultiple(sel,el)}))):[selector]:[]}function querySingle(selector,el){return queryMultiple(selector,el)[0]}function qPseudos(list,selector){if(selector=selector.trim(),!selector)return list;if(">"===selector[0])if(pseudos.scope){var id=getUid();list.forEach(function(el){el.setAttribute("__scoped",id)}),selector='[__scoped="'+id+'"]'+selector}else selector=":scope"+selector;var pseudo,pseudoFn,pseudoParam,pseudoParamId,parts=paren.parse(selector),match=parts[0].match(pseudoRE);if(match){pseudo=match[1],pseudoParamId=match[2],pseudoParamId&&(pseudoParam=paren.stringify(parts[pseudoParamId.slice(1)],parts));var preSelector=paren.stringify(parts[0].slice(0,match.index),parts);return preSelector||mappers[pseudo]||(preSelector="*"),preSelector&&(list=qList(list,preSelector)),pseudoFn=function(el){return pseudos[pseudo](el,pseudoParam)},filters[pseudo]?list=list.filter(pseudoFn):mappers[pseudo]&&(list=unique(arrayify(list.map(pseudoFn)))),selector=parts[0].slice(match.index+match[0].length),qPseudos(list,paren.stringify(selector,parts))}return qList(list,selector)}function qList(list,selector){return unique(arrayify(list.map(function(el){return slice(el.querySelectorAll(selector))})))}function registerFilter(name,filter,incSelf){pseudos[name]||(pseudos[name]=filter,pseudos[name].includeSelf=incSelf,filters[name]=!0,regenerateRegExp())}function registerMapper(name,mapper,incSelf){pseudos[name]||(pseudos[name]=mapper,pseudos[name].includeSelf=incSelf,mappers[name]=!0,regenerateRegExp())}function regenerateRegExp(){pseudoRE=new RegExp("::?("+Object.keys(pseudos).join("|")+")(\\\\[0-9]+)?")}var pseudoRE,slice=require("sliced"),unique=require("array-unique"),getUid=require("get-uid"),paren=require("parenthesis"),isString=require("mutype/is-string"),isArray=require("mutype/is-array"),isArrayLike=require("mutype/is-array-like"),arrayify=require("arrayify-compact"),doc=require("get-doc"),pseudos={},filters={},mappers={};querySingle.all=queryMultiple,querySingle.registerFilter=registerFilter,querySingle.registerMapper=registerMapper,querySingle.document=doc,module.exports=querySingle},{"array-unique":4,"arrayify-compact":5,"get-doc":11,"get-uid":12,"mutype/is-array":29,"mutype/is-array-like":28,"mutype/is-string":31,parenthesis:32,sliced:44}],38:[function(require,module){function has(el,subSelector){return!!q(subSelector,el)}var q=require("..");module.exports=has},{"..":37}],39:[function(require,module){function matches(el,selector){if(!el.parentNode){var fragment=q.document.createDocumentFragment();fragment.appendChild(el)}return q.all(selector,el.parentNode).indexOf(el)>-1}var q=require("..");module.exports=matches},{"..":37}],40:[function(require,module){function not(el,selector){return!matches(el,selector)}var matches=require("./matches");module.exports=not},{"./matches":39}],41:[function(require,module){var q=require("..");module.exports=function(el){return el===q.document.documentElement}},{"..":37}],42:[function(require,module){module.exports=function(el){return el.hasAttribute("scoped")}},{}],43:[function(require,module){!function(global){function SignalBinding(signal,listener,isOnce,listenerContext,priority){this._listener=listener,this._isOnce=isOnce,this.context=listenerContext,this._signal=signal,this._priority=priority||0}function validateListener(listener,fnName){if("function"!=typeof listener)throw new Error("listener is a required param of {fn}() and should be a Function.".replace("{fn}",fnName))}function Signal(){this._bindings=[],this._prevParams=null;var self=this;this.dispatch=function(){Signal.prototype.dispatch.apply(self,arguments)}}SignalBinding.prototype={active:!0,params:null,execute:function(paramsArr){var handlerReturn,params;return this.active&&this._listener&&(params=this.params?this.params.concat(paramsArr):paramsArr,handlerReturn=this._listener.apply(this.context,params),this._isOnce&&this.detach()),handlerReturn},detach:function(){return this.isBound()?this._signal.remove(this._listener,this.context):null},isBound:function(){return!!this._signal&&!!this._listener},isOnce:function(){return this._isOnce},getListener:function(){return this._listener},getSignal:function(){return this._signal},_destroy:function(){delete this._signal,delete this._listener,delete this.context},toString:function(){return"[SignalBinding isOnce:"+this._isOnce+", isBound:"+this.isBound()+", active:"+this.active+"]"}},Signal.prototype={VERSION:"1.0.0",memorize:!1,_shouldPropagate:!0,active:!0,_registerListener:function(listener,isOnce,listenerContext,priority){var binding,prevIndex=this._indexOfListener(listener,listenerContext);if(-1!==prevIndex){if(binding=this._bindings[prevIndex],binding.isOnce()!==isOnce)throw new Error("You cannot add"+(isOnce?"":"Once")+"() then add"+(isOnce?"Once":"")+"() the same listener without removing the relationship first.")}else binding=new SignalBinding(this,listener,isOnce,listenerContext,priority),this._addBinding(binding);return this.memorize&&this._prevParams&&binding.execute(this._prevParams),binding},_addBinding:function(binding){var n=this._bindings.length;do--n;while(this._bindings[n]&&binding._priority<=this._bindings[n]._priority);this._bindings.splice(n+1,0,binding)},_indexOfListener:function(listener,context){for(var cur,n=this._bindings.length;n--;)if(cur=this._bindings[n],cur._listener===listener&&cur.context===context)return n;return-1},has:function(listener,context){return-1!==this._indexOfListener(listener,context)},add:function(listener,listenerContext,priority){return validateListener(listener,"add"),this._registerListener(listener,!1,listenerContext,priority)},addOnce:function(listener,listenerContext,priority){return validateListener(listener,"addOnce"),this._registerListener(listener,!0,listenerContext,priority)},remove:function(listener,context){validateListener(listener,"remove");var i=this._indexOfListener(listener,context);return-1!==i&&(this._bindings[i]._destroy(),this._bindings.splice(i,1)),listener},removeAll:function(){for(var n=this._bindings.length;n--;)this._bindings[n]._destroy();this._bindings.length=0},getNumListeners:function(){return this._bindings.length},halt:function(){this._shouldPropagate=!1},dispatch:function(){if(this.active){var bindings,paramsArr=Array.prototype.slice.call(arguments),n=this._bindings.length;if(this.memorize&&(this._prevParams=paramsArr),n){bindings=this._bindings.slice(),this._shouldPropagate=!0;do n--;while(bindings[n]&&this._shouldPropagate&&bindings[n].execute(paramsArr)!==!1)}}},forget:function(){this._prevParams=null},dispose:function(){this.removeAll(),delete this._bindings,delete this._prevParams},toString:function(){return"[Signal active:"+this.active+" numListeners:"+this.getNumListeners()+"]"}};var signals=Signal;signals.Signal=Signal,"function"==typeof define&&define.amd?define(function(){return signals}):"undefined"!=typeof module&&module.exports?module.exports=signals:global.signals=signals}(this)},{}],44:[function(require,module,exports){module.exports=exports=require("./lib/sliced")},{"./lib/sliced":45}],45:[function(require,module){module.exports=function(args,slice,sliceEnd){var ret=[],len=args.length;if(0===len)return ret;var start=0>slice?Math.max(0,slice+len):slice||0;for(void 0!==sliceEnd&&(len=0>sliceEnd?sliceEnd+len:sliceEnd);len-->start;)ret[len-start]=args[len];return ret}},{}],46:[function(require,module){function check_kb(ev,opts){return(ev.ctrlKey!=(opts.ctrlKey||!1)||ev.altKey!=(opts.altKey||!1)||ev.shiftKey!=(opts.shiftKey||!1)||ev.metaKey!=(opts.metaKey||!1)||ev.keyCode!=(opts.keyCode||0)||ev.charCode!=(opts.charCode||0))&&(ev=document.createEvent("Event"),ev.initEvent(opts.type,opts.bubbles,opts.cancelable),ev.ctrlKey=opts.ctrlKey||!1,ev.altKey=opts.altKey||!1,ev.shiftKey=opts.shiftKey||!1,ev.metaKey=opts.metaKey||!1,ev.keyCode=opts.keyCode||0,ev.charCode=opts.charCode||0),ev}var doc=(window,document||{}),use_key_event=(doc.documentElement||{},!0);try{doc.createEvent("KeyEvents")}catch(err){use_key_event=!1}var modern=function(type,opts){opts=opts||{};var family=typeOf(type),init_fam=family;"KeyboardEvent"===family&&use_key_event&&(family="KeyEvents",init_fam="KeyEvent");var ev=doc.createEvent(family),init_fn="init"+init_fam,init="function"==typeof ev[init_fn]?init_fn:"initEvent",sig=initSignatures[init],args=[],used={};opts.type=type;for(var i=0;i<sig.length;++i){var key=sig[i],val=opts[key];void 0===val&&(val=ev[key]),used[key]=!0,args.push(val)}ev[init].apply(ev,args),"KeyboardEvent"===family&&(ev=check_kb(ev,opts));for(var key in opts)used[key]||(ev[key]=opts[key]);return ev},legacy=function(type,opts){opts=opts||{};var ev=doc.createEventObject();ev.type=type;for(var key in opts)void 0!==opts[key]&&(ev[key]=opts[key]);return ev};module.exports=doc.createEvent?modern:legacy;
Пример #29
0
function linkObj(url)
{
	if (url===undefined || isString(url)===false)
	{
		url = null;
	}
	
	var link = 
	{
		url:
		{
			original: url,      // The URL as it was inputted
			resolved: null,     // The URL, resolved as a browser would do so
			redirected: null    // The URL, after its last redirection, if any
		},
		
		base:
		{
			original: null,     // The base URL as it was inputted
			resolved: null      // The base URL, resolved as a browser would do so
		},
		
		html:
		{
			index: null,        // The order in which the link appeared in its document -- using max-level tag filter
			offsetIndex: null,  // Sequential (gap-free) indicies for skipped and unskipped links
			location:null,      // Source code location of the attribute that the link was found within
			selector: null,     // CSS selector for element in document
			tagName: null,      // Tag name that the link was found on
			attrName: null,     // Attribute name that the link was found within
			attrs: null,        // All attributes on the element
			text: null,         // TextNode/innerText within the element
			tag: null,          // The entire tag string
			
			// Temporary keys
			base: null
		},
		
		http:
		{
			cached: null,       // If the response was pulled from cache
			response: null      // The request response
		},
		
		broken: null,           // If the link was determined to be broken or not
		internal: null,         // If the link is to the same server as its base/document
		samePage: null,         // If the link is to the same page as its base/document
		excluded: null,         // If the link was excluded due to any filtering
		
		brokenReason: null,     // The reason why the link was considered broken, if it indeed is
		excludedReason: null,   // The reason why the link was excluded from being checked, if it indeed was
		
		// Temporary keys
		broken_link_checker: true,
		resolved: false
	};
	
	// Not enumerable -- hidden from `JSON.stringify()`
	Object.defineProperty(link.base, "parsed", { value:null, writable:true });  // Same as `link.base.resolved`, but is an Object
	Object.defineProperty(link.url,  "parsed", { value:null, writable:true });  // Same as `link.url.resolved`, but is an Object
	
	return link;
}
Пример #30
0
module.exports = function whyNotEqual(value, other) {
	if (value === other) { return ''; }
	if (value == null || other == null) {
		return value === other ? '' : String(value) + ' !== ' + String(other);
	}

	var valToStr = toStr.call(value);
	var otherToStr = toStr.call(other);
	if (valToStr !== otherToStr) {
		return 'toStringTag is not the same: ' + valToStr + ' !== ' + otherToStr;
	}

	var valIsBool = isBoolean(value);
	var otherIsBool = isBoolean(other);
	if (valIsBool || otherIsBool) {
		if (!valIsBool) { return 'first argument is not a boolean; second argument is'; }
		if (!otherIsBool) { return 'second argument is not a boolean; first argument is'; }
		var valBoolVal = booleanValue.call(value);
		var otherBoolVal = booleanValue.call(other);
		if (valBoolVal === otherBoolVal) { return ''; }
		return 'primitive value of boolean arguments do not match: ' + valBoolVal + ' !== ' + otherBoolVal;
	}

	var valIsNumber = isNumber(value);
	var otherIsNumber = isNumber(value);
	if (valIsNumber || otherIsNumber) {
		if (!valIsNumber) { return 'first argument is not a number; second argument is'; }
		if (!otherIsNumber) { return 'second argument is not a number; first argument is'; }
		var valNum = Number(value);
		var otherNum = Number(other);
		if (valNum === otherNum) { return ''; }
		var valIsNaN = isNaN(value);
		var otherIsNaN = isNaN(other);
		if (valIsNaN && !otherIsNaN) {
			return 'first argument is NaN; second is not';
		} else if (!valIsNaN && otherIsNaN) {
			return 'second argument is NaN; first is not';
		} else if (valIsNaN && otherIsNaN) {
			return '';
		}
		return 'numbers are different: ' + value + ' !== ' + other;
	}

	var valIsString = isString(value);
	var otherIsString = isString(other);
	if (valIsString || otherIsString) {
		if (!valIsString) { return 'second argument is string; first is not'; }
		if (!otherIsString) { return 'first argument is string; second is not'; }
		var stringVal = String(value);
		var otherVal = String(other);
		if (stringVal === otherVal) { return ''; }
		return 'string values are different: "' + stringVal + '" !== "' + otherVal + '"';
	}

	var valIsDate = isDate(value);
	var otherIsDate = isDate(other);
	if (valIsDate || otherIsDate) {
		if (!valIsDate) { return 'second argument is Date, first is not'; }
		if (!otherIsDate) { return 'first argument is Date, second is not'; }
		var valTime = +value;
		var otherTime = +other;
		if (valTime === otherTime) { return ''; }
		return 'Dates have different time values: ' + valTime + ' !== ' + otherTime;
	}

	var valIsRegex = isRegex(value);
	var otherIsRegex = isRegex(other);
	if (valIsRegex || otherIsRegex) {
		if (!valIsRegex) { return 'second argument is RegExp, first is not'; }
		if (!otherIsRegex) { return 'first argument is RegExp, second is not'; }
		var regexStringVal = String(value);
		var regexStringOther = String(other);
		if (regexStringVal === regexStringOther) { return ''; }
		return 'regular expressions differ: ' + regexStringVal + ' !== ' + regexStringOther;
	}

	var valIsArray = isArray(value);
	var otherIsArray = isArray(other);
	if (valIsArray || otherIsArray) {
		if (!valIsArray) { return 'second argument is an Array, first is not'; }
		if (!otherIsArray) { return 'first argument is an Array, second is not'; }
		if (value.length !== other.length) {
			return 'arrays have different length: ' + value.length + ' !== ' + other.length;
		}

		var index = value.length - 1;
		var equal = '';
		var valHasIndex, otherHasIndex;
		while (equal === '' && index >= 0) {
			valHasIndex = has(value, index);
			otherHasIndex = has(other, index);
			if (!valHasIndex && otherHasIndex) { return 'second argument has index ' + index + '; first does not'; }
			if (valHasIndex && !otherHasIndex) { return 'first argument has index ' + index + '; second does not'; }
			equal = whyNotEqual(value[index], other[index]);
			index -= 1;
		}
		return equal;
	}

	var valueIsSym = isSymbol(value);
	var otherIsSym = isSymbol(other);
	if (valueIsSym !== otherIsSym) {
		if (valueIsSym) { return 'first argument is Symbol; second is not'; }
		return 'second argument is Symbol; first is not';
	}
	if (valueIsSym && otherIsSym) {
		return symbolValue.call(value) === symbolValue.call(other) ? '' : 'first Symbol value !== second Symbol value';
	}

	var valueIsBigInt = isBigInt(value);
	var otherIsBigInt = isBigInt(other);
	if (valueIsBigInt !== otherIsBigInt) {
		if (valueIsBigInt) { return 'first argument is BigInt; second is not'; }
		return 'second argument is BigInt; first is not';
	}
	if (valueIsBigInt && otherIsBigInt) {
		return bigIntValue.call(value) === bigIntValue.call(other) ? '' : 'first BigInt value !== second BigInt value';
	}

	var valueIsGen = isGenerator(value);
	var otherIsGen = isGenerator(other);
	if (valueIsGen !== otherIsGen) {
		if (valueIsGen) { return 'first argument is a Generator; second is not'; }
		return 'second argument is a Generator; first is not';
	}

	var valueIsArrow = isArrowFunction(value);
	var otherIsArrow = isArrowFunction(other);
	if (valueIsArrow !== otherIsArrow) {
		if (valueIsArrow) { return 'first argument is an Arrow function; second is not'; }
		return 'second argument is an Arrow function; first is not';
	}

	if (isCallable(value) || isCallable(other)) {
		if (functionsHaveNames && whyNotEqual(value.name, other.name) !== '') {
			return 'Function names differ: "' + value.name + '" !== "' + other.name + '"';
		}
		if (whyNotEqual(value.length, other.length) !== '') {
			return 'Function lengths differ: ' + value.length + ' !== ' + other.length;
		}

		var valueStr = normalizeFnWhitespace(String(value));
		var otherStr = normalizeFnWhitespace(String(other));
		if (whyNotEqual(valueStr, otherStr) === '') { return ''; }

		if (!valueIsGen && !valueIsArrow) {
			return whyNotEqual(valueStr.replace(/\)\s*\{/, '){'), otherStr.replace(/\)\s*\{/, '){')) === '' ? '' : 'Function string representations differ';
		}
		return whyNotEqual(valueStr, otherStr) === '' ? '' : 'Function string representations differ';
	}

	if (typeof value === 'object' || typeof other === 'object') {
		if (typeof value !== typeof other) { return 'arguments have a different typeof: ' + typeof value + ' !== ' + typeof other; }
		if (isProto.call(value, other)) { return 'first argument is the [[Prototype]] of the second'; }
		if (isProto.call(other, value)) { return 'second argument is the [[Prototype]] of the first'; }
		if (getPrototypeOf(value) !== getPrototypeOf(other)) { return 'arguments have a different [[Prototype]]'; }

		if (symbolIterator) {
			var valueIteratorFn = value[symbolIterator];
			var valueIsIterable = isCallable(valueIteratorFn);
			var otherIteratorFn = other[symbolIterator];
			var otherIsIterable = isCallable(otherIteratorFn);
			if (valueIsIterable !== otherIsIterable) {
				if (valueIsIterable) { return 'first argument is iterable; second is not'; }
				return 'second argument is iterable; first is not';
			}
			if (valueIsIterable && otherIsIterable) {
				var valueIterator = valueIteratorFn.call(value);
				var otherIterator = otherIteratorFn.call(other);
				var valueNext, otherNext, nextWhy;
				do {
					valueNext = valueIterator.next();
					otherNext = otherIterator.next();
					if (!valueNext.done && !otherNext.done) {
						nextWhy = whyNotEqual(valueNext, otherNext);
						if (nextWhy !== '') {
							return 'iteration results are not equal: ' + nextWhy;
						}
					}
				} while (!valueNext.done && !otherNext.done);
				if (valueNext.done && !otherNext.done) { return 'first argument finished iterating before second'; }
				if (!valueNext.done && otherNext.done) { return 'second argument finished iterating before first'; }
				return '';
			}
		} else if (collectionsForEach.Map || collectionsForEach.Set) {
			var valueEntries = tryMapSetEntries(value);
			var otherEntries = tryMapSetEntries(other);
			var valueEntriesIsArray = isArray(valueEntries);
			var otherEntriesIsArray = isArray(otherEntries);
			if (valueEntriesIsArray && !otherEntriesIsArray) { return 'first argument has Collection entries, second does not'; }
			if (!valueEntriesIsArray && otherEntriesIsArray) { return 'second argument has Collection entries, first does not'; }
			if (valueEntriesIsArray && otherEntriesIsArray) {
				var entriesWhy = whyNotEqual(valueEntries, otherEntries);
				return entriesWhy === '' ? '' : 'Collection entries differ: ' + entriesWhy;
			}
		}

		var key, valueKeyIsRecursive, otherKeyIsRecursive, keyWhy;
		for (key in value) {
			if (has(value, key)) {
				if (!has(other, key)) { return 'first argument has key "' + key + '"; second does not'; }
				valueKeyIsRecursive = !!value[key] && value[key][key] === value;
				otherKeyIsRecursive = !!other[key] && other[key][key] === other;
				if (valueKeyIsRecursive !== otherKeyIsRecursive) {
					if (valueKeyIsRecursive) { return 'first argument has a circular reference at key "' + key + '"; second does not'; }
					return 'second argument has a circular reference at key "' + key + '"; first does not';
				}
				if (!valueKeyIsRecursive && !otherKeyIsRecursive) {
					keyWhy = whyNotEqual(value[key], other[key]);
					if (keyWhy !== '') {
						return 'value at key "' + key + '" differs: ' + keyWhy;
					}
				}
			}
		}
		for (key in other) {
			if (has(other, key) && !has(value, key)) {
				return 'second argument has key "' + key + '"; first does not';
			}
		}
		return '';
	}

	return false;
};