<commit_before>//////////////////////////////////
//MagJS
//////////////////////////////////
/**!
 * @name mag.js - Copyright (c) 2013, 2014 Michael Glazer
 * @description MagnumJS core code library
 * @requires - jQuery http://www.jquery.com
 * @author Michael Glazer
 * @date 8/18/13, 4/9/14
 * @version 0.1 - Alpha - 0.2
 * @license MIT https://github.com/magnumjs/mag.js/blob/master/LICENSE
 * @link https://github.com/magnumjs
 */
;
'use strict';
(function(mag, undefined) {
  var LOG_LEVEL = 'warn'; //info|warn|error|debug|log
  window.log = function() {
    var level = [].shift.apply(arguments);
    var args = Array.prototype.slice.call(arguments);
    if (level == LOG_LEVEL && console) console[LOG_LEVEL](args.join(','));
  };
  mag.reserved = ['__requires', '__instance'];
  mag.aspect = {
    injectors: [],
    namespace: null,
    add: function(type, name, fun) {
      mag.aspect.injectors.push({
        type: type,
        name: name,
        fun: fun
      });
    },
    attach: function() {
      for (var i in mag.aspect.injectors) {
        var inject = mag.aspect.injectors[i];
        if (mag.aspect[inject.type]) {
          mag.aspect[inject.type](inject.name, inject.fun);
        }
      }
    },
    around: function(pointcut, advice) {
      var ns = mag.aspect.namespace;
      for (var member in mag.aspect.namespace) {
        if (typeof ns[member] == 'function' && member.match(pointcut)) {
          (function(fn, fnName, ns) {
            ns[fnName] = function() {
              return advice.call(ns, {
                fn: fn,
                fnName: fnName,
                arguments: arguments
              });
            };
          })(ns[member], member, ns);
        }
      }
    },
    before: function(pointcut, advice) {
      mag.aspect.around(pointcut,
        function(f) {
          advice.apply(mag.aspect.namespace, f.arguments);
          return mag.aspect.next(f)
        });
    },
    after: function(pointcut, advice) {
      mag.aspect.around(pointcut,
        function(f) {
          var ret = mag.aspect.next(f);
          advice.apply(mag.aspect.namespace, f.arguments);
          return ret;
        });
    },
    next: function(f) {
      return f.fn.apply(mag.aspect.namespace, f.arguments);
    }
  };
  mag.inject = function(ns) {
    mag.aspect.namespace = ns;
    mag.aspect.attach();
  };
  mag.module = function(name, /* [] = create new override existing 'name' */ dependentModules) {
    log('info', 'module name:' + name);
    this.modules = this.modules || {};
    var instance = this.modules[name];
    //TODO: create new instance if second parameter is empty array
    if (instance && (!dependentModules || (dependentModules && dependentModules.length == 0))) {
      return instance;
    }
    var Injector = {
      namespace: undefined,
      dependencies: {},
      waiting: [],
      findArgs: function(target) {
        if (typeof target !== 'function') return;
        var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
        var FN_ARG_SPLIT = /,/;
        var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
        var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
        var text = target.toString().replace(STRIP_COMMENTS, '');
        var argDecl = text.match(FN_ARGS);
        var args = argDecl[1].split(FN_ARG_SPLIT).map(
          function(arg) {
            return arg.trim()
          });
        return args;
      },
      getInstance: function(instance) {
        this.instances = this.instances || {};
        this.instances[this.namespace] = this.instances[this.namespace] || {};
        if (this.instances[this.namespace][instance]) {
          return this.instances[this.namespace][instance];
        }
      },
      setInstance:function(instance, object){
          this.instances[this.namespace][instance] = object;
      },
      process: function(target, sargs, instance) {
        var args = this.findArgs(target);
        var these = sargs || args;

        function construct(constructor, args, context) {
          function F() {
            return constructor.apply(context || this, args);
          }
          F.prototype = constructor.prototype;
          return new F();
        }
        if (instance) {
          //TODO: cache to maintain state for services, good idea?
          var object = this.getInstance(instance);
          if (object) return object;
          object = construct(target, this.getArrayDependencies(these));
          this.setInstance(instance, object);
          return object;
        }
        if (this.isRegistered(these)) {
          target.apply(target, this.getArrayDependencies(these));
        } else {
          //wait for notice
          var waiter = {
            target: target,
            args: these
          };
          this.waiting.push(waiter);
        }
      },
      isRegistered: function(args) {
        var registered = true;
        log('info', 'isRegistered args:', args);
        for (var i in args) {
          var name = args[i];
          if (!this.getDependencies()[name]) {
            log('warn', 'Dependency not registered when called:', name);
            registered = false;
            break;
          }
        }
        return registered;
      },
      getArrayDependencies: function(arr) {
        var depends = this.getDependencies();
        // make sure dependencies requires are loaded
        var that = this;
        return arr.map(function(value) {
          // need to return promise/deferred objects
          if (depends[value] && depends[value]['__requires']) {
            log('info', 'this dependency has dependencies: ' + value);
            log('info', 'requires: ' + depends[value]['__requires']);
          }
          if (depends[value] && depends[value]['__instance']) {
            return that.process(depends[value], null, value);
            //return new depends[value];
          }
          return depends[value];
        });
      },
      getDependencies: function(namespace) {
        return this.dependencies[namespace || this.namespace] || {};
      },
      register: function(name, dependency, instance) {
        var depends = this.findArgs(dependency);
        log('info', name + ' requires ' + depends);
        this.getDependencies()[name] = dependency;
        if (instance) this.getDependencies()[name]['__instance'] = instance;
        this.getDependencies()[name]['__requires'] = depends;
        this.service();
      },
      service: function() {
        for (var i in this.waiting) {
          var waiter = this.waiting[i];
          if (this.isRegistered(waiter.args)) {
            waiter.target.apply(waiter.target, this.getArrayDependencies(waiter.args));
            delete this.waiting[i];
          }
        }
      }
    };
    Injector.namespace = name;
    Injector.dependencies[name] = {};
    // load dependency modules first
    if (dependentModules) {
      var loadDependencies = function(dependentModules) {
        var depends = [];
        for (var index = 0, size = dependentModules.length; index < size; index++) {
          var dependent = dependentModules[index];
          if (this.modules[dependent]) {
            var depend = this.modules[dependent];
            depends.push(depend);
            //if dependency not yet defined give it to the waiter
            for (var skey in depend.services) {
              Injector.register(skey, depend.services[skey], 1);
            }
            for (var fkey in depend.factories) {
              Injector.register(fkey, depend.factories[fkey]());
            }
          }
        }
      }.bind(this);
      loadDependencies(dependentModules);
    }

    function processArgs(fun) {
      var args;
      if (typeof fun != 'function') {
        args = fun;
        mfun = args.pop();
        var fs = mfun.toString();
        var nf = fs.substring(fs.indexOf("{") + 1, fs.lastIndexOf("}"));
        fun = new Function(args.join(), nf);
      }
      return [fun, args];
    }
    return this.modules[name] = new function() {
      this.name = name;
      this.config = function(fun) {
        Injector.process(fun);
      };
      this.service = function(name, fun) {
        this.services = this.services || {};
        this.services[name] = this.services[name] || fun;
        Injector.register(name, fun, 1);
      };
      this.factory = function(name, fun) {
        this.factories = this.factories || {};
        this.factories[name] = this.factories[name] || fun;
        Injector.register(name, this.factories[name]());
      }
      this.control = function(name, fun) {
        this.controls = this.controls || {};
        Injector.register('Scope', this.getScope(name));
        var ret = processArgs(fun);
        this.fire('mag.control.process.begin', [name]);
        Injector.process(ret[0], ret[1]);
        this.fire('mag.control.process.end', [name]);
      }
      this.getScope = function(name) {
        this.controls = this.controls || {};
        return this.controls[name] = this.controls[name] || {};
      }
      this.observers = {};
      this.on = function(eventNames, listener) {
        eventNames = eventNames.split(/\s+/);
        while (eventName = eventNames.shift()) {
          if (!this.observers[eventName]) this.observers[eventName] = [];
          this.observers[eventName].push(listener);
        }
      }
      this.fire = function(eventName, args) {
        if (this.observers[eventName]) {
          for (var i = 0; i < this.observers[eventName].length; i++) {
            this.observers[eventName][i].apply(this, args);
          }
        }
      }
      mag.inject(this);
    }
  }
})(window.mag = {});
<commit_msg>Update mag.js<commit_after>//////////////////////////////////
//MagJS
//////////////////////////////////
/**!
 * @name mag.js - Copyright (c) 2013, 2014 Michael Glazer
 * @description MagnumJS core code library
 * @requires - jQuery http://www.jquery.com
 * @author Michael Glazer
 * @date 4/16/2014
 * @version Alpha - 0.2.15
 * @license MIT https://github.com/magnumjs/mag.js/blob/master/LICENSE
 * @link https://github.com/magnumjs
 */
