<commit_before>"use babel"
export { config } from "./config"
import PathsProvider from "./paths-provider"
import { CompositeDisposable } from "atom"
import { OptionScopes } from "./config/option-scopes"

const subscriptions = new CompositeDisposable()
let _provider
let _statusBar
let _statusBarInterval
let _statusBarTile
let _statusBarElement
let _displayStatusBarItemOnConsumption

export function activate() {
  subscriptions.add(
    atom.commands.add("atom-workspace", {
      "autocomplete-paths:rebuild-cache": () => {
        _provider.rebuildCache()
      },
    })
  )

  const cacheOptions = [
    "core.ignoredNames",
    "core.excludeVcsIgnoredPaths",
    "autocomplete-paths.ignoreSubmodules",
    "autocomplete-paths.ignoredNames",
    "autocomplete-paths.ignoredPatterns",
    "autocomplete-paths.maxFileCount",
  ]
  cacheOptions.forEach((cacheOption) => {
    subscriptions.add(
      atom.config.observe(cacheOption, () => {
        if (!_provider) {
          return
        }
        _provider._pathsCache.updateConfig()
        _provider.rebuildCache()
      })
    )
  })

  const scopeOptions = ["autocomplete-paths.scopes"]
  for (const key in OptionScopes) {
    scopeOptions.push(`autocomplete-paths.${key}`)
  }
  scopeOptions.forEach((scopeOption) => {
    subscriptions.add(
      atom.config.observe(scopeOption, () => {
        if (!_provider) {
          return
        }
        _provider.reloadScopes()
      })
    )
  })
}

export function deactivate() {
  if (_statusBarInterval) {
    clearInterval(_statusBarInterval)
  }
  subscriptions.dispose()
  if (_provider) {
    _provider.dispose(true)
    _provider = null
  }
  if (_statusBarTile) {
    _statusBarTile.destroy()
    _statusBarTile = null
  }
}

/**
 * Invoked when the status bar becomes available
 * @param  {StatusBar} statusBar
 */
export function consumeStatusBar(statusBar) {
  _statusBar = statusBar
  if (_displayStatusBarItemOnConsumption) {
    _displayStatusBarTile()
  }
}

/**
 * Displays the status bar tile
 */
function _displayStatusBarTile() {
  if (!_statusBar) {
    _displayStatusBarItemOnConsumption = true
    return
  }
  if (_statusBarTile) {
    return
  }

  _statusBarElement = document.createElement("autocomplete-paths-status-bar")
  _statusBarElement.innerHTML = "Rebuilding paths cache..."
  _statusBarTile = _statusBar.addRightTile({
    item: _statusBarElement,
    priority: 100,
  })
  if (!_provider) {
    // TODO check why we need this check
    getProvider()
    if (!_provider) {
      return
    }
  }
  _statusBarInterval = setInterval(() => {
    const fileCount = _provider.fileCount
    if (fileCount > 0) {
      _statusBarElement.innerHTML = `Rebuilding paths cache... ${fileCount} files`
    }
  }, 500)
}

/**
 * Hides the status bar tile
 */
function _hideStatusBarTile() {
  if (_statusBarInterval) {
    clearInterval(_statusBarInterval)
  }
  _statusBarTile && _statusBarTile.destroy()
  _statusBarTile = null
  _statusBarElement = null
}

export function getProvider() {
  if (!_provider) {
    _provider = new PathsProvider()
    _provider.on("rebuild-cache", () => {
      _displayStatusBarTile()
    })
    _provider.on("rebuild-cache-done", () => {
      _hideStatusBarTile()
    })
    _provider.rebuildCache()
  }
  return _provider
}
<commit_msg>chore: use if<commit_after>"use babel"
export { config } from "./config"
import PathsProvider from "./paths-provider"
import { CompositeDisposable } from "atom"
import { OptionScopes } from "./config/option-scopes"

const subscriptions = new CompositeDisposable()
let _provider
let _statusBar
let _statusBarInterval
let _statusBarTile
let _statusBarElement
let _displayStatusBarItemOnConsumption

export function activate() {
  subscriptions.add(
    atom.commands.add("atom-workspace", {
      "autocomplete-paths:rebuild-cache": () => {
        _provider.rebuildCache()
      },
    })
  )

  const cacheOptions = [
    "core.ignoredNames",
    "core.excludeVcsIgnoredPaths",
    "autocomplete-paths.ignoreSubmodules",
    "autocomplete-paths.ignoredNames",
    "autocomplete-paths.ignoredPatterns",
    "autocomplete-paths.maxFileCount",
  ]
  cacheOptions.forEach((cacheOption) => {
    subscriptions.add(
      atom.config.observe(cacheOption, () => {
        if (!_provider) {
          return
        }
        _provider._pathsCache.updateConfig()
        _provider.rebuildCache()
      })
    )
  })

  const scopeOptions = ["autocomplete-paths.scopes"]
  for (const key in OptionScopes) {
    scopeOptions.push(`autocomplete-paths.${key}`)
  }
  scopeOptions.forEach((scopeOption) => {
    subscriptions.add(
      atom.config.observe(scopeOption, () => {
        if (!_provider) {
          return
        }
        _provider.reloadScopes()
      })
    )
  })
}

export function deactivate() {
  if (_statusBarInterval) {
    clearInterval(_statusBarInterval)
  }
  subscriptions.dispose()
  if (_provider) {
    _provider.dispose(true)
    _provider = null
  }
  if (_statusBarTile) {
    _statusBarTile.destroy()
    _statusBarTile = null
  }
}

/**
 * Invoked when the status bar becomes available
 * @param  {StatusBar} statusBar
 */
export function consumeStatusBar(statusBar) {
  _statusBar = statusBar
  if (_displayStatusBarItemOnConsumption) {
    _displayStatusBarTile()
  }
}

/**
 * Displays the status bar tile
 */
function _displayStatusBarTile() {
  if (!_statusBar) {
    _displayStatusBarItemOnConsumption = true
    return
  }
  if (_statusBarTile) {
    return
  }

  _statusBarElement = document.createElement("autocomplete-paths-status-bar")
  _statusBarElement.innerHTML = "Rebuilding paths cache..."
  _statusBarTile = _statusBar.addRightTile({
    item: _statusBarElement,
    priority: 100,
  })
  if (!_provider) {
    // TODO check why we need this check
    getProvider()
    if (!_provider) {
      return
    }
  }
  _statusBarInterval = setInterval(() => {
    const fileCount = _provider.fileCount
    if (fileCount > 0) {
      _statusBarElement.innerHTML = `Rebuilding paths cache... ${fileCount} files`
    }
  }, 500)
}

/**
 * Hides the status bar tile
 */
function _hideStatusBarTile() {
  if (_statusBarInterval) {
    clearInterval(_statusBarInterval)
  }
  if (_statusBarTile) {
    _statusBarTile.destroy()
  }
  _statusBarTile = null
  _statusBarElement = null
}

export function getProvider() {
  if (!_provider) {
    _provider = new PathsProvider()
    _provider.on("rebuild-cache", () => {
      _displayStatusBarTile()
    })
    _provider.on("rebuild-cache-done", () => {
      _hideStatusBarTile()
    })
    _provider.rebuildCache()
  }
  return _provider
}
<|endoftext|>


<commit_before>var healpixParallel = 41 + 48 / 36 + 37 / 3600; // TODO automate

function healpix(h) {
  var lambert = d3.geo.cylindricalEqualArea.raw(0),
      φ0 = healpixParallel * π / 180,
      dx0 = lambert(π, 0)[0] - lambert(-π, 0)[0],
      dx1 = d3.geo.collignon.raw(π, φ0)[0] - d3.geo.collignon.raw(-π, φ0)[0],
      y0 = lambert(0, φ0)[1],
      y1 = d3.geo.collignon.raw(0, φ0)[1],
      dy1 = d3.geo.collignon.raw(0, π / 2)[1] - y1,
      k = 2 * π / h;

  return function(λ, φ) {
    var point;
    if (Math.abs(φ) > φ0) {
      var i = Math.min(h - 1, Math.max(0, Math.floor((λ + π) / k)));
      λ = λ + π * (h - 1) / h - i * k;
      point = d3.geo.collignon.raw(λ, Math.abs(φ));
      point[0] = point[0] * dx0 / dx1 - dx0 * (h - 1) / (2 * h) + i * dx0 / h;
      point[1] = y0 + (point[1] - y1) * 4 * dy1 / dx0;
      if (φ < 0) point[1] = -point[1];
    } else {
      point = lambert(λ, φ);
    }
    point[0] /= 2;
    return point;
  };
}

function healpixProjection() {
  var n = 2,
      m = projectionMutator(healpix),
      p = m(n),
      stream_ = p.stream;

  p.lobes = function(_) {
    if (!arguments.length) return n;
    return m(n = +_);
  };

  p.stream = function(stream) {
    var rotate = p.rotate(),
        rotateStream = stream_(stream),
        sphereStream = (p.rotate([0, 0]), stream_(stream));
    p.rotate(rotate);
    rotateStream.sphere = function() { d3.geo.stream(sphere(), sphereStream); };
    return rotateStream;
  };

  function sphere() {
    var step = 180 / n;
    return {
      type: "Polygon",
      coordinates: [
        d3.range(-180, 180 + step / 2, step).map(function(x, i) { return [x, i & 1 ? 90 - 1e-6 : healpixParallel]; })
        .concat(d3.range(180, -180 - step / 2, -step).map(function(x, i) { return [x, i & 1 ? -90 + 1e-6 : -healpixParallel]; }))
      ]
    };
  }

  return p;
}

(d3.geo.healpix = healpixProjection).raw = healpix;
<commit_msg>Add d3.geo.healpix.invert.<commit_after>var healpixParallel = 41 + 48 / 36 + 37 / 3600; // TODO automate

function healpix(h) {
  var lambert = d3.geo.cylindricalEqualArea.raw(0),
      φ0 = healpixParallel * π / 180,
      dx0 = 2 * π,
      dx1 = d3.geo.collignon.raw(π, φ0)[0] - d3.geo.collignon.raw(-π, φ0)[0],
      y0 = lambert(0, φ0)[1],
      y1 = d3.geo.collignon.raw(0, φ0)[1],
      dy1 = d3.geo.collignon.raw(0, π / 2)[1] - y1,
      k = 2 * π / h;

  function forward(λ, φ) {
    var point,
        φ2 = Math.abs(φ);
    if (φ2 > φ0) {
      var i = Math.min(h - 1, Math.max(0, Math.floor((λ + π) / k)));
      λ += π * (h - 1) / h - i * k;
      point = d3.geo.collignon.raw(λ, φ2);
      point[0] = point[0] * dx0 / dx1 - dx0 * (h - 1) / (2 * h) + i * dx0 / h;
      point[1] = y0 + (point[1] - y1) * 4 * dy1 / dx0;
      if (φ < 0) point[1] = -point[1];
    } else {
      point = lambert(λ, φ);
    }
    point[0] /= 2;
    return point;
  }

  forward.invert = function(x, y) {
    x *= 2;
    var y2 = Math.abs(y);
    if (y2 > y0) {
      var i = Math.min(h - 1, Math.max(0, Math.floor((x + π) / k)));
      x = (x + π * (h - 1) / h - i * k) * dx1 / dx0;
      var point = d3.geo.collignon.raw.invert(x, .25 * (y2 - y0) * dx0 / dy1 + y1);
      point[0] -= π * (h - 1) / h - i * k;
      if (y < 0) point[1] = -point[1];
      return point;
    }
    return lambert.invert(x, y);
  };

  return forward;
}

function healpixProjection() {
  var n = 2,
      m = projectionMutator(healpix),
      p = m(n),
      stream_ = p.stream;

  p.lobes = function(_) {
    if (!arguments.length) return n;
    return m(n = +_);
  };

  p.stream = function(stream) {
    var rotate = p.rotate(),
        rotateStream = stream_(stream),
        sphereStream = (p.rotate([0, 0]), stream_(stream));
    p.rotate(rotate);
    rotateStream.sphere = function() { d3.geo.stream(sphere(), sphereStream); };
    return rotateStream;
  };

  function sphere() {
    var step = 180 / n;
    return {
      type: "Polygon",
      coordinates: [
        d3.range(-180, 180 + step / 2, step).map(function(x, i) { return [x, i & 1 ? 90 - 1e-6 : healpixParallel]; })
        .concat(d3.range(180, -180 - step / 2, -step).map(function(x, i) { return [x, i & 1 ? -90 + 1e-6 : -healpixParallel]; }))
      ]
    };
  }

  return p;
}

