<commit_before>"use strict";
/* DEPENDENCIES */

var net = require('net')
  , appLogger = require('../../../logger.js').get('appium')
  , _ = require('underscore')
  , messages = require('./remote-messages.js')
  , atoms = require('./webdriver-atoms')
  , status = require("../../uiauto/lib/status")
  , bplistCreate = require('node-bplist-creator')
  , bplistParse = require('bplist-parser')
  , bufferpack = require('bufferpack')
  , uuid = require('node-uuid')
  , colors = require('colors')
  , noop = function () {}
  , assert = require('assert')
  , util = require('util');

var logger = {
  info: function(msg) {
    appLogger.info("[REMOTE] " + msg);
  }
  , debug: function(msg) {
    appLogger.debug(("[REMOTE] " + msg).grey);
  }
  , error: function(msg) {
    appLogger.error("[REMOTE] " + msg);
  }
};

// ====================================
// CONFIG
// ====================================

var RemoteDebugger = function(onDisconnect) {
  this.socket = null;
  this.connId = uuid.v4();
  this.senderId = uuid.v4();
  this.appIdKey = null;
  this.pageIdKey = null;
  this.pageLoading = false;
  this.curMsgId = 0;
  this.dataCbs = {};
  this.onAppDisconnect = onDisconnect || noop;
  this.pageChangeCb = noop;
  this.specialCbs = {
    '_rpc_reportIdentifier:': noop
    , '_rpc_forwardGetListing:': noop
    , 'connect': noop
  };
  this.pageLoadedCbs = [];
  this.setHandlers();
  this.received = new Buffer(0);
  this.readPos = 0;
};

// ====================================
// API
// ====================================

RemoteDebugger.prototype.connect = function(cb, pageChangeCb) {
  var me = this;
  this.pageChangeCb = pageChangeCb;
  this.socket = new net.Socket({type: 'tcp6'});
  this.socket.on('close', function() {
    logger.info('Debugger socket disconnected');
    me.onAppDisconnect();
  });
  this.socket.on('data', _.bind(me.receive, this));

  this.socket.connect(27753, '::1', function () {
    logger.info("Debugger socket connected to " + me.socket.remoteAddress +
                ':' + me.socket.remotePort);
    me.setConnectionKey(cb);
  });
};

RemoteDebugger.prototype.disconnect = function() {
  logger.info("Disconnecting from remote debugger");
  this.socket.destroy();
};

RemoteDebugger.prototype.setConnectionKey = function(cb) {
  assert.ok(this.connId);
  var setConnKey = messages.setConnectionKey(this.connId);
  logger.info("Sending connection key");
  this.send(setConnKey, function(simNameKey, simBuildKey) {
    logger.debug("Sim name: " + simNameKey);
    logger.debug("Sim build: " + simBuildKey);
  }, function(appDict) {
    var newDict = {};
    _.each(appDict, function(dict) {
      newDict[dict.WIRApplicationIdentifierKey] = dict.WIRApplicationNameKey;
    });
    cb(newDict);
  });
};

RemoteDebugger.prototype.selectApp = function(appIdKey, cb) {
  assert.ok(this.connId);
  this.appIdKey = appIdKey;
  var connectToApp = messages.connectToApp(this.connId, this.appIdKey);
  logger.info("Selecting app");
  this.send(connectToApp, _.bind(function(pageDict) {
    cb(this.pageArrayFromDict(pageDict));
    this.specialCbs['_rpc_forwardGetListing:'] = _.bind(this.onPageChange, this);
  }, this));
};

RemoteDebugger.prototype.pageArrayFromDict = function(pageDict) {
  var newPageArray = [];
  _.each(pageDict, function(dict) {
    newPageArray.push({
      id: dict.WIRPageIdentifierKey
      , title: dict.WIRTitleKey
      , url: dict.WIRURLKey
      , isKey: typeof dict.WIRConnectionIdentifierKey !== "undefined"
    });
  });
  return newPageArray;
};

RemoteDebugger.prototype.selectPage = function(pageIdKey, cb) {
  var me = this;
  assert.ok(this.connId); assert.ok(this.appIdKey); assert.ok(this.senderId);
  this.pageIdKey = pageIdKey;
  var setSenderKey = messages.setSenderKey(this.connId, this.appIdKey,
                                           this.senderId, this.pageIdKey);
  logger.info("Selecting page and forwarding socket setup");
  this.send(setSenderKey, function() {
    var enablePage = messages.enablePage(me.appIdKey, me.connId,
                                         me.senderId, me.pageIdKey);
    me.send(enablePage, function() {
      me.execute('(function(){return document.readyState;})()', function(err, res) {
        if (err || res.result.value == 'loading') {
          me.pageUnload();
        }
        cb();
      });
    });
  });
};

RemoteDebugger.prototype.onPageChange = function(pageDict) {
  this.pageChangeCb(this.pageArrayFromDict(pageDict));
};

RemoteDebugger.prototype.executeAtom = function(atom, args, frame, cb) {
  var atomSrc = atoms.get(atom);
  args = _.map(args, JSON.stringify);
  var script = "(function(window) { ";
  script += "return (" + atomSrc + ");";
  script += "})(" + frame + ")";
  script += "(" + args.join(',') + ")";
  this.execute(script, function(err, res) {
    if (err) {
      cb(err, {
        status: status.codes.UnknownError.code
        , value: res
      });
    } else {
      if (typeof res.result.value === 'string') {
        res.result.value = JSON.parse(res.result.value);
      }
      cb(null, res.result.value);
    }
  });
};

RemoteDebugger.prototype.execute = function(command, cb) {
  var me = this;
  if (this.pageLoading) {
    this.waitForDom(function() {
      me.execute(command, cb);
    });
  } else {
    assert.ok(this.connId); assert.ok(this.appIdKey); assert.ok(this.senderId);
    assert.ok(this.pageIdKey);
    logger.info("Sending javascript command");
    var sendJSCommand = messages.sendJSCommand(command, this.appIdKey,
        this.connId, this.senderId, this.pageIdKey);
    this.send(sendJSCommand, cb);
  }
};

RemoteDebugger.prototype.callFunction = function(objId, fn, args, cb) {
  assert.ok(this.connId); assert.ok(this.appIdKey); assert.ok(this.senderId);
  assert.ok(this.pageIdKey);
  logger.info("Calling javascript function");
  var callJSFunction = messages.callJSFunction(objId, fn, args, this.appIdKey,
      this.connId, this.senderId, this.pageIdKey);
  this.send(callJSFunction, cb);
};

RemoteDebugger.prototype.navToUrl = function(url, cb) {
  assert.ok(this.connId); assert.ok(this.appIdKey); assert.ok(this.senderId);
  assert.ok(this.pageIdKey);
  logger.info("Navigating to new URL: " + url);
  var navToUrl = messages.setUrl(url, this.appIdKey, this.connId,
      this.senderId, this.pageIdKey);
  this.waitForDom(cb);
  this.send(navToUrl, noop);
};

RemoteDebugger.prototype.pageLoad = function() {
  clearTimeout(this.loadingTimeout);
  var cbs = this.pageLoadedCbs;
  this.pageLoadedCbs = [];
  logger.debug("Page loaded");
  this.pageLoading = false;
  _.each(cbs, function(cb) {
    cb();
  });
};

RemoteDebugger.prototype.pageUnload = function() {
  logger.debug("Page loading");
  this.pageLoading = true;
  this.waitForDom(noop);
};

RemoteDebugger.prototype.waitForDom = function(cb) {
  this.pageLoadedCbs.push(cb);
  this.loadingTimeout = setTimeout(this.pageLoad, 60000);
};

// ====================================
// HANDLERS
// ====================================

RemoteDebugger.prototype.handleMessage = function(plist) {
  var handlerFor = plist.__selector;
  if (!handlerFor) {
    logger.debug("Got an invalid plist");
    return;
  }
  if (_.has(this.handlers, handlerFor)) {
    this.handlers[handlerFor](plist);
  } else {
    logger.info("Debugger got a message for '" + handlerFor + "' and have no " +
                "handler, doing nothing.");
  }
};

RemoteDebugger.prototype.handleSpecialMessage = function(specialCb) {
  var fn = this.specialCbs[specialCb];
  if (fn) {
    if (specialCb != "_rpc_forwardGetListing:") {
      this.specialCbs[specialCb] = null;
    } else {
    }
    fn.apply(this, _.rest(arguments));
  }
};

RemoteDebugger.prototype.setHandlers = function() {
  var me = this;
  this.handlers = {
    '_rpc_reportSetup:': function (plist) {
      me.handleSpecialMessage('_rpc_reportIdentifier:',
          plist.__argument.WIRSimulatorNameKey,
          plist.__argument.WIRSimulatorBuildKey);
    },
    '_rpc_reportConnectedApplicationList:': function (plist) {
      me.handleSpecialMessage('connect',
          plist.__argument.WIRApplicationDictionaryKey);
    },
    '_rpc_applicationSentListing:': function (plist) {
      me.handleSpecialMessage('_rpc_forwardGetListing:',
          plist.__argument.WIRListingKey);
    },
    '_rpc_applicationSentData:': function(plist) {
      var dataKey = JSON.parse(plist.__argument.WIRMessageDataKey.toString('utf8'))
      , msgId = dataKey.id
      , result = dataKey.result
      , error = dataKey.error || null;
      if (msgId !== null && typeof msgId !== "undefined") {
        msgId = msgId.toString();
      }
      if (dataKey.method == "Profiler.resetProfiles") {
        logger.info("Device is telling us to reset profiles. Should probably " +
                    "do some kind of callback here");
      } else if (dataKey.method == "Page.frameNavigated") {
        me.pageUnload();
      } else if (dataKey.method == "Page.loadEventFired") {
        me.pageLoad();
      } else if (typeof me.dataCbs[msgId] === "function") {
        me.dataCbs[msgId](error, result);
        me.dataCbs[msgId] = null;
      } else if (me.dataCbs[msgId] === null) {
        logger.error("Debugger returned data for message " + msgId +
                     "but we already ran that callback! WTF??");
      } else {
        if (!msgId && !result && !error) {
          logger.info("Got a blank data response from debugger");
        } else {
          logger.error("Debugger returned data for message " + msgId +
                      " but we weren't waiting for that message! " +
                      " result: " + JSON.stringify(result) +
                      " error: " + error);
        }
      }
    },
    '_rpc_applicationDisconnected:': this.onAppDisconnect
  };
};

// ====================================
// SOCKET I/O
// ====================================

RemoteDebugger.prototype.send = function (data, cb, cb2) {
  var immediateCb = false
    , plist;

  cb = cb || noop;
  cb2 = cb2 || noop;

  if (_.has(this.specialCbs, data.__selector)) {
    this.specialCbs[data.__selector] = cb;
    if (data.__selector == '_rpc_reportIdentifier:') {
      this.specialCbs.connect = cb2;
    }
  } else if( data.__argument && data.__argument.WIRSocketDataKey ) {
    //console.log("MsgId was " + this.curMsgId);
    this.curMsgId += 1;
    //console.log("Giving message new id of " + this.curMsgId);
    this.dataCbs[this.curMsgId.toString()] = cb;
    //_.each(this.dataCbs, function(cb, msgId) {
      //console.log(msgId + ": " + cb);
    //});
    //console.log(JSON.stringify(this.dataCbs));
    data.__argument.WIRSocketDataKey.id = this.curMsgId;
    data.__argument.WIRSocketDataKey = new
      Buffer(JSON.stringify(data.__argument.WIRSocketDataKey));
  } else {
    immediateCb = true;
  }

  logger.debug("Sending message to remote debugger:");
  logger.debug(util.inspect(data, false, null));

  try {
    plist = bplistCreate(data);
  } catch(e) {
    logger.error("Could not create binary plist from data");
    return logger.info(e);
  }

  this.socket.write(bufferpack.pack('L', [plist.length]));
  this.socket.write(plist, immediateCb ? cb : noop);
};