;
'use strict';
(function(mag, undefined) {
  var LOG_LEVEL = 'warn'; //info|warn|error|debug|log
  window.log = function() {
    var level = [].shift.apply(arguments);
    var args = Array.prototype.slice.call(arguments);
    if (level == LOG_LEVEL && console) console[LOG_LEVEL](args.join(','));
  };
  mag.reserved = ['__requires', '__instance'];
  mag.aspect = {
    injectors: [],
    namespace: null,
    add: function(type, name, fun) {
      mag.aspect.injectors.push({
        type: type,
        name: name,
        fun: fun
      });
    },
    attach: function() {
      for (var i in mag.aspect.injectors) {
        var inject = mag.aspect.injectors[i];
        if (mag.aspect[inject.type]) {
          mag.aspect[inject.type](inject.name, inject.fun);
        }
      }
    },
    around: function(pointcut, advice) {
      var ns = mag.aspect.namespace;
      for (var member in mag.aspect.namespace) {
        if (typeof ns[member] == 'function' && member.match(pointcut)) {
          (function(fn, fnName, ns) {
            ns[fnName] = function() {
              return advice.call(ns, {
                fn: fn,
                fnName: fnName,
                arguments: arguments
              });
            };
          })(ns[member], member, ns);
        }
      }
    },
    before: function(pointcut, advice) {
      mag.aspect.around(pointcut,
        function(f) {
          advice.apply(mag.aspect.namespace, f.arguments);
          return mag.aspect.next(f)
        });
    },
    after: function(pointcut, advice) {
      mag.aspect.around(pointcut,
        function(f) {
          var ret = mag.aspect.next(f);
          advice.apply(mag.aspect.namespace, f.arguments);
          return ret;
        });
    },
    next: function(f) {
      return f.fn.apply(mag.aspect.namespace, f.arguments);
    }
  };
  mag.inject = function(ns) {
    mag.aspect.namespace = ns;
    mag.aspect.attach();
  };
  mag.module = function(name, /* [] = create new override existing 'name' */ dependentModules) {
    log('info', 'module name:' + name);
    this.modules = this.modules || {};
    var instance = this.modules[name];
    //TODO: create new instance if second parameter is empty array
    if (instance && (!dependentModules || (dependentModules && dependentModules.length == 0))) {
      return instance;
    }
    var Injector = {
      namespace: undefined,
      dependencies: {},
      waiting: [],
      findArgs: function(target) {
        if (typeof target !== 'function') return;
        var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
        var FN_ARG_SPLIT = /,/;
        var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
        var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
        var text = target.toString().replace(STRIP_COMMENTS, '');
        var argDecl = text.match(FN_ARGS);
        var args = argDecl[1].split(FN_ARG_SPLIT).map(
          function(arg) {
            return arg.trim()
          });
        return args;
      },
      getInstance: function(instance) {
        this.instances = this.instances || {};
        this.instances[this.namespace] = this.instances[this.namespace] || {};
        if (this.instances[this.namespace][instance]) {
          return this.instances[this.namespace][instance];
        }
      },
      setInstance: function(instance, object) {
        this.instances[this.namespace][instance] = object;
      },
      process: function(target, sargs, instance) {
        var args = this.findArgs(target);
        var these = sargs || args;

        function construct(constructor, args, context) {
          function F() {
            return constructor.apply(context || this, args);
          }
          F.prototype = constructor.prototype;
          return new F();
        }
        if (instance) {
          //TODO: cache to maintain state for services, good idea?
          var object = this.getInstance(instance);
          if (object) return object;
          object = construct(target, this.getArrayDependencies(these));
          this.setInstance(instance, object);
          return object;
        }
        if (this.isRegistered(these)) {
          target.apply(target, this.getArrayDependencies(these));
        } else {
          //wait for notice
          var waiter = {
            target: target,
            args: these
          };
          this.waiting.push(waiter);
        }
      },
      isRegistered: function(args) {
        var registered = true;
        log('info', 'isRegistered args:', args);
        for (var i in args) {
          var name = args[i];
          if (!this.getDependencies()[name]) {
            log('info', 'Dependency not registered when called:', name);
            registered = false;
            break;
          }
        }
        return registered;
      },
      getArrayDependencies: function(arr) {
        var depends = this.getDependencies();
        // make sure dependencies requires are loaded
        var that = this;
        return arr.map(function(value) {
          // need to return promise/deferred objects
          if (depends[value] && depends[value]['__requires']) {
            log('info', 'this dependency has dependencies: ' + value);
            log('info', 'requires: ' + depends[value]['__requires']);
          }
          if (depends[value] && depends[value]['__instance']) {
            return that.process(depends[value], null, value);
            //return new depends[value];
          }
          return depends[value];
        });
      },
      getDependencies: function(namespace) {
        return this.dependencies[namespace || this.namespace] || {};
      },
      register: function(name, dependency, instance) {
        var depends = this.findArgs(dependency);
        log('info', name + ' requires ' + depends);
        this.getDependencies()[name] = dependency;
        if (instance) this.getDependencies()[name]['__instance'] = instance;
        this.getDependencies()[name]['__requires'] = depends;
        this.service();
      },
      service: function() {
        for (var i in this.waiting) {
          var waiter = this.waiting[i];
          if (this.isRegistered(waiter.args)) {
            waiter.target.apply(waiter.target, this.getArrayDependencies(waiter.args));
            delete this.waiting[i];
          }
        }
      }
    };
    Injector.namespace = name;
    Injector.dependencies[name] = {};
    // load dependency modules first
    if (dependentModules) {
      var loadDependencies = function(dependentModules) {
        var depends = [];
        for (var index = 0, size = dependentModules.length; index < size; index++) {
          var dependent = dependentModules[index];
          if (this.modules[dependent]) {
            var depend = this.modules[dependent];
            depends.push(depend);
            //if dependency not yet defined give it to the waiter
            for (var skey in depend.services) {
              Injector.register(skey, depend.services[skey], 1);
            }
            for (var fkey in depend.factories) {
              Injector.register(fkey, depend.factories[fkey]());
            }
          }
        }
      }.bind(this);
      loadDependencies(dependentModules);
    }

    function processArgs(fun) {
      var args;
      if (typeof fun != 'function') {
        args = fun;
        mfun = args.pop();
        var fs = mfun.toString();
        var nf = fs.substring(fs.indexOf("{") + 1, fs.lastIndexOf("}"));
        fun = new Function(args.join(), nf);
      }
      return [fun, args];
    }
    return this.modules[name] = new function() {
      this.name = name;
      this.config = function(fun) {
        Injector.process(fun);
      };
      this.service = function(name, fun) {
        this.services = this.services || {};
        this.services[name] = this.services[name] || fun;
        Injector.register(name, fun, 1);
      };
      this.factory = function(name, fun) {
        this.factories = this.factories || {};
        this.factories[name] = this.factories[name] || fun;
        Injector.register(name, this.factories[name]());
      }
      this.control = function(name, fun) {
        this.controls = this.controls || {};
        Injector.register('Scope', this.getScope(name));
        var ret = processArgs(fun);
        this.fire('mag.control.process.begin', [name]);
        Injector.process(ret[0], ret[1]);
        this.fire('mag.control.process.end', [name]);
      }
      this.getScope = function(name) {
        this.controls = this.controls || {};
        return this.controls[name] = this.controls[name] || {};
      }
      this.observers = {};
      this.on = function(eventNames, listener) {
        eventNames = eventNames.split(/\s+/);
        while (eventName = eventNames.shift()) {
          if (!this.observers[eventName]) this.observers[eventName] = [];
          this.observers[eventName].push(listener);
        }
      }
      this.fire = function(eventName, args) {
        if (this.observers[eventName]) {
          for (var i = 0; i < this.observers[eventName].length; i++) {
            this.observers[eventName][i].apply(this, args);
          }
        }
      }
      mag.inject(this);
    }
  }
})(window.mag = {});
<|endoftext|>


<commit_before>import { isArray, isStringOrNumber, isFunction, isNullOrUndefined, isStatefulComponent, isInvalidNode } from '../core/utils';
import { replaceNode, SVGNamespace, MathNamespace } from './utils';
import { patchNonKeyedChildren, patchKeyedChildren, patchAttribute, patchComponent, patchStyle } from './patching';
import { mountChildren, mountNode } from './mounting';
import { removeEventFromRegistry, addEventToRegistry } from './events';

function updateTextNode(dom, lastChildren, nextChildren) {
	if (isStringOrNumber(lastChildren)) {
		dom.firstChild.nodeValue = nextChildren;
	} else {
		dom.textContent = nextChildren;
	}
}

function diffChildren(lastNode, nextNode, dom, namespace, lifecycle, context, staticCheck, instance) {
	const nextChildren = nextNode.children;
	const lastChildren = lastNode.children;

	if (lastChildren === nextChildren) {
		return;
	}

	if (!isInvalidNode(lastChildren)) {
		if (!isInvalidNode(nextChildren)) {
			if (isArray(lastChildren)) {
				if (isArray(nextChildren)) {
					const isKeyed = nextChildren.length && !isNullOrUndefined(nextChildren[0]) && !isNullOrUndefined(nextChildren[0].key)
						|| lastChildren.length && !isNullOrUndefined(lastChildren[0]) && !isNullOrUndefined(lastChildren[0].key);

					if (isKeyed) {
						patchKeyedChildren(lastChildren, nextChildren, dom, namespace, lifecycle, context, instance);
					} else {
						patchNonKeyedChildren(lastChildren, nextChildren, dom, namespace, lifecycle, context, null, instance);
					}
				} else {
					patchNonKeyedChildren(lastChildren, [nextChildren], dom, namespace, lifecycle, context, null, instance);
				}
			} else {
				if (isArray(nextChildren)) {
					patchNonKeyedChildren([lastChildren], nextChildren, dom, namespace, lifecycle, context, null, instance);
				} else if (isStringOrNumber(nextChildren)) {
					updateTextNode(dom, lastChildren, nextChildren);
				} else {
					diffNodes(lastChildren, nextChildren, dom, namespace, lifecycle, context, staticCheck, instance);
				}
			}
		} else {
			dom.textContent = '';
		}
	} else {
		if (isStringOrNumber(nextChildren)) {
			updateTextNode(dom, lastChildren, nextChildren);
		} else if (!isNullOrUndefined(nextChildren)) {
			if (typeof nextChildren === 'object') {
				if (isArray(nextChildren)) {
					mountChildren(nextChildren, dom, namespace, lifecycle, context, instance);
				} else {
					mountNode(nextChildren, dom, namespace, lifecycle, context, instance);
				}
			}
		}
	}
}

function diffRef(instance, lastValue, nextValue, dom) {
	if (!isNullOrUndefined(instance)) {
		if (isString(lastValue)) {
			delete instance.refs[lastValue];
		}
		if (isString(nextValue)) {
			instance.refs[nextValue] = dom;
		}
	}
}

function diffAttributes(lastNode, nextNode, dom, instance) {
	const nextAttrs = nextNode.attrs;
	const lastAttrs = lastNode.attrs;
	const nextAttrsIsUndef = isNullOrUndefined(nextAttrs);
	const lastAttrsIsUndef = isNullOrUndefined(lastAttrs);

	if (!nextAttrsIsUndef) {
		const nextAttrsKeys = Object.keys(nextAttrs);
		const attrKeysLength = nextAttrsKeys.length;

		for (let i = 0; i < attrKeysLength; i++) {
			const attr = nextAttrsKeys[i];
			const lastAttrVal = !lastAttrsIsUndef && lastAttrs[attr];
			const nextAttrVal = nextAttrs[attr];

			if (lastAttrVal !== nextAttrVal) {
				if (attr === 'ref') {
					diffRef(instance, lastAttrVal, nextAttrVal, dom);
				} else {
					patchAttribute(attr, nextAttrVal, dom);
				}
			}
		}
	}
	if (!lastAttrsIsUndef) {
		const lastAttrsKeys = Object.keys(lastAttrs);
		const attrKeysLength = lastAttrsKeys.length;

		for (let i = 0; i < attrKeysLength; i++) {
			const attr = lastAttrsKeys[i];

			if (nextAttrsIsUndef || isNullOrUndefined(nextAttrs[attr])) {
				if (attr === 'ref') {
					diffRef(instance, lastAttrs[attr], null, dom);
				} else {
					dom.removeAttribute(attr);
				}
			}
		}
	}
}

function diffEvents(lastNode, nextNode, dom) {
	const lastEvents = lastNode.events;

	if (!isNullOrUndefined(lastEvents)) {
		const nextEvents = nextNode.events;
		if (!isNullOrUndefined(nextEvents)) {
			const lastEventsKeys = Object.keys(lastEvents);
			const nextEventsKeys = Object.keys(nextEvents);

			for (let i = 0; i < lastEventsKeys.length; i++) {
				const event = lastEventsKeys[i];
				const nextEvent = nextEvents[event];
				const lastEvent = lastEvents[lastEventsKeys];

				if (isNullOrUndefined(nextEvent)) {
					removeEventFromRegistry(event, lastEvent);
				} else if (nextEvent !== lastEvent) {
					// TODO: feels lot of looping here, but also this is real edge case
					// Callback has changed and is not same as before
					removeEventFromRegistry(event, lastEvent); // remove old
					addEventToRegistry(event, dom, nextEvent); // add new
				}
			}
		}
	}
}