(d3.geo.healpix = healpixProjection).raw = healpix;
<|endoftext|>


<commit_before>var crypto = require('crypto');

/** @const */ var TOKEN_SEP = ".";
/** @const */ var TOKEN_VERSION = 0;

/**
 * Builds a new object that can generate Firebase authentication tokens.
 * @constructor
 * @export
 * @param {String} secret The secret for the Firebase being used (get yours from the Firebase Admin Console).
 */
FirebaseTokenGenerator = function(secret) {
  this.mSecret = secret;
};

/**
 * Creates a token that authenticates a client with arbitrary data "data", and the specified options.
 *
 * @export
 * @param {Object} data Arbitrary JSON data that will be passed to the Firebase Rules API, once a client authenticates.
 * @param {Object} options The developer-supplied options for this token. Supported options are:
 *                a) "expires" -- (Number) A timestamp (as a number of seconds since the epoch) denoting a time after which
 *                          this token should no longer be valid.
 *                b) "notBefore" -- (Number) A timestamp (as a number of seconds since the epoch) denoting a time before
 *                          which this token should be rejected by the server.
 *                c) "admin" -- (Boolean) Set to true to bypass all security rules (use this for your trusted servers).
 *                d) "debug" -- (Boolean) Set to true to enable debug mode (so you can see the results of Rules API operations)
 *                e) "simulate" -- (Boolean) (internal-only for now) Set to true to neuter all API operations (listens / puts
 *                                 will run security rules but not actually write or return data)
 *                f) "iat" -- (Number) (internal-only, for testing) Set the issued at time for the generated token
 * @return {String} The authentication token
 */
FirebaseTokenGenerator.prototype.createToken = function(data, options) {
  var funcName = 'FirebaseTokenGenerator.createToken';

  var claims = this.createOptionsClaims(funcName, options);
  claims["v"] = TOKEN_VERSION;
  claims["d"] = data;

  if (!claims["iat"]) {
    claims["iat"] = Math.floor(new Date().getTime() / 1000);
  }

  return this.createToken_(claims);
};

/**
 * Take the options supplied on the public API and turn them into claims we can put in the token.
 * @param opts The developer-supplied options for this token.
 * @return The resulting options dictionary to include in the token.
 */
FirebaseTokenGenerator.prototype.createOptionsClaims = function(func_name, opts) {

  var claims = {};

  for(var o in opts) {
    if (opts.hasOwnProperty(o)) {
      switch(o) {
        case "expires":
          if (opts[o] instanceof Date) {
            claims["exp"] = Math.round(opts[o].getTime() / 1000);
          } else {
            claims["exp"] = opts[o];
          }
          break;
        case "notBefore" :
          if (opts[o] instanceof Date) {
            claims["nbf"] = Math.round(opts[o].getTime() / 1000);
          } else {
            claims["nbf"] = opts[o];
          }
          break;
        case "admin" :
          claims["admin"] = opts[o];
          break;
        case "debug" :
          claims["debug"] = opts[o];
          break;
        case "simulate" :
          claims["simulate"] = opts[o];
          break;
        case "iat":
          claims["iat"] = opts[o];
          break;
        default: {
          throw new Error(func_name + " unrecognized option: " + o);
        }
      }
    }
  }

  return claims;
};

/**
 * Generates a secure authentication token.
 *
 * Our token format follows the JSON Web Token (JWT) standard:
 * header.claims.signature
 *
 * Where:
 * 1) "header" is a stringified, base64-encoded JSON object containing version and algorithm information.
 * 2) "claims" is a stringified, base64-encoded JSON object containing a set of claims:
 *    Library-generated claims:
 *    "iat" -> The issued at time in seconds since the epoch as a number
 *    "d" -> The arbitrary JSON object supplied by the user.
 *    User-supplied claims (these are all optional):
 *    "exp" (optional) -> The expiration time of this token, as a number of seconds since the epoch.
 *    "nbf" (optional) -> The "not before" time before which the token should be rejected (seconds since the epoch)
 *    "admin" (optional) -> If set to true, this client will bypass all security rules (use this to authenticate servers)
 *    "debug" (optional) -> "set to true to make this client receive debug information about security rule execution.
 *    "simulate" (optional, internal-only for now) -> Set to true to neuter all API operations (listens / puts
 *               will run security rules but not actually write or return data).
 * 3) A signature that proves the validity of this token (see: http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-07)
 *
 * For base64-encoding we use URL-safe base64 encoding. This ensures that the entire token is URL-safe
 * and could, for instance, be placed as a query argument without any encoding (and this is what the JWT spec requires).
 *
 * @param {Object} claims A JSON object containing the security payload of this token (see "claims" above).
 * @return {String} The authentication token.
 */
FirebaseTokenGenerator.prototype.createToken_ = function(claims) {

  //set up the header
  var headerData = {"typ": "JWT", "alg":"HS256"};

  //encode the header and payload
  var encodedHeader = this.noPadWebsafeBase64Encode_(JSON.stringify(headerData));
  var encodedClaims = this.noPadWebsafeBase64Encode_(JSON.stringify(claims));

  //generate the signature
  var secureBits = encodedHeader + TOKEN_SEP + encodedClaims;
  var hmac = crypto.createHmac('sha256', this.mSecret);
  hmac.update(secureBits);
  var hashBytes = hmac.digest('binary');
  var sig = this.noPadWebsafeBase64Encode_(hashBytes, 'binary');
  return encodedHeader + TOKEN_SEP + encodedClaims + TOKEN_SEP + sig;
};

/**
 * Base64 encodes a string with a URL-safe encoding with no padding characters.
 *
 * @param {String} str The string to encode
 * @param {String=} encoding optional encoding the of the string
 * @return {String} The base64 encoded version
 */
FirebaseTokenGenerator.prototype.noPadWebsafeBase64Encode_ = function(str, encoding) {
  var encoded = new Buffer(str, encoding).toString('base64');
  return encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
};

// For the node client, we need to export our self.
module['exports'] = FirebaseTokenGenerator;<commit_msg>Simplify nbf/exp handling a bit<commit_after>var crypto = require('crypto');

/** @const */ var TOKEN_SEP = ".";
/** @const */ var TOKEN_VERSION = 0;

/**
 * Builds a new object that can generate Firebase authentication tokens.
 * @constructor
 * @export
 * @param {String} secret The secret for the Firebase being used (get yours from the Firebase Admin Console).
 */
FirebaseTokenGenerator = function(secret) {
  this.mSecret = secret;
};

/**
 * Creates a token that authenticates a client with arbitrary data "data", and the specified options.
 *
 * @export
 * @param {Object} data Arbitrary JSON data that will be passed to the Firebase Rules API, once a client authenticates.
 * @param {Object} options The developer-supplied options for this token. Supported options are:
 *                a) "expires" -- (Number) A timestamp (as a number of seconds since the epoch) denoting a time after which
 *                          this token should no longer be valid.
 *                b) "notBefore" -- (Number) A timestamp (as a number of seconds since the epoch) denoting a time before
 *                          which this token should be rejected by the server.
 *                c) "admin" -- (Boolean) Set to true to bypass all security rules (use this for your trusted servers).
 *                d) "debug" -- (Boolean) Set to true to enable debug mode (so you can see the results of Rules API operations)
 *                e) "simulate" -- (Boolean) (internal-only for now) Set to true to neuter all API operations (listens / puts
 *                                 will run security rules but not actually write or return data)
 *                f) "iat" -- (Number) (internal-only, for testing) Set the issued at time for the generated token
 * @return {String} The authentication token
 */
FirebaseTokenGenerator.prototype.createToken = function(data, options) {
  var funcName = 'FirebaseTokenGenerator.createToken';

  var claims = this.createOptionsClaims(funcName, options);
  claims["v"] = TOKEN_VERSION;
  claims["d"] = data;

  if (!claims["iat"]) {
    claims["iat"] = Math.floor(new Date().getTime() / 1000);
  }

  return this.createToken_(claims);
};

/**
 * Take the options supplied on the public API and turn them into claims we can put in the token.
 * @param opts The developer-supplied options for this token.
 * @return The resulting options dictionary to include in the token.
 */
FirebaseTokenGenerator.prototype.createOptionsClaims = function(func_name, opts) {

  var claims = {};

  for (var o in opts) {
    if (opts.hasOwnProperty(o)) {
      switch (o) {
        case "expires":
        case "notBefore":
          var code = (o == "notBefore" ? "nbf" : "exp");
          if (opts[o] instanceof Date) {
            claims[code] = Math.round(opts[o].getTime() / 1000);
          } else {
            claims[code] = opts[o];
          }
          break;
        case "admin" :
          claims["admin"] = opts[o];
          break;
        case "debug" :
          claims["debug"] = opts[o];
          break;
        case "simulate" :
          claims["simulate"] = opts[o];
          break;
        case "iat":
          claims["iat"] = opts[o];
          break;
        default: {
          throw new Error(func_name + " unrecognized option: " + o);
        }
      }
    }
  }

  return claims;
};

/**
 * Generates a secure authentication token.
 *
 * Our token format follows the JSON Web Token (JWT) standard:
 * header.claims.signature
 *
 * Where:
 * 1) "header" is a stringified, base64-encoded JSON object containing version and algorithm information.
 * 2) "claims" is a stringified, base64-encoded JSON object containing a set of claims:
 *    Library-generated claims:
 *    "iat" -> The issued at time in seconds since the epoch as a number
 *    "d" -> The arbitrary JSON object supplied by the user.
 *    User-supplied claims (these are all optional):
 *    "exp" (optional) -> The expiration time of this token, as a number of seconds since the epoch.
 *    "nbf" (optional) -> The "not before" time before which the token should be rejected (seconds since the epoch)
 *    "admin" (optional) -> If set to true, this client will bypass all security rules (use this to authenticate servers)
 *    "debug" (optional) -> "set to true to make this client receive debug information about security rule execution.
 *    "simulate" (optional, internal-only for now) -> Set to true to neuter all API operations (listens / puts
 *               will run security rules but not actually write or return data).
 * 3) A signature that proves the validity of this token (see: http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-07)
 *
 * For base64-encoding we use URL-safe base64 encoding. This ensures that the entire token is URL-safe
 * and could, for instance, be placed as a query argument without any encoding (and this is what the JWT spec requires).
 *
 * @param {Object} claims A JSON object containing the security payload of this token (see "claims" above).
 * @return {String} The authentication token.
 */
FirebaseTokenGenerator.prototype.createToken_ = function(claims) {

  //set up the header
  var headerData = {"typ": "JWT", "alg":"HS256"};

  //encode the header and payload
  var encodedHeader = this.noPadWebsafeBase64Encode_(JSON.stringify(headerData));
  var encodedClaims = this.noPadWebsafeBase64Encode_(JSON.stringify(claims));

  //generate the signature
  var secureBits = encodedHeader + TOKEN_SEP + encodedClaims;
  var hmac = crypto.createHmac('sha256', this.mSecret);
  hmac.update(secureBits);
  var hashBytes = hmac.digest('binary');
  var sig = this.noPadWebsafeBase64Encode_(hashBytes, 'binary');
  return encodedHeader + TOKEN_SEP + encodedClaims + TOKEN_SEP + sig;
};

/**
 * Base64 encodes a string with a URL-safe encoding with no padding characters.
 *
 * @param {String} str The string to encode
 * @param {String=} encoding optional encoding the of the string
 * @return {String} The base64 encoded version
 */
FirebaseTokenGenerator.prototype.noPadWebsafeBase64Encode_ = function(str, encoding) {
  var encoded = new Buffer(str, encoding).toString('base64');
  return encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
};

// For the node client, we need to export our self.
module['exports'] = FirebaseTokenGenerator;<|endoftext|>


<commit_before>// @flow

export type IObservableMapInitialValues<K, V> = IMapEntries<K, V> | KeyValueMap<V> | IMap<K, V>

export interface IMobxConfigurationOptions {
    enforceActions?: boolean,
    computedRequiresReaction?: boolean,
    isolateGlobalState?: boolean,
    disableErrorBoundaries?: boolean,
    arrayBuffer?: number,
    reactionScheduler?: (f: () => void) => void
}

declare export function configure(options: IMobxConfigurationOptions): void

export interface IAutorunOptions {
    delay?: number,
    name?: string,
    scheduler?: (callback: () => void) => any,
    onError?: (error: any) => void
}

export interface IReactionOptions extends IAutorunOptions {
    fireImmediately?: boolean,
    equals?: IEqualsComparer<any>
}