RemoteDebugger.prototype.receive = function(data) {
  var dataLeftOver, oldReadPos, prefix, msgLength, body, plist, chunk, leftOver;
  logger.debug('Receiving data from remote debugger');

  // Append this new data to the existing Buffer
  this.received = Buffer.concat([this.received, data]);
  dataLeftOver = true;

  // Parse multiple messages in the same packet
  while(dataLeftOver) {

    // Store a reference to where we were
    oldReadPos = this.readPos;

    // Read the prefix (plist length) to see how far to read next
    // It's always 4 bytes long
    prefix = this.received.slice(this.readPos, this.readPos + 4);

    try {
      msgLength = bufferpack.unpack('L', prefix)[0];
    } catch(e) {
      logger.error("Butter could not unpack");
      return logger.info(e);
    }

    // Jump forward 4 bytes
    this.readPos += 4;

    // Is there enough data here?
    // If not, jump back to our original position and gtfo
    if( this.received.length < msgLength + this.readPos ) {
      this.readPos = oldReadPos;
      break;
    }

    // Extract the main body of the message (where the plist should be)
    body = this.received.slice(this.readPos, msgLength + this.readPos);

    // Extract the plist
    try {
      plist = bplistParse.parseBuffer(body);
    } catch (e) {
      logger.error("Error parsing binary plist");
      logger.info(e);
    }

    // bplistParse.parseBuffer returns an array
    if( plist.length === 1 ) {
      plist = plist[0];
    }

    logger.debug(util.inspect(plist, false, null));

    // Jump forward the length of the plist
    this.readPos += msgLength;

    // Calculate how much buffer is left
    leftOver = this.received.length - this.readPos;

    // Is there some left over?
    if (leftOver !== 0) {
      // Copy what's left over into a new buffer, and save it for next time
      chunk = new Buffer(leftOver);
      this.received.copy(chunk, 0, this.readPos);
      this.received = chunk;
    } else {
      // Otherwise, empty the buffer and get out of the loop
      this.received = new Buffer(0);
      dataLeftOver = false;
    }

    // Reset the read position
    this.readPos = 0;

    // Now do something with the plist
    if (plist) {
      this.handleMessage(plist);
    }

  }
};

exports.init = function(onDisconnect) {
  return new RemoteDebugger(onDisconnect);
};
<commit_msg>scope all atom commands to some window object<commit_after>"use strict";
/* DEPENDENCIES */

var net = require('net')
  , appLogger = require('../../../logger.js').get('appium')
  , _ = require('underscore')
  , messages = require('./remote-messages.js')
  , atoms = require('./webdriver-atoms')
  , status = require("../../uiauto/lib/status")
  , bplistCreate = require('node-bplist-creator')
  , bplistParse = require('bplist-parser')
  , bufferpack = require('bufferpack')
  , uuid = require('node-uuid')
  , colors = require('colors')
  , noop = function () {}
  , assert = require('assert')
  , util = require('util');

var logger = {
  info: function(msg) {
    appLogger.info("[REMOTE] " + msg);
  }
  , debug: function(msg) {
    appLogger.debug(("[REMOTE] " + msg).grey);
  }
  , error: function(msg) {
    appLogger.error("[REMOTE] " + msg);
  }
};

// ====================================
// CONFIG
// ====================================

var RemoteDebugger = function(onDisconnect) {
  this.socket = null;
  this.connId = uuid.v4();
  this.senderId = uuid.v4();
  this.appIdKey = null;
  this.pageIdKey = null;
  this.pageLoading = false;
  this.curMsgId = 0;
  this.dataCbs = {};
  this.onAppDisconnect = onDisconnect || noop;
  this.pageChangeCb = noop;
  this.specialCbs = {
    '_rpc_reportIdentifier:': noop
    , '_rpc_forwardGetListing:': noop
    , 'connect': noop
  };
  this.pageLoadedCbs = [];
  this.setHandlers();
  this.received = new Buffer(0);
  this.readPos = 0;
};

// ====================================
// API
// ====================================

RemoteDebugger.prototype.connect = function(cb, pageChangeCb) {
  var me = this;
  this.pageChangeCb = pageChangeCb;
  this.socket = new net.Socket({type: 'tcp6'});
  this.socket.on('close', function() {
    logger.info('Debugger socket disconnected');
    me.onAppDisconnect();
  });
  this.socket.on('data', _.bind(me.receive, this));

  this.socket.connect(27753, '::1', function () {
    logger.info("Debugger socket connected to " + me.socket.remoteAddress +
                ':' + me.socket.remotePort);
    me.setConnectionKey(cb);
  });
};

RemoteDebugger.prototype.disconnect = function() {
  logger.info("Disconnecting from remote debugger");
  this.socket.destroy();
};

RemoteDebugger.prototype.setConnectionKey = function(cb) {
  assert.ok(this.connId);
  var setConnKey = messages.setConnectionKey(this.connId);
  logger.info("Sending connection key");
  this.send(setConnKey, function(simNameKey, simBuildKey) {
    logger.debug("Sim name: " + simNameKey);
    logger.debug("Sim build: " + simBuildKey);
  }, function(appDict) {
    var newDict = {};
    _.each(appDict, function(dict) {
      newDict[dict.WIRApplicationIdentifierKey] = dict.WIRApplicationNameKey;
    });
    cb(newDict);
  });
};

RemoteDebugger.prototype.selectApp = function(appIdKey, cb) {
  assert.ok(this.connId);
  this.appIdKey = appIdKey;
  var connectToApp = messages.connectToApp(this.connId, this.appIdKey);
  logger.info("Selecting app");
  this.send(connectToApp, _.bind(function(pageDict) {
    cb(this.pageArrayFromDict(pageDict));
    this.specialCbs['_rpc_forwardGetListing:'] = _.bind(this.onPageChange, this);
  }, this));
};

RemoteDebugger.prototype.pageArrayFromDict = function(pageDict) {
  var newPageArray = [];
  _.each(pageDict, function(dict) {
    newPageArray.push({
      id: dict.WIRPageIdentifierKey
      , title: dict.WIRTitleKey
      , url: dict.WIRURLKey
      , isKey: typeof dict.WIRConnectionIdentifierKey !== "undefined"
    });
  });
  return newPageArray;
};

RemoteDebugger.prototype.selectPage = function(pageIdKey, cb) {
  var me = this;
  assert.ok(this.connId); assert.ok(this.appIdKey); assert.ok(this.senderId);
  this.pageIdKey = pageIdKey;
  var setSenderKey = messages.setSenderKey(this.connId, this.appIdKey,
                                           this.senderId, this.pageIdKey);
  logger.info("Selecting page and forwarding socket setup");
  this.send(setSenderKey, function() {
    var enablePage = messages.enablePage(me.appIdKey, me.connId,
                                         me.senderId, me.pageIdKey);
    me.send(enablePage, function() {
      me.execute('(function(){return document.readyState;})()', function(err, res) {
        if (err || res.result.value == 'loading') {
          me.pageUnload();
        }
        cb();
      });
    });
  });
};

RemoteDebugger.prototype.onPageChange = function(pageDict) {
  this.pageChangeCb(this.pageArrayFromDict(pageDict));
};

RemoteDebugger.prototype.executeAtom = function(atom, args, frame, cb) {
  var atomSrc = atoms.get(atom);
  args = _.map(args, JSON.stringify);
  var script = "(function(window) { var document = window.document; ";
  script += "return (" + atomSrc + ");";
  script += "})(" + frame + ")";
  script += "(" + args.join(',') + ")";
  this.execute(script, function(err, res) {
    if (err) {
      cb(err, {
        status: status.codes.UnknownError.code
        , value: res
      });
    } else {
      if (typeof res.result.value === 'string') {
        res.result.value = JSON.parse(res.result.value);
      }
      cb(null, res.result.value);
    }
  });
};

RemoteDebugger.prototype.execute = function(command, cb) {
  var me = this;
  if (this.pageLoading) {
    this.waitForDom(function() {
      me.execute(command, cb);
    });
  } else {
    assert.ok(this.connId); assert.ok(this.appIdKey); assert.ok(this.senderId);
    assert.ok(this.pageIdKey);
    logger.info("Sending javascript command");
    var sendJSCommand = messages.sendJSCommand(command, this.appIdKey,
        this.connId, this.senderId, this.pageIdKey);
    this.send(sendJSCommand, cb);
  }
};

RemoteDebugger.prototype.callFunction = function(objId, fn, args, cb) {
  assert.ok(this.connId); assert.ok(this.appIdKey); assert.ok(this.senderId);
  assert.ok(this.pageIdKey);
  logger.info("Calling javascript function");
  var callJSFunction = messages.callJSFunction(objId, fn, args, this.appIdKey,
      this.connId, this.senderId, this.pageIdKey);
  this.send(callJSFunction, cb);
};

RemoteDebugger.prototype.navToUrl = function(url, cb) {
  assert.ok(this.connId); assert.ok(this.appIdKey); assert.ok(this.senderId);
  assert.ok(this.pageIdKey);
  logger.info("Navigating to new URL: " + url);
  var navToUrl = messages.setUrl(url, this.appIdKey, this.connId,
      this.senderId, this.pageIdKey);
  this.waitForDom(cb);
  this.send(navToUrl, noop);
};

RemoteDebugger.prototype.pageLoad = function() {
  clearTimeout(this.loadingTimeout);
  var cbs = this.pageLoadedCbs;
  this.pageLoadedCbs = [];
  logger.debug("Page loaded");
  this.pageLoading = false;
  _.each(cbs, function(cb) {
    cb();
  });
};

RemoteDebugger.prototype.pageUnload = function() {
  logger.debug("Page loading");
  this.pageLoading = true;
  this.waitForDom(noop);
};

RemoteDebugger.prototype.waitForDom = function(cb) {
  this.pageLoadedCbs.push(cb);
  this.loadingTimeout = setTimeout(this.pageLoad, 60000);
};

// ====================================
// HANDLERS
// ====================================

RemoteDebugger.prototype.handleMessage = function(plist) {
  var handlerFor = plist.__selector;
  if (!handlerFor) {
    logger.debug("Got an invalid plist");
    return;
  }
  if (_.has(this.handlers, handlerFor)) {
    this.handlers[handlerFor](plist);
  } else {
    logger.info("Debugger got a message for '" + handlerFor + "' and have no " +
                "handler, doing nothing.");
  }
};

RemoteDebugger.prototype.handleSpecialMessage = function(specialCb) {
  var fn = this.specialCbs[specialCb];
  if (fn) {
    if (specialCb != "_rpc_forwardGetListing:") {
      this.specialCbs[specialCb] = null;
    } else {
    }
    fn.apply(this, _.rest(arguments));
  }
};