export function diffNodes(lastNode, nextNode, parentDom, namespace, lifecycle, context, staticCheck, instance) {
	if (nextNode === false || nextNode === null) {
		return;
	}
	if (!isNullOrUndefined(nextNode.then)) {
		nextNode.then(node => {
			diffNodes(lastNode, node, parentDom, namespace, lifecycle, context, staticCheck, instance);
		});
		return;
	}
	if (isStringOrNumber(lastNode)) {
		if (isStringOrNumber(nextNode)) {
			parentDom.firstChild.nodeValue = nextNode;
		} else {
			replaceNode(lastNode, nextNode, parentDom, namespace, lifecycle, context, instance);
		}
		return;
	}
	const nextHooks = nextNode.hooks;
	if (!isNullOrUndefined(nextHooks) && !isNullOrUndefined(nextHooks.willUpdate)) {
		nextHooks.willUpdate(lastNode.dom);
	}
	const nextTag = nextNode.tag || (staticCheck && !isNullOrUndefined(nextNode.tpl) ? nextNode.tpl.tag : null);
	const lastTag = lastNode.tag || (staticCheck && !isNullOrUndefined(lastNode.tpl) ? lastNode.tpl.tag : null);

	namespace = namespace || nextTag === 'svg' ? SVGNamespace : nextTag === 'math' ? MathNamespace : null;
	if (lastTag !== nextTag) {
		if (isFunction(lastTag) && !isFunction(nextTag)) {
			if (isStatefulComponent(lastTag)) {
				diffNodes(lastNode.instance._lastNode, nextNode, parentDom, namespace, lifecycle, context, true, instance);
			} else {
				diffNodes(lastNode.instance, nextNode, parentDom, namespace, lifecycle, context, true, instance);
			}
		} else {
			replaceNode(lastNode, nextNode, parentDom, namespace, lifecycle, context, instance);
		}
		return;
	} else if (isNullOrUndefined(lastTag)) {
		nextNode.dom = lastNode.dom;
		return;
	}
	if (isFunction(lastTag) && isFunction(nextTag)) {
		nextNode.instance = lastNode.instance;
		nextNode.dom = lastNode.dom;
		patchComponent(nextNode, nextNode.tag, nextNode.instance, lastNode.attrs || {}, nextNode.attrs || {}, nextNode.hooks, nextNode.children, parentDom, lifecycle, context);
		return;
	}
	const dom = lastNode.dom;

	nextNode.dom = dom;
	diffChildren(lastNode, nextNode, dom, namespace, lifecycle, context, staticCheck, instance);
	const nextClassName = nextNode.className;
	const nextStyle = nextNode.style;

	if (lastNode.className !== nextClassName) {
		if (isNullOrUndefined(nextClassName)) {
			dom.removeAttribute('class');
		} else {
			dom.className = nextClassName;
		}
	}
	// TODO Should check for null & undefined BEFORE calling this function?
	if (lastNode.style !== nextStyle) {
		patchStyle(lastNode.style, nextStyle, dom);
	}
	diffAttributes(lastNode, nextNode, dom, instance);
	diffEvents(lastNode, nextNode, dom);
	if (!isNullOrUndefined(nextHooks) && !isNullOrUndefined(nextHooks.didUpdate)) {
		nextHooks.didUpdate(dom);
	}
}
<commit_msg>fixed typo in event diffing<commit_after>import { isArray, isStringOrNumber, isFunction, isNullOrUndefined, isStatefulComponent, isInvalidNode } from '../core/utils';
import { replaceNode, SVGNamespace, MathNamespace } from './utils';
import { patchNonKeyedChildren, patchKeyedChildren, patchAttribute, patchComponent, patchStyle } from './patching';
import { mountChildren, mountNode } from './mounting';
import { removeEventFromRegistry, addEventToRegistry } from './events';

function updateTextNode(dom, lastChildren, nextChildren) {
	if (isStringOrNumber(lastChildren)) {
		dom.firstChild.nodeValue = nextChildren;
	} else {
		dom.textContent = nextChildren;
	}
}

function diffChildren(lastNode, nextNode, dom, namespace, lifecycle, context, staticCheck, instance) {
	const nextChildren = nextNode.children;
	const lastChildren = lastNode.children;

	if (lastChildren === nextChildren) {
		return;
	}

	if (!isInvalidNode(lastChildren)) {
		if (!isInvalidNode(nextChildren)) {
			if (isArray(lastChildren)) {
				if (isArray(nextChildren)) {
					const isKeyed = nextChildren.length && !isNullOrUndefined(nextChildren[0]) && !isNullOrUndefined(nextChildren[0].key)
						|| lastChildren.length && !isNullOrUndefined(lastChildren[0]) && !isNullOrUndefined(lastChildren[0].key);

					if (isKeyed) {
						patchKeyedChildren(lastChildren, nextChildren, dom, namespace, lifecycle, context, instance);
					} else {
						patchNonKeyedChildren(lastChildren, nextChildren, dom, namespace, lifecycle, context, null, instance);
					}
				} else {
					patchNonKeyedChildren(lastChildren, [nextChildren], dom, namespace, lifecycle, context, null, instance);
				}
			} else {
				if (isArray(nextChildren)) {
					patchNonKeyedChildren([lastChildren], nextChildren, dom, namespace, lifecycle, context, null, instance);
				} else if (isStringOrNumber(nextChildren)) {
					updateTextNode(dom, lastChildren, nextChildren);
				} else {
					diffNodes(lastChildren, nextChildren, dom, namespace, lifecycle, context, staticCheck, instance);
				}
			}
		} else {
			dom.textContent = '';
		}
	} else {
		if (isStringOrNumber(nextChildren)) {
			updateTextNode(dom, lastChildren, nextChildren);
		} else if (!isNullOrUndefined(nextChildren)) {
			if (typeof nextChildren === 'object') {
				if (isArray(nextChildren)) {
					mountChildren(nextChildren, dom, namespace, lifecycle, context, instance);
				} else {
					mountNode(nextChildren, dom, namespace, lifecycle, context, instance);
				}
			}
		}
	}
}

function diffRef(instance, lastValue, nextValue, dom) {
	if (!isNullOrUndefined(instance)) {
		if (isString(lastValue)) {
			delete instance.refs[lastValue];
		}
		if (isString(nextValue)) {
			instance.refs[nextValue] = dom;
		}
	}
}

function diffAttributes(lastNode, nextNode, dom, instance) {
	const nextAttrs = nextNode.attrs;
	const lastAttrs = lastNode.attrs;
	const nextAttrsIsUndef = isNullOrUndefined(nextAttrs);
	const lastAttrsIsUndef = isNullOrUndefined(lastAttrs);

	if (!nextAttrsIsUndef) {
		const nextAttrsKeys = Object.keys(nextAttrs);
		const attrKeysLength = nextAttrsKeys.length;

		for (let i = 0; i < attrKeysLength; i++) {
			const attr = nextAttrsKeys[i];
			const lastAttrVal = !lastAttrsIsUndef && lastAttrs[attr];
			const nextAttrVal = nextAttrs[attr];

			if (lastAttrVal !== nextAttrVal) {
				if (attr === 'ref') {
					diffRef(instance, lastAttrVal, nextAttrVal, dom);
				} else {
					patchAttribute(attr, nextAttrVal, dom);
				}
			}
		}
	}
	if (!lastAttrsIsUndef) {
		const lastAttrsKeys = Object.keys(lastAttrs);
		const attrKeysLength = lastAttrsKeys.length;

		for (let i = 0; i < attrKeysLength; i++) {
			const attr = lastAttrsKeys[i];

			if (nextAttrsIsUndef || isNullOrUndefined(nextAttrs[attr])) {
				if (attr === 'ref') {
					diffRef(instance, lastAttrs[attr], null, dom);
				} else {
					dom.removeAttribute(attr);
				}
			}
		}
	}
}

function diffEvents(lastNode, nextNode, dom) {
	const lastEvents = lastNode.events;

	if (!isNullOrUndefined(lastEvents)) {
		const nextEvents = nextNode.events;
		if (!isNullOrUndefined(nextEvents)) {
			const lastEventsKeys = Object.keys(lastEvents);
			const nextEventsKeys = Object.keys(nextEvents);

			for (let i = 0; i < lastEventsKeys.length; i++) {
				const event = lastEventsKeys[i];
				const nextEvent = nextEvents[event];
				const lastEvent = lastEvents[event];

				if (isNullOrUndefined(nextEvent)) {
					removeEventFromRegistry(event, lastEvent);
				} else if (nextEvent !== lastEvent) {
					// TODO: feels lot of looping here, but also this is real edge case
					// Callback has changed and is not same as before
					removeEventFromRegistry(event, lastEvent); // remove old
					addEventToRegistry(event, dom, nextEvent); // add new
				}
			}
		}
	}
}

export function diffNodes(lastNode, nextNode, parentDom, namespace, lifecycle, context, staticCheck, instance) {
	if (nextNode === false || nextNode === null) {
		return;
	}
	if (!isNullOrUndefined(nextNode.then)) {
		nextNode.then(node => {
			diffNodes(lastNode, node, parentDom, namespace, lifecycle, context, staticCheck, instance);
		});
		return;
	}
	if (isStringOrNumber(lastNode)) {
		if (isStringOrNumber(nextNode)) {
			parentDom.firstChild.nodeValue = nextNode;
		} else {
			replaceNode(lastNode, nextNode, parentDom, namespace, lifecycle, context, instance);
		}
		return;
	}
	const nextHooks = nextNode.hooks;
	if (!isNullOrUndefined(nextHooks) && !isNullOrUndefined(nextHooks.willUpdate)) {
		nextHooks.willUpdate(lastNode.dom);
	}
	const nextTag = nextNode.tag || (staticCheck && !isNullOrUndefined(nextNode.tpl) ? nextNode.tpl.tag : null);
	const lastTag = lastNode.tag || (staticCheck && !isNullOrUndefined(lastNode.tpl) ? lastNode.tpl.tag : null);

	namespace = namespace || nextTag === 'svg' ? SVGNamespace : nextTag === 'math' ? MathNamespace : null;
	if (lastTag !== nextTag) {
		if (isFunction(lastTag) && !isFunction(nextTag)) {
			if (isStatefulComponent(lastTag)) {
				diffNodes(lastNode.instance._lastNode, nextNode, parentDom, namespace, lifecycle, context, true, instance);
			} else {
				diffNodes(lastNode.instance, nextNode, parentDom, namespace, lifecycle, context, true, instance);
			}
		} else {
			replaceNode(lastNode, nextNode, parentDom, namespace, lifecycle, context, instance);
		}
		return;
	} else if (isNullOrUndefined(lastTag)) {
		nextNode.dom = lastNode.dom;
		return;
	}
	if (isFunction(lastTag) && isFunction(nextTag)) {
		nextNode.instance = lastNode.instance;
		nextNode.dom = lastNode.dom;
		patchComponent(nextNode, nextNode.tag, nextNode.instance, lastNode.attrs || {}, nextNode.attrs || {}, nextNode.hooks, nextNode.children, parentDom, lifecycle, context);
		return;
	}
	const dom = lastNode.dom;

	nextNode.dom = dom;
	diffChildren(lastNode, nextNode, dom, namespace, lifecycle, context, staticCheck, instance);
	const nextClassName = nextNode.className;
	const nextStyle = nextNode.style;

	if (lastNode.className !== nextClassName) {
		if (isNullOrUndefined(nextClassName)) {
			dom.removeAttribute('class');
		} else {
			dom.className = nextClassName;
		}
	}
	// TODO Should check for null & undefined BEFORE calling this function?
	if (lastNode.style !== nextStyle) {
		patchStyle(lastNode.style, nextStyle, dom);
	}
	diffAttributes(lastNode, nextNode, dom, instance);
	diffEvents(lastNode, nextNode, dom);
	if (!isNullOrUndefined(nextHooks) && !isNullOrUndefined(nextHooks.didUpdate)) {
		nextHooks.didUpdate(dom);
	}
}
<|endoftext|>


<commit_before>function ChartGraph(canvas, options) {
  this.options = options;
  this.context = canvas.getContext('2d');
  this.canvas = canvas;
  this.reports = options.reports || [];
  this.xOffset = 30;
  this.yOffset = 60;
  this.dateStep = (canvas.width - this.xOffset * 2) / (this.reports.length);
  this.countStep = (canvas.height - this.yOffset * 2) / this.maxCount();
  this.scaleFontSize = 12;
  this.scaleFontFamily = 'Roboto, Arial, sans-serif';
  this.scaleFontColor = "#3d3d3d";
}

ChartGraph.prototype.maxCount = function() {
  let max = -1;

  this.reports.forEach((report) => {
    if (report[1] > max) {
      max = report[1];
    }
  });

  return max + 1;
};

ChartGraph.prototype.dotXCoord = function(index) {
  return this.dateStep * index + this.xOffset;
};

ChartGraph.prototype.dotYCoord = function(index) {
  return this.canvas.height - this.yOffset - this.reports[index][1] * this.countStep;
};

ChartGraph.prototype.clear = function(ctx) {
  return ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
};