export interface IInterceptable<T> {
    interceptors: IInterceptor<T>[] | any,
    intercept(handler: IInterceptor<T>): Lambda
}

export type IEqualsComparer<T> = (a: T, b: T) => boolean

export type IInterceptor<T> = (change: T) => T

export type IMapEntry<K, V> = [K, V]

export type IMapEntries<K, V> = IMapEntry<K, V>[]

export interface IMap<K, V> {
    clear(): void,
    delete(key: K): boolean,
    forEach(callbackfn: (value: V, index: K, map: IMap<K, V>) => void, thisArg?: any): void,
    get(key: K): V | any,
    has(key: K): boolean,
    set(key: K, value?: V): any,
    size: number
}

declare export function isObservableMap(x: any): boolean

export interface IComputedValueOptions<T> {
    get?: () => T,
    set?: (value: T) => void,
    name?: string,
    equals?: IEqualsComparer<T>,
    context?: any
}

declare type PropertyDescriptor = any

export interface IComputed {
    <T>(func: () => T, setter?: (value: T) => void): IComputedValue<T>,
    <T>(func: () => T, options: IComputedValueOptions<T>): IComputedValue<T>,
    (target: Object, key: string, baseDescriptor?: PropertyDescriptor): void,
    struct(target: Object, key: string, baseDescriptor?: PropertyDescriptor): void
}

export interface IDependencyTree {
    name: string,
    dependencies?: IDependencyTree[]
}

export interface IObserverTree {
    name: string,
    observers?: IObserverTree[]
}

export interface IAtom {
    reportObserved: () => void,
    reportChanged: () => void
}

export interface IComputedValue<T> {
    get(): T,
    set(value: T): void,
    observe(listener: (newValue: T, oldValue: T) => void, fireImmediately?: boolean): Lambda
}

export interface IObservable {}

export interface IDepTreeNode {
    name: string,
    observing?: IObservable[]
}

export interface IDerivation {
    name: string
}

export interface IReactionPublic {
    dispose: () => void,
    trace: (enterBreakPoint?: boolean) => void
}

declare export class IListenable {
    observe(handler: (change: any, oldValue?: any) => void, fireImmediately?: boolean): Lambda
}

export interface IObservableArray<T> extends Array<T> {
    spliceWithArray(index: number, deleteCount?: number, newItems?: T[]): T[],
    observe(
        listener: (changeData: IArrayChange<T> | IArraySplice<T>) => void,
        fireImmediately?: boolean
    ): Lambda,
    intercept(handler: IInterceptor<IArrayWillChange<T> | IArrayWillSplice<T>>): Lambda,
    intercept(handler: IInterceptor<IArrayChange<T> | IArraySplice<T>>): Lambda, // TODO: remove in 4.0
    intercept<T>(handler: IInterceptor<IArrayChange<T> | IArraySplice<T>>): Lambda, // TODO: remove in 4.0
    clear(): T[],
    peek(): T[],
    replace(newItems: T[]): T[],
    find(
        predicate: (item: T, index: number, array: Array<T>) => boolean,
        thisArg?: any,
        fromIndex?: number
    ): T | any,
    findIndex(
        predicate: (item: T, index: number, array: Array<T>) => boolean,
        thisArg?: any,
        fromIndex?: number
    ): number,
    remove(value: T): boolean
}

export interface IArrayChange<T> {
    type: "update",
    object: IObservableArray<T>,
    index: number,
    newValue: T,
    oldValue: T
}

export interface IArraySplice<T> {
    type: "splice",
    object: IObservableArray<T>,
    index: number,
    added: T[],
    addedCount: number,
    removed: T[],
    removedCount: number
}

export interface IArrayWillChange<T> {
    type: "update",
    object: IObservableArray<T>,
    index: number,
    newValue: T
}

export interface IArrayWillSplice<T> {
    type: "splice",
    object: IObservableArray<T>,
    index: number,
    added: T[],
    removedCount: number
}

export type KeyValueMap<V> = {
    [key: string]: V
}

export interface IMapChange<T> {
    object: ObservableMap<T>,
    type: "update" | "add" | "delete",
    name: string,
    newValue?: any,
    oldValue?: any
}

export interface IMapWillChange<T> {
    object: ObservableMap<T>,
    type: "update" | "add" | "delete",
    name: string,
    newValue?: any
}

export interface IObservableObject {}

export interface IObjectChange {
    name: string,
    object: any,
    type: "update" | "add" | "remove",
    oldValue?: any,
    newValue: any
}

export interface IObjectWillChange {
    object: any,
    type: "update" | "add" | "remove",
    name: string,
    newValue: any
}

export interface IValueWillChange<T> {
    object: any,
    type: "update",
    newValue: T
}

export interface IValueDidChange<T> extends IValueWillChange<T> {
    oldValue: ?T
}

export interface IObservableValue<T> {
    get(): T,
    set(value: T): void,
    intercept(handler: IInterceptor<IValueWillChange<T>>): Lambda,
    observe(listener: (change: IValueDidChange<T>) => void, fireImmediately?: boolean): Lambda
}

export interface IEnhancer<T> {
    (newValue: T, oldValue: T | void, name: string): T
}

export interface IObservableFactory {
    // observable overloads
    (target: Object, key: string, baseDescriptor?: PropertyDescriptor): any,
    <T>(value: Array<T>): IObservableArray<T>,
    <T>(value: null | void): IObservableValue<T>,
    (value: null | void): IObservableValue<any>,
    <T>(value: IMap<string | number | boolean, T>): ObservableMap<T>,
    <T: Object>(value: T): T
}

declare export class IObservableFactories {
    box<T>(value?: T, name?: string): IObservableValue<T>,
    array<T>(initialValues?: T[], name?: string): IObservableArray<T>,
    map<T>(initialValues?: IObservableMapInitialValues<T>, name?: string): ObservableMap<T>,
    object<T>(props: T, name?: string): T & IObservableObject,
    ref(target: Object, property?: string, descriptor?: PropertyDescriptor): any,
    shallow(target: Object, property?: string, descriptor?: PropertyDescriptor): any,
    deep(target: Object, property?: string, descriptor?: PropertyDescriptor): any
}

export interface Iterator<T> {
    next(): {
        done: boolean,
        value?: T
    }
}

export interface Lambda {
    (): void,
    name?: string
}

export interface IActionFactory {
    (a1: any, a2?: any, a3?: any, a4?: any, a6?: any): any,
    bound(target: Object, propertyKey: string, descriptor?: PropertyDescriptor): void
}

declare export class ObservableMap<K, V> {
    constructor(initialData?: IMapEntries<K, V> | KeyValueMap<V>, valueModeFunc?: Function): this,
    has(key: K): boolean,
    set(key: K, value: V): void,
    delete(key: K): boolean,
    get(key: K): V,
    keys(): Iterator<K>,
    values(): Iterator<V>,
    entries(): IMapEntries<K, V> & Iterator<IMapEntry<K, V>>,
    forEach(callback: (value: V, key: K, object: KeyValueMap<K, V>) => void, thisArg?: any): void,
    merge(other: ObservableMap<K, V> | KeyValueMap<K, V>): ObservableMap<K, V>,
    clear(): void,
    replace(other: ObservableMap<K, V> | KeyValueMap<K, V>): ObservableMap<K, V>,
    size: number,
    toJS(): Map<K, V>,
    toPOJO(): KeyValueMap<V>,
    toJSON(): KeyValueMap<V>,
    toString(): string,
    observe(listener: (changes: IMapChange<K, V>) => void, fireImmediately?: boolean): Lambda,
    intercept(handler: IInterceptor<IMapWillChange<K, V>>): Lambda
}

declare export function action(
    targetOrName: any,
    propertyKeyOrFuc?: any,
    descriptor?: PropertyDescriptor
): any
declare export function action<T>(name: string, func: T): T
declare export function action<T>(func: T): T

declare export function runInAction<T>(block: () => T): T
declare export function isAction(thing: any): boolean
declare export function autorun(
    nameOrFunction: string | ((r: IReactionPublic) => any),
    options?: IAutorunOptions
): any
declare export function reaction<T>(
    expression: (r: IReactionPublic) => T,
    effect: (arg: T, r: IReactionPublic) => void,
    opts?: IReactionOptions
): any

export interface IWhenOptions {
    name?: string,
    timeout?: number,
    onError?: (error: any) => void
}

declare export function when(cond: () => boolean, effect: Lambda, options?: IWhenOptions): any
declare export function when(cond: () => boolean, options?: IWhenOptions): Promise<any>

declare export function computed<T>(
    target: any,
    key?: string,
    baseDescriptor?: PropertyDescriptor
): any

declare export function extendObservable<A, B>(
    target: A,
    properties: B,
    decorators?: any,
    options?: any
): A & B

declare export function intercept(
    object: Object,
    property: string,
    handler: IInterceptor<any>
): Lambda

declare export function isComputed(value: any): boolean
declare export function isComputedProp(value: any, property: string): boolean

declare export function isObservable(value: any): boolean
declare export function isObservableProp(value: any, property: string): boolean

declare export var observable: IObservableFactory &
    IObservableFactories & {
        deep: {
            struct<T>(initialValue?: T): T
        },
        ref: {
            struct<T>(initialValue?: T): T
        }
    }

declare export function observe<T>(
    value: IObservableValue<T> | IComputedValue<T>,
    listener: (change: IValueDidChange<T>) => void,
    fireImmediately?: boolean
): Lambda
declare export function observe<T>(
    observableArray: IObservableArray<T>,
    listener: (change: IArrayChange<T> | IArraySplice<T>) => void,
    fireImmediately?: boolean
): Lambda
declare export function observe<K, T>(
    observableMap: ObservableMap<K, T>,
    listener: (change: IMapChange<K, T>) => void,
    fireImmediately?: boolean
): Lambda
declare export function observe<K, T>(
    observableMap: ObservableMap<K, T>,
    property: string,
    listener: (change: IValueDidChange<K, T>) => void,
    fireImmediately?: boolean
): Lambda
declare export function observe(
    object: any,
    listener: (change: IObjectChange) => void,
    fireImmediately?: boolean
): Lambda
declare export function observe(
    object: any,
    property: string,
    listener: (change: IValueDidChange<any>) => void,
    fireImmediately?: boolean
): Lambda

export interface ToJSOptions {
    detectCycles?: boolean,
    exportMapsAsObjects?: boolean
}

declare export function toJS<T>(source: T, options?: ToJSOptions): T

declare export function untracked<T>(action: () => T): T

declare export function spy(listener: (change: any) => void): Lambda

declare export function transaction<T>(action: () => T, thisArg?: any, report?: boolean): T

declare export function isObservableArray(thing: any): boolean

declare export function isObservableObject<T>(thing: T): boolean

declare export function isArrayLike(x: any): boolean

declare export class Reaction {
    name: string,
    isDisposed: boolean,
    constructor(name: string, onInvalidate: () => void): this,
    schedule(): void,
    isScheduled(): boolean,
    track(fn: () => void): void,
    dispose(): void,
    getDisposer(): Lambda & {
        $mosbservable: Reaction
    },
    toString(): string,
    trace(enterBreakPoint?: boolean): void
}

declare export function createAtom(
    name: string,
    onBecomeObservedHandler?: () => void,
    onBecomeUnobservedHandler?: () => void
): IAtom

declare export function decorate<T>(target: T, decorators: any): T

declare export function flow<T>(fn: (...args: any[]) => T): (...args: any[]) => Promise<T>
declare export function flow<T>(
    name: string,
    fn: (...args: any[]) => T
): (...args: any[]) => Promise<T>

declare export function keys<K>(map: ObservableMap<K, any>): K[]
declare export function keys(obj: any): string[]

declare export function values<K, T>(map: ObservableMap<K, T>): T[]
declare export function values<T>(ar: IObservableArray<T>): T[]
declare export function values(obj: any): any[]

declare export function set<V>(obj: ObservableMap<string, V>, values: { [key: string]: V }): void
declare export function set<K, V>(obj: ObservableMap<K, V>, key: K, value: V): void
declare export function set<T>(obj: IObservableArray<T>, index: number, value: T): void
declare export function set(obj: any, values: { [key: string]: any }): void
declare export function set(obj: any, key: string, value: any): void

declare export function remove<K, V>(obj: ObservableMap<K, V>, key: K): void
declare export function remove<T>(obj: IObservableArray<T>, index: number): void
declare export function remove(obj: any, key: string): void