RemoteDebugger.prototype.setHandlers = function() {
  var me = this;
  this.handlers = {
    '_rpc_reportSetup:': function (plist) {
      me.handleSpecialMessage('_rpc_reportIdentifier:',
          plist.__argument.WIRSimulatorNameKey,
          plist.__argument.WIRSimulatorBuildKey);
    },
    '_rpc_reportConnectedApplicationList:': function (plist) {
      me.handleSpecialMessage('connect',
          plist.__argument.WIRApplicationDictionaryKey);
    },
    '_rpc_applicationSentListing:': function (plist) {
      me.handleSpecialMessage('_rpc_forwardGetListing:',
          plist.__argument.WIRListingKey);
    },
    '_rpc_applicationSentData:': function(plist) {
      var dataKey = JSON.parse(plist.__argument.WIRMessageDataKey.toString('utf8'))
      , msgId = dataKey.id
      , result = dataKey.result
      , error = dataKey.error || null;
      if (msgId !== null && typeof msgId !== "undefined") {
        msgId = msgId.toString();
      }
      if (dataKey.method == "Profiler.resetProfiles") {
        logger.info("Device is telling us to reset profiles. Should probably " +
                    "do some kind of callback here");
      } else if (dataKey.method == "Page.frameNavigated") {
        me.pageUnload();
      } else if (dataKey.method == "Page.loadEventFired") {
        me.pageLoad();
      } else if (typeof me.dataCbs[msgId] === "function") {
        me.dataCbs[msgId](error, result);
        me.dataCbs[msgId] = null;
      } else if (me.dataCbs[msgId] === null) {
        logger.error("Debugger returned data for message " + msgId +
                     "but we already ran that callback! WTF??");
      } else {
        if (!msgId && !result && !error) {
          logger.info("Got a blank data response from debugger");
        } else {
          logger.error("Debugger returned data for message " + msgId +
                      " but we weren't waiting for that message! " +
                      " result: " + JSON.stringify(result) +
                      " error: " + error);
        }
      }
    },
    '_rpc_applicationDisconnected:': this.onAppDisconnect
  };
};

// ====================================
// SOCKET I/O
// ====================================

RemoteDebugger.prototype.send = function (data, cb, cb2) {
  var immediateCb = false
    , plist;

  cb = cb || noop;
  cb2 = cb2 || noop;

  if (_.has(this.specialCbs, data.__selector)) {
    this.specialCbs[data.__selector] = cb;
    if (data.__selector == '_rpc_reportIdentifier:') {
      this.specialCbs.connect = cb2;
    }
  } else if( data.__argument && data.__argument.WIRSocketDataKey ) {
    //console.log("MsgId was " + this.curMsgId);
    this.curMsgId += 1;
    //console.log("Giving message new id of " + this.curMsgId);
    this.dataCbs[this.curMsgId.toString()] = cb;
    //_.each(this.dataCbs, function(cb, msgId) {
      //console.log(msgId + ": " + cb);
    //});
    //console.log(JSON.stringify(this.dataCbs));
    data.__argument.WIRSocketDataKey.id = this.curMsgId;
    data.__argument.WIRSocketDataKey = new
      Buffer(JSON.stringify(data.__argument.WIRSocketDataKey));
  } else {
    immediateCb = true;
  }

  logger.debug("Sending message to remote debugger:");
  logger.debug(util.inspect(data, false, null));

  try {
    plist = bplistCreate(data);
  } catch(e) {
    logger.error("Could not create binary plist from data");
    return logger.info(e);
  }

  this.socket.write(bufferpack.pack('L', [plist.length]));
  this.socket.write(plist, immediateCb ? cb : noop);
};

RemoteDebugger.prototype.receive = function(data) {
  var dataLeftOver, oldReadPos, prefix, msgLength, body, plist, chunk, leftOver;
  logger.debug('Receiving data from remote debugger');

  // Append this new data to the existing Buffer
  this.received = Buffer.concat([this.received, data]);
  dataLeftOver = true;

  // Parse multiple messages in the same packet
  while(dataLeftOver) {

    // Store a reference to where we were
    oldReadPos = this.readPos;

    // Read the prefix (plist length) to see how far to read next
    // It's always 4 bytes long
    prefix = this.received.slice(this.readPos, this.readPos + 4);

    try {
      msgLength = bufferpack.unpack('L', prefix)[0];
    } catch(e) {
      logger.error("Butter could not unpack");
      return logger.info(e);
    }

    // Jump forward 4 bytes
    this.readPos += 4;

    // Is there enough data here?
    // If not, jump back to our original position and gtfo
    if( this.received.length < msgLength + this.readPos ) {
      this.readPos = oldReadPos;
      break;
    }

    // Extract the main body of the message (where the plist should be)
    body = this.received.slice(this.readPos, msgLength + this.readPos);

    // Extract the plist
    try {
      plist = bplistParse.parseBuffer(body);
    } catch (e) {
      logger.error("Error parsing binary plist");
      logger.info(e);
    }

    // bplistParse.parseBuffer returns an array
    if( plist.length === 1 ) {
      plist = plist[0];
    }

    logger.debug(util.inspect(plist, false, null));

    // Jump forward the length of the plist
    this.readPos += msgLength;

    // Calculate how much buffer is left
    leftOver = this.received.length - this.readPos;

    // Is there some left over?
    if (leftOver !== 0) {
      // Copy what's left over into a new buffer, and save it for next time
      chunk = new Buffer(leftOver);
      this.received.copy(chunk, 0, this.readPos);
      this.received = chunk;
    } else {
      // Otherwise, empty the buffer and get out of the loop
      this.received = new Buffer(0);
      dataLeftOver = false;
    }

    // Reset the read position
    this.readPos = 0;

    // Now do something with the plist
    if (plist) {
      this.handleMessage(plist);
    }

  }
};

exports.init = function(onDisconnect) {
  return new RemoteDebugger(onDisconnect);
};
<|endoftext|>


<commit_before>export function initialize( container, application ) {
  // application.inject('route', 'foo', 'service:foo');
  let store = container.lookup('store:main');
  store.pushMany('statement', statementData);
  store.pushMany('step', stepData);
}

export default {
  name: 'load-fixtures',
  initialize: initialize,
  after: ['store'],
};

var statementData = [{  id: 1 }];

var stepData =   [
  {
    id: 1,
    statement: 1,
    title: 'Information',
    name: 'step-data-types'
  },
  {  id: 2,
    statement: 1,
    title: 'Collection',
    name: 'step-data-sources'
  },
  {
    id: 3,
    statement: 1,
    title: 'Applicable Laws',
    name: "step-legal-requirement"
  },
  {
    id: 4,
    statement: 1,
    title: 'Purpose',
    name: 'step-why'
  },

  {
    id: 5,
    statement: 1,
    title: 'Sharing',
    name: 'step-sharing'
  },
  {
    id: 6,
    statement: 1,
    title: 'Contact',
    name: "step-contact"
  },
  {
    id: 7,
    statement: 1,
    title: 'Optional Info',
    name: "step-optional-info"
  },
  {
    id: 8,
    statement: 1,
    title: 'Privacy Statement',
    name: "step-statement",
  },
  {
    id: 9,
    statement: 1,
    title: 'Security',
    name: "step-security",
    nextStep: 8,
    showInNav: false,
  },
  {
    id: 10,
    statement: 1,
    title: 'Retention',
    name: "step-retention",
    nextStep: 8,
    showInNav: false,
  }
  ];
<commit_msg>Stomp out the jshint warning<commit_after>export function initialize( container /*, application*/ ) {
  // application.inject('route', 'foo', 'service:foo');
  let store = container.lookup('store:main');
  store.pushMany('statement', statementData);
  store.pushMany('step', stepData);
}

export default {
  name: 'load-fixtures',
  initialize: initialize,
  after: ['store'],
};

var statementData = [{  id: 1 }];

var stepData =   [
  {
    id: 1,
    statement: 1,
    title: 'Information',
    name: 'step-data-types'
  },
  {  id: 2,
    statement: 1,
    title: 'Collection',
    name: 'step-data-sources'
  },
  {
    id: 3,
    statement: 1,
    title: 'Applicable Laws',
    name: "step-legal-requirement"
  },
  {
    id: 4,
    statement: 1,
    title: 'Purpose',
    name: 'step-why'
  },

  {
    id: 5,
    statement: 1,
    title: 'Sharing',
    name: 'step-sharing'
  },
  {
    id: 6,
    statement: 1,
    title: 'Contact',
    name: "step-contact"
  },
  {
    id: 7,
    statement: 1,
    title: 'Optional Info',
    name: "step-optional-info"
  },
  {
    id: 8,
    statement: 1,
    title: 'Privacy Statement',
    name: "step-statement",
  },
  {
    id: 9,
    statement: 1,
    title: 'Security',
    name: "step-security",
    nextStep: 8,
    showInNav: false,
  },
  {
    id: 10,
    statement: 1,
    title: 'Retention',
    name: "step-retention",
    nextStep: 8,
    showInNav: false,
  }
  ];
<|endoftext|>


<commit_before>//Global variables only change base url. NEVER leave a trailing /
var baseUrl = 'http://localhost:5000';
var protocol = 'http://'
//Dont change anything past here
var linkToGo = ['/'];
var visited = [];
var resources = [];
var ajaxes = [];
var index = 0;

//Constants
var spider = require('casper').create();
var fs = require('fs');
var getDirectory = /^(.+)\/([^\/]+)$/;
var stripUrlParams = /(.+?)(\?.*)$/;
// /vars