ChartGraph.prototype.drawAxis = function(ctx) {
  ctx.beginPath();
  ctx.moveTo(this.xOffset, this.yOffset);
  ctx.lineTo(this.xOffset, this.canvas.height - this.yOffset);

  for (let i = 0; i < this.maxCount() + 1; i++) {
    ctx.moveTo(this.xOffset, this.canvas.height - this.yOffset - this.countStep * i);
    ctx.font = `${this.scaleFontSize}px ${this.scaleFontFamily}`;
    ctx.fillText(i, 0, this.canvas.height - this.yOffset - this.countStep * i + this.scaleFontSize / 2);
    ctx.lineTo(this.canvas.width - this.xOffset, this.canvas.height - this.yOffset - this.countStep * i);
  }

  ctx.strokeStyle = "#3d3d3d";
  ctx.stroke();
};

ChartGraph.prototype.drawReportDots = function(ctx) {
  this.reports.forEach((report, index) => {
    ctx.beginPath();
    ctx.arc(this.dotXCoord(index), this.dotYCoord(index), 5, 0, 2 * Math.PI, false);
    ctx.fillStyle = "#00afd7";
    ctx.fill();
  });
};

ChartGraph.prototype.drawReportLines = function(ctx) {
  this.reports.forEach((report, index) => {
    if (index < this.reports.length - 1) {
      ctx.beginPath();
      ctx.moveTo(this.dotXCoord(index), this.dotYCoord(index));
      ctx.lineTo(this.dotXCoord(index + 1), this.dotYCoord(index + 1));
      ctx.lineWidth = 3;
      ctx.strokeStyle = "#00afd7";
      ctx.stroke();
    }
  });
};

ChartGraph.prototype.drawText = function (ctx, x, y, text) {
    ctx.save();

    ctx.translate(x, y);
    ctx.rotate(Math.PI / 4);
    ctx.translate(-x, -y);

    ctx.font = `${this.scaleFontSize}px ${this.scaleFontFamily}`;
    ctx.fillStyle = this.scaleFontColor;
    ctx.fillText(text, x, y);

    ctx.restore();
};

ChartGraph.prototype.drawDates = function(ctx) {
  ctx.beginPath();

  this.reports.forEach((report, index) => {
    this.drawText(
      ctx,
      this.dateStep * index + this.xOffset,
      this.canvas.height - this.yOffset * 0.75,
      report[0]
    );
  });
};

ChartGraph.prototype.draw = function() {
  let ctx = this.context;

  this.clear(ctx);
  this.drawAxis(ctx);
  this.drawReportDots(ctx);
  this.drawReportLines(ctx);
  this.drawDates(ctx);
};

export default ChartGraph;
<commit_msg>Show report date in format -> Dec 1<commit_after>function ChartGraph(canvas, options) {
  this.options = options;
  this.context = canvas.getContext('2d');
  this.canvas = canvas;
  this.reports = options.reports || [];
  this.xOffset = 30;
  this.yOffset = 60;
  this.dateStep = (canvas.width - this.xOffset * 2) / (this.reports.length);
  this.countStep = (canvas.height - this.yOffset * 2) / this.maxCount();
  this.scaleFontSize = 12;
  this.scaleFontFamily = 'Roboto, Arial, sans-serif';
  this.scaleFontColor = "#3d3d3d";
}

ChartGraph.prototype.maxCount = function() {
  let max = -1;

  this.reports.forEach((report) => {
    if (report[1] > max) {
      max = report[1];
    }
  });

  return max + 1;
};

ChartGraph.prototype.dotXCoord = function(index) {
  return this.dateStep * index + this.xOffset;
};

ChartGraph.prototype.dotYCoord = function(index) {
  return this.canvas.height - this.yOffset - this.reports[index][1] * this.countStep;
};

ChartGraph.prototype.clear = function(ctx) {
  return ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
};

ChartGraph.prototype.drawAxis = function(ctx) {
  ctx.beginPath();
  ctx.moveTo(this.xOffset, this.yOffset);
  ctx.lineTo(this.xOffset, this.canvas.height - this.yOffset);

  for (let i = 0; i < this.maxCount() + 1; i++) {
    ctx.moveTo(this.xOffset, this.canvas.height - this.yOffset - this.countStep * i);
    ctx.font = `${this.scaleFontSize}px ${this.scaleFontFamily}`;
    ctx.fillText(i, 0, this.canvas.height - this.yOffset - this.countStep * i + this.scaleFontSize / 2);
    ctx.lineTo(this.canvas.width - this.xOffset, this.canvas.height - this.yOffset - this.countStep * i);
  }

  ctx.strokeStyle = "#3d3d3d";
  ctx.stroke();
};

ChartGraph.prototype.drawReportDots = function(ctx) {
  this.reports.forEach((report, index) => {
    ctx.beginPath();
    ctx.arc(this.dotXCoord(index), this.dotYCoord(index), 5, 0, 2 * Math.PI, false);
    ctx.fillStyle = "#00afd7";
    ctx.fill();
  });
};

ChartGraph.prototype.drawReportLines = function(ctx) {
  this.reports.forEach((report, index) => {
    if (index < this.reports.length - 1) {
      ctx.beginPath();
      ctx.moveTo(this.dotXCoord(index), this.dotYCoord(index));
      ctx.lineTo(this.dotXCoord(index + 1), this.dotYCoord(index + 1));
      ctx.lineWidth = 3;
      ctx.strokeStyle = "#00afd7";
      ctx.stroke();
    }
  });
};

ChartGraph.prototype.drawText = function (ctx, x, y, text) {
    ctx.save();

    ctx.translate(x, y);
    ctx.rotate(Math.PI / 4);
    ctx.translate(-x, -y);

    ctx.font = `${this.scaleFontSize}px ${this.scaleFontFamily}`;
    ctx.fillStyle = this.scaleFontColor;
    ctx.fillText(text, x, y);

    ctx.restore();
};

ChartGraph.prototype.drawDates = function(ctx) {
  ctx.beginPath();

  this.reports.forEach((report, index) => {
    let date = moment(report[0]).format("MMM D");

    this.drawText(
      ctx,
      this.dateStep * index + this.xOffset,
      this.canvas.height - this.yOffset * 0.75,
      date
    );
  });
};

ChartGraph.prototype.draw = function() {
  let ctx = this.context;

  this.clear(ctx);
  this.drawAxis(ctx);
  this.drawReportDots(ctx);
  this.drawReportLines(ctx);
  this.drawDates(ctx);
};

export default ChartGraph;
<|endoftext|>


<commit_before>/* Saves repository followers into a file */

var inputFile = process.argv[2];
if (!inputFile) {
  printUsage();
  return -2;
}
var dbFileName = process.argv[3];
if (!dbFileName) {
  printUsage();
  return -1;
}

saveOutput(readInput(inputFile), dbFileName);

function readInput(inputFile) {
  var allRepo = require(inputFile);
  console.log('Read ' + Object.keys(allRepo).length + ' repositories;');
  return allRepo;
}

function saveOutput(repositories, dbFileName) {
  var level = require('level');
  var db = level(dbFileName, {valueEncoding: 'json'});
  var repoNames = Object.keys(repositories);

  var writeOps = repoNames.map(function (name) {
    return { type: 'put', key: name, value: repositories[name] };
  });

  db.batch(writeOps, function (err) {
    if (err) throw new Error('Failed to save ' + repoNames.length + ' records for ' + dbFileName + '. Error: ' + err);
    console.log('Saved records to database: ', repoNames.length);
  });
}

function printUsage() {
  console.log('Save json file of followers into a leveldb database');
  console.log('  node savetodb ./allRepoFollowers.json ./db/followers');
}

function handleError(err) {
  if (err) throw err;
}
<commit_msg>No longer required<commit_after><|endoftext|>


<commit_before>'use strict';

var Ajv = require('./ajv')
  , util = require('../lib/compile/util');

module.exports = getAjvInstances;

var firstTime = true;

var isBrowser = typeof window == 'object';
var fullTest = isBrowser || !process.env.AJV_FAST_TEST;

function getAjvInstances(opts) {
  opts = opts || {};
  var instances = [];
  var options = [
    {},
    { async: true },
    { async: 'co*' },
    { async: 'es7' },
    { async: 'es7', transpile: 'nodent' },
    { async: '*', transpile: 'regenerator' },
    { async: 'co*', allErrors: true },
    { async: 'es7', allErrors: true },
    { async: 'es7', transpile: 'nodent', allErrors: true },
    { async: '*', transpile: 'regenerator', allErrors: true }
  ];

  if (fullTest) options = options.concat([
    { async: '*' },
    { transpile: 'regenerator' },
    { async: true, transpile: 'regenerator' },
    { async: 'co*', transpile: 'regenerator' },
    { async: 'es7', transpile: 'regenerator' },
    { allErrors: true },
    { async: true, allErrors: true },
    { async: '*', allErrors: true },
    { transpile: 'regenerator', allErrors: true },
    { async: true, transpile: 'regenerator', allErrors: true },
    { async: 'co*', transpile: 'regenerator', allErrors: true },
    { async: 'es7', transpile: 'regenerator', allErrors: true }
  ]);

  // options = options.filter(function (_opts) {
  //   return _opts.transpile == 'nodent';
  // });

  // var i = 10, repeatOptions = [];
  // while (i--) repeatOptions = repeatOptions.concat(options);
  // options = repeatOptions;

  options.forEach(function (_opts) {
    util.copy(opts, _opts);
    var ajv = getAjv(_opts);
    if (ajv) instances.push(ajv);
  });

  if (firstTime) {
    var asyncModes = [];
    instances.forEach(function (ajv) {
      if (!ajv._opts.async) return;
      var t = ajv._opts.transpile;
      var mode = ajv._opts.async + (t === true ? '' : '.' + t);
      if (asyncModes.indexOf(mode) == -1) asyncModes.push(mode);
    });
    console.log('Testing', instances.length, 'ajv instances:', asyncModes.join(','));
    firstTime = false;
  }

  return instances;
}

function getAjv(opts){
  try { return Ajv(opts); } catch(e) {}
}
<commit_msg>exclude es7.regenerator async test when running in Safari<commit_after>'use strict';

var Ajv = require('./ajv')
  , util = require('../lib/compile/util');

module.exports = getAjvInstances;

var firstTime = true;

var isBrowser = typeof window == 'object';
var fullTest = isBrowser || !process.env.AJV_FAST_TEST;

function getAjvInstances(opts) {
  opts = opts || {};
  var instances = [];
  var options = [
    {},
    { async: true },
    { async: 'co*' },
    { async: 'es7' },
    { async: 'es7', transpile: 'nodent' },
    { async: '*', transpile: 'regenerator' },
    { async: 'co*', allErrors: true },
    { async: 'es7', allErrors: true },
    { async: 'es7', transpile: 'nodent', allErrors: true },
    { async: '*', transpile: 'regenerator', allErrors: true }
  ];

  if (fullTest) {
    options = options.concat([
      { async: '*' },
      { async: 'co*', transpile: 'regenerator' },
      { allErrors: true },
      { async: true, allErrors: true },
      { async: '*', allErrors: true },
      { async: 'co*', transpile: 'regenerator', allErrors: true }
    ]);

    var ua;
    try { ua = window.navigator.userAgent.toLowerCase(); } catch(e) {}

    // es7 functions transpiled with regenerator are excluded from test in Safari.
    // They emit multiple 'uncaught exception' warnings in Safari anc cause remote tests to disconnect.
    if (ua && (!/safari/.test(ua) || /chrome/.test(ua))) {
      options = options.concat([
        { transpile: 'regenerator' },
        { async: true, transpile: 'regenerator' },
        { async: 'es7', transpile: 'regenerator' },
        { transpile: 'regenerator', allErrors: true },
        { async: true, transpile: 'regenerator', allErrors: true },
        { async: 'es7', transpile: 'regenerator', allErrors: true }
      ]);
    }
  }

  // options = options.filter(function (_opts) {
  //   return _opts.transpile == 'nodent';
  // });

  // var i = 10, repeatOptions = [];
  // while (i--) repeatOptions = repeatOptions.concat(options);
  // options = repeatOptions;

  options.forEach(function (_opts) {
    util.copy(opts, _opts);
    var ajv = getAjv(_opts);
    if (ajv) instances.push(ajv);
  });

  if (firstTime) {
    var asyncModes = [];
    instances.forEach(function (ajv) {
      if (!ajv._opts.async) return;
      var t = ajv._opts.transpile;
      var mode = ajv._opts.async + (t === true ? '' : '.' + t);
      if (asyncModes.indexOf(mode) == -1) asyncModes.push(mode);
    });
    console.log('Testing', instances.length, 'ajv instances:', asyncModes.join(','));
    firstTime = false;
  }

  return instances;
}