declare export function has<K>(obj: ObservableMap<K, any>, key: K): boolean
declare export function has<T>(obj: IObservableArray<T>, index: number): boolean
declare export function has(obj: any, key: string): boolean

declare export function get<K, V>(obj: ObservableMap<K, V>, key: K): V | void
declare export function get<T>(obj: IObservableArray<T>, index: number): T | void
declare export function get(obj: any, key: string): any

declare export function onReactionError(
    handler: (error: any, derivation: IDerivation) => void
): () => void

declare export function onBecomeObserved(
    value: IObservable | IComputedValue<any> | IObservableArray<any> | ObservableMap<any, any>,
    listener: Lambda
): Lambda
declare export function onBecomeObserved<K>(
    value: ObservableMap<K, any> | Object,
    property: K,
    listener: Lambda
): Lambda

declare export function onBecomeUnobserved(
    value: IObservable | IComputedValue<any> | IObservableArray<any> | ObservableMap<any, any>,
    listener: Lambda
): Lambda
declare export function onBecomeUnobserved<K>(
    value: ObservableMap<K, any> | Object,
    property: K,
    listener: Lambda
): Lambda

declare export function getAtom(thing: any, property?: string): IDepTreeNode
declare export function getDebugName(thing: any, property?: string): string
declare export function getDependencyTree(thing: any, property?: string): IDependencyTree
declare export function getObserverTree(thing: any, property?: string): IObserverTree
<commit_msg>Flow-typed: add missing runInAction declaration<commit_after>// @flow

export type IObservableMapInitialValues<K, V> = IMapEntries<K, V> | KeyValueMap<V> | IMap<K, V>

export interface IMobxConfigurationOptions {
    enforceActions?: boolean,
    computedRequiresReaction?: boolean,
    isolateGlobalState?: boolean,
    disableErrorBoundaries?: boolean,
    arrayBuffer?: number,
    reactionScheduler?: (f: () => void) => void
}

declare export function configure(options: IMobxConfigurationOptions): void

export interface IAutorunOptions {
    delay?: number,
    name?: string,
    scheduler?: (callback: () => void) => any,
    onError?: (error: any) => void
}

export interface IReactionOptions extends IAutorunOptions {
    fireImmediately?: boolean,
    equals?: IEqualsComparer<any>
}

export interface IInterceptable<T> {
    interceptors: IInterceptor<T>[] | any,
    intercept(handler: IInterceptor<T>): Lambda
}

export type IEqualsComparer<T> = (a: T, b: T) => boolean

export type IInterceptor<T> = (change: T) => T

export type IMapEntry<K, V> = [K, V]

export type IMapEntries<K, V> = IMapEntry<K, V>[]

export interface IMap<K, V> {
    clear(): void,
    delete(key: K): boolean,
    forEach(callbackfn: (value: V, index: K, map: IMap<K, V>) => void, thisArg?: any): void,
    get(key: K): V | any,
    has(key: K): boolean,
    set(key: K, value?: V): any,
    size: number
}

declare export function isObservableMap(x: any): boolean

export interface IComputedValueOptions<T> {
    get?: () => T,
    set?: (value: T) => void,
    name?: string,
    equals?: IEqualsComparer<T>,
    context?: any
}

declare type PropertyDescriptor = any

export interface IComputed {
    <T>(func: () => T, setter?: (value: T) => void): IComputedValue<T>,
    <T>(func: () => T, options: IComputedValueOptions<T>): IComputedValue<T>,
    (target: Object, key: string, baseDescriptor?: PropertyDescriptor): void,
    struct(target: Object, key: string, baseDescriptor?: PropertyDescriptor): void
}

export interface IDependencyTree {
    name: string,
    dependencies?: IDependencyTree[]
}

export interface IObserverTree {
    name: string,
    observers?: IObserverTree[]
}

export interface IAtom {
    reportObserved: () => void,
    reportChanged: () => void
}

export interface IComputedValue<T> {
    get(): T,
    set(value: T): void,
    observe(listener: (newValue: T, oldValue: T) => void, fireImmediately?: boolean): Lambda
}

export interface IObservable {}

export interface IDepTreeNode {
    name: string,
    observing?: IObservable[]
}

export interface IDerivation {
    name: string
}

export interface IReactionPublic {
    dispose: () => void,
    trace: (enterBreakPoint?: boolean) => void
}

declare export class IListenable {
    observe(handler: (change: any, oldValue?: any) => void, fireImmediately?: boolean): Lambda
}

export interface IObservableArray<T> extends Array<T> {
    spliceWithArray(index: number, deleteCount?: number, newItems?: T[]): T[],
    observe(
        listener: (changeData: IArrayChange<T> | IArraySplice<T>) => void,
        fireImmediately?: boolean
    ): Lambda,
    intercept(handler: IInterceptor<IArrayWillChange<T> | IArrayWillSplice<T>>): Lambda,
    intercept(handler: IInterceptor<IArrayChange<T> | IArraySplice<T>>): Lambda, // TODO: remove in 4.0
    intercept<T>(handler: IInterceptor<IArrayChange<T> | IArraySplice<T>>): Lambda, // TODO: remove in 4.0
    clear(): T[],
    peek(): T[],
    replace(newItems: T[]): T[],
    find(
        predicate: (item: T, index: number, array: Array<T>) => boolean,
        thisArg?: any,
        fromIndex?: number
    ): T | any,
    findIndex(
        predicate: (item: T, index: number, array: Array<T>) => boolean,
        thisArg?: any,
        fromIndex?: number
    ): number,
    remove(value: T): boolean
}

export interface IArrayChange<T> {
    type: "update",
    object: IObservableArray<T>,
    index: number,
    newValue: T,
    oldValue: T
}

export interface IArraySplice<T> {
    type: "splice",
    object: IObservableArray<T>,
    index: number,
    added: T[],
    addedCount: number,
    removed: T[],
    removedCount: number
}

export interface IArrayWillChange<T> {
    type: "update",
    object: IObservableArray<T>,
    index: number,
    newValue: T
}

export interface IArrayWillSplice<T> {
    type: "splice",
    object: IObservableArray<T>,
    index: number,
    added: T[],
    removedCount: number
}

export type KeyValueMap<V> = {
    [key: string]: V
}

export interface IMapChange<T> {
    object: ObservableMap<T>,
    type: "update" | "add" | "delete",
    name: string,
    newValue?: any,
    oldValue?: any
}

export interface IMapWillChange<T> {
    object: ObservableMap<T>,
    type: "update" | "add" | "delete",
    name: string,
    newValue?: any
}

export interface IObservableObject {}

export interface IObjectChange {
    name: string,
    object: any,
    type: "update" | "add" | "remove",
    oldValue?: any,
    newValue: any
}

export interface IObjectWillChange {
    object: any,
    type: "update" | "add" | "remove",
    name: string,
    newValue: any
}

export interface IValueWillChange<T> {
    object: any,
    type: "update",
    newValue: T
}

export interface IValueDidChange<T> extends IValueWillChange<T> {
    oldValue: ?T
}

export interface IObservableValue<T> {
    get(): T,
    set(value: T): void,
    intercept(handler: IInterceptor<IValueWillChange<T>>): Lambda,
    observe(listener: (change: IValueDidChange<T>) => void, fireImmediately?: boolean): Lambda
}

export interface IEnhancer<T> {
    (newValue: T, oldValue: T | void, name: string): T
}

export interface IObservableFactory {
    // observable overloads
    (target: Object, key: string, baseDescriptor?: PropertyDescriptor): any,
    <T>(value: Array<T>): IObservableArray<T>,
    <T>(value: null | void): IObservableValue<T>,
    (value: null | void): IObservableValue<any>,
    <T>(value: IMap<string | number | boolean, T>): ObservableMap<T>,
    <T: Object>(value: T): T
}

declare export class IObservableFactories {
    box<T>(value?: T, name?: string): IObservableValue<T>,
    array<T>(initialValues?: T[], name?: string): IObservableArray<T>,
    map<T>(initialValues?: IObservableMapInitialValues<T>, name?: string): ObservableMap<T>,
    object<T>(props: T, name?: string): T & IObservableObject,
    ref(target: Object, property?: string, descriptor?: PropertyDescriptor): any,
    shallow(target: Object, property?: string, descriptor?: PropertyDescriptor): any,
    deep(target: Object, property?: string, descriptor?: PropertyDescriptor): any
}

export interface Iterator<T> {
    next(): {
        done: boolean,
        value?: T
    }
}

export interface Lambda {
    (): void,
    name?: string
}

export interface IActionFactory {
    (a1: any, a2?: any, a3?: any, a4?: any, a6?: any): any,
    bound(target: Object, propertyKey: string, descriptor?: PropertyDescriptor): void
}

declare export class ObservableMap<K, V> {
    constructor(initialData?: IMapEntries<K, V> | KeyValueMap<V>, valueModeFunc?: Function): this,
    has(key: K): boolean,
    set(key: K, value: V): void,
    delete(key: K): boolean,
    get(key: K): V,
    keys(): Iterator<K>,
    values(): Iterator<V>,
    entries(): IMapEntries<K, V> & Iterator<IMapEntry<K, V>>,
    forEach(callback: (value: V, key: K, object: KeyValueMap<K, V>) => void, thisArg?: any): void,
    merge(other: ObservableMap<K, V> | KeyValueMap<K, V>): ObservableMap<K, V>,
    clear(): void,
    replace(other: ObservableMap<K, V> | KeyValueMap<K, V>): ObservableMap<K, V>,
    size: number,
    toJS(): Map<K, V>,
    toPOJO(): KeyValueMap<V>,
    toJSON(): KeyValueMap<V>,
    toString(): string,
    observe(listener: (changes: IMapChange<K, V>) => void, fireImmediately?: boolean): Lambda,
    intercept(handler: IInterceptor<IMapWillChange<K, V>>): Lambda
}

declare export function action(
    targetOrName: any,
    propertyKeyOrFuc?: any,
    descriptor?: PropertyDescriptor
): any
declare export function action<T>(name: string, func: T): T
declare export function action<T>(func: T): T

declare export function runInAction<T>(name: string, block: () => T): T
declare export function runInAction<T>(block: () => T): T
declare export function isAction(thing: any): boolean
declare export function autorun(
    nameOrFunction: string | ((r: IReactionPublic) => any),
    options?: IAutorunOptions
): any
declare export function reaction<T>(
    expression: (r: IReactionPublic) => T,
    effect: (arg: T, r: IReactionPublic) => void,
    opts?: IReactionOptions
): any

export interface IWhenOptions {
    name?: string,
    timeout?: number,
    onError?: (error: any) => void
}

declare export function when(cond: () => boolean, effect: Lambda, options?: IWhenOptions): any
declare export function when(cond: () => boolean, options?: IWhenOptions): Promise<any>

declare export function computed<T>(
    target: any,
    key?: string,
    baseDescriptor?: PropertyDescriptor
): any

declare export function extendObservable<A, B>(
    target: A,
    properties: B,
    decorators?: any,
    options?: any
): A & B

declare export function intercept(
    object: Object,
    property: string,
    handler: IInterceptor<any>
): Lambda

declare export function isComputed(value: any): boolean
declare export function isComputedProp(value: any, property: string): boolean

declare export function isObservable(value: any): boolean
declare export function isObservableProp(value: any, property: string): boolean

declare export var observable: IObservableFactory &
    IObservableFactories & {
        deep: {
            struct<T>(initialValue?: T): T
        },
        ref: {
            struct<T>(initialValue?: T): T
        }
    }

declare export function observe<T>(
    value: IObservableValue<T> | IComputedValue<T>,
    listener: (change: IValueDidChange<T>) => void,
    fireImmediately?: boolean
): Lambda
declare export function observe<T>(
    observableArray: IObservableArray<T>,
    listener: (change: IArrayChange<T> | IArraySplice<T>) => void,
    fireImmediately?: boolean
): Lambda
declare export function observe<K, T>(
    observableMap: ObservableMap<K, T>,
    listener: (change: IMapChange<K, T>) => void,
    fireImmediately?: boolean
): Lambda
declare export function observe<K, T>(
    observableMap: ObservableMap<K, T>,
    property: string,
    listener: (change: IValueDidChange<K, T>) => void,
    fireImmediately?: boolean
): Lambda
declare export function observe(
    object: any,
    listener: (change: IObjectChange) => void,
    fireImmediately?: boolean
): Lambda
declare export function observe(
    object: any,
    property: string,
    listener: (change: IValueDidChange<any>) => void,
    fireImmediately?: boolean
): Lambda