function saveResources() {
    spider.echo('Saving resources...');
    for (var i = 0; i < resources.length; i++) {
        this.download(resources[i], resources[i].replace(/^(?:\/\/|[^\/]+)*\//, "./"));
        spider.echo('Saved ' + resources[i] + ' (' + (i + 1) + '/' + resources.length + ')');
    }
    spider.echo('Finished saving resources.');
}

function stripLinks() {
    var links = document.querySelectorAll('a');
    return Array.prototype.map.call(links, function(e) {
        return e.getAttribute('href');
    });
}

function cleanLinks(links) {
    return links.filter(function(element, position) {
        return links.indexOf(element) == position && element.charAt(0) == '/';
    });
}

function processLinks(links) {
    filtered = links.filter(function(element, position) {
        return links.indexOf(element) == position && element.charAt(0) == '/' && linkToGo.indexOf(element) == -1 && visited.indexOf(element) == -1;
    });

    linkToGo = linkToGo.concat(filtered);
}

function grab(url) {
    this.then(function() {
        var linklist = this.evaluate(stripLinks);
        if (linklist) {
            processLinks(linklist);
        }
    });
}

function parseUrl(url) {
    var matches = /^(.+:\/\/)(.+?)\/(.*)$/.exec(url);
    protocol = matches[1];
    domain = matches[2];
}

function getSaveName(url) {
    url = url.replace(baseUrl, '');
    if (url.charAt(url.length - 1) === '/')
        url += 'index.html';
    else
        url += '.html';
    this.echo('Saving as .' + url);
    return '.' + url;
}

function clone() {
    this.getUrl = baseUrl + linkToGo[index];

    this.then(function() {

        var html = fs.open(getSaveName.call(this, this.getUrl), 'w');
        var src = this.evaluate(function(url) {
            return __utils__.sendAJAX(url);
        }, this.getUrl);

        src = src.replace(/\"(?:\/\/|["\/]+)*\//g, '"' + fs.workingDirectory + '/');
        html.write(src);

        if (buildFauxJax.call(this))
            html.write('<script src="' + fs.workingDirectory + '/static/js/jquery.mockjax.js"></script>\n<script src="./fauxJax.js"></script>');

        html.close();
    });
}

function buildFauxJax() {
    this.echo('Mocking AJAX...')
    if (ajaxes.length > 0) {
        var fauxJax = fs.open('.' + linkToGo[index] + 'fauxJax.js', 'w');

        fauxJax.write('(function() {\n');

        for (var i = 0; i < ajaxes.length; i++) {
            this.echo('Mocking request to ' + ajaxes[i] + ' (' + (i + 1) + '/' + ajaxes.length + ')');
            fauxJax.write('$.mockjax({\nurl: \'' + ajaxes[i] + '\',\ndataType: \'json\',\nresponseText: ');

            fauxJax.write(this.evaluate(function(ajax) {
                return __utils__.sendAJAX(ajax);
            }, ajaxes[i]));

            fauxJax.write('\n});');
        }

        fauxJax.write('})();');
        fauxJax.close();
        ajaxes = [];
        this.echo('Finished mocking.')
        return true;
    }
    this.echo('Finished mocking.')
    return false;
};

spider.on('resource.requested', function(resource) {

    resource.url = resource.url.replace(stripUrlParams, '$1');
    if (resource.url != baseUrl + linkToGo[index] && resource.url.indexOf(baseUrl) != -1) {

        if (resource.url.indexOf('.') == -1 && resource.url != baseUrl + linkToGo[index] && ajaxes.indexOf(resource.url.replace(baseUrl, '')) == -1) {
            resource.url = resource.url.replace(baseUrl, '');
            ajaxes.push(resource.url);
            this.echo('Pushed ' + resource.url + ' to ajax queue.');
        } else if (resources.indexOf(resource.url) == -1) {
            resources.push(resource.url);
        }
    }
});

//Here lives the big daddy driver function

function toSpiderOrNotToSpider() {
    if (linkToGo[index]) {

        if (visited.indexOf(linkToGo[index]) != -1) {
            index++;
            this.run(toSpiderOrNotToSpider);
        }
        this.echo('Crawling ' + baseUrl + linkToGo[index]);
        this.start(baseUrl + linkToGo[index]);
        grab.call(this, linkToGo[index]);
        clone.call(this);
        visited.push(linkToGo[index]);
        this.then(function(){index++});
        this.run(toSpiderOrNotToSpider);
    } else {
        saveResources.call(this);
        this.echo('Found ' + visited.length + ' links.');
        this.echo(' - ' + visited.join('\n - '));
        this.echo('Caught ' + resources.length + ' resources.');
        this.echo(' - ' + resources.join('\n - '));
        this.exit();
    }
}

//////////////Execution begins here/////////////////
var domain = baseUrl.replace(protocol, '');
//Creating the base directory
if (!fs.exists(domain))
    fs.makeDirectory(domain);
fs.changeWorkingDirectory(domain);

spider.start().then(function() {
    this.echo('===============');
    this.echo('Spider started.');
    this.echo('===============\n');
});

//Lift off!
spider.run(toSpiderOrNotToSpider);
<commit_msg>Actively clones website.<commit_after>//Global variables only change base url. NEVER leave a trailing /
var baseUrl = 'http://staging.osf.io';
var protocol = 'http://'
//Dont change anything past here
var linkToGo = ['/'];
var visited = [];
var resources = [];
var ajaxes = [];
var index = 0;

//Constants
var spider = require('casper').create({
    verbose: true,
    logLevel: "debug"
});
var fs = require('fs');
var getDirectory = /^(.+)\/([^\/]+)$/;
var stripUrlParams = /(.+?)(\?.*)$/;
// /vars

function saveResources() {
    spider.echo('Saving resources...');
    for (var i = 0; i < resources.length; i++) {
        this.download(resources[i], resources[i].replace(/^(?:\/\/|[^\/]+)*\//, "./"));
        spider.echo('Saved ' + resources[i] + ' (' + (i + 1) + '/' + resources.length + ')');
    }
    spider.echo('Finished saving resources.');
}

function stripLinks() {
    var links = document.querySelectorAll('a');
    return Array.prototype.map.call(links, function(e) {
        return e.getAttribute('href');
    });
}

function cleanLinks(links) {
    return links.filter(function(element, position) {
        return links.indexOf(element) == position && element.charAt(0) == '/';
    });
}

function processLinks(links) {
    filtered = links.filter(function(element, position) {
        return links.indexOf(element) == position && element.charAt(0) == '/' && linkToGo.indexOf(element) == -1 && visited.indexOf(element) == -1;
    });

    linkToGo = linkToGo.concat(filtered);
}

function grab(url) {
    this.then(function() {
        var linklist = this.evaluate(stripLinks);
        if (linklist) {
            processLinks(linklist);
        }
    });
}

function parseUrl(url) {
    var matches = /^(.+:\/\/)(.+?)\/(.*)$/.exec(url);
    protocol = matches[1];
    domain = matches[2];
}

function getSaveName(url) {
    url = url.replace(baseUrl, '');
    if (url.charAt(url.length - 1) === '/')
        url += 'index.html';
    else
        url += '.html';
    this.echo('Saving as .' + url);
    return '.' + url;
}

function clone() {
    this.getUrl = baseUrl + linkToGo[index];

    this.then(function() {

        var html = fs.open(getSaveName.call(this, this.getUrl), 'w');
        var src = this.evaluate(function(url) {
            return __utils__.sendAJAX(url);
        }, this.getUrl);

        src = src.replace(/\"(?:\/\/|["\/]+)*\//g, '"' + fs.workingDirectory + '/');
        html.write(src);

        if (buildFauxJax.call(this))
            html.write('<script src="' + fs.workingDirectory + '/static/js/jquery.mockjax.js"></script>\n<script src="./fauxJax.js"></script>');

        html.close();
    });
}

function buildFauxJax() {
    if (ajaxes.length > 0) {
        this.echo('Mocking AJAX...')
        var fauxJax = fs.open('.' + linkToGo[index] + 'fauxJax.js', 'w');

        fauxJax.write('(function() {\n');

        for (var i = 0; i < ajaxes.length; i++) {
            this.echo('Mocking request to ' + ajaxes[i] + ' (' + (i + 1) + '/' + ajaxes.length + ')');
            fauxJax.write('$.mockjax({\nurl: \'' + ajaxes[i] + '\',\ndataType: \'json\',\nresponseText: ');

            fauxJax.write(this.evaluate(function(ajax) {
                return __utils__.sendAJAX(ajax);
            }, ajaxes[i]));

            fauxJax.write('\n});');
        }

        fauxJax.write('})();');
        fauxJax.close();
        ajaxes = [];
        this.echo('Finished mocking.')
        return true;
    }
    return false;
};

spider.on('resource.requested', function(resource) {

    resource.url = resource.url.replace(stripUrlParams, '$1');

    if (linkToGo.indexOf(resource.url.replace(baseUrl,'')) == -1 && resource.url.indexOf(baseUrl) != -1) {

        if (resource.url.indexOf('.') == -1 && resource.url != baseUrl + linkToGo[index] && ajaxes.indexOf(resource.url.replace(baseUrl, '')) == -1) {
            resource.url = resource.url.replace(baseUrl, '');
            ajaxes.push(resource.url);
            this.echo('Pushed ' + resource.url + ' to ajax queue.');
        } else if (resources.indexOf(resource.url) == -1) {
            resources.push(resource.url);
        }
    }
});

//Here lives the big daddy driver function

function toSpiderOrNotToSpider() {
    if (linkToGo[index]) {

        if (visited.indexOf(linkToGo[index]) != -1) {
            index++;
            this.run(toSpiderOrNotToSpider);
        }
        this.echo('Crawling ' + baseUrl + linkToGo[index]);
        this.start(baseUrl + linkToGo[index]);
        grab.call(this, linkToGo[index]);
        clone.call(this);
        visited.push(linkToGo[index]);
        this.then(function(){index++});
        this.run(toSpiderOrNotToSpider);
    } else {
        saveResources.call(this);
        this.echo('Found ' + visited.length + ' links.');
        this.echo(' - ' + visited.join('\n - '));
        this.echo('Caught ' + resources.length + ' resources.');
        this.echo(' - ' + resources.join('\n - '));
        this.exit();
    }
}

//////////////Execution begins here/////////////////
var domain = baseUrl.replace(protocol, '');
//Creating the base directory
if (!fs.exists(domain))
    fs.makeDirectory(domain);
fs.changeWorkingDirectory(domain);

spider.start().then(function() {
    this.echo('===============');
    this.echo('Spider started.');
    this.echo('===============\n');
});

//Lift off!
spider.run(toSpiderOrNotToSpider);
<|endoftext|>


<commit_before>
define(['ByteSource'], function(ByteSource) {

  'use strict';

  var PHYSICAL_BLOCK_BYTES = 512;

  var MAC_CHARSET_128_255
    = '\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8'
    + '\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC'
    + '\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8'
    + '\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u03A9\xE6\xF8'
    + '\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153'
    + '\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\u20AC\u2039\u203A\uFB01\uFB02'
    + '\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4'
    + '\uF8FF\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7';

  function macintoshRoman(u8array, offset, length) {
    switch(arguments.length) {
      case 2: u8array = u8array.subarray(offset); break;
      case 3: u8array = u8array.subarray(offset, offset + length); break;
    }
    return String.fromCharCode.apply(null, u8array)
      .replace(/[\x80-\xFF]/g, function(c) {
        return MAC_CHARSET_128_255[c.charCodeAt(0) - 128];
      });
  }

  function nullTerminate(str) {
    return str.replace(/\0.*/, '');
  }

  function AppleVolume(byteSource) {
    this.byteSource = byteSource;
  }
  AppleVolume.prototype = {
    read: function(reader) {
      var byteSource = this.byteSource;
      function doPartition(n) {
        byteSource.slice(PHYSICAL_BLOCK_BYTES * n, PHYSICAL_BLOCK_BYTES * (n+1)).read({
          onbytes: function(bytes) {
            if (macintoshRoman(bytes, 0, 4) !== 'PM\0\0') {
              console.error('invalid partition map signature');
              return;
            }
            var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
            var mapBlockCount = dv.getInt32(4, false);
            var partitionInfo = {
              blockOffset: dv.getInt32(8, false),
              blockCount: dv.getInt32(12, false),
              type: nullTerminate(macintoshRoman(bytes, 48, 32)),
              status: dv.getInt32(88, false),
            };
            var dataAreaBlockCount = dv.getInt32(84, false);
            if (dataAreaBlockCount > 0) {
              partitionInfo.dataArea = {
                blockCount: dataAreaBlockCount,
                blockOffset: dv.getInt32(80, false);
              };
            }
            var bootCodeByteLength = dv.getInt32(96, false);
            if (bootCodeByteLength > 0) {
              partitionInfo.bootCode = {
                byteLength: bootCodeByteLength,
                blockOffset: dv.getInt32(92, false),
                loadAddress: dv.getInt32(100, false),
                entryPoint: dv.getInt32(108, false),
                checksum: dv.getInt32(116, false),
              };
            }
            var partitionName = nullTerminate(macintoshRoman(bytes, 16, 32));
            if (partitionName) partitionInfo.name = partitionName;
            var processorType = nullTerminate(macintoshRoman(bytes, 124, 16));
            if (processorType) partitionInfo.processorType = processorType;
            if (typeof reader.onpartition === 'function') {
              reader.onpartition(partitionInfo);
            }
            if (n < mapBlockCount) {
              doPartition(n + 1);
            }
          },
        });

      }
      doPartition(1);
    },
  };

  return AppleVolume;

});
<commit_msg>Fix another typo<commit_after>
define(['ByteSource'], function(ByteSource) {

  'use strict';

  var PHYSICAL_BLOCK_BYTES = 512;

  var MAC_CHARSET_128_255
    = '\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8'
    + '\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC'
    + '\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8'
    + '\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u03A9\xE6\xF8'
    + '\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153'
    + '\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\u20AC\u2039\u203A\uFB01\uFB02'
    + '\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4'
    + '\uF8FF\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7';

  function macintoshRoman(u8array, offset, length) {
    switch(arguments.length) {
      case 2: u8array = u8array.subarray(offset); break;
      case 3: u8array = u8array.subarray(offset, offset + length); break;
    }
    return String.fromCharCode.apply(null, u8array)
      .replace(/[\x80-\xFF]/g, function(c) {
        return MAC_CHARSET_128_255[c.charCodeAt(0) - 128];
      });
  }

  function nullTerminate(str) {
    return str.replace(/\0.*/, '');
  }

  function AppleVolume(byteSource) {
    this.byteSource = byteSource;
  }
  AppleVolume.prototype = {
    read: function(reader) {
      var byteSource = this.byteSource;
      function doPartition(n) {
        byteSource.slice(PHYSICAL_BLOCK_BYTES * n, PHYSICAL_BLOCK_BYTES * (n+1)).read({
          onbytes: function(bytes) {
            if (macintoshRoman(bytes, 0, 4) !== 'PM\0\0') {
              console.error('invalid partition map signature');
              return;
            }
            var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
            var mapBlockCount = dv.getInt32(4, false);
            var partitionInfo = {
              blockOffset: dv.getInt32(8, false),
              blockCount: dv.getInt32(12, false),
              type: nullTerminate(macintoshRoman(bytes, 48, 32)),
              status: dv.getInt32(88, false),
            };
            var dataAreaBlockCount = dv.getInt32(84, false);
            if (dataAreaBlockCount > 0) {
              partitionInfo.dataArea = {
                blockCount: dataAreaBlockCount,
                blockOffset: dv.getInt32(80, false),
              };
            }
            var bootCodeByteLength = dv.getInt32(96, false);
            if (bootCodeByteLength > 0) {
              partitionInfo.bootCode = {
                byteLength: bootCodeByteLength,
                blockOffset: dv.getInt32(92, false),
                loadAddress: dv.getInt32(100, false),
                entryPoint: dv.getInt32(108, false),
                checksum: dv.getInt32(116, false),
              };
            }
            var partitionName = nullTerminate(macintoshRoman(bytes, 16, 32));
            if (partitionName) partitionInfo.name = partitionName;
            var processorType = nullTerminate(macintoshRoman(bytes, 124, 16));
            if (processorType) partitionInfo.processorType = processorType;
            if (typeof reader.onpartition === 'function') {
              reader.onpartition(partitionInfo);
            }
            if (n < mapBlockCount) {
              doPartition(n + 1);
            }
          },
        });

      }
      doPartition(1);
    },
  };

  return AppleVolume;

});
<|endoftext|>


<commit_before><commit_msg>Remove accidentally duplicated code + minor cleanups<commit_after><|endoftext|>


<commit_before>var gulp = require("gulp");
var git = require("gulp-git");
var path = require("path");
var fs = require("fs");

function _runTest(runTestFunc, browserArr, done) {
    console.log("run test...");

    runTestFunc(browserArr).then(function (failList) {
        console.log("pass test");

        console.log("done");

        done()
    }, function (e) {
        console.log("fail");
        console.error(e);
        done();
    })
}

function _runTestInLocal(reportFilePath, runTestFunc, generateReportFunc, browserArr, done) {
    console.log("run test...");

    runTestFunc(browserArr).then(function (compareResultData) {
        console.log("pass test");

        console.log("generate report...");

        generateReportFunc(reportFilePath, compareResultData).then(function () {
            console.log("done");

            done()
        }, function (e) {
            console.log("fail");
            console.error(e);
            done()
        })
    }, function (e) {
        var failMessage = e[0];
        var compareResultData = e[1];

        console.log("fail");
        console.error(failMessage);

        console.log("generate report...");

        // generateReportFunc(reportFilePath, compareResultData)
        // done();

        generateReportFunc(reportFilePath, compareResultData).then(function () {
            console.log("done");

            done()
        }, function (e) {
            console.log("fail");
            console.error(e);
            done()
        })
    })
}

function _runBuild(cb) {
    var exec = require("child_process").exec;

    console.log("build...");

    exec("npm run buildAll", { maxBuffer: 8192 * 4000 }, function (err, stdout, stderr) {
        if (err) {
            throw err;
        }

        cb()
    });
}

function _deepCopyJson(json) {
    return JSON.parse(JSON.stringify(json));
}

function _writeGenerateBasedCommitIdToConfig(commitId, config, type, configFilePath) {
    console.log("_write generate based commitId...");
    var copiedConfig = _deepCopyJson(config);
    copiedConfig[type].last_generate_based_commit_id = commitId;
    fs.writeFileSync(configFilePath, JSON.stringify(copiedConfig));
}

function _restoreToCurrentCommid(currentCommitId, done) {
    git.reset(currentCommitId, { args: '--hard' }, function (err) {
        if (!!err) {
            console.error(err);
            done();
            return;
        }

        _runBuild(function () {
            done()
        });
    });
}

module.exports = {
    testInCI: function (generateDataInfo, type, generateCorrectDataFunc, runTestFunc, done) {
        var configFilePath = path.join(process.cwd(), "test/e2e/config/e2eConfig.json");

        git.revParse({ args: "HEAD" }, function (err, commitId) {
            var currentCommitId = commitId;

            var config = JSON.parse(fs.readFileSync(configFilePath));
            var basedCommitId = config[type].base_commit_id;

            if (!!err) {
                console.error(err);
                done();
                return;
            }

            // if (basedCommitId === config[type].last_generate_based_commit_id) {
            //     _runBuild(function () {
            //         _runTest(runTestFunc, [], done);
            //     });
            //     return
            // }

            console.log("reset hard to basedCommitId:", basedCommitId, "...");

            git.reset(basedCommitId, { args: '--hard' }, function (err) {
                if (!!err) {
                    console.error(err);
                    done();
                    return;
                }

                _runBuild(function () {
                    console.log(generateDataInfo);

                    generateCorrectDataFunc().then(function (browser) {
                        console.log("reset hard to currentCommitId:", currentCommitId, "...");

                        git.reset(currentCommitId, { args: '--hard' }, function (err) {
                            if (!!err) {
                                console.error(err);

                                return;
                            }

                            // _writeGenerateBasedCommitIdToConfig(basedCommitId, config, type, configFilePath);

                            _runBuild(function () {
                                _runTest(runTestFunc, [browser], done);
                            });
                        });
                    }, function (e) {
                        console.error(e);

                        console.log("restore to origin commitId...");

                        _restoreToCurrentCommid(currentCommitId, done);
                    })
                });
            });
        });
    },
    testInLocal: function (generateDataInfo, reportFilePath, type, generateCorrectDataFunc, generateReportFunc, runTestFunc, done) {
        var configFilePath = path.join(process.cwd(), "test/e2e/config/e2eConfig.json");

        git.revParse({ args: "HEAD" }, function (err, commitId) {
            var currentCommitId = commitId;

            var config = JSON.parse(fs.readFileSync(configFilePath));
            var basedCommitId = config[type].base_commit_id;

            if (!!err) {
                console.error(err);
                done();
                return;
            }

            if (basedCommitId === config[type].last_generate_based_commit_id) {
                console.log("already generate data based on the same commit id, not generate again...");

                _runBuild(function () {
                    _runTestInLocal(reportFilePath, runTestFunc, generateReportFunc, [], done);
                });
                return
            }

            console.log("reset hard to basedCommitId:", basedCommitId, "...");

            git.reset(basedCommitId, { args: '--hard' }, function (err) {
                if (!!err) {
                    console.error(err);
                    done();
                    return;
                }

                _runBuild(function () {
                    console.log(generateDataInfo);

                    generateCorrectDataFunc().then(function (browser) {
                        console.log("reset hard to currentCommitId:", currentCommitId, "...");

                        git.reset(currentCommitId, { args: '--hard' }, function (err) {
                            if (!!err) {
                                console.error(err);

                                return;
                            }

                            _writeGenerateBasedCommitIdToConfig(basedCommitId, config, type, configFilePath);

                            _runBuild(function () {
                                _runTestInLocal(reportFilePath, runTestFunc, generateReportFunc, [browser], done);
                            });
                        });
                    }, function (e) {
                        console.error(e);

                        console.log("restore to origin commitId...");

                        _restoreToCurrentCommid(currentCommitId, done);
                    })
                });
            });
        });

    }
}
<commit_msg>test(e2e-test): if pass test, not generate report<commit_after>var gulp = require("gulp");
var git = require("gulp-git");
var path = require("path");
var fs = require("fs");

function _runTest(runTestFunc, browserArr, done) {
    console.log("run test...");

    runTestFunc(browserArr).then(function (failList) {
        console.log("pass test");

        console.log("done");

        done()
    }, function (e) {
        console.log("fail");
        console.error(e);
        done();
    })
}

function _runTestInLocal(reportFilePath, runTestFunc, generateReportFunc, browserArr, done) {
    console.log("run test...");

    runTestFunc(browserArr).then(function (compareResultData) {
        console.log("pass test");

        console.log("done");

        done()
    }, function (e) {
        var failMessage = e[0];
        var compareResultData = e[1];

        console.log("fail");
        console.error(failMessage);

        console.log("generate report...");

        generateReportFunc(reportFilePath, compareResultData).then(function () {
            console.log("done");

            done()
        }, function (e) {
            console.log("fail");
            console.error(e);
            done()
        })
    })
}

function _runBuild(cb) {
    var exec = require("child_process").exec;

    console.log("build...");

    exec("npm run buildAll", { maxBuffer: 8192 * 4000 }, function (err, stdout, stderr) {
        if (err) {
            throw err;
        }

        cb()
    });
}

function _deepCopyJson(json) {
    return JSON.parse(JSON.stringify(json));
}

function _writeGenerateBasedCommitIdToConfig(commitId, config, type, configFilePath) {
    console.log("_write generate based commitId...");
    var copiedConfig = _deepCopyJson(config);
    copiedConfig[type].last_generate_based_commit_id = commitId;
    fs.writeFileSync(configFilePath, JSON.stringify(copiedConfig));
}

function _restoreToCurrentCommid(currentCommitId, done) {
    git.reset(currentCommitId, { args: '--hard' }, function (err) {
        if (!!err) {
            console.error(err);
            done();
            return;
        }

        _runBuild(function () {
            done()
        });
    });
}

module.exports = {
    testInCI: function (generateDataInfo, type, generateCorrectDataFunc, runTestFunc, done) {
        var configFilePath = path.join(process.cwd(), "test/e2e/config/e2eConfig.json");

        git.revParse({ args: "HEAD" }, function (err, commitId) {
            var currentCommitId = commitId;

            var config = JSON.parse(fs.readFileSync(configFilePath));
            var basedCommitId = config[type].base_commit_id;

            if (!!err) {
                console.error(err);
                done();
                return;
            }

            // if (basedCommitId === config[type].last_generate_based_commit_id) {
            //     _runBuild(function () {
            //         _runTest(runTestFunc, [], done);
            //     });
            //     return
            // }

            console.log("reset hard to basedCommitId:", basedCommitId, "...");

            git.reset(basedCommitId, { args: '--hard' }, function (err) {
                if (!!err) {
                    console.error(err);
                    done();
                    return;
                }

                _runBuild(function () {
                    console.log(generateDataInfo);

                    generateCorrectDataFunc().then(function (browser) {
                        console.log("reset hard to currentCommitId:", currentCommitId, "...");

                        git.reset(currentCommitId, { args: '--hard' }, function (err) {
                            if (!!err) {
                                console.error(err);

                                return;
                            }

                            // _writeGenerateBasedCommitIdToConfig(basedCommitId, config, type, configFilePath);

                            _runBuild(function () {
                                _runTest(runTestFunc, [browser], done);
                            });
                        });
                    }, function (e) {
                        console.error(e);

                        console.log("restore to origin commitId...");

                        _restoreToCurrentCommid(currentCommitId, done);
                    })
                });
            });
        });
    },
    testInLocal: function (generateDataInfo, reportFilePath, type, generateCorrectDataFunc, generateReportFunc, runTestFunc, done) {
        var configFilePath = path.join(process.cwd(), "test/e2e/config/e2eConfig.json");

        git.revParse({ args: "HEAD" }, function (err, commitId) {
            var currentCommitId = commitId;

            var config = JSON.parse(fs.readFileSync(configFilePath));
            var basedCommitId = config[type].base_commit_id;

            if (!!err) {
                console.error(err);
                done();
                return;
            }

            if (basedCommitId === config[type].last_generate_based_commit_id) {
                console.log("already generate data based on the same commit id, not generate again...");

                _runBuild(function () {
                    _runTestInLocal(reportFilePath, runTestFunc, generateReportFunc, [], done);
                });
                return
            }

            console.log("reset hard to basedCommitId:", basedCommitId, "...");

            git.reset(basedCommitId, { args: '--hard' }, function (err) {
                if (!!err) {
                    console.error(err);
                    done();
                    return;
                }

                _runBuild(function () {
                    console.log(generateDataInfo);

                    generateCorrectDataFunc().then(function (browser) {
                        console.log("reset hard to currentCommitId:", currentCommitId, "...");

                        git.reset(currentCommitId, { args: '--hard' }, function (err) {
                            if (!!err) {
                                console.error(err);

                                return;
                            }

                            _writeGenerateBasedCommitIdToConfig(basedCommitId, config, type, configFilePath);

                            _runBuild(function () {
                                _runTestInLocal(reportFilePath, runTestFunc, generateReportFunc, [browser], done);
                            });
                        });
                    }, function (e) {
                        console.error(e);

                        console.log("restore to origin commitId...");

                        _restoreToCurrentCommid(currentCommitId, done);
                    })
                });
            });
        });

    }
}
<|endoftext|>


<commit_before>(function(e){if(typeof module!=="undefined"&&module&&module.exports){module.exports=e()}else if(typeof define==="function"&&define.amd){define(e)}else{P=e()}})(function(){"use strict";var e=p(typeof process)&&{}.toString.call(process)==="[object process]",t=p(typeof setImmediate),n={f:null,n:null},r=n,i=false,o=e&&_||y(h)||w(h),u=[],f=w(d),a,c,s,l=p.call,v=p.apply;function p(e){return e==="object"||e==="function"}function d(){if(u.length){throw u.shift()}}function h(){while(n.n){n=n.n;var e=n.f;n.f=null;e.call()}i=false}var m=function(e){r=r.n={f:e,n:null};if(!i){i=true;o()}};function _(){var e=process.domain;if(e){if(!s)s=(1,require)("domain");s.active=process.domain=null}if(i&&t){setImmediate(h)}else{process.nextTick(h)}if(e){s.active=process.domain=e}}function y(e){var t=p(typeof MutationObserver)?new MutationObserver(e):p(typeof WebKitMutationObserver)?new WebKitMutationObserver(e):null;if(!t){return null}var n=1;var r=document.createTextNode("");t.observe(r,{characterData:true});return function(){n=-n;r.data=n}}function w(e){return function(){var t=setTimeout(r,0);var n=setInterval(r,50);function r(){clearTimeout(t);clearInterval(n);e()}}}if(e){a=function(e){var t=process.domain;return function(){if(t){if(t._disposed)return;t.enter()}try{e.call()}finally{o()}if(t){t.exit()}}};c=function(e){var t=process.domain;m(!t?e:function(){if(!t._disposed){t.enter();e.call();t.exit()}})}}else{a=function(e){return function(){try{e.call()}catch(t){u.push(t);f()}}};c=m}function g(e){m(a(e))}function T(e,t){for(var n=0,r=e.length;n<r;++n){if(n in e){t(e[n],n)}}}function b(e){g(function(){if(I.onerror){I.onerror.call(null,e)}else{throw e}})}var j=0;var x=1;var O=2;function I(e){return e instanceof D?e:K(new D,e)}function M(t,n,r,i){if(t._state){return t}t._state=n;t._value=r;if(i){t._domain=i}else if(e&&n===O){t._domain=process.domain}if(t._pending.length){T(t._pending,m)}t._pending=null;return t}function E(e,t){e._pending.push(t)}function k(e,t){M(t,e._state,e._value,e._domain)}function K(e,t){if(e._state){return e}if(t instanceof D){if(t===e){M(e,O,new TypeError("You can't resolve a promise with itself"))}else if(t._state){k(t,e)}else{E(t,function(){k(t,e)})}}else if(t!==Object(t)){M(e,x,t)}else{c(function(){var n=S(e);try{var r=t.then;if(typeof r==="function"){l.call(r,t,n.resolve,n.reject)}else{M(e,x,t)}}catch(i){n.reject(i)}})}return e}function S(e){var t=false;return{promise:e,resolve:function(n){if(!t){t=true;K(e,n)}},reject:function(n){if(!t){t=true;M(e,O,n)}}}}I.defer=W;function W(){return S(new D)}I.reject=q;function q(e){return M(new D,O,e)}function D(){this._state=0;this._value=void 0;this._domain=null;this._pending=[]}D.prototype.then=function(t,n){var r=typeof t==="function"?t:null;var i=typeof n==="function"?n:null;var o=this;var u=new D;var f=e&&process.domain;function a(){var e=o._state===x?r:i;if(!e){k(o,u);return}var t,n=false;var a=o._domain||f;if(a){if(a._disposed)return;a.enter()}try{t=e(o._value)}catch(c){n=true;M(u,O,c)}if(!n){K(u,t)}if(a){a.exit()}}if(o._state===j){E(o,a)}else{m(a)}return u};D.prototype.done=function(e,t){var n=this;if(e||t){n=n.then(e,t)}n.then(null,b)};D.prototype.fail=function(e){return this.then(null,e)};D.prototype.spread=function(e,t){return this.then(e&&function(n){return Y(n,[]).then(function(t){return v.call(e,void 0,t)},t)},t)};D.prototype.timeout=function(e,t){var n=this;var r=new D;if(n._state!==j){k(n,r)}else{var i=setTimeout(function(){M(r,O,new Error(t||"Timed out after "+e+" ms"))},e);E(n,function(){clearTimeout(i);k(n,r)})}return r};D.prototype.delay=function(e){var t=W();this.then(function(n){setTimeout(function(){t.resolve(n)},e)},t.reject);return t.promise};D.prototype.inspect=function(){switch(this._state){case j:return{state:"pending"};case x:return{state:"fulfilled",value:this._value};case O:return{state:"rejected",reason:this._value};default:throw new TypeError("invalid state")}};function N(e){function t(t){return e(t,[])}function n(e){return I(e).then(t)}n._=e;return n}I.allSettled=N(P);function P(e,t){var n=0;var r=new D;T(e,function(e,i){var o=I(e);if(o._state===j){++n;E(o,function(){t[i]=o.inspect();if(--n===0){M(r,x,t)}})}else{t[i]=o.inspect()}});if(n===0){M(r,x,t)}return r}I.all=N(Y);function Y(e,t){var n=0;var r=W();T(e,function(e,i){var o=I(e);if(o._state===x){t[i]=o._value}else{++n;o.then(function(e){t[i]=e;if(--n===0){r.resolve(t)}},r.reject)}});if(n===0){r.resolve(t)}return r.promise}I.promised=z;function z(e){function t(t){return v.apply(e,t)}return function(){var e=Y(arguments,[]);return Y([this,e],[]).then(t)}}I.onerror=null;I.nextTick=g;return I});<commit_msg>Minify<commit_after>(function(e){if(typeof module!=="undefined"&&module&&module.exports){module.exports=e()}else if(typeof define==="function"&&define.amd){define(e)}else{P=e()}})(function(){"use strict";var e=p(typeof process)&&{}.toString.call(process)==="[object process]",t=p(typeof setImmediate),n={f:null,n:null},r=n,i=false,o=e&&_||y(h)||w(h),u=[],f=w(d),a,c,s,l=p.call,v=p.apply;function p(e){return e==="object"||e==="function"}function d(){if(u.length){throw u.shift()}}function h(){while(n.n){n=n.n;var e=n.f;n.f=null;e.call()}i=false}var m=function(e){r=r.n={f:e,n:null};if(!i){i=true;o()}};function _(){var e=process.domain;if(e){if(!s)s=(1,require)("domain");s.active=process.domain=null}if(i&&t){setImmediate(h)}else{process.nextTick(h)}if(e){s.active=process.domain=e}}function y(e){var t=p(typeof MutationObserver)?new MutationObserver(e):p(typeof WebKitMutationObserver)?new WebKitMutationObserver(e):null;if(!t){return null}var n=1;var r=document.createTextNode("");t.observe(r,{characterData:true});return function(){n=-n;r.data=n}}function w(e){return function(){var t=setTimeout(r,0);var n=setInterval(r,50);function r(){clearTimeout(t);clearInterval(n);e()}}}if(e){a=function(e){var t=process.domain;return function(){if(t){if(t._disposed)return;t.enter()}try{e.call()}catch(n){o();throw n}if(t){t.exit()}}};c=function(e){var t=process.domain;m(!t?e:function(){if(!t._disposed){t.enter();e.call();t.exit()}})}}else{a=function(e){return function(){try{e.call()}catch(t){u.push(t);f()}}};c=m}function g(e){m(a(e))}function T(e,t){for(var n=0,r=e.length;n<r;++n){if(n in e){t(e[n],n)}}}function b(e){g(function(){if(I.onerror){I.onerror.call(null,e)}else{throw e}})}var j=0;var x=1;var O=2;function I(e){return e instanceof D?e:K(new D,e)}function M(t,n,r,i){if(t._state){return t}t._state=n;t._value=r;if(i){t._domain=i}else if(e&&n===O){t._domain=process.domain}if(t._pending.length){T(t._pending,m)}t._pending=null;return t}function E(e,t){e._pending.push(t)}function k(e,t){M(t,e._state,e._value,e._domain)}function K(e,t){if(e._state){return e}if(t instanceof D){if(t===e){M(e,O,new TypeError("You can't resolve a promise with itself"))}else if(t._state){k(t,e)}else{E(t,function(){k(t,e)})}}else if(t!==Object(t)){M(e,x,t)}else{c(function(){var n=S(e);try{var r=t.then;if(typeof r==="function"){l.call(r,t,n.resolve,n.reject)}else{M(e,x,t)}}catch(i){n.reject(i)}})}return e}function S(e){var t=false;return{promise:e,resolve:function(n){if(!t){t=true;K(e,n)}},reject:function(n){if(!t){t=true;M(e,O,n)}}}}I.defer=W;function W(){return S(new D)}I.reject=q;function q(e){return M(new D,O,e)}function D(){this._state=0;this._value=void 0;this._domain=null;this._pending=[]}D.prototype.then=function(t,n){var r=typeof t==="function"?t:null;var i=typeof n==="function"?n:null;var o=this;var u=new D;var f=e&&process.domain;function a(){var e=o._state===x?r:i;if(!e){k(o,u);return}var t,n=false;var a=o._domain||f;if(a){if(a._disposed)return;a.enter()}try{t=e(o._value)}catch(c){n=true;M(u,O,c)}if(!n){K(u,t)}if(a){a.exit()}}if(o._state===j){E(o,a)}else{m(a)}return u};D.prototype.done=function(e,t){var n=this;if(e||t){n=n.then(e,t)}n.then(null,b)};D.prototype.fail=function(e){return this.then(null,e)};D.prototype.spread=function(e,t){return this.then(e&&function(n){return Y(n,[]).then(function(t){return v.call(e,void 0,t)},t)},t)};D.prototype.timeout=function(e,t){var n=this;var r=new D;if(n._state!==j){k(n,r)}else{var i=setTimeout(function(){M(r,O,new Error(t||"Timed out after "+e+" ms"))},e);E(n,function(){clearTimeout(i);k(n,r)})}return r};D.prototype.delay=function(e){var t=W();this.then(function(n){setTimeout(function(){t.resolve(n)},e)},t.reject);return t.promise};D.prototype.inspect=function(){switch(this._state){case j:return{state:"pending"};case x:return{state:"fulfilled",value:this._value};case O:return{state:"rejected",reason:this._value};default:throw new TypeError("invalid state")}};function N(e){function t(t){return e(t,[])}function n(e){return I(e).then(t)}n._=e;return n}I.allSettled=N(P);function P(e,t){var n=0;var r=new D;T(e,function(e,i){var o=I(e);if(o._state===j){++n;E(o,function(){t[i]=o.inspect();if(--n===0){M(r,x,t)}})}else{t[i]=o.inspect()}});if(n===0){M(r,x,t)}return r}I.all=N(Y);function Y(e,t){var n=0;var r=W();T(e,function(e,i){var o=I(e);if(o._state===x){t[i]=o._value}else{++n;o.then(function(e){t[i]=e;if(--n===0){r.resolve(t)}},r.reject)}});if(n===0){r.resolve(t)}return r.promise}I.promised=z;function z(e){function t(t){return v.apply(e,t)}return function(){var e=Y(arguments,[]);return Y([this,e],[]).then(t)}}I.onerror=null;I.nextTick=g;return I});<|endoftext|>


<commit_before>/*
 * Salvattore 1.0.4 by @rnmp and @ppold
 * https://github.com/rnmp/salvattore
 */
!function(a,b){"object"==typeof exports?module.exports=b():"function"==typeof define&&define.amd?define("salvattore",[],b):a.salvattore=b()}(this,function(){window.matchMedia||(window.matchMedia=function(){"use strict";var a=window.styleMedia||window.media;if(!a){var b=document.createElement("style"),c=document.getElementsByTagName("script")[0],d=null;b.type="text/css",b.id="matchmediajs-test",c.parentNode.insertBefore(b,c),d="getComputedStyle"in window&&window.getComputedStyle(b,null)||b.currentStyle,a={matchMedium:function(a){var c="@media "+a+"{ #matchmediajs-test { width: 1px; } }";return b.styleSheet?b.styleSheet.cssText=c:b.textContent=c,"1px"===d.width}}}return function(b){return{matches:a.matchMedium(b||"all"),media:b||"all"}}}()),function(){if(window.matchMedia&&window.matchMedia("all").addListener)return!1;var a=window.matchMedia,b=a("only all").matches,c=!1,d=0,e=[],f=function(){clearTimeout(d),d=setTimeout(function(){for(var b=0,c=e.length;c>b;b++){var d=e[b].mql,f=e[b].listeners||[],g=a(d.media).matches;if(g!==d.matches){d.matches=g;for(var h=0,i=f.length;i>h;h++)f[h].call(window,d)}}},30)};window.matchMedia=function(d){var g=a(d),h=[],i=0;return g.addListener=function(a){b&&(c||(c=!0,window.addEventListener("resize",f,!0)),0===i&&(i=e.push({mql:g,listeners:h})),h.push(a))},g.removeListener=function(a){for(var b=0,c=h.length;c>b;b++)h[b]===a&&h.splice(b,1)},g}}(),function(){for(var a=0,b=["ms","moz","webkit","o"],c=0;c<b.length&&!window.requestAnimationFrame;++c)window.requestAnimationFrame=window[b[c]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[b[c]+"CancelAnimationFrame"]||window[b[c]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(b){var c=(new Date).getTime(),d=Math.max(0,16-(c-a)),e=window.setTimeout(function(){b(c+d)},d);return a=c+d,e}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(a){clearTimeout(a)})}(),"function"!=typeof window.CustomEvent&&!function(){function a(a,b){b=b||{bubbles:!1,cancelable:!1,detail:void 0};var c=document.createEvent("CustomEvent");return c.initCustomEvent(a,b.bubbles,b.cancelable,b.detail),c}a.prototype=window.CustomEvent.prototype,window.CustomEvent=a}();var a=function(a,b){"use strict";var c={},d=[],e=function(a,b,c){a.dataset?a.dataset[b]=c:a.setAttribute("data-"+b,c)};return c.ready=c.ready||!1,c.obtain_grid_settings=function(b){var c,d,e=a.getComputedStyle(b,":before"),f=e.getPropertyValue("content").slice(1,-1),g=f.match(/^\s*(\d+)(?:\s?\.(.+))?\s*$/);return g?(c=g[1],d=g[2],d=d?d.split("."):["column"]):(g=f.match(/^\s*\.(.+)\s+(\d+)\s*$/),d=g[1],c=g[2],c&&(c=c.split("."))),{numberOfColumns:c,columnClasses:d}},c.add_columns=function(a,d){for(var f,g=c.obtain_grid_settings(a),h=g.numberOfColumns,i=g.columnClasses,j=new Array(+h),k=b.createDocumentFragment(),l=h;0!==l--;)f="[data-columns] > *:nth-child("+h+"n-"+l+")",j.push(d.querySelectorAll(f));j.forEach(function(a){var c=b.createElement("div"),d=b.createDocumentFragment();c.className=i.join(" "),Array.prototype.forEach.call(a,function(a){d.appendChild(a)}),c.appendChild(d),k.appendChild(c)}),a.appendChild(k),e(a,"columns",h)},c.remove_columns=function(c){var d=b.createRange();d.selectNodeContents(c);var f=Array.prototype.filter.call(d.extractContents().childNodes,function(b){return b instanceof a.HTMLElement}),g=f.length,h=f[0].childNodes.length,i=new Array(h*g);Array.prototype.forEach.call(f,function(a,b){Array.prototype.forEach.call(a.children,function(a,c){i[c*g+b]=a})});var j=b.createElement("div");return e(j,"columns",0),i.filter(function(a){return!!a}).forEach(function(a){j.appendChild(a)}),j},c.recreate_columns=function(b){a.requestAnimationFrame(function(){c.add_columns(b,c.remove_columns(b));var a=new CustomEvent("salvattoreChange",{detail:b});window.dispatchEvent(a)})},c.media_query_change=function(a){a.matches&&Array.prototype.forEach.call(d,c.recreate_columns)},c.get_css_rules=function(a){var b;try{b=a.sheet.cssRules||a.sheet.rules}catch(c){return[]}return b||[]},c.get_stylesheets=function(){return Array.prototype.concat.call(Array.prototype.slice.call(b.querySelectorAll("style[type='text/css']")),Array.prototype.slice.call(b.querySelectorAll("link[rel='stylesheet']")))},c.media_rule_has_columns_selector=function(a){for(var b,c=a.length;c--;)if(b=a[c],b.selectorText&&b.selectorText.match(/\[data-columns\](.*)::?before$/))return!0;return!1},c.scan_media_queries=function(){var b=[];a.matchMedia&&(c.get_stylesheets().forEach(function(d){Array.prototype.forEach.call(c.get_css_rules(d),function(d){d.media&&c.media_rule_has_columns_selector(d.cssRules)&&b.push(a.matchMedia(d.media.mediaText))})}),b.forEach(function(a){a.addListener(c.media_query_change)}))},c.next_element_column_index=function(a){var b,c,d,e=a.children,f=e.length,g=e.length-1;for(g;g>=0&&(c=e[g],d=c.children.length,!(0!==g&&b>d));g--){if(g+1===f){g=0;break}b=d}return g},c.create_list_of_fragments=function(a){for(var c=new Array(a),d=0;d!==a;)c[d]=b.createDocumentFragment(),d++;return c},c.append_elements=function(a,b){var d=a.children,e=d.length,f=c.create_list_of_fragments(e),g=c.next_element_column_index(a);b.forEach(function(a){f[g].appendChild(a),g===e-1?g=0:g++}),Array.prototype.forEach.call(d,function(a,b){a.appendChild(f[b])})},c.prepend_elements=function(a,d){var e=a.children,f=e.length,g=c.create_list_of_fragments(f),h=f-1;d.forEach(function(a){var b=g[h];b.insertBefore(a,b.firstChild),0===h?h=f-1:h--}),Array.prototype.forEach.call(e,function(a,b){a.insertBefore(g[b],a.firstChild)});for(var i=b.createDocumentFragment(),j=d.length%f;0!==j--;)i.appendChild(a.lastChild);a.insertBefore(i,a.firstChild)},c.register_grid=function(f){if("none"!==a.getComputedStyle(f).display){var g=b.createRange();g.selectNodeContents(f);var h=b.createElement("div");h.appendChild(g.extractContents()),e(h,"columns",0),c.add_columns(f,h),d.push(f)}},c.init=function(){var a=b.querySelectorAll("[data-columns]"),d=new CustomEvent("salvattoreInit");Array.prototype.forEach.call(a,c.register_grid),c.scan_media_queries(),c.ready=!0,window.dispatchEvent(d)},{append_elements:c.append_elements,prepend_elements:c.prepend_elements,register_grid:c.register_grid,init:c.init,ready:function(){return c.ready}}}(window,window.document);return a});<commit_msg>Updated version to a custom one so library handlers will differentiate - grunt<commit_after>/*
 * Salvattore 1.0.4-f1 by @rnmp and @ppold
 * https://github.com/rnmp/salvattore
 */
!function(a,b){"object"==typeof exports?module.exports=b():"function"==typeof define&&define.amd?define("salvattore",[],b):a.salvattore=b()}(this,function(){window.matchMedia||(window.matchMedia=function(){"use strict";var a=window.styleMedia||window.media;if(!a){var b=document.createElement("style"),c=document.getElementsByTagName("script")[0],d=null;b.type="text/css",b.id="matchmediajs-test",c.parentNode.insertBefore(b,c),d="getComputedStyle"in window&&window.getComputedStyle(b,null)||b.currentStyle,a={matchMedium:function(a){var c="@media "+a+"{ #matchmediajs-test { width: 1px; } }";return b.styleSheet?b.styleSheet.cssText=c:b.textContent=c,"1px"===d.width}}}return function(b){return{matches:a.matchMedium(b||"all"),media:b||"all"}}}()),function(){if(window.matchMedia&&window.matchMedia("all").addListener)return!1;var a=window.matchMedia,b=a("only all").matches,c=!1,d=0,e=[],f=function(){clearTimeout(d),d=setTimeout(function(){for(var b=0,c=e.length;c>b;b++){var d=e[b].mql,f=e[b].listeners||[],g=a(d.media).matches;if(g!==d.matches){d.matches=g;for(var h=0,i=f.length;i>h;h++)f[h].call(window,d)}}},30)};window.matchMedia=function(d){var g=a(d),h=[],i=0;return g.addListener=function(a){b&&(c||(c=!0,window.addEventListener("resize",f,!0)),0===i&&(i=e.push({mql:g,listeners:h})),h.push(a))},g.removeListener=function(a){for(var b=0,c=h.length;c>b;b++)h[b]===a&&h.splice(b,1)},g}}(),function(){for(var a=0,b=["ms","moz","webkit","o"],c=0;c<b.length&&!window.requestAnimationFrame;++c)window.requestAnimationFrame=window[b[c]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[b[c]+"CancelAnimationFrame"]||window[b[c]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(b){var c=(new Date).getTime(),d=Math.max(0,16-(c-a)),e=window.setTimeout(function(){b(c+d)},d);return a=c+d,e}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(a){clearTimeout(a)})}(),"function"!=typeof window.CustomEvent&&!function(){function a(a,b){b=b||{bubbles:!1,cancelable:!1,detail:void 0};var c=document.createEvent("CustomEvent");return c.initCustomEvent(a,b.bubbles,b.cancelable,b.detail),c}a.prototype=window.CustomEvent.prototype,window.CustomEvent=a}();var a=function(a,b){"use strict";var c={},d=[],e=function(a,b,c){a.dataset?a.dataset[b]=c:a.setAttribute("data-"+b,c)};return c.ready=c.ready||!1,c.obtain_grid_settings=function(b){var c,d,e=a.getComputedStyle(b,":before"),f=e.getPropertyValue("content").slice(1,-1),g=f.match(/^\s*(\d+)(?:\s?\.(.+))?\s*$/);return g?(c=g[1],d=g[2],d=d?d.split("."):["column"]):(g=f.match(/^\s*\.(.+)\s+(\d+)\s*$/),d=g[1],c=g[2],c&&(c=c.split("."))),{numberOfColumns:c,columnClasses:d}},c.add_columns=function(a,d){for(var f,g=c.obtain_grid_settings(a),h=g.numberOfColumns,i=g.columnClasses,j=new Array(+h),k=b.createDocumentFragment(),l=h;0!==l--;)f="[data-columns] > *:nth-child("+h+"n-"+l+")",j.push(d.querySelectorAll(f));j.forEach(function(a){var c=b.createElement("div"),d=b.createDocumentFragment();c.className=i.join(" "),Array.prototype.forEach.call(a,function(a){d.appendChild(a)}),c.appendChild(d),k.appendChild(c)}),a.appendChild(k),e(a,"columns",h)},c.remove_columns=function(c){var d=b.createRange();d.selectNodeContents(c);var f=Array.prototype.filter.call(d.extractContents().childNodes,function(b){return b instanceof a.HTMLElement}),g=f.length,h=f[0].childNodes.length,i=new Array(h*g);Array.prototype.forEach.call(f,function(a,b){Array.prototype.forEach.call(a.children,function(a,c){i[c*g+b]=a})});var j=b.createElement("div");return e(j,"columns",0),i.filter(function(a){return!!a}).forEach(function(a){j.appendChild(a)}),j},c.recreate_columns=function(b){a.requestAnimationFrame(function(){c.add_columns(b,c.remove_columns(b));var a=new CustomEvent("salvattoreChange",{detail:b});window.dispatchEvent(a)})},c.media_query_change=function(a){a.matches&&Array.prototype.forEach.call(d,c.recreate_columns)},c.get_css_rules=function(a){var b;try{b=a.sheet.cssRules||a.sheet.rules}catch(c){return[]}return b||[]},c.get_stylesheets=function(){return Array.prototype.concat.call(Array.prototype.slice.call(b.querySelectorAll("style[type='text/css']")),Array.prototype.slice.call(b.querySelectorAll("link[rel='stylesheet']")))},c.media_rule_has_columns_selector=function(a){for(var b,c=a.length;c--;)if(b=a[c],b.selectorText&&b.selectorText.match(/\[data-columns\](.*)::?before$/))return!0;return!1},c.scan_media_queries=function(){var b=[];a.matchMedia&&(c.get_stylesheets().forEach(function(d){Array.prototype.forEach.call(c.get_css_rules(d),function(d){d.media&&c.media_rule_has_columns_selector(d.cssRules)&&b.push(a.matchMedia(d.media.mediaText))})}),b.forEach(function(a){a.addListener(c.media_query_change)}))},c.next_element_column_index=function(a){var b,c,d,e=a.children,f=e.length,g=e.length-1;for(g;g>=0&&(c=e[g],d=c.children.length,!(0!==g&&b>d));g--){if(g+1===f){g=0;break}b=d}return g},c.create_list_of_fragments=function(a){for(var c=new Array(a),d=0;d!==a;)c[d]=b.createDocumentFragment(),d++;return c},c.append_elements=function(a,b){var d=a.children,e=d.length,f=c.create_list_of_fragments(e),g=c.next_element_column_index(a);b.forEach(function(a){f[g].appendChild(a),g===e-1?g=0:g++}),Array.prototype.forEach.call(d,function(a,b){a.appendChild(f[b])})},c.prepend_elements=function(a,d){var e=a.children,f=e.length,g=c.create_list_of_fragments(f),h=f-1;d.forEach(function(a){var b=g[h];b.insertBefore(a,b.firstChild),0===h?h=f-1:h--}),Array.prototype.forEach.call(e,function(a,b){a.insertBefore(g[b],a.firstChild)});for(var i=b.createDocumentFragment(),j=d.length%f;0!==j--;)i.appendChild(a.lastChild);a.insertBefore(i,a.firstChild)},c.register_grid=function(f){if("none"!==a.getComputedStyle(f).display){var g=b.createRange();g.selectNodeContents(f);var h=b.createElement("div");h.appendChild(g.extractContents()),e(h,"columns",0),c.add_columns(f,h),d.push(f)}},c.init=function(){var a=b.querySelectorAll("[data-columns]"),d=new CustomEvent("salvattoreInit");Array.prototype.forEach.call(a,c.register_grid),c.scan_media_queries(),c.ready=!0,window.dispatchEvent(d)},{append_elements:c.append_elements,prepend_elements:c.prepend_elements,register_grid:c.register_grid,init:c.init,ready:function(){return c.ready}}}(window,window.document);return a});<|endoftext|>


<commit_before>window.pager = {};

pager.start = function (viewModel) {
    $(window).bind('hashchange', function () {
        pager.route(viewModel.$page, window.location.hash);
    });
    //pager.route(viewModel.$page, window.location.hash);
};

pager.extendWithPage = function (viewModel) {
    viewModel.$page = ko.observable({
        children:ko.observableArray([]),
        route:ko.observableArray([]),
        parentRoute:ko.observableArray([]),
        matched:0,
        __id__:Math.random()
    });
};

pager.route = function ($page, hash) {
    // skip #
    if (hash[0] === '#') {
        hash = hash.slice(1);
    }
    // split on '/'
    var hashRoute = hash.split('/');
    // update route
    $page().route(hashRoute);
};

/**
 *
 * @class ko.bindingHandlers.page
 *
 * Configuration options:
 * id
 * with
 *
 */
ko.bindingHandlers.page = {
    init:function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        $(element).hide();
        var value = ko.utils.unwrapObservable(valueAccessor());
        var $page = bindingContext.$page || bindingContext.$data.$page;
        var page = $page();
        var route = ko.observableArray([]);
        var parentRoute = ko.observableArray([]);
        ko.computed(function () {
            route(page.route().slice(1));

            if (page.parentRoute) {
                var copyOfParent = page.parentRoute().slice(0);
                copyOfParent.push(value.id);
                parentRoute(copyOfParent);
            } else {
                parentRoute([value.id]);
            }
        });
        var pagerValues = {
            "$page":ko.observable({
                children:ko.observableArray([]),
                parentRoute:parentRoute,
                route:route,
                matched:0,
                __id__:Math.random()
            })
        };

        // Fetch source
        if (value.source) {
            $(element).load(value.source);
        }

        var childBindingContext = bindingContext.createChildContext(value.with ? value.with : viewModel);
        ko.utils.extend(childBindingContext, pagerValues);
        ko.applyBindingsToDescendants(childBindingContext, element);
        return { controlsDescendantBindings:true};
    },
    update:function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        var $page = bindingContext.$page || bindingContext.$data.$page;
        var page = $page();

        var show = function () {
            var $element = $(element);
            if (!$element.is(':visible')) {
                page.matched++;
                $(element).show();

                // Fetch source
                if (value.sourceOnShow) {
                    if (!value.sourceCache
                        || !element.__pagerLoaded__
                        || (typeof(value.sourceCache) === 'number' && element.__pagerLoaded__ + value.sourceCache * 1000 < Date.now())) {
                        element.__pagerLoaded__ = Date.now();
                        $(element).load(value.sourceOnShow);
                    }
                }
            }
        };

        if (value.id === '?' || value.id === 'start') {
            console.error(value.id + ', matched: ' + page.matched + ', pageid: ' + page.__id__);
        }
        if (value.id === page.route()[0]) {
            // show element
            show();
        } else if ((page.route()[0] === '' || page.route()[0] == null ) && value.id === 'start') {
            show();
        } else if (page.matched === 0 && value.id === '?') {
            show();
        } else {
            // hide element
            if ($(element).is(':visible')) {
                page.matched--;
                console.error("id: " + value.id + ", pageid: " + page.__id__);
                $(element).hide();
            }
        }
    }
};

ko.bindingHandlers['page-href'] = {
    init:function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {

    },
    update:function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        var $page = bindingContext.$page || bindingContext.$data.$page;
        var page = $page();

        var parentsToTrim = 0;
        while (value.substring(0, 3) === '../') {
            parentsToTrim++;
            value = value.slice(3);
        }

        var parentPath = page.parentRoute().slice(0, page.parentRoute().length - parentsToTrim).join('/');
        $(element).attr({
            'href':'#' + (parentPath === '' ? '' : parentPath + '/') + value
        });
    }
};<commit_msg>Removed console.error<commit_after>window.pager = {};

pager.start = function (viewModel) {
    $(window).bind('hashchange', function () {
        pager.route(viewModel.$page, window.location.hash);
    });
    //pager.route(viewModel.$page, window.location.hash);
};

pager.extendWithPage = function (viewModel) {
    viewModel.$page = ko.observable({
        children:ko.observableArray([]),
        route:ko.observableArray([]),
        parentRoute:ko.observableArray([]),
        matched:0,
        __id__:Math.random()
    });
};

pager.route = function ($page, hash) {
    // skip #
    if (hash[0] === '#') {
        hash = hash.slice(1);
    }
    // split on '/'
    var hashRoute = hash.split('/');
    // update route
    $page().route(hashRoute);
};

/**
 *
 * @class ko.bindingHandlers.page
 *
 * Configuration options:
 * id
 * with
 *
 */
ko.bindingHandlers.page = {
    init:function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        $(element).hide();
        var value = ko.utils.unwrapObservable(valueAccessor());
        var $page = bindingContext.$page || bindingContext.$data.$page;
        var page = $page();
        var route = ko.observableArray([]);
        var parentRoute = ko.observableArray([]);
        ko.computed(function () {
            route(page.route().slice(1));

            if (page.parentRoute) {
                var copyOfParent = page.parentRoute().slice(0);
                copyOfParent.push(value.id);
                parentRoute(copyOfParent);
            } else {
                parentRoute([value.id]);
            }
        });
        var pagerValues = {
            "$page":ko.observable({
                children:ko.observableArray([]),
                parentRoute:parentRoute,
                route:route,
                matched:0,
                __id__:Math.random()
            })
        };

        // Fetch source
        if (value.source) {
            $(element).load(value.source);
        }

        var childBindingContext = bindingContext.createChildContext(value.with ? value.with : viewModel);
        ko.utils.extend(childBindingContext, pagerValues);
        ko.applyBindingsToDescendants(childBindingContext, element);
        return { controlsDescendantBindings:true};
    },
    update:function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        var $page = bindingContext.$page || bindingContext.$data.$page;
        var page = $page();

        var show = function () {
            var $element = $(element);
            if (!$element.is(':visible')) {
                page.matched++;
                $(element).show();

                // Fetch source
                if (value.sourceOnShow) {
                    if (!value.sourceCache
                        || !element.__pagerLoaded__
                        || (typeof(value.sourceCache) === 'number' && element.__pagerLoaded__ + value.sourceCache * 1000 < Date.now())) {
                        element.__pagerLoaded__ = Date.now();
                        $(element).load(value.sourceOnShow);
                    }
                }
            }
        };

        if (value.id === page.route()[0]) {
            // show element
            show();
        } else if ((page.route()[0] === '' || page.route()[0] == null ) && value.id === 'start') {
            show();
        } else if (page.matched === 0 && value.id === '?') {
            show();
        } else {
            // hide element
            if ($(element).is(':visible')) {
                page.matched--;
                $(element).hide();
            }
        }
    }
};

ko.bindingHandlers['page-href'] = {
    init:function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {

    },
    update:function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        var $page = bindingContext.$page || bindingContext.$data.$page;
        var page = $page();

        var parentsToTrim = 0;
        while (value.substring(0, 3) === '../') {
            parentsToTrim++;
            value = value.slice(3);
        }

        var parentPath = page.parentRoute().slice(0, page.parentRoute().length - parentsToTrim).join('/');
        $(element).attr({
            'href':'#' + (parentPath === '' ? '' : parentPath + '/') + value
        });
    }
};<|endoftext|>