function getAjv(opts){
  try { return Ajv(opts); } catch(e) {}
}
<|endoftext|>


<commit_before>// @flow

import chalk from 'chalk';
import fsp from 'fs-promise';
import path from 'path';
import pathExists from 'path-exists';
import spawn from 'cross-spawn';
import log from '../util/log';

// UPDATE DEPENDENCY VERSIONS HERE
const DEFAULT_DEPENDENCIES = {
  expo: '^16.0.0',
  react: '16.0.0-alpha.6',
<<<<<<< HEAD
  'react-native': '^0.43.4',
=======
  'react-native': '^0.43.3',
>>>>>>> Bump versions for RN 0.43 & Expo 16.
};

// TODO figure out how this interacts with ejection
const DEFAULT_DEV_DEPENDENCIES = {
  'jest-expo': '^0.4.0',
  'react-test-renderer': '16.0.0-alpha.6',
};

module.exports = async (appPath: string, appName: string, verbose: boolean, cwd: string = '') => {
  const ownPackageName: string = require('../../package.json').name;
  const ownPath: string = path.join(appPath, 'node_modules', ownPackageName);
  const useYarn: boolean = await pathExists(path.join(appPath, 'yarn.lock'));

  const readmeExists: boolean = await pathExists(path.join(appPath, 'README.md'));
  if (readmeExists) {
    await fsp.rename(path.join(appPath, 'README.md'), path.join(appPath, 'README.old.md'));
  }

  const appPackagePath: string = path.join(appPath, 'package.json');
  const appPackage = JSON.parse(await fsp.readFile(appPackagePath));

  // mutate the default package.json in any ways we need to
  appPackage.main = './node_modules/react-native-scripts/build/bin/crna-entry.js';
  appPackage.scripts = {
    start: 'react-native-scripts start',
    eject: 'react-native-scripts eject',
    android: 'react-native-scripts android',
    ios: 'react-native-scripts ios',
    test: 'node node_modules/jest/bin/jest.js --watch',
  };

  appPackage.jest = {
    preset: 'jest-expo',
  };

  if (!appPackage.dependencies) {
    appPackage.dependencies = {};
  }

  if (!appPackage.devDependencies) {
    appPackage.devDependencies = {};
  }

  // react-native-scripts is already in the package.json devDependencies
  // so we need to merge instead of assigning
  Object.assign(appPackage.dependencies, DEFAULT_DEPENDENCIES);
  Object.assign(appPackage.devDependencies, DEFAULT_DEV_DEPENDENCIES);

  // Write the new appPackage after copying so that we can include any existing
  await fsp.writeFile(appPackagePath, JSON.stringify(appPackage, null, 2));

  // Copy the files for the user
  await fsp.copy(path.join(ownPath, 'template'), appPath);

  // Rename gitignore after the fact to prevent npm from renaming it to .npmignore
  try {
    await fsp.rename(path.join(appPath, 'gitignore'), path.join(appPath, '.gitignore'));
  } catch (err) {
    // Append if there's already a `.gitignore` file there
    if (err.code === 'EEXIST') {
      const data = await fsp.readFile(path.join(appPath, 'gitignore'));
      await fsp.appendFile(path.join(appPath, '.gitignore'), data);
      await fsp.unlink(path.join(appPath, 'gitignore'));
    } else {
      throw err;
    }
  }

  // Run yarn or npm
  let command = '';
  let args = [];

  if (useYarn) {
    command = 'yarnpkg';
  } else {
    command = 'npm';
    args = ['install', '--save'];

    if (verbose) {
      args.push('--verbose');
    }
  }

  log(`Installing dependencies using ${command}...`);
  log(); // why is this here

  if (command === 'yarnpkg') {
    // it's weird to print a yarn alias that no one uses
    command = 'yarn';
  }

  const proc = spawn(command, args, { stdio: 'inherit' });
  proc.on('close', code => {
    if (code !== 0) {
      console.error(`\`${command} ${args.join(' ')}\` failed`);
      return;
    }

    // display the cleanest way to get to the app dir
    // if the cwd + appName is equal to the full path, then just cd into appName
    let cdpath;
    if (path.resolve(cwd, appName) === appPath) {
      cdpath = appName;
    } else {
      cdpath = appPath;
    }

    log(
      `

Success! Created ${appName} at ${appPath}
Inside that directory, you can run several commands:

  ${chalk.cyan(command + ' start')}
    Starts the development server so you can open your app in the Expo
    app on your phone.

  ${chalk.cyan(command + ' run ios')}
    (Mac only, requires Xcode)
    Starts the development server and loads your app in an iOS simulator.

  ${chalk.cyan(command + ' run android')}
    (Requires Android build tools)
    Starts the development server and loads your app on a connected Android
    device or emulator.

  ${chalk.cyan(command + ' test')}
    Starts the test runner.

  ${chalk.cyan(command + ' run eject')}
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  ${chalk.cyan('cd ' + cdpath)}
  ${chalk.cyan(command + ' start')}`
    );

    if (readmeExists) {
      log(
        `
${chalk.yellow('You had a `README.md` file, we renamed it to `README.old.md`')}`
      );
    }

    log();
    log('Happy hacking!');
  });
};
<commit_msg>stupid stupid stupid<commit_after>// @flow

import chalk from 'chalk';
import fsp from 'fs-promise';
import path from 'path';
import pathExists from 'path-exists';
import spawn from 'cross-spawn';
import log from '../util/log';

// UPDATE DEPENDENCY VERSIONS HERE
const DEFAULT_DEPENDENCIES = {
  expo: '^16.0.0',
  react: '16.0.0-alpha.6',
  'react-native': '^0.43.4',
};

// TODO figure out how this interacts with ejection
const DEFAULT_DEV_DEPENDENCIES = {
  'jest-expo': '^0.4.0',
  'react-test-renderer': '16.0.0-alpha.6',
};

module.exports = async (appPath: string, appName: string, verbose: boolean, cwd: string = '') => {
  const ownPackageName: string = require('../../package.json').name;
  const ownPath: string = path.join(appPath, 'node_modules', ownPackageName);
  const useYarn: boolean = await pathExists(path.join(appPath, 'yarn.lock'));

  const readmeExists: boolean = await pathExists(path.join(appPath, 'README.md'));
  if (readmeExists) {
    await fsp.rename(path.join(appPath, 'README.md'), path.join(appPath, 'README.old.md'));
  }

  const appPackagePath: string = path.join(appPath, 'package.json');
  const appPackage = JSON.parse(await fsp.readFile(appPackagePath));

  // mutate the default package.json in any ways we need to
  appPackage.main = './node_modules/react-native-scripts/build/bin/crna-entry.js';
  appPackage.scripts = {
    start: 'react-native-scripts start',
    eject: 'react-native-scripts eject',
    android: 'react-native-scripts android',
    ios: 'react-native-scripts ios',
    test: 'node node_modules/jest/bin/jest.js --watch',
  };

  appPackage.jest = {
    preset: 'jest-expo',
  };

  if (!appPackage.dependencies) {
    appPackage.dependencies = {};
  }

  if (!appPackage.devDependencies) {
    appPackage.devDependencies = {};
  }

  // react-native-scripts is already in the package.json devDependencies
  // so we need to merge instead of assigning
  Object.assign(appPackage.dependencies, DEFAULT_DEPENDENCIES);
  Object.assign(appPackage.devDependencies, DEFAULT_DEV_DEPENDENCIES);

  // Write the new appPackage after copying so that we can include any existing
  await fsp.writeFile(appPackagePath, JSON.stringify(appPackage, null, 2));

  // Copy the files for the user
  await fsp.copy(path.join(ownPath, 'template'), appPath);

  // Rename gitignore after the fact to prevent npm from renaming it to .npmignore
  try {
    await fsp.rename(path.join(appPath, 'gitignore'), path.join(appPath, '.gitignore'));
  } catch (err) {
    // Append if there's already a `.gitignore` file there
    if (err.code === 'EEXIST') {
      const data = await fsp.readFile(path.join(appPath, 'gitignore'));
      await fsp.appendFile(path.join(appPath, '.gitignore'), data);
      await fsp.unlink(path.join(appPath, 'gitignore'));
    } else {
      throw err;
    }
  }

  // Run yarn or npm
  let command = '';
  let args = [];

  if (useYarn) {
    command = 'yarnpkg';
  } else {
    command = 'npm';
    args = ['install', '--save'];

    if (verbose) {
      args.push('--verbose');
    }
  }

  log(`Installing dependencies using ${command}...`);
  log(); // why is this here

  if (command === 'yarnpkg') {
    // it's weird to print a yarn alias that no one uses
    command = 'yarn';
  }

  const proc = spawn(command, args, { stdio: 'inherit' });
  proc.on('close', code => {
    if (code !== 0) {
      console.error(`\`${command} ${args.join(' ')}\` failed`);
      return;
    }

    // display the cleanest way to get to the app dir
    // if the cwd + appName is equal to the full path, then just cd into appName
    let cdpath;
    if (path.resolve(cwd, appName) === appPath) {
      cdpath = appName;
    } else {
      cdpath = appPath;
    }

    log(
      `

Success! Created ${appName} at ${appPath}
Inside that directory, you can run several commands:

  ${chalk.cyan(command + ' start')}
    Starts the development server so you can open your app in the Expo
    app on your phone.

  ${chalk.cyan(command + ' run ios')}
    (Mac only, requires Xcode)
    Starts the development server and loads your app in an iOS simulator.

  ${chalk.cyan(command + ' run android')}
    (Requires Android build tools)
    Starts the development server and loads your app on a connected Android
    device or emulator.

  ${chalk.cyan(command + ' test')}
    Starts the test runner.

  ${chalk.cyan(command + ' run eject')}
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  ${chalk.cyan('cd ' + cdpath)}
  ${chalk.cyan(command + ' start')}`
    );

    if (readmeExists) {
      log(
        `
${chalk.yellow('You had a `README.md` file, we renamed it to `README.old.md`')}`
      );
    }

    log();
    log('Happy hacking!');
  });
};
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Profiler processor is used to process log file produced
 * by V8 and produce an internal profile representation which is used
 * for building profile views in 'Profiles' tab.
 */
goog.provide('devtools.profiler.Processor');

/**
 * Creates a Profile View builder object compatible with WebKit Profiler UI.
 *
 * @param {number} samplingRate Number of ms between profiler ticks.
 * @constructor
 */
devtools.profiler.WebKitViewBuilder = function(samplingRate) {
  devtools.profiler.ViewBuilder.call(this, samplingRate);
};
goog.inherits(devtools.profiler.WebKitViewBuilder,
    devtools.profiler.ViewBuilder);

/**
 * @override
 */
devtools.profiler.WebKitViewBuilder.prototype.createViewNode = function(
    funcName, totalTime, selfTime, head) {
  return new devtools.profiler.WebKitViewNode(
      funcName, totalTime, selfTime, head);
};

/**
 * Constructs a Profile View node object for displaying in WebKit Profiler UI.
 *
 * @param {string} internalFuncName A fully qualified function name.
 * @param {number} totalTime Amount of time that application spent in the
 *     corresponding function and its descendants (not that depending on
 *     profile they can be either callees or callers.)
 * @param {number} selfTime Amount of time that application spent in the
 *     corresponding function only.
 * @param {devtools.profiler.ProfileView.Node} head Profile view head.
 * @constructor
 */