export interface ToJSOptions {
    detectCycles?: boolean,
    exportMapsAsObjects?: boolean
}

declare export function toJS<T>(source: T, options?: ToJSOptions): T

declare export function untracked<T>(action: () => T): T

declare export function spy(listener: (change: any) => void): Lambda

declare export function transaction<T>(action: () => T, thisArg?: any, report?: boolean): T

declare export function isObservableArray(thing: any): boolean

declare export function isObservableObject<T>(thing: T): boolean

declare export function isArrayLike(x: any): boolean

declare export class Reaction {
    name: string,
    isDisposed: boolean,
    constructor(name: string, onInvalidate: () => void): this,
    schedule(): void,
    isScheduled(): boolean,
    track(fn: () => void): void,
    dispose(): void,
    getDisposer(): Lambda & {
        $mosbservable: Reaction
    },
    toString(): string,
    trace(enterBreakPoint?: boolean): void
}

declare export function createAtom(
    name: string,
    onBecomeObservedHandler?: () => void,
    onBecomeUnobservedHandler?: () => void
): IAtom

declare export function decorate<T>(target: T, decorators: any): T

declare export function flow<T>(fn: (...args: any[]) => T): (...args: any[]) => Promise<T>
declare export function flow<T>(
    name: string,
    fn: (...args: any[]) => T
): (...args: any[]) => Promise<T>

declare export function keys<K>(map: ObservableMap<K, any>): K[]
declare export function keys(obj: any): string[]

declare export function values<K, T>(map: ObservableMap<K, T>): T[]
declare export function values<T>(ar: IObservableArray<T>): T[]
declare export function values(obj: any): any[]

declare export function set<V>(obj: ObservableMap<string, V>, values: { [key: string]: V }): void
declare export function set<K, V>(obj: ObservableMap<K, V>, key: K, value: V): void
declare export function set<T>(obj: IObservableArray<T>, index: number, value: T): void
declare export function set(obj: any, values: { [key: string]: any }): void
declare export function set(obj: any, key: string, value: any): void

declare export function remove<K, V>(obj: ObservableMap<K, V>, key: K): void
declare export function remove<T>(obj: IObservableArray<T>, index: number): void
declare export function remove(obj: any, key: string): void

declare export function has<K>(obj: ObservableMap<K, any>, key: K): boolean
declare export function has<T>(obj: IObservableArray<T>, index: number): boolean
declare export function has(obj: any, key: string): boolean

declare export function get<K, V>(obj: ObservableMap<K, V>, key: K): V | void
declare export function get<T>(obj: IObservableArray<T>, index: number): T | void
declare export function get(obj: any, key: string): any

declare export function onReactionError(
    handler: (error: any, derivation: IDerivation) => void
): () => void

declare export function onBecomeObserved(
    value: IObservable | IComputedValue<any> | IObservableArray<any> | ObservableMap<any, any>,
    listener: Lambda
): Lambda
declare export function onBecomeObserved<K>(
    value: ObservableMap<K, any> | Object,
    property: K,
    listener: Lambda
): Lambda

declare export function onBecomeUnobserved(
    value: IObservable | IComputedValue<any> | IObservableArray<any> | ObservableMap<any, any>,
    listener: Lambda
): Lambda
declare export function onBecomeUnobserved<K>(
    value: ObservableMap<K, any> | Object,
    property: K,
    listener: Lambda
): Lambda

declare export function getAtom(thing: any, property?: string): IDepTreeNode
declare export function getDebugName(thing: any, property?: string): string
declare export function getDependencyTree(thing: any, property?: string): IDependencyTree
declare export function getObserverTree(thing: any, property?: string): IObserverTree
<|endoftext|>


<commit_before>/*globals Backbone:true, _:true, jQuery:true*/
Backbone.Paginator = (function ( Backbone, _, $ ) {
	"use strict";

	var Paginator = {};
	Paginator.version = "0.15";

	// @name: clientPager
	//
	// @tagline: Paginator for client-side data
	//
	// @description:
	// This paginator is responsible for providing pagination
	// and sort capabilities for a single payload of data
	// we wish to paginate by the UI for easier browsering.
	//
	Paginator.clientPager = Backbone.Collection.extend({

		sortColumn: "ASDFASFS",
		sortDirection: "desc",
		filterFields: "",
		filterExpression: "",

		sync: function ( method, model, options ) {

			var queryMap = {};
				queryMap[this.perPageAttribute] =  this.perPage;
				queryMap[this.skipAttribute] = this.page * this.perPage;
				queryMap[this.orderAttribute] =  this.sortField;
				queryMap[this.customAttribute1] =  this.customParam1;
				queryMap[this.formatAttribute] =  this.format;
				queryMap[this.customAttribute2] = this.customParam2;
				queryMap[this.queryAttribute] =  this.query;

			var params = _.extend({
				type: 'GET',
				dataType: 'jsonp',
				jsonpCallback: 'callback',
				data: decodeURIComponent($.param(queryMap)),
				url: getValue(this, 'url') || urlError(),
				processData: false
			}, options);

			return $.ajax(params);
		},

		nextPage: function () {
			this.page = ++this.page;
			this.pager();
		},

		previousPage: function () {
			this.page = --this.page || 1;
			this.pager();
		},

		goTo: function ( page ) {
			if(page !== undefined){
				this.page = parseInt(page, 10);
				this.pager();
			}
		},

		howManyPer: function ( perPage ) {
			if(perPage !== undefined){
				this.displayPerPage = parseInt(perPage, 10);
				this.page = 1;
				this.pager();
			}
		},

		// where 'column' is the key to sort on
		setSort: function ( column, direction ) {
			if(column !== undefined && direction !== undefined){
				this.sortColumn = column;
				this.sortDirection = direction;
				this.pager();
				this.info();
			}
		},

		setFilter: function ( fields, filter ) {
			if( fields !== undefined && filter !== undefined ){
				this.filterFields = fields;
				this.filterExpression = filter;
				this.pager();
				this.info();
			}
		},

		pager: function () {
			var self = this,
				disp = this.displayPerPage,
				start = (self.page - 1) * disp,
				stop = start + disp;

			if (self.origModels === undefined) {
				self.origModels = self.models;
			}

			self.models = self.origModels;

			if ( this.sortColumn !== "" ) {
				self.models = self._sort(self.models, this.sortColumn, this.sortDirection);
			}

			if ( this.filterExpression !== "" ) {
				self.models = self._filter(self.models, this.filterFields, this.filterExpression);
			}

			self.sortedAndFilteredModels = self.models;

			self.reset(self.models.slice(start, stop));
		},

		_sort: function ( models, sort, direction ) {
			models = models.sort(function (a, b) {
				var ac = a.get(sort),
					bc = b.get(sort);

				if ( !ac || !bc ) {
					return 0;
				} else {
					/* Make sure that both ac and bc are lowercase strings.
					* .toString() first so we don't have to worry if ac or bc
					* have other String-only methods.
					*/
					ac = ac.toString().toLowerCase();
					bc = bc.toString().toLowerCase();
				}

				if (direction === 'desc') {

					if((!ac.match(/[^\d\.]/) && ac.match(/[\d\.]*/)) &&
						(!bc.match(/[^\d\.]/) && bc.match(/[\d\.]*/))
					){

						if( (ac - 0) < (bc - 0) ) {
							return 1;
						}
						if( (ac - 0) > (bc - 0) ) {
							return -1;
						}
					} else {
						if (ac < bc) {
							return 1;
						}
						if (ac > bc) {
							return -1;
						}
					}

				} else {

					if((!ac.match(/[^\d\.]/) && ac.match(/[\d\.]*/)) &&
						(!bc.match(/[^\d\.]/) && bc.match(/[\d\.]*/))
					){
						if( (ac - 0) < (bc - 0) ) {
							return -1;
						}
						if( (ac - 0) > (bc - 0) ) {
							return 1;
						}
					} else {
						if (ac < bc) {
							return -1;
						}
						if (ac > bc) {
							return 1;
						}
					}

				}

				return 0;
			});

			return models;
		},

		_filter: function ( models, fields, filter ) {

			if( _.isString( fields ) ) {
				var tmp_s = fields;
				fields = [];
				fields.push(tmp_s);
			}

			if( filter === '' ) {
				return models;
			} else {
				filter = filter.match(/\w+/ig);
				filter = _.uniq(filter);
				var pattern = "(" + filter.join("|") + ")";
				var regexp = new RegExp(pattern, "igm");
			}

			var filteredModels = [];

			_.each( models, function( model ) {

				_.each( fields, function( field ) {

					var value = model.get( field );

					if( value ) {

						var matches = model.get( field ).toString().match( regexp );
						matches = _.map(matches, function(match) {
							return match.toString().toLowerCase();
						});

						if( _.isEmpty( _.difference(filter, matches) ) ) {
							filteredModels.push(model);
						}

					}

				});

			});

			return filteredModels;
		},

		info: function () {
			var self = this,
				info = {},
				totalRecords = (self.sortedAndFilteredModels) ? self.sortedAndFilteredModels.length : self.length,
				totalPages = Math.ceil(totalRecords / self.displayPerPage);

			info = {
				totalRecords: totalRecords,
				page: self.page,
				perPage: this.displayPerPage,
				totalPages: totalPages,
				lastPage: totalPages,
				lastPagem1: totalPages - 1,
				previous: false,
				next: false,
				page_set: [],
				startRecord: (self.page - 1) * this.displayPerPage + 1,
				endRecord: Math.min(totalRecords, self.page * this.displayPerPage)
			};

			if (self.page > 1) {
				info.prev = self.page - 1;
			}

			if (self.page < info.totalPages) {
				info.next = self.page + 1;
			}

			info.pageSet = self.setPagination(info);

			self.information = info;
			return info;
		},

		setPagination: function ( info ) {
			var pages = [], i = 0, l = 0;

			// How many adjacent pages should be shown on each side?
			var ADJACENT = 3,
				ADJACENTx2 = ADJACENT * 2,
				LASTPAGE = Math.ceil(info.totalRecords / info.perPage),
				LPM1 = -1;

			if (LASTPAGE > 1) {
				// not enough pages to bother breaking it up
				if (LASTPAGE < (7 + ADJACENTx2)) {
					for (i = 1, l = LASTPAGE; i <= l; i++) {
						pages.push(i);
					}
				}
				// enough pages to hide some
				else if (LASTPAGE > (5 + ADJACENTx2)) {

					//close to beginning; only hide later pages
					if (info.page < (1 + ADJACENTx2)) {
						for (i = 1, l = 4 + ADJACENTx2; i < l; i++) {
							pages.push(i);
						}
					}

					// in middle; hide some front and some back
					else if (LASTPAGE - ADJACENTx2 > info.page && info.page > ADJACENTx2) {
						for (i = info.page - ADJACENT; i <= info.page + ADJACENT; i++) {
							pages.push(i);
						}
					}
					// close to end; only hide early pages
					else {
						for (i = LASTPAGE - (2 + ADJACENTx2); i <= LASTPAGE; i++) {
							pages.push(i);
						}
					}
				}
			}

			return pages;
		}

	});

	// @name: requestPager
	//
	// Paginator for server-side data being requested from a backend/API
	//
	// @description:
	// This paginator is responsible for providing pagination
	// and sort capabilities for requests to a server-side
	// data service (e.g an API)
	//
	Paginator.requestPager = Backbone.Collection.extend({

		sync: function ( method, model, options ) {

			var queryMap = {}, params;
				queryMap[this.perPageAttribute] =  this.perPage;
				queryMap[this.skipAttribute] = this.page * this.perPage;
				queryMap[this.orderAttribute] =  this.sortField;
				queryMap[this.customAttribute1] =  this.customParam1;
				queryMap[this.formatAttribute] =  this.format;
				queryMap[this.customAttribute2] = this.customParam2;
				queryMap[this.queryAttribute] =  this.query;

				params = _.extend({
				type: 'GET',
				dataType: 'jsonp',
				jsonpCallback: 'callback',
				data: decodeURIComponent($.param(queryMap)),
				url: getValue(this, 'url') || urlError(),
				processData: false
			}, options);

			return $.ajax(params);
		},

		requestNextPage: function () {
			if ( this.page !== undefined ) {
				this.page += 1;
				// customize as needed. For the Netflix API, skipping ahead based on
				// page * number of results per page was necessary. You may have a
				// simpler server-side pagination API where just updating
				// the 'page' value is all you need to do.
				// This applies similarly to requestPreviousPage()
				this.pager();
			}
		},

		requestPreviousPage: function () {
			if ( this.page !== undefined ) {
				this.page -= 1;
				this.pager();
			}
		},

		updateOrder: function ( column ) {
			if (column !== undefined) {
				this.sortField = column;
				this.pager();
			}

		},

		goTo: function ( page ) {
			if(page !== undefined){
				this.page = parseInt(page, 10);
				this.pager();
			}
		},

		howManyPer: function ( count ) {
			if( count !== undefined ){
				this.page = this.firstPage;
				this.perPage = count;
				this.pager();
			}
		},

		sort: function () {
			//assign to as needed.
		},

		info: function () {

			var info = {
				page: this.page,
				firstPage: this.firstPage,
				totalPages: this.totalPages,
				lastPage: this.totalPages,
				perPage: this.perPage
			};

			this.information = info;
			return info;
		},

		// fetches the latest results from the server
		pager: function () {
			this.fetch({});
		}

	});

	// Helper function to get a value from a Backbone object as a property
	// or as a function.
	var getValue = function(object, prop) {
		if ( !(object && object[prop]) ) {
			return null;
		}
		return _.isFunction(object[prop]) ? object[prop]() : object[prop];
	};

	// Throw an error when a URL is needed, and none is supplied.
	var urlError = function() {
		throw new Error('A "url" property or function must be specified');
	};

	return Paginator;

}( Backbone, _, jQuery ));<commit_msg>There is no need of getValue() as an external function. We already have that with _.result() from underscore.js .<commit_after>/*globals Backbone:true, _:true, jQuery:true*/
Backbone.Paginator = (function ( Backbone, _, $ ) {
	"use strict";

	var Paginator = {};
	Paginator.version = "0.15";

	// @name: clientPager
	//
	// @tagline: Paginator for client-side data
	//
	// @description:
	// This paginator is responsible for providing pagination
	// and sort capabilities for a single payload of data
	// we wish to paginate by the UI for easier browsering.
	//
	Paginator.clientPager = Backbone.Collection.extend({

		sortColumn: "ASDFASFS",
		sortDirection: "desc",
		filterFields: "",
		filterExpression: "",

		sync: function ( method, model, options ) {

			var queryMap = {};
				queryMap[this.perPageAttribute] =  this.perPage;
				queryMap[this.skipAttribute] = this.page * this.perPage;
				queryMap[this.orderAttribute] =  this.sortField;
				queryMap[this.customAttribute1] =  this.customParam1;
				queryMap[this.formatAttribute] =  this.format;
				queryMap[this.customAttribute2] = this.customParam2;
				queryMap[this.queryAttribute] =  this.query;

			var params = _.extend({
				type: 'GET',
				dataType: 'jsonp',
				jsonpCallback: 'callback',
				data: decodeURIComponent($.param(queryMap)),
				url: _.result(this, 'url'),
				processData: false
			}, options);

			return $.ajax(params);
		},

		nextPage: function () {
			this.page = ++this.page;
			this.pager();
		},

		previousPage: function () {
			this.page = --this.page || 1;
			this.pager();
		},

		goTo: function ( page ) {
			if(page !== undefined){
				this.page = parseInt(page, 10);
				this.pager();
			}
		},

		howManyPer: function ( perPage ) {
			if(perPage !== undefined){
				this.displayPerPage = parseInt(perPage, 10);
				this.page = 1;
				this.pager();
			}
		},

		// where 'column' is the key to sort on
		setSort: function ( column, direction ) {
			if(column !== undefined && direction !== undefined){
				this.sortColumn = column;
				this.sortDirection = direction;
				this.pager();
				this.info();
			}
		},

		setFilter: function ( fields, filter ) {
			if( fields !== undefined && filter !== undefined ){
				this.filterFields = fields;
				this.filterExpression = filter;
				this.pager();
				this.info();
			}
		},

		pager: function () {
			var self = this,
				disp = this.displayPerPage,
				start = (self.page - 1) * disp,
				stop = start + disp;

			if (self.origModels === undefined) {
				self.origModels = self.models;
			}

			self.models = self.origModels;

			if ( this.sortColumn !== "" ) {
				self.models = self._sort(self.models, this.sortColumn, this.sortDirection);
			}

			if ( this.filterExpression !== "" ) {
				self.models = self._filter(self.models, this.filterFields, this.filterExpression);
			}

			self.sortedAndFilteredModels = self.models;

			self.reset(self.models.slice(start, stop));
		},

		_sort: function ( models, sort, direction ) {
			models = models.sort(function (a, b) {
				var ac = a.get(sort),
					bc = b.get(sort);

				if ( !ac || !bc ) {
					return 0;
				} else {
					/* Make sure that both ac and bc are lowercase strings.
					* .toString() first so we don't have to worry if ac or bc
					* have other String-only methods.
					*/
					ac = ac.toString().toLowerCase();
					bc = bc.toString().toLowerCase();
				}

				if (direction === 'desc') {

					if((!ac.match(/[^\d\.]/) && ac.match(/[\d\.]*/)) &&
						(!bc.match(/[^\d\.]/) && bc.match(/[\d\.]*/))
					){

						if( (ac - 0) < (bc - 0) ) {
							return 1;
						}
						if( (ac - 0) > (bc - 0) ) {
							return -1;
						}
					} else {
						if (ac < bc) {
							return 1;
						}
						if (ac > bc) {
							return -1;
						}
					}

				} else {

					if((!ac.match(/[^\d\.]/) && ac.match(/[\d\.]*/)) &&
						(!bc.match(/[^\d\.]/) && bc.match(/[\d\.]*/))
					){
						if( (ac - 0) < (bc - 0) ) {
							return -1;
						}
						if( (ac - 0) > (bc - 0) ) {
							return 1;
						}
					} else {
						if (ac < bc) {
							return -1;
						}
						if (ac > bc) {
							return 1;
						}
					}

				}

				return 0;
			});

			return models;
		},

		_filter: function ( models, fields, filter ) {

			if( _.isString( fields ) ) {
				var tmp_s = fields;
				fields = [];
				fields.push(tmp_s);
			}

			if( filter === '' ) {
				return models;
			} else {
				filter = filter.match(/\w+/ig);
				filter = _.uniq(filter);
				var pattern = "(" + filter.join("|") + ")";
				var regexp = new RegExp(pattern, "igm");
			}

			var filteredModels = [];

			_.each( models, function( model ) {

				_.each( fields, function( field ) {

					var value = model.get( field );

					if( value ) {

						var matches = model.get( field ).toString().match( regexp );
						matches = _.map(matches, function(match) {
							return match.toString().toLowerCase();
						});

						if( _.isEmpty( _.difference(filter, matches) ) ) {
							filteredModels.push(model);
						}

					}

				});

			});

			return filteredModels;
		},

		info: function () {
			var self = this,
				info = {},
				totalRecords = (self.sortedAndFilteredModels) ? self.sortedAndFilteredModels.length : self.length,
				totalPages = Math.ceil(totalRecords / self.displayPerPage);

			info = {
				totalRecords: totalRecords,
				page: self.page,
				perPage: this.displayPerPage,
				totalPages: totalPages,
				lastPage: totalPages,
				lastPagem1: totalPages - 1,
				previous: false,
				next: false,
				page_set: [],
				startRecord: (self.page - 1) * this.displayPerPage + 1,
				endRecord: Math.min(totalRecords, self.page * this.displayPerPage)
			};

			if (self.page > 1) {
				info.prev = self.page - 1;
			}

			if (self.page < info.totalPages) {
				info.next = self.page + 1;
			}

			info.pageSet = self.setPagination(info);

			self.information = info;
			return info;
		},

		setPagination: function ( info ) {
			var pages = [], i = 0, l = 0;

			// How many adjacent pages should be shown on each side?
			var ADJACENT = 3,
				ADJACENTx2 = ADJACENT * 2,
				LASTPAGE = Math.ceil(info.totalRecords / info.perPage),
				LPM1 = -1;

			if (LASTPAGE > 1) {
				// not enough pages to bother breaking it up
				if (LASTPAGE < (7 + ADJACENTx2)) {
					for (i = 1, l = LASTPAGE; i <= l; i++) {
						pages.push(i);
					}
				}
				// enough pages to hide some
				else if (LASTPAGE > (5 + ADJACENTx2)) {

					//close to beginning; only hide later pages
					if (info.page < (1 + ADJACENTx2)) {
						for (i = 1, l = 4 + ADJACENTx2; i < l; i++) {
							pages.push(i);
						}
					}

					// in middle; hide some front and some back
					else if (LASTPAGE - ADJACENTx2 > info.page && info.page > ADJACENTx2) {
						for (i = info.page - ADJACENT; i <= info.page + ADJACENT; i++) {
							pages.push(i);
						}
					}
					// close to end; only hide early pages
					else {
						for (i = LASTPAGE - (2 + ADJACENTx2); i <= LASTPAGE; i++) {
							pages.push(i);
						}
					}
				}
			}

			return pages;
		}

	});

	// @name: requestPager
	//
	// Paginator for server-side data being requested from a backend/API
	//
	// @description:
	// This paginator is responsible for providing pagination
	// and sort capabilities for requests to a server-side
	// data service (e.g an API)
	//
	Paginator.requestPager = Backbone.Collection.extend({

		sync: function ( method, model, options ) {

			var queryMap = {}, params;
				queryMap[this.perPageAttribute] =  this.perPage;
				queryMap[this.skipAttribute] = this.page * this.perPage;
				queryMap[this.orderAttribute] =  this.sortField;
				queryMap[this.customAttribute1] =  this.customParam1;
				queryMap[this.formatAttribute] =  this.format;
				queryMap[this.customAttribute2] = this.customParam2;
				queryMap[this.queryAttribute] =  this.query;

				params = _.extend({
				type: 'GET',
				dataType: 'jsonp',
				jsonpCallback: 'callback',
				data: decodeURIComponent($.param(queryMap)),
				url: _.result(this, 'url'),
				processData: false
			}, options);

			return $.ajax(params);
		},

		requestNextPage: function () {
			if ( this.page !== undefined ) {
				this.page += 1;
				// customize as needed. For the Netflix API, skipping ahead based on
				// page * number of results per page was necessary. You may have a
				// simpler server-side pagination API where just updating
				// the 'page' value is all you need to do.
				// This applies similarly to requestPreviousPage()
				this.pager();
			}
		},

		requestPreviousPage: function () {
			if ( this.page !== undefined ) {
				this.page -= 1;
				this.pager();
			}
		},

		updateOrder: function ( column ) {
			if (column !== undefined) {
				this.sortField = column;
				this.pager();
			}

		},

		goTo: function ( page ) {
			if(page !== undefined){
				this.page = parseInt(page, 10);
				this.pager();
			}
		},

		howManyPer: function ( count ) {
			if( count !== undefined ){
				this.page = this.firstPage;
				this.perPage = count;
				this.pager();
			}
		},

		sort: function () {
			//assign to as needed.
		},

		info: function () {

			var info = {
				page: this.page,
				firstPage: this.firstPage,
				totalPages: this.totalPages,
				lastPage: this.totalPages,
				perPage: this.perPage
			};

			this.information = info;
			return info;
		},

		// fetches the latest results from the server
		pager: function () {
			this.fetch({});
		}

	});

	return Paginator;

}( Backbone, _, jQuery ));<|endoftext|>


<commit_before>var debugProtocol = require('debug')('node-inspector:protocol:devtools');

var RuntimeAgent = require('./RuntimeAgent').RuntimeAgent,
  PageAgent = require('./PageAgent').PageAgent,
  NetworkAgent = require('./NetworkAgent').NetworkAgent,
  DebuggerAgent = require('./DebuggerAgent').DebuggerAgent;

/**
 * @param {Object} config
 * @param {FrontendClient} frontendClient
 * @param {DebuggerClient} debuggerClient
 * @param {BreakEventHandler} breakEventHandler
 * @param {ScriptManager} scriptManager
 * @param {InjectorClient} injectorClient
 */
function FrontendCommandHandler(config,
                                frontendClient,
                                debuggerClient,
                                breakEventHandler,
                                scriptManager,
                                injectorClient) {
  this._config = config;
  this._agents = {};
  this._specialCommands = {};
  this._frontendClient = frontendClient;
  this._debuggerClient = debuggerClient;
  this._breakEventHandler = breakEventHandler;
  this._scriptManager = scriptManager;
  this._injectorClient = injectorClient;
  this._initializeRegistry();
  this._registerEventHandlers();
  this._pauseInitialEvents();
}