devtools.profiler.WebKitViewNode = function(
    internalFuncName, totalTime, selfTime, head) {
  devtools.profiler.ProfileView.Node.call(this,
      internalFuncName, totalTime, selfTime, head);
  this.initFuncInfo_();
  this.callUID = internalFuncName;
};
goog.inherits(devtools.profiler.WebKitViewNode,
    devtools.profiler.ProfileView.Node);

/**
 * RegEx for stripping V8's prefixes of compiled functions.
 */
devtools.profiler.WebKitViewNode.FUNC_NAME_STRIP_RE =
    /^(?:LazyCompile|Function): (.*)$/;

/**
 * RegEx for extracting script source URL and line number.
 */
devtools.profiler.WebKitViewNode.FUNC_NAME_PARSE_RE =
    /^([^ ]+) (.*):(\d+)( \{\d+\})?$/;

/**
 * Inits 'functionName', 'url', and 'lineNumber' fields using 'internalFuncName'
 * field.
 * @private
 */
devtools.profiler.WebKitViewNode.prototype.initFuncInfo_ = function() {
  var nodeAlias = devtools.profiler.WebKitViewNode;
  this.functionName = this.internalFuncName;

  var strippedName = nodeAlias.FUNC_NAME_STRIP_RE.exec(this.functionName);
  if (strippedName) {
    this.functionName = strippedName[1];
  }

  var parsedName = nodeAlias.FUNC_NAME_PARSE_RE.exec(this.functionName);
  if (parsedName) {
    this.functionName = parsedName[1];
    if (parsedName[4]) {
      this.functionName += parsedName[4];
    }
    this.url = parsedName[2];
    this.lineNumber = parsedName[3];
  } else {
    this.url = '';
    this.lineNumber = 0;
  }
};

/**
 * Ancestor of a profile object that leaves out only JS-related functions.
 * @constructor
 */
devtools.profiler.JsProfile = function() {
  devtools.profiler.Profile.call(this);
};
goog.inherits(devtools.profiler.JsProfile, devtools.profiler.Profile);

/**
 * RegExp that leaves only JS functions.
 * @type {RegExp}
 */
devtools.profiler.JsProfile.JS_FUNC_RE = /^(LazyCompile|Function|Script):/;

/**
 * RegExp that filters out native code (ending with "native src.js:xxx").
 * @type {RegExp}
 */
devtools.profiler.JsProfile.JS_NATIVE_FUNC_RE = /\ native\ \w+\.js:\d+$/;

/**
 * RegExp that filters out native scripts.
 * @type {RegExp}
 */
devtools.profiler.JsProfile.JS_NATIVE_SCRIPT_RE = /^Script:\ native/;

/**
 * RegExp that filters out devtools functions. See inject.js and
 * inject_dispatch.js.
 * @type {RegExp}
 */
devtools.profiler.JsProfile.JS_DEVTOOLS_FUNC_RE =
    /^\w+:\ devtools(\$\$|\.Injected)/;

/**
 * @override
 */
devtools.profiler.JsProfile.prototype.skipThisFunction = function(name) {
  return !devtools.profiler.JsProfile.JS_FUNC_RE.test(name) ||
      // To profile V8's natives comment out two lines below and '||' above.
      devtools.profiler.JsProfile.JS_NATIVE_FUNC_RE.test(name) ||
      devtools.profiler.JsProfile.JS_NATIVE_SCRIPT_RE.test(name) ||
      devtools.profiler.JsProfile.JS_DEVTOOLS_FUNC_RE.test(name);
};

/**
 * Profiler processor. Consumes profiler log and builds profile views.
 *
 * @param {function(devtools.profiler.ProfileView)} newProfileCallback Callback
 *     that receives a new processed profile.
 * @constructor
 */
devtools.profiler.Processor = function() {
  devtools.profiler.LogReader.call(this, {
      'code-creation': {
          parsers: [null, this.createAddressParser('code'), parseInt, null],
          processor: this.processCodeCreation_, backrefs: true,
          needsProfile: true },
      'code-move': { parsers: [this.createAddressParser('code'),
          this.createAddressParser('code-move-to')],
          processor: this.processCodeMove_, backrefs: true,
          needsProfile: true },
      'code-delete': { parsers: [this.createAddressParser('code')],
          processor: this.processCodeDelete_, backrefs: true,
          needsProfile: true },
      'tick': { parsers: [this.createAddressParser('code'),
          this.createAddressParser('stack'), parseInt, 'var-args'],
          processor: this.processTick_, backrefs: true, needProfile: true },
      'profiler': { parsers: [null, 'var-args'],
          processor: this.processProfiler_, needsProfile: false },
      'heap-sample-begin': { parsers: [null, null, parseInt],
          processor: this.processHeapSampleBegin_ },
      'heap-sample-stats': { parsers: [null, null, parseInt, parseInt],
          processor: this.processHeapSampleStats_ },
      'heap-sample-item': { parsers: [null, parseInt, parseInt],
          processor: this.processHeapSampleItem_ },
      'heap-js-cons-item': { parsers: [null, parseInt, parseInt],
          processor: this.processHeapJsConsItem_ },
      'heap-sample-end': { parsers: [null, null],
          processor: this.processHeapSampleEnd_ },
      // Not used in DevTools Profiler.
      'shared-library': null,
      // Obsolete row types.
      'code-allocate': null,
      'begin-code-region': null,
      'end-code-region': null});

  /**
   * Callback that is called when a new profile is encountered in the log.
   * @type {function()}
   */
  this.startedProfileProcessing_ = null;

  /**
   * Callback that is called periodically to display processing status.
   * @type {function()}
   */
  this.profileProcessingStatus_ = null;

  /**
   * Callback that is called when a profile has been processed and is ready
   * to be shown.
   * @type {function(devtools.profiler.ProfileView)}
   */
  this.finishedProfileProcessing_ = null;

  /**
   * The current profile.
   * @type {devtools.profiler.JsProfile}
   */
  this.currentProfile_ = null;

  /**
   * Builder of profile views. Created during "profiler,begin" event processing.
   * @type {devtools.profiler.WebKitViewBuilder}
   */
  this.viewBuilder_ = null;

  /**
   * Next profile id.
   * @type {number}
   */
  this.profileId_ = 1;

  /**
   * Counter for processed ticks.
   * @type {number}
   */
  this.ticksCount_ = 0;

  /**
   * The current heap snapshot.
   * @type {string}
   */
  this.currentHeapSnapshot_ = null;

  /**
   * Next heap snapshot id.
   * @type {number}
   */
  this.heapSnapshotId_ = 1;
};
goog.inherits(devtools.profiler.Processor, devtools.profiler.LogReader);

/**
 * @override
 */
devtools.profiler.Processor.prototype.printError = function(str) {
  debugPrint(str);
};

/**
 * @override
 */
devtools.profiler.Processor.prototype.skipDispatch = function(dispatch) {
  return dispatch.needsProfile && this.currentProfile_ == null;
};

/**
 * Sets profile processing callbacks.
 *
 * @param {function()} started Started processing callback.
 * @param {function(devtools.profiler.ProfileView)} finished Finished
 *     processing callback.
 */
devtools.profiler.Processor.prototype.setCallbacks = function(
    started, processing, finished) {
  this.startedProfileProcessing_ = started;
  this.profileProcessingStatus_ = processing;
  this.finishedProfileProcessing_ = finished;
};

/**
 * An address for the fake "(program)" entry. WebKit's visualisation
 * has assumptions on how the top of the call tree should look like,
 * and we need to add a fake entry as the topmost function. This
 * address is chosen because it's the end address of the first memory
 * page, which is never used for code or data, but only as a guard
 * page for catching AV errors.
 *
 * @type {number}
 */
devtools.profiler.Processor.PROGRAM_ENTRY = 0xffff;
/**
 * @type {string}
 */
devtools.profiler.Processor.PROGRAM_ENTRY_STR = '0xffff';

/**
 * Sets new profile callback.
 * @param {function(devtools.profiler.ProfileView)} callback Callback function.
 */
devtools.profiler.Processor.prototype.setNewProfileCallback = function(
    callback) {
  this.newProfileCallback_ = callback;
};

devtools.profiler.Processor.prototype.processProfiler_ = function(
    state, params) {
  var processingInterval = null;
  switch (state) {
    case 'resume':
      if (this.currentProfile_ == null) {
        this.currentProfile_ = new devtools.profiler.JsProfile();
        // see the comment for devtools.profiler.Processor.PROGRAM_ENTRY
        this.currentProfile_.addCode(
          'Function', '(program)',
          devtools.profiler.Processor.PROGRAM_ENTRY, 1);
        if (this.startedProfileProcessing_) {
          this.startedProfileProcessing_();
        }
        this.ticksCount_ = 0;
        var self = this;
        if (this.profileProcessingStatus_) {
          processingInterval = window.setInterval(
              function() { self.profileProcessingStatus_(self.ticksCount_); },
              1000);
        }
      }
      break;
    case 'pause':
      if (this.currentProfile_ != null) {
        window.clearInterval(processingInterval);
        if (this.finishedProfileProcessing_) {
          this.finishedProfileProcessing_(this.createProfileForView());
        }
        this.currentProfile_ = null;
      }
      break;
    case 'begin':
      var samplingRate = NaN;
      if (params.length > 0) {
        samplingRate = parseInt(params[0]);
      }
      if (isNaN(samplingRate)) {
        samplingRate = 1;
      }
      this.viewBuilder_ = new devtools.profiler.WebKitViewBuilder(samplingRate);
      break;
    // These events are valid but aren't used.
    case 'compression':
    case 'end': break;
    default:
      throw new Error('unknown profiler state: ' + state);
  }
};

devtools.profiler.Processor.prototype.processCodeCreation_ = function(
    type, start, size, name) {
  this.currentProfile_.addCode(this.expandAlias(type), name, start, size);
};

devtools.profiler.Processor.prototype.processCodeMove_ = function(from, to) {
  this.currentProfile_.moveCode(from, to);
};

devtools.profiler.Processor.prototype.processCodeDelete_ = function(start) {
  this.currentProfile_.deleteCode(start);
};

devtools.profiler.Processor.prototype.processTick_ = function(
    pc, sp, vmState, stack) {
  // see the comment for devtools.profiler.Processor.PROGRAM_ENTRY
  stack.push(devtools.profiler.Processor.PROGRAM_ENTRY_STR);
  this.currentProfile_.recordTick(this.processStack(pc, stack));
  this.ticksCount_++;
};

devtools.profiler.Processor.prototype.processHeapSampleBegin_ = function(
    space, state, ticks) {
  if (space != 'Heap') return;
  this.currentHeapSnapshot_ = {
      number: this.heapSnapshotId_++,
      entries: {},
      lowlevels: {},
      ticks: ticks
  };
};

devtools.profiler.Processor.prototype.processHeapSampleStats_ = function(
    space, state, capacity, used) {
  if (space != 'Heap') return;
  this.currentHeapSnapshot_.capacity = capacity;
  this.currentHeapSnapshot_.used = used;
};

devtools.profiler.Processor.prototype.processHeapSampleItem_ = function(
    item, number, size) {
  if (!this.currentHeapSnapshot_) return;
  this.currentHeapSnapshot_.lowlevels[item] = {
    type: item, count: number, size: size
  };
};

devtools.profiler.Processor.prototype.processHeapJsConsItem_ = function(
    item, number, size) {
  if (!this.currentHeapSnapshot_) return;
  this.currentHeapSnapshot_.entries[item] = {
    cons: item, count: number, size: size
  };
};

devtools.profiler.Processor.prototype.processHeapSampleEnd_ = function(
    space, state) {
  if (space != 'Heap') return;
  var snapshot = this.currentHeapSnapshot_;
  this.currentHeapSnapshot_ = null;
  // For some reason, 'used' from 'heap-sample-stats' sometimes differ from
  // the sum of objects sizes. To avoid discrepancy, we re-calculate 'used'.
  snapshot.used = 0;
  for (var item in snapshot.lowlevels) {
      snapshot.used += snapshot.lowlevels[item].size;
  }
  WebInspector.panels.heap.addSnapshot(snapshot);
};