FrontendCommandHandler.prototype = {
  _initializeRegistry: function() {
    this._registerAgent(
      'Debugger',
      new DebuggerAgent(
        this._config,
        this._frontendClient,
        this._debuggerClient,
        this._breakEventHandler,
        this._scriptManager,
        this._injectorClient)
    );

    this._registerAgent('Runtime', new RuntimeAgent(this._config, this._debuggerClient));

    this._registerAgent(
      'Page',
      new PageAgent(
        this._config,
        this._debuggerClient,
        this._scriptManager)
    );

    this._registerAgent('Network', new NetworkAgent());

    this._registerNoopCommands(
      'Network.enable',
      'Console.enable',
      'Console.clearMessages',
      'Database.enable',
      'DOMStorage.enable',
      'DOM.hideHighlight',
      'Inspector.enable',
      'Page.clearDeviceOrientationOverride',
      'Page.clearGeolocationOverride',
      'Page.setContinuousPaintingEnabled',
      'Page.setEmulatedMedia',
      'Page.setDeviceMetricsOverride',
      'Page.setShowDebugBorders',
      'Page.setShowFPSCounter',
      'Page.setShowScrollBottleneckRects',
      'Page.setShowViewportSizeOnResize',
      'Profiler.enable',
      'CSS.enable'
    );

    this._registerQuery('CSS.getSupportedCSSProperties', { cssProperties: []});
    this._registerQuery('Worker.canInspectWorkers', { result: false });
    this._registerQuery('Page.getScriptExecutionStatus', { result: 'enabled' });
  },

  _registerAgent: function(name, agent) {
    this._agents[name] = agent;
  },

  _registerNoopCommands: function() {
    var i, fullMethodName;
    for (i = 0; i < arguments.length; i++) {
      fullMethodName = arguments[i];
      this._specialCommands[fullMethodName] = {};
    }
  },

  _registerQuery: function(fullMethodName, result) {
    this._specialCommands[fullMethodName] = { result: result };
  },

  _registerEventHandlers: function() {
    this._frontendClient.on(
      'message',
       this._handleFrontendMessage.bind(this));
  },

  _handleFrontendMessage: function(message) {
    debugProtocol('frontend: ' + message);
    var command = JSON.parse(message);
    this.handleCommand(command);
  },

  _pauseInitialEvents: function() {
    this._frontendClient.pauseEvents();
    this._agents.Page.on('resource-tree', function() {
      this._frontendClient.resumeEvents();
    }.bind(this));
  },

  handleCommand: function(messageObject) {
    var fullMethodName = messageObject.method,
      domainAndMethod = fullMethodName.split('.'),
      domainName = domainAndMethod[0],
      methodName = domainAndMethod[1],
      requestId = messageObject.id,
      agent,
      method;

    if (this._specialCommands[fullMethodName]) {
      this._handleMethodResult(
        requestId,
        fullMethodName,
        null,
        this._specialCommands[fullMethodName].result);
      return;
    }

    agent = this._agents[domainName];
    if (!agent) {
      this._sendNotImplementedResponse(requestId, fullMethodName);
      return;
    }

    method = agent[methodName];
    if (!method || typeof method !== 'function') {
      this._sendNotImplementedResponse(requestId, fullMethodName);
      return;
    }

    method.call(agent, messageObject.params, function(error, result) {
      this._handleMethodResult(messageObject.id, fullMethodName, error, result);
    }.bind(this));
  },

  _sendNotImplementedResponse: function(requestId, fullMethodName) {
    console.log(
      'Received request for a method not implemented:',
      fullMethodName
    );

    this._handleMethodResult(
      requestId,
      fullMethodName,
      new Error('Not implemented.')
    );
  },

  _handleMethodResult: function(requestId, fullMethodName, error, result) {
    var response;

    if (!requestId) {
      if (response !== undefined)
        console.log('Warning: discarded result of ' + fullMethodName);
      return;
    }

    this._frontendClient.sendResponse(requestId, fullMethodName, error, result);
  }
};

exports.FrontendCommandHandler = FrontendCommandHandler;
<commit_msg>Extend noop-commands list<commit_after>var debugProtocol = require('debug')('node-inspector:protocol:devtools');

var RuntimeAgent = require('./RuntimeAgent').RuntimeAgent,
  PageAgent = require('./PageAgent').PageAgent,
  NetworkAgent = require('./NetworkAgent').NetworkAgent,
  DebuggerAgent = require('./DebuggerAgent').DebuggerAgent;

/**
 * @param {Object} config
 * @param {FrontendClient} frontendClient
 * @param {DebuggerClient} debuggerClient
 * @param {BreakEventHandler} breakEventHandler
 * @param {ScriptManager} scriptManager
 * @param {InjectorClient} injectorClient
 */
function FrontendCommandHandler(config,
                                frontendClient,
                                debuggerClient,
                                breakEventHandler,
                                scriptManager,
                                injectorClient) {
  this._config = config;
  this._agents = {};
  this._specialCommands = {};
  this._frontendClient = frontendClient;
  this._debuggerClient = debuggerClient;
  this._breakEventHandler = breakEventHandler;
  this._scriptManager = scriptManager;
  this._injectorClient = injectorClient;
  this._initializeRegistry();
  this._registerEventHandlers();
  this._pauseInitialEvents();
}

FrontendCommandHandler.prototype = {
  _initializeRegistry: function() {
    this._registerAgent(
      'Debugger',
      new DebuggerAgent(
        this._config,
        this._frontendClient,
        this._debuggerClient,
        this._breakEventHandler,
        this._scriptManager,
        this._injectorClient)
    );

    this._registerAgent('Runtime', new RuntimeAgent(this._config, this._debuggerClient));

    this._registerAgent(
      'Page',
      new PageAgent(
        this._config,
        this._debuggerClient,
        this._scriptManager)
    );

    this._registerAgent('Network', new NetworkAgent());

    //TODO(3y3):
    //  Remove next from noop before closing #341:
    //  - DOMDebugger.setXHRBreakpoint
    //  - DOMDebugger.removeXHRBreakpoint
    this._registerNoopCommands(
      'Network.enable',
      'Network.setCacheDisabled',
      'Console.enable',
      'Console.clearMessages',
      'Console.setMonitoringXHREnabled',
      'Database.enable',
      'DOMDebugger.setXHRBreakpoint',
      'DOMDebugger.removeXHRBreakpoint',
      'DOMDebugger.setInstrumentationBreakpoint',
      'DOMDebugger.removeInstrumentationBreakpoint',
      'DOMStorage.enable',
      'DOM.hideHighlight',
      'Inspector.enable',
      'Page.addScriptToEvaluateOnLoad',
      'Page.removeScriptToEvaluateOnLoad',
      'Page.setDeviceOrientationOverride',
      'Page.clearDeviceOrientationOverride',
      'Page.setGeolocationOverride',
      'Page.clearGeolocationOverride',
      'Page.setContinuousPaintingEnabled',
      'Page.setEmulatedMedia',
      'Page.setDeviceMetricsOverride',
      'Page.setScriptExecutionDisabled',
      'Page.setShowDebugBorders',
      'Page.setShowFPSCounter',
      'Page.setShowScrollBottleneckRects',
      'Page.setShowViewportSizeOnResize',
      'Page.setShowPaintRects',
      'Page.setForceCompositingMode',
      'Profiler.enable',
      'CSS.enable'
    );

    this._registerQuery('CSS.getSupportedCSSProperties', { cssProperties: []});
    this._registerQuery('Worker.canInspectWorkers', { result: false });
    this._registerQuery('Page.getScriptExecutionStatus', { result: 'enabled' });
  },

  _registerAgent: function(name, agent) {
    this._agents[name] = agent;
  },

  _registerNoopCommands: function() {
    var i, fullMethodName;
    for (i = 0; i < arguments.length; i++) {
      fullMethodName = arguments[i];
      this._specialCommands[fullMethodName] = {};
    }
  },

  _registerQuery: function(fullMethodName, result) {
    this._specialCommands[fullMethodName] = { result: result };
  },

  _registerEventHandlers: function() {
    this._frontendClient.on(
      'message',
       this._handleFrontendMessage.bind(this));
  },

  _handleFrontendMessage: function(message) {
    debugProtocol('frontend: ' + message);
    var command = JSON.parse(message);
    this.handleCommand(command);
  },

  _pauseInitialEvents: function() {
    this._frontendClient.pauseEvents();
    this._agents.Page.on('resource-tree', function() {
      this._frontendClient.resumeEvents();
    }.bind(this));
  },

  handleCommand: function(messageObject) {
    var fullMethodName = messageObject.method,
      domainAndMethod = fullMethodName.split('.'),
      domainName = domainAndMethod[0],
      methodName = domainAndMethod[1],
      requestId = messageObject.id,
      agent,
      method;

    if (this._specialCommands[fullMethodName]) {
      this._handleMethodResult(
        requestId,
        fullMethodName,
        null,
        this._specialCommands[fullMethodName].result);
      return;
    }

    agent = this._agents[domainName];
    if (!agent) {
      this._sendNotImplementedResponse(requestId, fullMethodName);
      return;
    }

    method = agent[methodName];
    if (!method || typeof method !== 'function') {
      this._sendNotImplementedResponse(requestId, fullMethodName);
      return;
    }

    method.call(agent, messageObject.params, function(error, result) {
      this._handleMethodResult(messageObject.id, fullMethodName, error, result);
    }.bind(this));
  },

  _sendNotImplementedResponse: function(requestId, fullMethodName) {
    console.log(
      'Received request for a method not implemented:',
      fullMethodName
    );

    this._handleMethodResult(
      requestId,
      fullMethodName,
      new Error('Not implemented.')
    );
  },

  _handleMethodResult: function(requestId, fullMethodName, error, result) {
    var response;

    if (!requestId) {
      if (response !== undefined)
        console.log('Warning: discarded result of ' + fullMethodName);
      return;
    }

    this._frontendClient.sendResponse(requestId, fullMethodName, error, result);
  }
};

exports.FrontendCommandHandler = FrontendCommandHandler;
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var axios = require('axios');
var fs = require('fs');
var http = require('http');
var https = require('https');
var Q = require('q');
var qs = require('qs');
var Response = require('../http/response');
var Request = require('../http/request');

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

var RequestClient = function() {};

/**
 * Make http request
 * @param {object} opts - The options argument
 * @param {string} opts.method - The http method
 * @param {string} opts.uri - The request uri
 * @param {string} [opts.username] - The username used for auth
 * @param {string} [opts.password] - The password used for auth
 * @param {object} [opts.headers] - The request headers
 * @param {object} [opts.params] - The request params
 * @param {object} [opts.data] - The request data
 * @param {int} [opts.timeout=30000] - The request timeout in milliseconds
 * @param {boolean} [opts.allowRedirects] - Should the client follow redirects
 * @param {boolean} [opts.forever] - Set to true to use the forever-agent
 */
RequestClient.prototype.request = function(opts) {
  opts = opts || {};
  if (!opts.method) {
    throw new Error('http method is required');
  }

  if (!opts.uri) {
    throw new Error('uri is required');
  }

  var deferred = Q.defer();
  var headers = opts.headers || {};

  if (!headers.Connection && !headers.connection) {
    headers.Connection = 'close';
  }

  if (opts.username && opts.password) {
    var b64Auth = Buffer.from(opts.username + ':' + opts.password).toString('base64');
    headers.Authorization = 'Basic ' + b64Auth;
  }

  var options = {
    timeout: opts.timeout || 30000,
    maxRedirects: opts.allowRedirects ? 10 : 0, // Same number of allowed redirects as request module default
    url: opts.uri,
    method: opts.method,
    headers: opts.headers,
    httpAgent: opts.forever ? new http.Agent({ keepAlive: true }) : undefined,
    httpsAgent: opts.forever ? new https.Agent({ keepAlive: true }) : undefined,
    validateStatus: status => status >= 100 && status < 600,
  };

  if (process.env.TWILIO_CA_BUNDLE !== undefined) {
    if (this.ca === undefined) {
      this.ca = fs.readFileSync(process.env.TWILIO_CA_BUNDLE);
    }
    options.ca = this.ca;
  }

  if (!_.isNull(opts.data)) {
    options.data = qs.stringify(opts.data, { arrayFormat: 'repeat'});
  }

  if (!_.isNull(opts.params)) {
    options.params = opts.params;
    options.paramSerializer = (params) => {
      return qs.stringify(params, { arrayFormat: 'repeat' });
    };
  }

  var optionsRequest = {
    method: options.method,
    url: options.url,
    auth: b64Auth || null,
    params: options.params,
    data: opts.data,
    headers: options.headers,
    ca: options.ca
  };

  var _this = this;
  this.lastResponse = undefined;
  this.lastRequest = new Request(optionsRequest);

  axios(options).then((response) => {
    _this.lastResponse = new Response(response.status, response.data);
    deferred.resolve({
      statusCode: response.status,
      body: response.data,
    });
  }).catch((error) => {
    _this.lastResponse = undefined;
    deferred.reject(error);
  });

  return deferred.promise;
};

module.exports = RequestClient;
<commit_msg>fix: axios expects paramsSerializer not paramSerializer (#551)<commit_after>'use strict';

var _ = require('lodash');
var axios = require('axios');
var fs = require('fs');
var http = require('http');
var https = require('https');
var Q = require('q');
var qs = require('qs');
var Response = require('../http/response');
var Request = require('../http/request');

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

var RequestClient = function() {};

/**
 * Make http request
 * @param {object} opts - The options argument
 * @param {string} opts.method - The http method
 * @param {string} opts.uri - The request uri
 * @param {string} [opts.username] - The username used for auth
 * @param {string} [opts.password] - The password used for auth
 * @param {object} [opts.headers] - The request headers
 * @param {object} [opts.params] - The request params
 * @param {object} [opts.data] - The request data
 * @param {int} [opts.timeout=30000] - The request timeout in milliseconds
 * @param {boolean} [opts.allowRedirects] - Should the client follow redirects
 * @param {boolean} [opts.forever] - Set to true to use the forever-agent
 */
RequestClient.prototype.request = function(opts) {
  opts = opts || {};
  if (!opts.method) {
    throw new Error('http method is required');
  }

  if (!opts.uri) {
    throw new Error('uri is required');
  }

  var deferred = Q.defer();
  var headers = opts.headers || {};

  if (!headers.Connection && !headers.connection) {
    headers.Connection = 'close';
  }

  if (opts.username && opts.password) {
    var b64Auth = Buffer.from(opts.username + ':' + opts.password).toString('base64');
    headers.Authorization = 'Basic ' + b64Auth;
  }

  var options = {
    timeout: opts.timeout || 30000,
    maxRedirects: opts.allowRedirects ? 10 : 0, // Same number of allowed redirects as request module default
    url: opts.uri,
    method: opts.method,
    headers: opts.headers,
    httpAgent: opts.forever ? new http.Agent({ keepAlive: true }) : undefined,
    httpsAgent: opts.forever ? new https.Agent({ keepAlive: true }) : undefined,
    validateStatus: status => status >= 100 && status < 600,
  };

  if (process.env.TWILIO_CA_BUNDLE !== undefined) {
    if (this.ca === undefined) {
      this.ca = fs.readFileSync(process.env.TWILIO_CA_BUNDLE);
    }
    options.ca = this.ca;
  }

  if (!_.isNull(opts.data)) {
    options.data = qs.stringify(opts.data, { arrayFormat: 'repeat'});
  }

  if (!_.isNull(opts.params)) {
    options.params = opts.params;
    options.paramsSerializer = (params) => {
      return qs.stringify(params, { arrayFormat: 'repeat' });
    };
  }

  var optionsRequest = {
    method: options.method,
    url: options.url,
    auth: b64Auth || null,
    params: options.params,
    data: opts.data,
    headers: options.headers,
    ca: options.ca
  };

  var _this = this;
  this.lastResponse = undefined;
  this.lastRequest = new Request(optionsRequest);

  axios(options).then((response) => {
    _this.lastResponse = new Response(response.status, response.data);
    deferred.resolve({
      statusCode: response.status,
      body: response.data,
    });
  }).catch((error) => {
    _this.lastResponse = undefined;
    deferred.reject(error);
  });

  return deferred.promise;
};

module.exports = RequestClient;
<|endoftext|>


<commit_before>import React from 'react';
import SPELLS from 'common/SPELLS';

import Analyzer from 'Parser/Core/Analyzer';
import Enemies from 'Parser/Core/Modules/Enemies';
import Combatants from 'Parser/Core/Modules/Combatants';
import StatTracker from 'Parser/Core/Modules/StatTracker';

import SpellIcon from 'common/SpellIcon';
import { formatPercentage } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import AbilityTracker from 'Parser/Core/Modules/AbilityTracker';

class TouchOfDeath extends Analyzer {
  static dependencies = {
    combatants: Combatants,
    enemies: Enemies,
    statTracker: StatTracker,
    abilityTracker: AbilityTracker,
  };

  expectedBaseDamage = 0;
  expectedGaleBurst = 0;
  totalGaleBurst = 0;
  highestGaleBurst = 0;
  // Vulnerability amplifiers are target specific damage taken increases like seen on Kin'garoth adds.
  highestVulnerabilityAmplifier = 0;
  totalVulnerabilityAmplifier = 0;

  on_byPlayer_cast(event) {
    const spellId = event.ability.guid;
    if (SPELLS.TOUCH_OF_DEATH.id !== spellId) {
      return;
    }
    this.expectedGaleBurst = 0;
    const masteryPercentage = this.statTracker.currentMasteryPercentage;
    const versatilityPercentage = this.statTracker.currentVersatilityPercentage;
    this.expectedBaseDamage = event.maxHitPoints * 0.5 * (1 + masteryPercentage) * (1 + versatilityPercentage);
  }

  on_byPlayer_damage(event) {
    const spellId = event.ability.guid;
    const enemy = this.enemies.getEntity(event);
    // Gale Burst does not count damage from clones, but rather takes increased damage from the player while Storm, Earth, and Fire is active
    const sefMultiplier = this.combatants.selected.hasBuff(SPELLS.STORM_EARTH_AND_FIRE_CAST.id) ? 0.3: 0.1;
    if (!enemy) {
      return;
    }
    if (enemy.hasBuff(SPELLS.TOUCH_OF_DEATH.id) && SPELLS.TOUCH_OF_DEATH_DAMAGE.id !== spellId) {
      this.expectedGaleBurst += (event.amount + (event.absorbed || 0)) * sefMultiplier;
    }
    if (SPELLS.TOUCH_OF_DEATH_DAMAGE.id !== spellId) {
      return;
    }
    const expectedTotalDamage = this.expectedGaleBurst + this.expectedBaseDamage;
    const vulnerabilityAmplifier = ((event.amount / expectedTotalDamage) - 1);
    if (vulnerabilityAmplifier > this.highestVulnerabilityAmplifier) {
      this.highestVulnerabilityAmplifier = vulnerabilityAmplifier;
    }
    const actualGaleBurst = this.expectedGaleBurst * (1 + vulnerabilityAmplifier);
    if (actualGaleBurst > this.highestGaleBurst) {
      this.highestGaleBurst = actualGaleBurst;
    }
    this.totalVulnerabilityAmplifier += vulnerabilityAmplifier;
    this.totalGaleBurst += actualGaleBurst
  }

  statistic() {
    const averageVulnerabilityAmplifier = this.totalVulnerabilityAmplifier / this.abilityTracker.getAbility(SPELLS.TOUCH_OF_DEATH.id).casts;
    const averageGaleBurst = this.totalGaleBurst / this.abilityTracker.getAbility(SPELLS.TOUCH_OF_DEATH.id).casts;
    return (
      <StatisticBox
        icon={<SpellIcon id={SPELLS.GALE_BURST_DAMAGE.id} />}
        value={`${(averageGaleBurst / 1000000).toFixed(2)} million`}
        label={`Average Gale Burst`}
        tooltip={`Damage done with Touch of Death is affected by % damage taken buffs on its target. This causes damage done by other abilities during the Gale burst window to benefit twice from those debuffs, due to the increase to their own hits as well as the Gale Burst component of Touch of Death .

 Your average modifier on Touch of Death was ~${((averageVulnerabilityAmplifier * 100).toFixed())}% and your highest was ~${(this.highestVulnerabilityAmplifier * 100).toFixed()}%. Your highest Gale Burst was ${(this.highestGaleBurst / 1000000).toFixed(2)} million `}
      />
    );
  }
}

export default TouchOfDeath;
<commit_msg>[Windwalker] Final cleanup in Touch of Death module<commit_after>import React from 'react';
import SPELLS from 'common/SPELLS';

import Analyzer from 'Parser/Core/Analyzer';
import Enemies from 'Parser/Core/Modules/Enemies';
import Combatants from 'Parser/Core/Modules/Combatants';
import StatTracker from 'Parser/Core/Modules/StatTracker';

import SpellIcon from 'common/SpellIcon';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import AbilityTracker from 'Parser/Core/Modules/AbilityTracker';

class TouchOfDeath extends Analyzer {
  static dependencies = {
    combatants: Combatants,
    enemies: Enemies,
    statTracker: StatTracker,
    abilityTracker: AbilityTracker,
  };

  expectedBaseDamage = 0;
  expectedGaleBurst = 0;
  totalGaleBurst = 0;
  highestGaleBurst = 0;
  // Vulnerability amplifiers are target specific damage taken increases like seen on Kin'garoth adds.
  highestVulnerabilityAmplifier = 0;
  totalVulnerabilityAmplifier = 0;

  on_byPlayer_cast(event) {
    const spellId = event.ability.guid;
    if (SPELLS.TOUCH_OF_DEATH.id !== spellId) {
      return;
    }
    this.expectedGaleBurst = 0;
    const masteryPercentage = this.statTracker.currentMasteryPercentage;
    const versatilityPercentage = this.statTracker.currentVersatilityPercentage;
    this.expectedBaseDamage = event.maxHitPoints * 0.5 * (1 + masteryPercentage) * (1 + versatilityPercentage);
  }

  on_byPlayer_damage(event) {
    const spellId = event.ability.guid;
    const enemy = this.enemies.getEntity(event);
    // Gale Burst does not count damage from clones, but rather takes increased damage from the player while Storm, Earth, and Fire is active
    const sefMultiplier = this.combatants.selected.hasBuff(SPELLS.STORM_EARTH_AND_FIRE_CAST.id) ? 0.3: 0.1;
    if (!enemy) {
      return;
    }
    if (enemy.hasBuff(SPELLS.TOUCH_OF_DEATH.id) && SPELLS.TOUCH_OF_DEATH_DAMAGE.id !== spellId) {
      this.expectedGaleBurst += (event.amount + (event.absorbed || 0)) * sefMultiplier;
    }
    if (SPELLS.TOUCH_OF_DEATH_DAMAGE.id !== spellId) {
      return;
    }
    const expectedTotalDamage = this.expectedGaleBurst + this.expectedBaseDamage;
    const vulnerabilityAmplifier = ((event.amount / expectedTotalDamage) - 1);
    if (vulnerabilityAmplifier > this.highestVulnerabilityAmplifier) {
      this.highestVulnerabilityAmplifier = vulnerabilityAmplifier;
    }
    const actualGaleBurst = this.expectedGaleBurst * (1 + vulnerabilityAmplifier);
    if (actualGaleBurst > this.highestGaleBurst) {
      this.highestGaleBurst = actualGaleBurst;
    }
    this.totalVulnerabilityAmplifier += vulnerabilityAmplifier;
    this.totalGaleBurst += actualGaleBurst;
  }

  statistic() {
    const averageVulnerabilityAmplifier = this.totalVulnerabilityAmplifier / this.abilityTracker.getAbility(SPELLS.TOUCH_OF_DEATH.id).casts;
    const averageGaleBurst = this.totalGaleBurst / this.abilityTracker.getAbility(SPELLS.TOUCH_OF_DEATH.id).casts;
    return (
      <StatisticBox
        icon={<SpellIcon id={SPELLS.GALE_BURST_DAMAGE.id} />}
        value={`${(averageGaleBurst / 1000000).toFixed(2)} million`}
        label={`Average Gale Burst`}
        tooltip={`Damage done with Touch of Death is affected by % damage taken buffs on its target. This causes damage done by other abilities during the Gale burst window to benefit twice from those debuffs, due to the increase to their own hits as well as the Gale Burst component of Touch of Death .

 Your average modifier on Touch of Death was ~${((averageVulnerabilityAmplifier * 100).toFixed())}% and your highest was ~${(this.highestVulnerabilityAmplifier * 100).toFixed()}%. Your highest Gale Burst was ${(this.highestGaleBurst / 1000000).toFixed(2)} million `}
      />
    );
  }
  statisticOrder = STATISTIC_ORDER.CORE(12);
}

export default TouchOfDeath;
<|endoftext|>