/**
 * Creates a profile for further displaying in ProfileView.
 */
devtools.profiler.Processor.prototype.createProfileForView = function() {
  var profile = this.viewBuilder_.buildView(
      this.currentProfile_.getTopDownProfile());
  profile.uid = this.profileId_++;
  profile.title = UserInitiatedProfileName + '.' + profile.uid;
  return profile;
};
<commit_msg>DevTools heap profiler: Add a stub for heap-js-ret-item log record.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Profiler processor is used to process log file produced
 * by V8 and produce an internal profile representation which is used
 * for building profile views in 'Profiles' tab.
 */
goog.provide('devtools.profiler.Processor');

/**
 * Creates a Profile View builder object compatible with WebKit Profiler UI.
 *
 * @param {number} samplingRate Number of ms between profiler ticks.
 * @constructor
 */
devtools.profiler.WebKitViewBuilder = function(samplingRate) {
  devtools.profiler.ViewBuilder.call(this, samplingRate);
};
goog.inherits(devtools.profiler.WebKitViewBuilder,
    devtools.profiler.ViewBuilder);

/**
 * @override
 */
devtools.profiler.WebKitViewBuilder.prototype.createViewNode = function(
    funcName, totalTime, selfTime, head) {
  return new devtools.profiler.WebKitViewNode(
      funcName, totalTime, selfTime, head);
};

/**
 * Constructs a Profile View node object for displaying in WebKit Profiler UI.
 *
 * @param {string} internalFuncName A fully qualified function name.
 * @param {number} totalTime Amount of time that application spent in the
 *     corresponding function and its descendants (not that depending on
 *     profile they can be either callees or callers.)
 * @param {number} selfTime Amount of time that application spent in the
 *     corresponding function only.
 * @param {devtools.profiler.ProfileView.Node} head Profile view head.
 * @constructor
 */
devtools.profiler.WebKitViewNode = function(
    internalFuncName, totalTime, selfTime, head) {
  devtools.profiler.ProfileView.Node.call(this,
      internalFuncName, totalTime, selfTime, head);
  this.initFuncInfo_();
  this.callUID = internalFuncName;
};
goog.inherits(devtools.profiler.WebKitViewNode,
    devtools.profiler.ProfileView.Node);

/**
 * RegEx for stripping V8's prefixes of compiled functions.
 */
devtools.profiler.WebKitViewNode.FUNC_NAME_STRIP_RE =
    /^(?:LazyCompile|Function): (.*)$/;

/**
 * RegEx for extracting script source URL and line number.
 */
devtools.profiler.WebKitViewNode.FUNC_NAME_PARSE_RE =
    /^([^ ]+) (.*):(\d+)( \{\d+\})?$/;

/**
 * Inits 'functionName', 'url', and 'lineNumber' fields using 'internalFuncName'
 * field.
 * @private
 */
devtools.profiler.WebKitViewNode.prototype.initFuncInfo_ = function() {
  var nodeAlias = devtools.profiler.WebKitViewNode;
  this.functionName = this.internalFuncName;

  var strippedName = nodeAlias.FUNC_NAME_STRIP_RE.exec(this.functionName);
  if (strippedName) {
    this.functionName = strippedName[1];
  }

  var parsedName = nodeAlias.FUNC_NAME_PARSE_RE.exec(this.functionName);
  if (parsedName) {
    this.functionName = parsedName[1];
    if (parsedName[4]) {
      this.functionName += parsedName[4];
    }
    this.url = parsedName[2];
    this.lineNumber = parsedName[3];
  } else {
    this.url = '';
    this.lineNumber = 0;
  }
};

/**
 * Ancestor of a profile object that leaves out only JS-related functions.
 * @constructor
 */
devtools.profiler.JsProfile = function() {
  devtools.profiler.Profile.call(this);
};
goog.inherits(devtools.profiler.JsProfile, devtools.profiler.Profile);

/**
 * RegExp that leaves only JS functions.
 * @type {RegExp}
 */
devtools.profiler.JsProfile.JS_FUNC_RE = /^(LazyCompile|Function|Script):/;

/**
 * RegExp that filters out native code (ending with "native src.js:xxx").
 * @type {RegExp}
 */
devtools.profiler.JsProfile.JS_NATIVE_FUNC_RE = /\ native\ \w+\.js:\d+$/;

/**
 * RegExp that filters out native scripts.
 * @type {RegExp}
 */
devtools.profiler.JsProfile.JS_NATIVE_SCRIPT_RE = /^Script:\ native/;

/**
 * RegExp that filters out devtools functions. See inject.js and
 * inject_dispatch.js.
 * @type {RegExp}
 */
devtools.profiler.JsProfile.JS_DEVTOOLS_FUNC_RE =
    /^\w+:\ devtools(\$\$|\.Injected)/;

/**
 * @override
 */
devtools.profiler.JsProfile.prototype.skipThisFunction = function(name) {
  return !devtools.profiler.JsProfile.JS_FUNC_RE.test(name) ||
      // To profile V8's natives comment out two lines below and '||' above.
      devtools.profiler.JsProfile.JS_NATIVE_FUNC_RE.test(name) ||
      devtools.profiler.JsProfile.JS_NATIVE_SCRIPT_RE.test(name) ||
      devtools.profiler.JsProfile.JS_DEVTOOLS_FUNC_RE.test(name);
};

/**
 * Profiler processor. Consumes profiler log and builds profile views.
 *
 * @param {function(devtools.profiler.ProfileView)} newProfileCallback Callback
 *     that receives a new processed profile.
 * @constructor
 */
devtools.profiler.Processor = function() {
  devtools.profiler.LogReader.call(this, {
      'code-creation': {
          parsers: [null, this.createAddressParser('code'), parseInt, null],
          processor: this.processCodeCreation_, backrefs: true,
          needsProfile: true },
      'code-move': { parsers: [this.createAddressParser('code'),
          this.createAddressParser('code-move-to')],
          processor: this.processCodeMove_, backrefs: true,
          needsProfile: true },
      'code-delete': { parsers: [this.createAddressParser('code')],
          processor: this.processCodeDelete_, backrefs: true,
          needsProfile: true },
      'tick': { parsers: [this.createAddressParser('code'),
          this.createAddressParser('stack'), parseInt, 'var-args'],
          processor: this.processTick_, backrefs: true, needProfile: true },
      'profiler': { parsers: [null, 'var-args'],
          processor: this.processProfiler_, needsProfile: false },
      'heap-sample-begin': { parsers: [null, null, parseInt],
          processor: this.processHeapSampleBegin_ },
      'heap-sample-stats': { parsers: [null, null, parseInt, parseInt],
          processor: this.processHeapSampleStats_ },
      'heap-sample-item': { parsers: [null, parseInt, parseInt],
          processor: this.processHeapSampleItem_ },
      'heap-js-cons-item': { parsers: [null, parseInt, parseInt],
          processor: this.processHeapJsConsItem_ },
      'heap-sample-end': { parsers: [null, null],
          processor: this.processHeapSampleEnd_ },
      // Not used in DevTools Profiler.
      'shared-library': null,
      'heap-js-ret-item': null,
      // Obsolete row types.
      'code-allocate': null,
      'begin-code-region': null,
      'end-code-region': null});

  /**
   * Callback that is called when a new profile is encountered in the log.
   * @type {function()}
   */
  this.startedProfileProcessing_ = null;

  /**
   * Callback that is called periodically to display processing status.
   * @type {function()}
   */
  this.profileProcessingStatus_ = null;

  /**
   * Callback that is called when a profile has been processed and is ready
   * to be shown.
   * @type {function(devtools.profiler.ProfileView)}
   */
  this.finishedProfileProcessing_ = null;

  /**
   * The current profile.
   * @type {devtools.profiler.JsProfile}
   */
  this.currentProfile_ = null;

  /**
   * Builder of profile views. Created during "profiler,begin" event processing.
   * @type {devtools.profiler.WebKitViewBuilder}
   */
  this.viewBuilder_ = null;

  /**
   * Next profile id.
   * @type {number}
   */
  this.profileId_ = 1;

  /**
   * Counter for processed ticks.
   * @type {number}
   */
  this.ticksCount_ = 0;

  /**
   * The current heap snapshot.
   * @type {string}
   */
  this.currentHeapSnapshot_ = null;

  /**
   * Next heap snapshot id.
   * @type {number}
   */
  this.heapSnapshotId_ = 1;
};
goog.inherits(devtools.profiler.Processor, devtools.profiler.LogReader);

/**
 * @override
 */
devtools.profiler.Processor.prototype.printError = function(str) {
  debugPrint(str);
};

/**
 * @override
 */
devtools.profiler.Processor.prototype.skipDispatch = function(dispatch) {
  return dispatch.needsProfile && this.currentProfile_ == null;
};

/**
 * Sets profile processing callbacks.
 *
 * @param {function()} started Started processing callback.
 * @param {function(devtools.profiler.ProfileView)} finished Finished
 *     processing callback.
 */
devtools.profiler.Processor.prototype.setCallbacks = function(
    started, processing, finished) {
  this.startedProfileProcessing_ = started;
  this.profileProcessingStatus_ = processing;
  this.finishedProfileProcessing_ = finished;
};

/**
 * An address for the fake "(program)" entry. WebKit's visualisation
 * has assumptions on how the top of the call tree should look like,
 * and we need to add a fake entry as the topmost function. This
 * address is chosen because it's the end address of the first memory
 * page, which is never used for code or data, but only as a guard
 * page for catching AV errors.
 *
 * @type {number}
 */
devtools.profiler.Processor.PROGRAM_ENTRY = 0xffff;
/**
 * @type {string}
 */
devtools.profiler.Processor.PROGRAM_ENTRY_STR = '0xffff';

/**
 * Sets new profile callback.
 * @param {function(devtools.profiler.ProfileView)} callback Callback function.
 */
devtools.profiler.Processor.prototype.setNewProfileCallback = function(
    callback) {
  this.newProfileCallback_ = callback;
};

devtools.profiler.Processor.prototype.processProfiler_ = function(
    state, params) {
  var processingInterval = null;
  switch (state) {
    case 'resume':
      if (this.currentProfile_ == null) {
        this.currentProfile_ = new devtools.profiler.JsProfile();
        // see the comment for devtools.profiler.Processor.PROGRAM_ENTRY
        this.currentProfile_.addCode(
          'Function', '(program)',
          devtools.profiler.Processor.PROGRAM_ENTRY, 1);
        if (this.startedProfileProcessing_) {
          this.startedProfileProcessing_();
        }
        this.ticksCount_ = 0;
        var self = this;
        if (this.profileProcessingStatus_) {
          processingInterval = window.setInterval(
              function() { self.profileProcessingStatus_(self.ticksCount_); },
              1000);
        }
      }
      break;
    case 'pause':
      if (this.currentProfile_ != null) {
        window.clearInterval(processingInterval);
        if (this.finishedProfileProcessing_) {
          this.finishedProfileProcessing_(this.createProfileForView());
        }
        this.currentProfile_ = null;
      }
      break;
    case 'begin':
      var samplingRate = NaN;
      if (params.length > 0) {
        samplingRate = parseInt(params[0]);
      }
      if (isNaN(samplingRate)) {
        samplingRate = 1;
      }
      this.viewBuilder_ = new devtools.profiler.WebKitViewBuilder(samplingRate);
      break;
    // These events are valid but aren't used.
    case 'compression':
    case 'end': break;
    default:
      throw new Error('unknown profiler state: ' + state);
  }
};

devtools.profiler.Processor.prototype.processCodeCreation_ = function(
    type, start, size, name) {
  this.currentProfile_.addCode(this.expandAlias(type), name, start, size);
};

devtools.profiler.Processor.prototype.processCodeMove_ = function(from, to) {
  this.currentProfile_.moveCode(from, to);
};

devtools.profiler.Processor.prototype.processCodeDelete_ = function(start) {
  this.currentProfile_.deleteCode(start);
};

devtools.profiler.Processor.prototype.processTick_ = function(
    pc, sp, vmState, stack) {
  // see the comment for devtools.profiler.Processor.PROGRAM_ENTRY
  stack.push(devtools.profiler.Processor.PROGRAM_ENTRY_STR);
  this.currentProfile_.recordTick(this.processStack(pc, stack));
  this.ticksCount_++;
};

devtools.profiler.Processor.prototype.processHeapSampleBegin_ = function(
    space, state, ticks) {
  if (space != 'Heap') return;
  this.currentHeapSnapshot_ = {
      number: this.heapSnapshotId_++,
      entries: {},
      lowlevels: {},
      ticks: ticks
  };
};

devtools.profiler.Processor.prototype.processHeapSampleStats_ = function(
    space, state, capacity, used) {
  if (space != 'Heap') return;
  this.currentHeapSnapshot_.capacity = capacity;
  this.currentHeapSnapshot_.used = used;
};

devtools.profiler.Processor.prototype.processHeapSampleItem_ = function(
    item, number, size) {
  if (!this.currentHeapSnapshot_) return;
  this.currentHeapSnapshot_.lowlevels[item] = {
    type: item, count: number, size: size
  };
};

devtools.profiler.Processor.prototype.processHeapJsConsItem_ = function(
    item, number, size) {
  if (!this.currentHeapSnapshot_) return;
  this.currentHeapSnapshot_.entries[item] = {
    cons: item, count: number, size: size
  };
};

devtools.profiler.Processor.prototype.processHeapSampleEnd_ = function(
    space, state) {
  if (space != 'Heap') return;
  var snapshot = this.currentHeapSnapshot_;
  this.currentHeapSnapshot_ = null;
  // For some reason, 'used' from 'heap-sample-stats' sometimes differ from
  // the sum of objects sizes. To avoid discrepancy, we re-calculate 'used'.
  snapshot.used = 0;
  for (var item in snapshot.lowlevels) {
      snapshot.used += snapshot.lowlevels[item].size;
  }
  WebInspector.panels.heap.addSnapshot(snapshot);
};

/**
 * Creates a profile for further displaying in ProfileView.
 */
devtools.profiler.Processor.prototype.createProfileForView = function() {
  var profile = this.viewBuilder_.buildView(
      this.currentProfile_.getTopDownProfile());
  profile.uid = this.profileId_++;
  profile.title = UserInitiatedProfileName + '.' + profile.uid;
  return profile;
};
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace string
*/
var string = {};

/**
* @name camelcase
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/camelcase}
*/
setReadOnly( string, 'camelcase', require( '@stdlib/string/camelcase' ) );

/**
* @name capitalize
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/capitalize}
*/
setReadOnly( string, 'capitalize', require( '@stdlib/string/capitalize' ) );

/**
* @name codePointAt
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/code-point-at}
*/
setReadOnly( string, 'codePointAt', require( '@stdlib/string/code-point-at' ) );

/**
* @name constantcase
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/constantcase
*/
setReadOnly( string, 'constantcase', require( '@stdlib/string/constantcase' ) );

/**
* @name endsWith
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/ends-with}
*/
setReadOnly( string, 'endsWith', require( '@stdlib/string/ends-with' ) );

/**
* @name fromCodePoint
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/from-code-point}
*/
setReadOnly( string, 'fromCodePoint', require( '@stdlib/string/from-code-point' ) );

/**
* @name kebabcase
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/kebabcase
*/
setReadOnly( string, 'kebabcase', require( '@stdlib/string/kebabcase' ) );

/**
* @name lpad
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/left-pad}
*/
setReadOnly( string, 'lpad', require( '@stdlib/string/left-pad' ) );

/**
* @name ltrim
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/left-trim}
*/
setReadOnly( string, 'ltrim', require( '@stdlib/string/left-trim' ) );

/**
* @name lowercase
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/lowercase}
*/
setReadOnly( string, 'lowercase', require( '@stdlib/string/lowercase' ) );

/**
* @name nextGraphemeClusterBreak
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/next-grapheme-cluster-break}
*/
setReadOnly( string, 'nextGraphemeClusterBreak', require( '@stdlib/string/next-grapheme-cluster-break' ) );

/**
* @name numGraphemeClusters
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/num-grapheme-clusters}
*/
setReadOnly( string, 'numGraphemeClusters', require( '@stdlib/string/num-grapheme-clusters' ) );

/**
* @name pad
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/pad}
*/
setReadOnly( string, 'pad', require( '@stdlib/string/pad' ) );

/**
* @name percentEncode
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/percent-encode}
*/
setReadOnly( string, 'percentEncode', require( '@stdlib/string/percent-encode' ) );

/**
* @name removeFirst
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/remove-first}
*/
setReadOnly( string, 'removeFirst', require( '@stdlib/string/remove-first' ) );

/**
* @name removeLast
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/remove-last}
*/
setReadOnly( string, 'removeLast', require( '@stdlib/string/remove-last' ) );

/**
* @name removePunctuation
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/remove-punctuation}
*/
setReadOnly( string, 'removePunctuation', require( '@stdlib/string/remove-punctuation' ) );

/**
* @name removeUTF8BOM
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/remove-utf8-bom}
*/
setReadOnly( string, 'removeUTF8BOM', require( '@stdlib/string/remove-utf8-bom' ) );

/**
* @name removeWords
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/remove-words}
*/
setReadOnly( string, 'removeWords', require( '@stdlib/string/remove-words' ) );

/**
* @name repeat
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/repeat}
*/
setReadOnly( string, 'repeat', require( '@stdlib/string/repeat' ) );

/**
* @name replace
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/replace}
*/
setReadOnly( string, 'replace', require( '@stdlib/string/replace' ) );

/**
* @name reverseString
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/reverse}
*/
setReadOnly( string, 'reverseString', require( '@stdlib/string/reverse' ) );

/**
* @name rpad
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/right-pad}
*/
setReadOnly( string, 'rpad', require( '@stdlib/string/right-pad' ) );

/**
* @name rtrim
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/right-trim}
*/
setReadOnly( string, 'rtrim', require( '@stdlib/string/right-trim' ) );

/**
* @name startcase
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/startcase}
*/
setReadOnly( string, 'startcase', require( '@stdlib/string/startcase' ) );

/**
* @name startsWith
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/starts-with}
*/
setReadOnly( string, 'startsWith', require( '@stdlib/string/starts-with' ) );

/**
* @name trim
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/trim}
*/
setReadOnly( string, 'trim', require( '@stdlib/string/trim' ) );

/**
* @name uncapitalize
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/uncapitalize}
*/
setReadOnly( string, 'uncapitalize', require( '@stdlib/string/uncapitalize' ) );

/**
* @name uppercase
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/uppercase}
*/
setReadOnly( string, 'uppercase', require( '@stdlib/string/uppercase' ) );

/**
* @name utf16ToUTF8Array
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/utf16-to-utf8-array}
*/
setReadOnly( string, 'utf16ToUTF8Array', require( '@stdlib/string/utf16-to-utf8-array' ) );

// EXPORTS //

module.exports = string;
<commit_msg>Add missing semicolon<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace string
*/
var string = {};

/**
* @name camelcase
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/camelcase}
*/
setReadOnly( string, 'camelcase', require( '@stdlib/string/camelcase' ) );

/**
* @name capitalize
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/capitalize}
*/
setReadOnly( string, 'capitalize', require( '@stdlib/string/capitalize' ) );

/**
* @name codePointAt
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/code-point-at}
*/
setReadOnly( string, 'codePointAt', require( '@stdlib/string/code-point-at' ) );

/**
* @name constantcase
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/constantcase
*/
setReadOnly( string, 'constantcase', require( '@stdlib/string/constantcase' ) );

/**
* @name endsWith
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/ends-with}
*/
setReadOnly( string, 'endsWith', require( '@stdlib/string/ends-with' ) );

/**
* @name fromCodePoint
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/from-code-point}
*/
setReadOnly( string, 'fromCodePoint', require( '@stdlib/string/from-code-point' ) );

/**
* @name kebabcase
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/kebabcase}
*/
setReadOnly( string, 'kebabcase', require( '@stdlib/string/kebabcase' ) );

/**
* @name lpad
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/left-pad}
*/
setReadOnly( string, 'lpad', require( '@stdlib/string/left-pad' ) );

/**
* @name ltrim
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/left-trim}
*/
setReadOnly( string, 'ltrim', require( '@stdlib/string/left-trim' ) );

/**
* @name lowercase
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/lowercase}
*/
setReadOnly( string, 'lowercase', require( '@stdlib/string/lowercase' ) );

/**
* @name nextGraphemeClusterBreak
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/next-grapheme-cluster-break}
*/
setReadOnly( string, 'nextGraphemeClusterBreak', require( '@stdlib/string/next-grapheme-cluster-break' ) );

/**
* @name numGraphemeClusters
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/num-grapheme-clusters}
*/
setReadOnly( string, 'numGraphemeClusters', require( '@stdlib/string/num-grapheme-clusters' ) );

/**
* @name pad
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/pad}
*/
setReadOnly( string, 'pad', require( '@stdlib/string/pad' ) );

/**
* @name percentEncode
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/percent-encode}
*/
setReadOnly( string, 'percentEncode', require( '@stdlib/string/percent-encode' ) );

/**
* @name removeFirst
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/remove-first}
*/
setReadOnly( string, 'removeFirst', require( '@stdlib/string/remove-first' ) );

/**
* @name removeLast
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/remove-last}
*/
setReadOnly( string, 'removeLast', require( '@stdlib/string/remove-last' ) );

/**
* @name removePunctuation
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/remove-punctuation}
*/
setReadOnly( string, 'removePunctuation', require( '@stdlib/string/remove-punctuation' ) );

/**
* @name removeUTF8BOM
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/remove-utf8-bom}
*/
setReadOnly( string, 'removeUTF8BOM', require( '@stdlib/string/remove-utf8-bom' ) );

/**
* @name removeWords
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/remove-words}
*/
setReadOnly( string, 'removeWords', require( '@stdlib/string/remove-words' ) );

/**
* @name repeat
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/repeat}
*/
setReadOnly( string, 'repeat', require( '@stdlib/string/repeat' ) );

/**
* @name replace
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/replace}
*/
setReadOnly( string, 'replace', require( '@stdlib/string/replace' ) );

/**
* @name reverseString
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/reverse}
*/
setReadOnly( string, 'reverseString', require( '@stdlib/string/reverse' ) );

/**
* @name rpad
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/right-pad}
*/
setReadOnly( string, 'rpad', require( '@stdlib/string/right-pad' ) );

/**
* @name rtrim
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/right-trim}
*/
setReadOnly( string, 'rtrim', require( '@stdlib/string/right-trim' ) );

/**
* @name startcase
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/startcase}
*/
setReadOnly( string, 'startcase', require( '@stdlib/string/startcase' ) );

/**
* @name startsWith
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/starts-with}
*/
setReadOnly( string, 'startsWith', require( '@stdlib/string/starts-with' ) );

/**
* @name trim
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/trim}
*/
setReadOnly( string, 'trim', require( '@stdlib/string/trim' ) );

/**
* @name uncapitalize
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/uncapitalize}
*/
setReadOnly( string, 'uncapitalize', require( '@stdlib/string/uncapitalize' ) );

/**
* @name uppercase
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/uppercase}
*/
setReadOnly( string, 'uppercase', require( '@stdlib/string/uppercase' ) );

/**
* @name utf16ToUTF8Array
* @memberof string
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/utf16-to-utf8-array}
*/
setReadOnly( string, 'utf16ToUTF8Array', require( '@stdlib/string/utf16-to-utf8-array' ) );

// EXPORTS //

module.exports = string;
<|endoftext|>