<commit_before>const {Transform} = require("../transform")
const RopeSequence = require("rope-sequence")

const {rebaseSteps} = require("./rebase")
exports.rebaseSteps = rebaseSteps

// !! This module implements an API into which a communication channel
// for collaborative editing can be hooked. See [this
// guide](guide/collab.html) for more details and an example.

function randomID() { return Math.floor(Math.random() * 0xFFFFFFFF) }

// ;; This state field accumulates changes that have to be sent to the
// central authority in the collaborating group and makes it possible
// to integrate changes made by peers into our local document. It is
// created and attached to the editor when the
// [plugin](#collabEditing) is enabled, and will be available as the
// `collab` field in the resulting editor state.
class CollabState {
  constructor(version, clientID, unconfirmed) {
    // : number
    // The version number of the last update received from the central
    // authority. Starts at 0 or the value of the `version` property
    // in the option object, for the editor's value when the option
    // was enabled.
    this.version = version

    // : number
    // This client's random ID. Used to identify the origin of
    // changes.
    this.clientID = clientID

    // : RopeSequence<{step: Step, inverted: Step}>
    // The local steps that havent been successfully sent to the
    // server yet.
    this.unconfirmed = unconfirmed
  }

  // :: () → ?{version: number, steps: [Step], clientID: number}
  // Provides the data describing the editor's unconfirmed steps. The
  // version and array of steps are the things you'd send to the
  // central authority. Returns null when there is nothing to send.
  sendableSteps() {
    if (this.unconfirmed.length == 0) return null
    return {
      version: this.version,
      steps: this.unconfirmed.map(s => s.step),
      clientID: this.clientID
    }
  }
}

function unconfirmedFrom(transform, start = 0) {
  let add = []
  for (let i = start; i < transform.steps.length; i++)
    add.push({step: transform.steps[i],
              inverted: transform.steps[i].invert(transform.docs[i])})
  return add
}

// :: (EditorState, [Step], [number]) → EditorState
// Pushes a set of steps (received from the central authority) into
// the editor state (which should have the collab plugin enabled).
// Will recognize its own changes, and confirm unconfirmed steps as
// appropriate. Remaining unconfirmed steps will be rebased over
// remote steps.
function receiveSteps(state, steps, clientIDs) {
  let collab = state.collab
  let version = collab.version + steps.length

  // Find out which prefix of the steps originated with us
  let ours = 0
  while (ours < clientIDs.length && clientIDs[ours] == collab.clientID) ++ours
  let unconfirmed = collab.unconfirmed.slice(ours)
  steps = ours ? steps.slice(ours) : steps

  // If all steps originated with us, we're done.
  if (!steps.length)
    return state.update({collab: new CollabState(version, collab.clientID, unconfirmed)})

  let nUnconfirmed = unconfirmed.length
  let transform = new Transform(state.doc)
  if (nUnconfirmed) {
    rebaseSteps(transform, unconfirmed.map(s => s.step), unconfirmed.map(s => s.inverted), steps)
  } else {
    for (let i = 0; i < steps.length; i++) transform.step(steps[i])
  }

  unconfirmed = RopeSequence.from(unconfirmedFrom(transform, nUnconfirmed + steps.length))
  let newCollabState = new CollabState(version, collab.clientID, unconfirmed)
  return state.applyTransform(transform, {rebased: nUnconfirmed, addToHistory: false, newCollabState})
}

// :: (?Object) → Object
//
// Creates a plugin that enables the collaborative editing framework
// for the editor.
//
// You can pass a `version` option, which determines the starting
// version number of the collaborative editing, and defaults to 0.
exports.collab = function(options) {
  return {
    stateFields: {
      collab: {
        init: () => new CollabState(options && options.version || 0, randomID(), RopeSequence.empty),
        applyTransform({collab}, transform, options) {
          return options.newCollabState ||
            new CollabState(collab.version, collab.clientID, collab.unconfirmed.append(unconfirmedFrom(transform)))
        }
      }
    },

    stateMethods: {
      collabReceive(steps, clientIDs) {
        return receiveSteps(this, steps, clientIDs)
      }
    }
  }
}
<commit_msg>Remove the concept of plugins, extend state class differently<commit_after>const {Transform} = require("../transform")
const RopeSequence = require("rope-sequence")

const {rebaseSteps} = require("./rebase")
exports.rebaseSteps = rebaseSteps

// !! This module implements an API into which a communication channel
// for collaborative editing can be hooked. See [this
// guide](guide/collab.html) for more details and an example.

function randomID() { return Math.floor(Math.random() * 0xFFFFFFFF) }

// ;; This state field accumulates changes that have to be sent to the
// central authority in the collaborating group and makes it possible
// to integrate changes made by peers into our local document. It is
// created and attached to the editor when the
// [plugin](#collabEditing) is enabled, and will be available as the
// `collab` field in the resulting editor state.
class CollabState {
  constructor(version, clientID, unconfirmed) {
    // : number
    // The version number of the last update received from the central
    // authority. Starts at 0 or the value of the `version` property
    // in the option object, for the editor's value when the option
    // was enabled.
    this.version = version

    // : number
    // This client's random ID. Used to identify the origin of
    // changes.
    this.clientID = clientID

    // : RopeSequence<{step: Step, inverted: Step}>
    // The local steps that havent been successfully sent to the
    // server yet.
    this.unconfirmed = unconfirmed
  }

  // :: () → ?{version: number, steps: [Step], clientID: number}
  // Provides the data describing the editor's unconfirmed steps. The
  // version and array of steps are the things you'd send to the
  // central authority. Returns null when there is nothing to send.
  sendableSteps() {
    if (this.unconfirmed.length == 0) return null
    return {
      version: this.version,
      steps: this.unconfirmed.map(s => s.step),
      clientID: this.clientID
    }
  }
}

function unconfirmedFrom(transform, start = 0) {
  let add = []
  for (let i = start; i < transform.steps.length; i++)
    add.push({step: transform.steps[i],
              inverted: transform.steps[i].invert(transform.docs[i])})
  return add
}

// :: (EditorState, [Step], [number]) → EditorState
// Pushes a set of steps (received from the central authority) into
// the editor state (which should have the collab plugin enabled).
// Will recognize its own changes, and confirm unconfirmed steps as
// appropriate. Remaining unconfirmed steps will be rebased over
// remote steps.
function receiveSteps(state, steps, clientIDs) {
  let collab = state.collab
  let version = collab.version + steps.length

  // Find out which prefix of the steps originated with us
  let ours = 0
  while (ours < clientIDs.length && clientIDs[ours] == collab.clientID) ++ours
  let unconfirmed = collab.unconfirmed.slice(ours)
  steps = ours ? steps.slice(ours) : steps

  // If all steps originated with us, we're done.
  if (!steps.length)
    return state.update({collab: new CollabState(version, collab.clientID, unconfirmed)})

  let nUnconfirmed = unconfirmed.length
  let transform = new Transform(state.doc)
  if (nUnconfirmed) {
    rebaseSteps(transform, unconfirmed.map(s => s.step), unconfirmed.map(s => s.inverted), steps)
  } else {
    for (let i = 0; i < steps.length; i++) transform.step(steps[i])
  }

  unconfirmed = RopeSequence.from(unconfirmedFrom(transform, nUnconfirmed + steps.length))
  let newCollabState = new CollabState(version, collab.clientID, unconfirmed)
  return state.applyTransform(transform, {rebased: nUnconfirmed, addToHistory: false, newCollabState})
}

// :: (?Object) → Object
//
// Creates a plugin that enables the collaborative editing framework
// for the editor.
//
// You can pass a `version` option, which determines the starting
// version number of the collaborative editing, and defaults to 0.
exports.collab = function(options) {
  return {
    fields: {
      collab: {
        init: () => new CollabState(options && options.version || 0, randomID(), RopeSequence.empty),
        applyTransform({collab}, transform, options) {
          return options.newCollabState ||
            new CollabState(collab.version, collab.clientID, collab.unconfirmed.append(unconfirmedFrom(transform)))
        }
      }
    },

    methods: {
      collabReceive(steps, clientIDs) {
        return receiveSteps(this, steps, clientIDs)
      }
    }
  }
}
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import ReactNative, {StyleSheet, Text, View, ScrollView, Dimensions, TouchableOpacity, ViewPagerAndroid, Platform} from 'react-native'

class CardsView extends Component {
  constructor(props) {
    super(props);
    this.scrollView = null;
    this.state = {
      width: 0,
      height: 0,
      childDimensions: []
    }
  }

  onScroll (options) {
    if(this.props.onScroll) this.props.onScroll(options);
  }

  onSelectedCard (index) {
    if(this.props.onSelectedCard) this.props.onSelectedCard(index);
  }

  getCardIndex(offset, velocity) {
    const VELOCITY_SCALE  = 0.6;
    console.log(velocity.x);
    const velocityOffset = {x:0, y:0};

    const CUTOFF_MIN = 0.5;
    const CUTOFF_MAX = 1.7;

    if(velocity.x <= -CUTOFF_MAX) velocityOffset.x = -this.state.width;
    else if(velocity.x < -CUTOFF_MIN) velocityOffset.x = this.state.width * 0.5 * (velocity.x/CUTOFF_MAX);
    else if(velocity.x <= CUTOFF_MIN) velocityOffset.x = 0;
    else if(velocity.x < CUTOFF_MAX) velocityOffset.x = this.state.width * 0.5 * (velocity.x/CUTOFF_MAX);
    else velocityOffset.x = this.state.width;

    if(velocity.y <= -CUTOFF_MAX) velocityOffset.y = -this.state.height;
    else if(velocity.y < -CUTOFF_MIN) velocityOffset.y = -this.state.height * 0.5 * (velocity.y/CUTOFF_MAX);
    else if(velocity.y <= CUTOFF_MIN) velocityOffset.y = 0;
    else if(velocity.y < CUTOFF_MAX) velocityOffset.y = this.state.height * 0.5 * (velocity.y/CUTOFF_MAX);
    else velocityOffset.y = this.state.height;

    console.log(`${velocity.x} :: ${velocityOffset.x}`)
    const center = {x:this.state.width * 0.5 + offset.x + velocityOffset.x, y: this.state.height * 0.5 + offset.y + velocityOffset.y};

    if(this.state.childDimensions) {
      if(this.props.horizontal && center.x < 0) return 0;
      else if(!this.props.horizontal && center.y < 0) return 0;

      for(var i = 0; i < this.state.childDimensions.length; i++) {
        const dimension = this.state.childDimensions[i];
        if(this.props.horizontal && center.x >= dimension.x && center.x < dimension.x + dimension.width) return i;
        if(!this.props.horizontal && center.y >= dimension.y && center.y < dimension.y + dimension.height) return i;
      }

      return this.state.childDimensions.length - 1;
    }
  }

  onScrollEndDrag(e) {
    const index = this.getCardIndex(e.nativeEvent.contentOffset, e.nativeEvent.velocity) ;

    const firstItemDim = this.state.childDimensions[0];
    const dimension = this.state.childDimensions[index];
    const x = dimension.x + (dimension.width - firstItemDim.width)/2;
    const y = dimension.y + (dimension.height - firstItemDim.height)/2;

    if(this.props.horizontal) this.scrollView.scrollTo({x});
    else this.scrollView.scrollTo({y});

    this.onSelectedCard(index);
  }

  getCardWidth(child, layoutWidth, layoutHeight) {
    if(child == null) return layoutWidth;
    if(child.props.cardWidth == null) return layoutWidth;
    if(child.props.cardWidth instanceof Function) {
      return parseFloat(child.props.cardWidth({width: layoutWidth, height: layoutHeight}));
    } else {
      return parseFloat(child.props.cardWidth)
    }
  }

  getCardHeight(child, layoutWidth, layoutHeight) {
    if(child == null) return layoutHeight;
    if(child.props.cardHeight == null) return layoutHeight;
    if(child.props.cardHeight instanceof Function) {
      return parseFloat(child.props.cardHeight({width: layoutWidth, height: layoutHeight}));
    } else {
      return parseFloat(child.props.cardHeight)
    }
  }

  onLayout(e) {
    const layoutWidth = e.nativeEvent.layout.width || 0;
    const layoutHeight = e.nativeEvent.layout.height || 0;

    let dimAcc = {x:0, y:0};
    const childDimensions = this.props.children && this.props.children.map( (child, i) => {
      const width = this.getCardWidth(child, layoutWidth, layoutHeight);
      const height = this.getCardHeight(child, layoutWidth, layoutHeight);
      const x = dimAcc.x;
      const y = dimAcc.y;
      dimAcc.x += width;
      dimAcc.y += height;
      return {width, height, x, y}
    });

    this.setState({ width: layoutWidth, height: layoutHeight, childDimensions })
  }

  render() {
    const children = this.props.children.map( (child, i) => {
      const dimensions = this.state.childDimensions[i];
      var st = {};
      if(dimensions && dimensions.width) st.width = dimensions.width;
      if(dimensions && dimensions.height) st.height = dimensions.height;
      return <View style={st} key={i}>{child}</View>
    })
    const paddingLeft = this.state.childDimensions && this.state.childDimensions[0] && this.state.childDimensions[0].width? (this.state.width - this.state.childDimensions[0].width)/2: 0
    const paddingRight = this.state.childDimensions && this.state.childDimensions[this.state.childDimensions.length - 1] && this.state.childDimensions[this.state.childDimensions.length - 1].width? (this.state.width - this.state.childDimensions[this.state.childDimensions.length - 1].width)/2 :0

    const paddingTop = this.state.childDimensions && this.state.childDimensions[0] && this.state.childDimensions[0].height? (this.state.height - this.state.childDimensions[0].height)/2: 0
    const paddingBottom = this.state.childDimensions && this.state.childDimensions[this.state.childDimensions.length - 1] && this.state.childDimensions[this.state.childDimensions.length - 1].height? (this.state.height - this.state.childDimensions[this.state.childDimensions.length - 1].height)/2 :0

    return <ScrollView
      ref={(scrollView) => { this.scrollView = scrollView; }}
      onScrollEndDrag={this.onScrollEndDrag.bind(this)}
      onScroll={this.onScroll.bind(this)}
      scrollEventThrottle={this.props.scrollEventThrottle}
      horizontal={this.props.horizontal}
      onLayout={this.onLayout.bind(this)}
      contentContainerStyle={{paddingLeft, paddingRight, paddingTop, paddingBottom}}>
      {children}
  </ScrollView>
  }
}

CardsView.defaultProps = {
  horizontal : true,
  scrollEventThrottle: 100,
}

CardsView.propTypes = {
  horizontal : React.PropTypes.bool,
  scrollEventThrottle: React.PropTypes.number,
  cardWidth: React.PropTypes.oneOfType([React.PropTypes.func, React.PropTypes.number]),
  cardHeight: React.PropTypes.oneOfType([React.PropTypes.func, React.PropTypes.number]),
  onSelectedCard: React.PropTypes.func,
}

export default CardsView;
<commit_msg>removed scrollbars<commit_after>import React, {Component} from 'react'
import ReactNative, {StyleSheet, Text, View, ScrollView, Dimensions, TouchableOpacity, ViewPagerAndroid, Platform} from 'react-native'

class CardsView extends Component {
  constructor(props) {
    super(props);
    this.scrollView = null;
    this.state = {
      width: 0,
      height: 0,
      childDimensions: []
    }
  }

  onScroll (options) {
    if(this.props.onScroll) this.props.onScroll(options);
  }

  onSelectedCard (index) {
    if(this.props.onSelectedCard) this.props.onSelectedCard(index);
  }

  getCardIndex(offset, velocity) {
    const VELOCITY_SCALE  = 0.6;
    const velocityOffset = {x:0, y:0};

    const CUTOFF_MIN = 0.5;
    const CUTOFF_MAX = 1.7;

    if(velocity.x <= -CUTOFF_MAX) velocityOffset.x = -this.state.width;
    else if(velocity.x < -CUTOFF_MIN) velocityOffset.x = this.state.width * 0.5 * (velocity.x/CUTOFF_MAX);
    else if(velocity.x <= CUTOFF_MIN) velocityOffset.x = 0;
    else if(velocity.x < CUTOFF_MAX) velocityOffset.x = this.state.width * 0.5 * (velocity.x/CUTOFF_MAX);
    else velocityOffset.x = this.state.width;

    if(velocity.y <= -CUTOFF_MAX) velocityOffset.y = -this.state.height;
    else if(velocity.y < -CUTOFF_MIN) velocityOffset.y = -this.state.height * 0.5 * (velocity.y/CUTOFF_MAX);
    else if(velocity.y <= CUTOFF_MIN) velocityOffset.y = 0;
    else if(velocity.y < CUTOFF_MAX) velocityOffset.y = this.state.height * 0.5 * (velocity.y/CUTOFF_MAX);
    else velocityOffset.y = this.state.height;

    const center = {x:this.state.width * 0.5 + offset.x + velocityOffset.x, y: this.state.height * 0.5 + offset.y + velocityOffset.y};

    if(this.state.childDimensions) {
      if(this.props.horizontal && center.x < 0) return 0;
      else if(!this.props.horizontal && center.y < 0) return 0;

      for(var i = 0; i < this.state.childDimensions.length; i++) {
        const dimension = this.state.childDimensions[i];
        if(this.props.horizontal && center.x >= dimension.x && center.x < dimension.x + dimension.width) return i;
        if(!this.props.horizontal && center.y >= dimension.y && center.y < dimension.y + dimension.height) return i;
      }

      return this.state.childDimensions.length - 1;
    }
  }

  onScrollEndDrag(e) {
    const index = this.getCardIndex(e.nativeEvent.contentOffset, e.nativeEvent.velocity) ;

    const firstItemDim = this.state.childDimensions[0];
    const dimension = this.state.childDimensions[index];
    const x = dimension.x + (dimension.width - firstItemDim.width)/2;
    const y = dimension.y + (dimension.height - firstItemDim.height)/2;

    if(this.props.horizontal) this.scrollView.scrollTo({x});
    else this.scrollView.scrollTo({y});

    this.onSelectedCard(index);
  }

  getCardWidth(child, layoutWidth, layoutHeight) {
    if(child == null) return layoutWidth;
    if(child.props.cardWidth == null) return layoutWidth;
    if(child.props.cardWidth instanceof Function) {
      return parseFloat(child.props.cardWidth({width: layoutWidth, height: layoutHeight}));
    } else {
      return parseFloat(child.props.cardWidth)
    }
  }

  getCardHeight(child, layoutWidth, layoutHeight) {
    if(child == null) return layoutHeight;
    if(child.props.cardHeight == null) return layoutHeight;
    if(child.props.cardHeight instanceof Function) {
      return parseFloat(child.props.cardHeight({width: layoutWidth, height: layoutHeight}));
    } else {
      return parseFloat(child.props.cardHeight)
    }
  }

  onLayout(e) {
    const layoutWidth = e.nativeEvent.layout.width || 0;
    const layoutHeight = e.nativeEvent.layout.height || 0;

    let dimAcc = {x:0, y:0};
    const childDimensions = this.props.children && this.props.children.map( (child, i) => {
      const width = this.getCardWidth(child, layoutWidth, layoutHeight);
      const height = this.getCardHeight(child, layoutWidth, layoutHeight);
      const x = dimAcc.x;
      const y = dimAcc.y;
      dimAcc.x += width;
      dimAcc.y += height;
      return {width, height, x, y}
    });

    this.setState({ width: layoutWidth, height: layoutHeight, childDimensions })
  }

  render() {
    const children = this.props.children.map( (child, i) => {
      const dimensions = this.state.childDimensions[i];
      var st = {};
      if(dimensions && dimensions.width) st.width = dimensions.width;
      if(dimensions && dimensions.height) st.height = dimensions.height;
      return <View style={st} key={i}>{child}</View>
    })
    const paddingLeft = this.state.childDimensions && this.state.childDimensions[0] && this.state.childDimensions[0].width? (this.state.width - this.state.childDimensions[0].width)/2: 0
    const paddingRight = this.state.childDimensions && this.state.childDimensions[this.state.childDimensions.length - 1] && this.state.childDimensions[this.state.childDimensions.length - 1].width? (this.state.width - this.state.childDimensions[this.state.childDimensions.length - 1].width)/2 :0

    const paddingTop = this.state.childDimensions && this.state.childDimensions[0] && this.state.childDimensions[0].height? (this.state.height - this.state.childDimensions[0].height)/2: 0
    const paddingBottom = this.state.childDimensions && this.state.childDimensions[this.state.childDimensions.length - 1] && this.state.childDimensions[this.state.childDimensions.length - 1].height? (this.state.height - this.state.childDimensions[this.state.childDimensions.length - 1].height)/2 :0

    return <ScrollView
      ref={(scrollView) => { this.scrollView = scrollView; }}
      onScrollEndDrag={this.onScrollEndDrag.bind(this)}
      onScroll={this.onScroll.bind(this)}
      scrollEventThrottle={this.props.scrollEventThrottle}
      horizontal={this.props.horizontal}
      onLayout={this.onLayout.bind(this)}
      contentContainerStyle={{paddingLeft, paddingRight, paddingTop, paddingBottom}}>
      {children}
  </ScrollView>
  }
}

CardsView.defaultProps = {
  horizontal : true,
  scrollEventThrottle: 100,
  showsHorizontalScrollIndicator: false,
  showsVerticalScrollIndicator: false,
}

CardsView.propTypes = {
  horizontal : React.PropTypes.bool,
  scrollEventThrottle: React.PropTypes.number,
  cardWidth: React.PropTypes.oneOfType([React.PropTypes.func, React.PropTypes.number]),
  cardHeight: React.PropTypes.oneOfType([React.PropTypes.func, React.PropTypes.number]),
  onSelectedCard: React.PropTypes.func,
  showsHorizontalScrollIndicator: React.PropTypes.bool,
  showsVerticalScrollIndicator: React.PropTypes.bool,
}

export default CardsView;
<|endoftext|>


<commit_before>var es = require('event-stream')
var RemoteEventEmitter = require('remote-events')
var _bs = require('browser-stream')

function MuxDemux () {
  var ree = new RemoteEventEmitter()
  var bs = _bs(ree)
  bs.getMuxDemuxStream = function () {
    return es.connect(
      es.split(),
      es.parse(),
      ree.getStream(),
      es.stringify()
    )
  }
  return bs
}

module.exports = MuxDemux
<commit_msg>rewrite. (breaking changes). MuxDemux is now a stream, and sub-streams allow half duplex<commit_after>var es = require('event-stream')

function MuxDemux () {

  function createID() {
    return (
      Math.random().toString(16).slice(2) +
      Math.random().toString(16).slice(2)
    )
  }

  var streams = {}, streamCount = 0
  var md = es.through(function (data) {
    var id = data.shift()
    var event = data[0]
    var s = streams[id]
    if(!s) {
      if(event != 'new')
        return md.emit('error', new Error('does not have stream:' + id))
      md.emit('connection', createStream(id, data[1]))
    }
    else if (event === 'pause')
      s.paused = true
    else if (event === 'resume') {
      var p = s.paused
      s.paused = false
      if(p) s.emit('drain')
    }
    else
      s.emit.apply(s, data)
  })

  md.once('close', function () {
    var err = new Error ('unexpected disconnection')
    for (var i in streams) {
      streams[i].emit('error', err)
      streams[i].destroy()
    }
  })

  function createStream(id, meta) {
    var s = es.through(function (data) {
      if(!this.writable)
        throw new Error('stream is not writable')
      md.emit('data', [s.id, 'data', data])
    }, function () {
      md.emit('data', [s.id, 'end'])
    })
    s.pause = function () {
      md.emit('data', [s.id, 'pause'])
    }
    s.resume = function () {
      md.emit('data', [s.id, 'resume'])
    }
    s.once('close', function () {
      delete streams[id]
    })
    streams[s.id = id] = s
    s.meta = meta
    return s
  }

  md.createStream = function (meta) {
    var s = createStream(createID(), meta)
    md.emit('data', [s.id, 'new', meta])
    return s
  }
  md.createWriteStream = md.createStream
  md.createReadStream = md.createStream
  return md
}

module.exports = MuxDemux
<|endoftext|>


<commit_before>'use strict'
require('@iarna/lib')('util', '.')

Object.defineProperty(exports, 'get', {
  get: () => require('./ff-get.js')
})

Object.defineProperty(exports, 'update', {
  get: () => require('./ff-update.js')
})

Object.defineProperty(exports, 'generate', {
  get: () => require('./ff-generate.js')
})

Object.defineProperty(exports, 'cacheClear', {
  get: () => require('./ff-cache-clear.js')
})
<commit_msg>index: Export our fic class as part of our public interface<commit_after>'use strict'
require('@iarna/lib')('util', '.')

Object.defineProperty(exports, 'get', {
  get: () => require('./ff-get.js')
})

Object.defineProperty(exports, 'update', {
  get: () => require('./ff-update.js')
})

Object.defineProperty(exports, 'generate', {
  get: () => require('./ff-generate.js')
})

Object.defineProperty(exports, 'cacheClear', {
  get: () => require('./ff-cache-clear.js')
})

Object.defineProperty(exports, 'Fic', {
  get: () => require('./fic.js')
})
<|endoftext|>


<commit_before>// ControllerRouter class

'use strict';

var includes             = require('es5-ext/array/#/contains')
  , customError          = require('es5-ext/error/custom')
  , identity             = require('es5-ext/function/identity')
  , assign               = require('es5-ext/object/assign')
  , isPromise            = require('es5-ext/object/is-promise')
  , ensureCallable       = require('es5-ext/object/valid-callable')
  , ensureObject         = require('es5-ext/object/valid-object')
  , ensureStringifiable  = require('es5-ext/object/validate-stringifiable-value')
  , forEach              = require('es5-ext/object/for-each')
  , endsWith             = require('es5-ext/string/#/ends-with')
  , ee                   = require('event-emitter')
  , d                    = require('d')
  , autoBind             = require('d/auto-bind')
  , lazy                 = require('d/lazy')
  , compareDynamicRoutes = require('./lib/compare-dynamic-routes')
  , isStatic             = require('./lib/is-token-static')
  , resolvePathMeta      = require('./lib/resolve-path-meta')
  , ensurePath           = require('./lib/ensure-path')

  , push = Array.prototype.push, slice = Array.prototype.slice, apply = Function.prototype.apply
  , create = Object.create, defineProperty = Object.defineProperty, stringify = JSON.stringify
  , routeCallIdIndex = 0;

var ControllerRouter = module.exports = Object.defineProperties(function (routes/*, options*/) {
	var options;
	// Validate initialization
	if (!(this instanceof ControllerRouter)) return new ControllerRouter(routes, arguments[1]);
	options = Object(arguments[1]);
	this.constructor.ensureRoutes(routes, options);

	defineProperty(this, 'eventProto', d((options.eventProto != null) ? ensureObject(options.eventProto) : {}));

	defineProperty(this, 'routes', d(routes));

	// Configure internal routes map
	forEach(this.constructor.normalizeRoutes(routes, options), function (conf, path) {
		var pathData = resolvePathMeta(path);
		if (pathData.static) {
			this._staticRoutes[path] = conf;
			return;
		}
		if (!this._dynamicRoutes[pathData.tokens.length]) {
			this._dynamicRoutes[pathData.tokens.length] = [];
		}
		pathData.conf = conf;
		pathData.matchPositionsLength = pathData.matchPositions.length;
		this._dynamicRoutes[pathData.tokens.length].push(pathData);
	}, this);
	forEach(this._dynamicRoutes, function (data) { data.sort(compareDynamicRoutes); });

	// Whether route should resolve with promise or not
	if (options.promiseResultImplementation) {
		defineProperty(this, 'Promise', d(ensureCallable(options.promiseResultImplementation)));
	}
}, {
	// Validates provided routes map
	ensureRoutes: d(function (routes) {
		forEach(ensureObject(routes), function (conf, path) {
			var isDynamic;
			ensureObject(conf);
			ensurePath(path);
			if (path !== '/') isDynamic = !path.split('/').every(isStatic);
			if (typeof conf === 'function') {
				if (isDynamic) {
					throw customError("Missing match function for " + stringify(path), 'MISSING_MATCH');
				}
				return;
			}
			if (typeof conf.controller !== 'function') {
				throw customError("Invalid controller for " + stringify(path), 'INVALID_CONTROLLER');
			}
			if (typeof conf.match !== 'function') {
				if (isDynamic) {
					throw customError("Invalid match function for " + stringify(path), 'INVALID_MATCH');
				}
				return;
			}
			if (!isDynamic) {
				throw customError("Missing regular expression in path " + stringify(path),
					'MISSING_PATH_REGEX');
			}
		});
		return routes;
	}),
	// Normalizes routes to bare ControllerRouter format. If ControllerRouter extension
	// provides more sophisticated routes format, this should be a function which transforms it
	// directly to map as understood by ControllerRouter
	normalizeRoutes: d(identity)
});

ee(Object.defineProperties(ControllerRouter.prototype, assign({
	_resolveResult: d(function (result) {
		var routeResult = result;
		if (result && isPromise(result.result)) {
			routeResult = result.result.then(function (resolvedResult) {
				result.result = resolvedResult;
				return result;
			});
		}
		return this.Promise ? this.Promise.resolve(routeResult) : routeResult;
	}),
	_resolveController: d(function (fn) {
		if (!this.Promise) {
			this.lastRouteData.result = fn();
		} else {
			try {
				this.lastRouteData.result = fn();
			} catch (e) {
				return this.Promise.reject(e);
			}
		}
		return this._resolveResult(this.lastRouteData);
	})

}, lazy({
	// Internal map of dynamic routes (those that contain regexp tokens)
	_dynamicRoutes: d(function () { return create(null); }),
	// Internal map of static routes (no regexp tokens)
	_staticRoutes: d(function () { return create(null); })
}), autoBind({
	// Routes path to controller and provides an event to be used for controller invocation
	routeEvent: d(function (event, path/*, …controllerArgs*/) {
		var pathTokens, controllerArgs = slice.call(arguments, 2), conf, initConf, controller
		  , asyncResult, callId = ++routeCallIdIndex;

		ensureObject(event);
		path = ensureStringifiable(path);

		this.emit("route:before", { event: event, path: path, args: controllerArgs });

		// Preprepare route data
		this.lastRouteData = { event: event };

		// Do not proceed for no path
		if (!path) return this._resolveResult(false);

		// Resolve path for route resolution
		if (path[0] === '/') path = path.slice(1);
		if (endsWith.call(path, '/')) path = path.slice(0, -1);
		event.path = path || '/';

		// Handle eventual static path
		conf = this._staticRoutes[path || '/'];
		if (conf) {
			initConf = this.routes[path || '/'];
			controller = conf.controller || conf;
			this.lastRouteData.conf =  initConf;
			return this._resolveController(apply.bind(controller, event, controllerArgs));
		}

		// Handle eventual dynamic paths
		pathTokens = path.split('/');
		if (!this._dynamicRoutes[pathTokens.length]) return this._resolveResult(false);
		this._dynamicRoutes[pathTokens.length].some(function (data) {
			var args = [], matchResult;

			// Check whether path matches
			if (!data.tokens.every(function (token, index) {
					var pathToken = pathTokens[index];
					if (includes.call(data.matchPositions, index)) {
						if (!token.test(pathToken)) return false;
						args.push(pathToken);
						return true;
					}
					return (token === pathToken);
				})) {
				return false;
			}

			// Path matches, now resolve with `match` function
			matchResult = data.conf.match.apply(event, args);
			if (isPromise(matchResult)) {
				asyncResult = matchResult.then(function (isMatch) {
					if (!isMatch) return false;
					this.lastRouteData = {
						event: event,
						conf: this.routes[data.path]
					};
					if (callId !== routeCallIdIndex) {
						// Cancel route (as promises are concerned we need to reject)
						throw customError("Route cancelled, as next one took action", 'OUTDATED_ROUTE_CALL');
					}
					this.lastRouteData.result = apply.call(data.conf.controller, event, controllerArgs);
					return this._resolveResult(this.lastRouteData);
				}.bind(this));
			} else if (matchResult) {
				conf = data.conf;
				initConf = this.routes[data.path];
			}
			return true;
		}, this);

		// If `match` is asynchronous return promise
		if (asyncResult) return this.Promise ? this.Promise.resolve(asyncResult) : asyncResult;
		if (!conf) return this._resolveResult(false);
		this.lastRouteData.conf = initConf;
		return this._resolveController(apply.bind(conf.controller, event, controllerArgs));
	}),

	// Routes path to controller
	route: d(function (path/*, …controllerArgs*/) {
		var args = [create(this.eventProto)];
		push.apply(args, arguments);
		return this.routeEvent.apply(this, args);
	})
}))));
<commit_msg>style: fix lint issue<commit_after>// ControllerRouter class

'use strict';

var includes             = require('es5-ext/array/#/contains')
  , customError          = require('es5-ext/error/custom')
  , identity             = require('es5-ext/function/identity')
  , assign               = require('es5-ext/object/assign')
  , isPromise            = require('es5-ext/object/is-promise')
  , ensureCallable       = require('es5-ext/object/valid-callable')
  , ensureObject         = require('es5-ext/object/valid-object')
  , ensureStringifiable  = require('es5-ext/object/validate-stringifiable-value')
  , forEach              = require('es5-ext/object/for-each')
  , endsWith             = require('es5-ext/string/#/ends-with')
  , ee                   = require('event-emitter')
  , d                    = require('d')
  , autoBind             = require('d/auto-bind')
  , lazy                 = require('d/lazy')
  , compareDynamicRoutes = require('./lib/compare-dynamic-routes')
  , isStatic             = require('./lib/is-token-static')
  , resolvePathMeta      = require('./lib/resolve-path-meta')
  , ensurePath           = require('./lib/ensure-path')

  , push = Array.prototype.push, slice = Array.prototype.slice, apply = Function.prototype.apply
  , create = Object.create, defineProperty = Object.defineProperty, stringify = JSON.stringify
  , routeCallIdIndex = 0;

var ControllerRouter = module.exports = Object.defineProperties(function (routes/*, options*/) {
	var options;
	// Validate initialization
	if (!(this instanceof ControllerRouter)) return new ControllerRouter(routes, arguments[1]);
	options = Object(arguments[1]);
	this.constructor.ensureRoutes(routes, options);

	defineProperty(this, 'eventProto',
		d((options.eventProto != null) ? ensureObject(options.eventProto) : {}));

	defineProperty(this, 'routes', d(routes));

	// Configure internal routes map
	forEach(this.constructor.normalizeRoutes(routes, options), function (conf, path) {
		var pathData = resolvePathMeta(path);
		if (pathData.static) {
			this._staticRoutes[path] = conf;
			return;
		}
		if (!this._dynamicRoutes[pathData.tokens.length]) {
			this._dynamicRoutes[pathData.tokens.length] = [];
		}
		pathData.conf = conf;
		pathData.matchPositionsLength = pathData.matchPositions.length;
		this._dynamicRoutes[pathData.tokens.length].push(pathData);
	}, this);
	forEach(this._dynamicRoutes, function (data) { data.sort(compareDynamicRoutes); });

	// Whether route should resolve with promise or not
	if (options.promiseResultImplementation) {
		defineProperty(this, 'Promise', d(ensureCallable(options.promiseResultImplementation)));
	}
}, {
	// Validates provided routes map
	ensureRoutes: d(function (routes) {
		forEach(ensureObject(routes), function (conf, path) {
			var isDynamic;
			ensureObject(conf);
			ensurePath(path);
			if (path !== '/') isDynamic = !path.split('/').every(isStatic);
			if (typeof conf === 'function') {
				if (isDynamic) {
					throw customError("Missing match function for " + stringify(path), 'MISSING_MATCH');
				}
				return;
			}
			if (typeof conf.controller !== 'function') {
				throw customError("Invalid controller for " + stringify(path), 'INVALID_CONTROLLER');
			}
			if (typeof conf.match !== 'function') {
				if (isDynamic) {
					throw customError("Invalid match function for " + stringify(path), 'INVALID_MATCH');
				}
				return;
			}
			if (!isDynamic) {
				throw customError("Missing regular expression in path " + stringify(path),
					'MISSING_PATH_REGEX');
			}
		});
		return routes;
	}),
	// Normalizes routes to bare ControllerRouter format. If ControllerRouter extension
	// provides more sophisticated routes format, this should be a function which transforms it
	// directly to map as understood by ControllerRouter
	normalizeRoutes: d(identity)
});

ee(Object.defineProperties(ControllerRouter.prototype, assign({
	_resolveResult: d(function (result) {
		var routeResult = result;
		if (result && isPromise(result.result)) {
			routeResult = result.result.then(function (resolvedResult) {
				result.result = resolvedResult;
				return result;
			});
		}
		return this.Promise ? this.Promise.resolve(routeResult) : routeResult;
	}),
	_resolveController: d(function (fn) {
		if (!this.Promise) {
			this.lastRouteData.result = fn();
		} else {
			try {
				this.lastRouteData.result = fn();
			} catch (e) {
				return this.Promise.reject(e);
			}
		}
		return this._resolveResult(this.lastRouteData);
	})

}, lazy({
	// Internal map of dynamic routes (those that contain regexp tokens)
	_dynamicRoutes: d(function () { return create(null); }),
	// Internal map of static routes (no regexp tokens)
	_staticRoutes: d(function () { return create(null); })
}), autoBind({
	// Routes path to controller and provides an event to be used for controller invocation
	routeEvent: d(function (event, path/*, …controllerArgs*/) {
		var pathTokens, controllerArgs = slice.call(arguments, 2), conf, initConf, controller
		  , asyncResult, callId = ++routeCallIdIndex;

		ensureObject(event);
		path = ensureStringifiable(path);

		this.emit("route:before", { event: event, path: path, args: controllerArgs });

		// Preprepare route data
		this.lastRouteData = { event: event };

		// Do not proceed for no path
		if (!path) return this._resolveResult(false);

		// Resolve path for route resolution
		if (path[0] === '/') path = path.slice(1);
		if (endsWith.call(path, '/')) path = path.slice(0, -1);
		event.path = path || '/';

		// Handle eventual static path
		conf = this._staticRoutes[path || '/'];
		if (conf) {
			initConf = this.routes[path || '/'];
			controller = conf.controller || conf;
			this.lastRouteData.conf =  initConf;
			return this._resolveController(apply.bind(controller, event, controllerArgs));
		}

		// Handle eventual dynamic paths
		pathTokens = path.split('/');
		if (!this._dynamicRoutes[pathTokens.length]) return this._resolveResult(false);
		this._dynamicRoutes[pathTokens.length].some(function (data) {
			var args = [], matchResult;

			// Check whether path matches
			if (!data.tokens.every(function (token, index) {
					var pathToken = pathTokens[index];
					if (includes.call(data.matchPositions, index)) {
						if (!token.test(pathToken)) return false;
						args.push(pathToken);
						return true;
					}
					return (token === pathToken);
				})) {
				return false;
			}

			// Path matches, now resolve with `match` function
			matchResult = data.conf.match.apply(event, args);
			if (isPromise(matchResult)) {
				asyncResult = matchResult.then(function (isMatch) {
					if (!isMatch) return false;
					this.lastRouteData = {
						event: event,
						conf: this.routes[data.path]
					};
					if (callId !== routeCallIdIndex) {
						// Cancel route (as promises are concerned we need to reject)
						throw customError("Route cancelled, as next one took action", 'OUTDATED_ROUTE_CALL');
					}
					this.lastRouteData.result = apply.call(data.conf.controller, event, controllerArgs);
					return this._resolveResult(this.lastRouteData);
				}.bind(this));
			} else if (matchResult) {
				conf = data.conf;
				initConf = this.routes[data.path];
			}
			return true;
		}, this);

		// If `match` is asynchronous return promise
		if (asyncResult) return this.Promise ? this.Promise.resolve(asyncResult) : asyncResult;
		if (!conf) return this._resolveResult(false);
		this.lastRouteData.conf = initConf;
		return this._resolveController(apply.bind(conf.controller, event, controllerArgs));
	}),

	// Routes path to controller
	route: d(function (path/*, …controllerArgs*/) {
		var args = [create(this.eventProto)];
		push.apply(args, arguments);
		return this.routeEvent.apply(this, args);
	})
}))));
<|endoftext|>


<commit_before>var magnet = require('magnet-uri')
var parseTorrentFile = require('parse-torrent-file')

/**
 * Given a torrentId, return a hex string.
 * @param  {string|Buffer} torrentId magnet uri, torrent file, infohash, or parsed torrent
 * @return {string} info hash (hex string)
 */

module.exports = function parseTorrent (torrentId) {
  if (typeof torrentId === 'string' && /magnet:/.test(torrentId)) {
    // magnet uri (string)
    return magnet(torrentId)
  } else if (typeof torrentId === 'string' &&
      (torrentId.length === 40 || torrentId.length === 32)) {
    // info hash (hex/base-32 string)
    var info = magnet('magnet:?xt=urn:btih:' + torrentId)
    if (info)
      return { infoHash: info.infoHash }
    else
      return null
  } else if (Buffer.isBuffer(torrentId) && torrentId.length === 20) {
    // info hash (buffer)
    return { infoHash: torrentId.toString('hex') }
  } else if (Buffer.isBuffer(torrentId)) {
    // .torrent file (buffer)
    try {
      return parseTorrentFile(torrentId)
    } catch (err) {
      return null
    }
  } else if (torrentId && torrentId.infoHash) {
    // parsed torrent (from `parse-torrent` or `magnet-uri` module)
    return torrentId
  } else {
    return null
  }
}

module.exports.toBuffer = parseTorrentFile.toBuffer
<commit_msg>fix comment<commit_after>var magnet = require('magnet-uri')
var parseTorrentFile = require('parse-torrent-file')

/**
 * Parse a torrent identifier (magnet uri, .torrent file, info hash)
 * @param  {string|Buffer|Object} torrentId
 * @return {Object}
 */
module.exports = function parseTorrent (torrentId) {
  if (typeof torrentId === 'string' && /magnet:/.test(torrentId)) {
    // magnet uri (string)
    return magnet(torrentId)
  } else if (typeof torrentId === 'string' &&
      (torrentId.length === 40 || torrentId.length === 32)) {
    // info hash (hex/base-32 string)
    var info = magnet('magnet:?xt=urn:btih:' + torrentId)
    if (info)
      return { infoHash: info.infoHash }
    else
      return null
  } else if (Buffer.isBuffer(torrentId) && torrentId.length === 20) {
    // info hash (buffer)
    return { infoHash: torrentId.toString('hex') }
  } else if (Buffer.isBuffer(torrentId)) {
    // .torrent file (buffer)
    try {
      return parseTorrentFile(torrentId)
    } catch (err) {
      return null
    }
  } else if (torrentId && torrentId.infoHash) {
    // parsed torrent (from `parse-torrent` or `magnet-uri` module)
    return torrentId
  } else {
    return null
  }
}

module.exports.toBuffer = parseTorrentFile.toBuffer
<|endoftext|>


<commit_before>"use strict"

var crypto = require("crypto")
var request = require("request")
var EventEmitter = require("events")
var util = require("util")
var url = require("url")
var path = require("path")
var os = require("os")
var deepcopy = require('deepcopy')

const VERSION = "0.0.17"
const DEFAULT_COLLECTOR_URL = "https://metrics-api.iopipe.com"

function _make_generateLog(emitter, func, start_time, config, context) {
  return function generateLog(err, callback) {
    var hash = crypto.createHash('sha256');
    hash.update(func.toString());
    var function_id = hash.digest('hex')

    var runtime_env = {
      agent: {
        runtime: "nodejs",
        version: VERSION
      },
      os: {
        hostname: os.hostname(),
        totalmem: os.totalmem(),
        uptime: os.uptime(),
        freemem: os.freemem(),
        cpus: os.cpus(),
        arch: os.arch()
      },
      nodejs: {
        title: process.title,
        version: process.version,
        modulesloadList: process.modulesloadList,
        versions: process.versions,
        arch: process.arch,
        platform: process.platform,
        argv: process.argv,
        execArgv: process.execArgv,
        pid: process.pid,
        features: process.features,
        execPath: process.execPath,
        debugPort: process.debugPort,
        _maxListeners: process._maxListeners,
        config: process.config,
        maxTickDepth: process.maxTickDepth,
        // /* Circular ref */ mainModule: process.mainModule,
        release: process.release,
      }
    }

    var retainErr = {};
    if (err) {
      retainErr = ((err) => {
                    return {
                      name: err.name,
                      message: err.message,
                      stack: err.stack,
                      lineNumber: err.lineNumber,
                      columnNumber: err.columnNumber,
                      fileName: err.fileName
                    }
                  })((typeof(err) === "string") ? new Error(err) : err)
    }

    var qfuncs = ["uptime", "getuid", "getgid", "geteuid", "getegid", "memoryUsage"]
    for (var i = 0; i < qfuncs.length; i++) {
      // Lacking a process.prototype, evil eval.
      runtime_env.nodejs[qfuncs[i]] = eval("process."+qfuncs[i]+"()")
    }

    var time_sec_nanosec = process.hrtime(start_time)
    var time_secs = time_sec_nanosec[0]
    var time_nanosecs = time_sec_nanosec[1]

    var response_body = {
          function_id: function_id,
          environment: runtime_env,
          aws: {
            functionName: context.functionName,
            functionVersion: context.functionVersion,
            invokedFunctionArn: context.invokedFunctionArn,
            memoryLimitInMB: context.memoryLimitInMB,
            awsRequestId: context.awsRequestId,
            logGroupName: context.logGroupName,
            logStreamName: context.logStreamName,
            getRemainingTimeInMillis: context.getRemainingTimeInMillis()
          },
          errors: retainErr,
          events: emitter.queue,
          time_sec_nanosec: time_sec_nanosec,
          time_sec: time_sec_nanosec[0],
          time_nanosec: time_sec_nanosec[1],
          client_id: config.clientId
        }

    if (config.debug) {
      console.log("IOPIPE-DEBUG: ", response_body)
      callback()
      return
    }
    if (!config.clientId) {
      callback()
      return
    }

    request(
      {
        url: config.url,
        method: "POST",
        json: true,
        body: response_body
      },
      function(reqErr, res, body) {
        // Throw uncaught errors from the wrapped function.
        if (err) {
          context.fail(err)
        }
        /*if (reqErr) {
          console.log("WOLF:IOpipeLoggingError: ", reqErr)
        }*/
        callback()
      }
    )
  }
}

function _agentEmitter() {
  this.queue = []
  EventEmitter.call(this);
}
util.inherits(_agentEmitter, EventEmitter)

module.exports = function(configObject) {
  return function(func) {
    return function() {
      var baseurl = (configObject && configObject.url) ? configObject.url : DEFAULT_COLLECTOR_URL
      var eventURL = url.parse(baseurl)
      eventURL.pathname = path.join(eventURL.pathname, 'v0/event')
      eventURL.path = eventURL.search ? eventURL.pathname + eventURL.search : eventURL.pathname

      var config = {
        url: eventURL,
        clientId: configObject.clientId || ""
      }

      var emitter = new _agentEmitter()
      emitter.on("iopipe_event", (type, data) => {
        emitter.queue.push([type, data])
      })

      var args = [].slice.call(arguments)

      var start_time = process.hrtime()
      var generateLog = _make_generateLog(emitter, func, start_time, config, args[1])
      var new_context = (old_context) => {
        var context = deepcopy(old_context)
        context.succeed = function(data) {
          //console.log("WOLF:CalledContextSucceed.")
          generateLog(null, () => {
            old_context.succeed(data)
          })
        }
        context.fail = function(err) {
          //console.log("WOLF:CalledContextFail.")
          generateLog(err, () => {
            old_context.fail(err)
          })
        }
        context.done = function(err, data) {
          //console.log("WOLF:CalledContextDone.")
          generateLog(err, () => {
            old_context.done(err, data)
          })
        }
        context.iopipe_log = function(level, data) {
          emitter.queue.push([level, data])
        }
        /* Map getters/setters */
        context.__defineGetter__('callbackWaitsForEmptyEventLoop',
                                 () => { return old_context.callbackWaitsForEmptyEventLoop })
        context.__defineSetter__('callbackWaitsForEmptyEventLoop',
                                 (value) => { old_context.callbackWaitsForEmptyEventLoop = value })

        return context
      }
      var new_callback = (callback) => {
        if (typeof(callback) !== 'function') {
          return undefined
        }
        return (err, data) => {
          //console.log("WOLF:CalledLambdaCallback.")
          generateLog(err, () => {
            callback.apply(callback, [err, data])
          })
        }
      }

      /* Mangle arguments, wrapping callbacks. */
      args[1] = new_context(args[1])
      args[2] = new_callback(args[2])

      try {
        return func.apply(emitter, args)
      }
      catch (err) {
        generateLog(err, () => {})
        return undefined
      }
    }
  }
}
<commit_msg>Only call getRemainingTimeInMillis if exists<commit_after>"use strict"

var crypto = require("crypto")
var request = require("request")
var EventEmitter = require("events")
var util = require("util")
var url = require("url")
var path = require("path")
var os = require("os")
var deepcopy = require('deepcopy')

const VERSION = "0.0.17"
const DEFAULT_COLLECTOR_URL = "https://metrics-api.iopipe.com"

function _make_generateLog(emitter, func, start_time, config, context) {
  return function generateLog(err, callback) {
    var hash = crypto.createHash('sha256');
    hash.update(func.toString());
    var function_id = hash.digest('hex')

    var runtime_env = {
      agent: {
        runtime: "nodejs",
        version: VERSION
      },
      os: {
        hostname: os.hostname(),
        totalmem: os.totalmem(),
        uptime: os.uptime(),
        freemem: os.freemem(),
        cpus: os.cpus(),
        arch: os.arch()
      },
      nodejs: {
        title: process.title,
        version: process.version,
        modulesloadList: process.modulesloadList,
        versions: process.versions,
        arch: process.arch,
        platform: process.platform,
        argv: process.argv,
        execArgv: process.execArgv,
        pid: process.pid,
        features: process.features,
        execPath: process.execPath,
        debugPort: process.debugPort,
        _maxListeners: process._maxListeners,
        config: process.config,
        maxTickDepth: process.maxTickDepth,
        // /* Circular ref */ mainModule: process.mainModule,
        release: process.release,
      }
    }

    var retainErr = {};
    if (err) {
      retainErr = ((err) => {
                    return {
                      name: err.name,
                      message: err.message,
                      stack: err.stack,
                      lineNumber: err.lineNumber,
                      columnNumber: err.columnNumber,
                      fileName: err.fileName
                    }
                  })((typeof(err) === "string") ? new Error(err) : err)
    }

    var qfuncs = ["uptime", "getuid", "getgid", "geteuid", "getegid", "memoryUsage"]
    for (var i = 0; i < qfuncs.length; i++) {
      // Lacking a process.prototype, evil eval.
      runtime_env.nodejs[qfuncs[i]] = eval("process."+qfuncs[i]+"()")
    }

    var time_sec_nanosec = process.hrtime(start_time)
    var time_secs = time_sec_nanosec[0]
    var time_nanosecs = time_sec_nanosec[1]

    var response_body = {
          function_id: function_id,
          environment: runtime_env,
          aws: {
            functionName: context.functionName,
            functionVersion: context.functionVersion,
            invokedFunctionArn: context.invokedFunctionArn,
            memoryLimitInMB: context.memoryLimitInMB,
            awsRequestId: context.awsRequestId,
            logGroupName: context.logGroupName,
            logStreamName: context.logStreamName
          },
          errors: retainErr,
          events: emitter.queue,
          time_sec_nanosec: time_sec_nanosec,
          time_sec: time_sec_nanosec[0],
          time_nanosec: time_sec_nanosec[1],
          client_id: config.clientId
        }

    if (context.indexOf('getRemainingTimeInMillis') != -1) {
      response_body['getRemainingTimeInMillis'] = context.getRemainingTimeInMillis()
    }

    if (config.debug) {
      console.log("IOPIPE-DEBUG: ", response_body)
      callback()
      return
    }
    if (!config.clientId) {
      callback()
      return
    }

    request(
      {
        url: config.url,
        method: "POST",
        json: true,
        body: response_body
      },
      function(reqErr, res, body) {
        // Throw uncaught errors from the wrapped function.
        if (err) {
          context.fail(err)
        }
        /*if (reqErr) {
          console.log("WOLF:IOpipeLoggingError: ", reqErr)
        }*/
        callback()
      }
    )
  }
}

function _agentEmitter() {
  this.queue = []
  EventEmitter.call(this);
}
util.inherits(_agentEmitter, EventEmitter)

module.exports = function(configObject) {
  return function(func) {
    return function() {
      var baseurl = (configObject && configObject.url) ? configObject.url : DEFAULT_COLLECTOR_URL
      var eventURL = url.parse(baseurl)
      eventURL.pathname = path.join(eventURL.pathname, 'v0/event')
      eventURL.path = eventURL.search ? eventURL.pathname + eventURL.search : eventURL.pathname

      var config = {
        url: eventURL,
        clientId: configObject.clientId || ""
      }

      var emitter = new _agentEmitter()
      emitter.on("iopipe_event", (type, data) => {
        emitter.queue.push([type, data])
      })

      var args = [].slice.call(arguments)

      var start_time = process.hrtime()
      var generateLog = _make_generateLog(emitter, func, start_time, config, args[1])
      var new_context = (old_context) => {
        var context = deepcopy(old_context)
        context.succeed = function(data) {
          //console.log("WOLF:CalledContextSucceed.")
          generateLog(null, () => {
            old_context.succeed(data)
          })
        }
        context.fail = function(err) {
          //console.log("WOLF:CalledContextFail.")
          generateLog(err, () => {
            old_context.fail(err)
          })
        }
        context.done = function(err, data) {
          //console.log("WOLF:CalledContextDone.")
          generateLog(err, () => {
            old_context.done(err, data)
          })
        }
        context.iopipe_log = function(level, data) {
          emitter.queue.push([level, data])
        }
        /* Map getters/setters */
        context.__defineGetter__('callbackWaitsForEmptyEventLoop',
                                 () => { return old_context.callbackWaitsForEmptyEventLoop })
        context.__defineSetter__('callbackWaitsForEmptyEventLoop',
                                 (value) => { old_context.callbackWaitsForEmptyEventLoop = value })

        return context
      }
      var new_callback = (callback) => {
        if (typeof(callback) !== 'function') {
          return undefined
        }
        return (err, data) => {
          //console.log("WOLF:CalledLambdaCallback.")
          generateLog(err, () => {
            callback.apply(callback, [err, data])
          })
        }
      }

      /* Mangle arguments, wrapping callbacks. */
      args[1] = new_context(args[1])
      args[2] = new_callback(args[2])

      try {
        return func.apply(emitter, args)
      }
      catch (err) {
        generateLog(err, () => {})
        return undefined
      }
    }
  }
}
<|endoftext|>


<commit_before>'use strict';
const path = require('path');

const lazyReq = require('lazy-req')(require);

const request = lazyReq('request');
const semver = lazyReq('semver');
const del = lazyReq('del');

const manager = lazyReq('bin-manager');

const osFilterObj = lazyReq('os-filter-obj');

const BIN_PATH = 'bin';

const VERSION_LIST_ENDPOINT = 'https://arduino-cli.github.io/arduino-version/list';

const MIRRORS = [{
  os: 'win32',
  uri: 'https://github.com/arduino-cli/arduino-version/releases/download/{{version}}/arduino-{{version}}-windows.zip',
  bin: 'arduino_debug.exe'
}, {
  os: 'darwin',
  uri: 'https://github.com/arduino-cli/arduino-version/releases/download/{{version}}/arduino-{{version}}-macosx.zip',
  bins: [{
    bin: 'Contents/MacOS/Arduino',
    version: '>=1.6.0'
  }, {
    bin: 'Contents/MacOS/JavaAppLauncher',
    version: '<=1.5.8'
  }]
}, {
  os: 'linux',
  arch: 'x32',
  uri: 'https://github.com/arduino-cli/arduino-version/releases/download/{{version}}/arduino-{{version}}-linux32.zip',
  bin: 'arduino'
}, {
  os: 'linux',
  arch: 'x64',
  uri: 'https://github.com/arduino-cli/arduino-version/releases/download/{{version}}/arduino-{{version}}-linux64.zip',
  bin: 'arduino'
}, {
  os: 'linux',
  arch: 'arm',
  uri: 'https://github.com/arduino-cli/arduino-version/releases/download/{{version}}/arduino-{{version}}-linuxarm.zip',
  bin: 'arduino'
}];

const SPLASH_SCREEN = [{
  os: 'win32',
  img: 'lib/splash.png'
}, {
  os: 'darwin',
  img: 'Contents/Java/lib/splash.png'
}];

/**
 * Initialize a new `Arduino`
 *
 * @param {Object} [opts]
 * @api public
 */

function arduino(opts) {
  const version = opts.version || 'latest';
  const binPath = opts.path || BIN_PATH;
  const binSlug = opts.tag ? ('-' + opts.tag) : '';
  let inited = false;
  let bin;

  /**
   * Runs the arduino binary
   *
   * @param {Array}    [argv]
   * @param {Function} callback
   * @api public
   */
  function run(argv, callback) {
    if (callback === undefined) {
      callback = argv;
      argv = [];
    }
    if (inited) {
      bin.run(argv, callback);
      return;
    }

    getFullVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      init(version);
      bin.run(argv, callback);
    });
  }

  /**
   * Load/download the current version of the binary
   *
   * @param {Function} callback
   * @api public
   */
  function load(callback) {
    const opts = {
      extract: true,
      strip: 1
    };

    if (inited) {
      bin.load(opts, err => callback(err));
      return;
    }

    getFullVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      init(version);
      bin.load(opts, err => {
        if (err) {
          callback(err);
          return;
        }

        // HACK: remove the splash.png file because the arduino IDE does not
        // hide it in command line mode.
        // See https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc
        const splash = osFilterObj()(SPLASH_SCREEN);
        if (splash.length === 0) {
          callback();
          return;
        }
        const dirs = splash.map(s => {
          return path.join(bin.path(), s.img);
        });
        del()(dirs)
          .then(() => callback())
          .catch(err => callback(err));
      });
    });
  }

  /**
   * Removes the current version of the binary
   *
   * @param  {Function} callback
   * @api public
   */
  function unload(callback) {
    if (inited) {
      bin.unload(err => callback(err));
      return;
    }

    getFullVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      init(version);
      bin.unload(err => callback(err));
    });
  }

  /**
   * Checks if a version is available.
   *
   * @param  {Function} callback
   * @api private
   */
  function getFullVersion(callback) {
    getVersionsList((err, vers) => {
      if (err) {
        callback(err);
        return;
      }
      if (version === 'latest') {
        callback(null, vers[vers.length - 1]);
        return;
      }
      const valid = vers.some(v => v === version);
      if (!valid) {
        callback(new Error('The version provided is not available'));
        return;
      }
      callback(null, version);
    });
  }

  /**
   * Retrieves the list of arduino ide versions available
   *
   * @param  {Function} callback
   * @api private
  */
  function getVersionsList(callback) {
    request()(VERSION_LIST_ENDPOINT, (err, res, body) => {
      if (err) {
        callback('Cannot get the version list: ' + err);
        return;
      }
      if (res.statusCode !== 200) {
        callback('Cannot get the version list: ' + res.statusCode);
        return;
      }
      const vers = body.split(',').map(v => semver().clean(v));
      callback(null, vers);
    });
  }

  /**
   * Initializes the binary mirrors
   *
   * @param {String} version
   * @api private
   */
  function init(version) {
    const slug = 'arduino-' + version + binSlug;
    bin = manager()(binPath, slug);
    MIRRORS.forEach(mirror => {
      bin.src(mirror.uri.replace(/{{version}}/g, version), mirror.os, mirror.arch);

      if (mirror.os === process.platform) {
        if (Array.isArray(mirror.bins)) {
          mirror.bins.some(b => {
            if (semver().satisfies(version, b.version)) {
              bin.use(b.bin.replace(/{{version}}/g, version));
              return true;
            }
            return false;
          });
          return;
        }
        bin.use(mirror.bin.replace(/{{version}}/g, version));
      }
    });

    inited = true;
  }

  /**
   * Gets the path to the binary
   *
   * @api public
   */
  function binary(callback) {
    if (inited) {
      callback(null, bin.bin());
      return;
    }
    getFullVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      init(version);
      callback(null, bin.bin());
    });
  }

  /**
   * Gets the path to the folder containing the Arduino IDE in use
   *
   * @api public
   */
  function root(callback) {
    if (inited) {
      callback(null, bin.path());
      return;
    }
    getFullVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      init(version);
      callback(null, bin.path());
    });
  }

  return {
    run,
    load,
    unload,
    binary,
    root
  };
}

module.exports = arduino;
<commit_msg>Update JSDoc<commit_after>'use strict';
const join = require('path').join;

const lazyReq = require('lazy-req')(require);

const request = lazyReq('request');
const semver = lazyReq('semver');
const del = lazyReq('del');

const manager = lazyReq('bin-manager');

const osFilterObj = lazyReq('os-filter-obj');

const BIN_PATH = 'bin';

const VERSION_LIST_ENDPOINT = 'https://arduino-cli.github.io/arduino-version/list';

const MIRRORS = [{
  os: 'win32',
  uri: 'https://github.com/arduino-cli/arduino-version/releases/download/{{version}}/arduino-{{version}}-windows.zip',
  bin: 'arduino_debug.exe'
}, {
  os: 'darwin',
  uri: 'https://github.com/arduino-cli/arduino-version/releases/download/{{version}}/arduino-{{version}}-macosx.zip',
  bins: [{
    bin: 'Contents/MacOS/Arduino',
    version: '>=1.6.0'
  }, {
    bin: 'Contents/MacOS/JavaAppLauncher',
    version: '<=1.5.8'
  }]
}, {
  os: 'linux',
  arch: 'x32',
  uri: 'https://github.com/arduino-cli/arduino-version/releases/download/{{version}}/arduino-{{version}}-linux32.zip',
  bin: 'arduino'
}, {
  os: 'linux',
  arch: 'x64',
  uri: 'https://github.com/arduino-cli/arduino-version/releases/download/{{version}}/arduino-{{version}}-linux64.zip',
  bin: 'arduino'
}, {
  os: 'linux',
  arch: 'arm',
  uri: 'https://github.com/arduino-cli/arduino-version/releases/download/{{version}}/arduino-{{version}}-linuxarm.zip',
  bin: 'arduino'
}];

const SPLASH_SCREEN = [{
  os: 'win32',
  img: 'lib/splash.png'
}, {
  os: 'darwin',
  img: 'Contents/Java/lib/splash.png'
}];

/**
 * Initialize a new `Arduino`
 *
 * @param {object} [opts]
 * @api public
 */

function arduino(opts) {
  const version = opts.version || 'latest';
  const binPath = opts.path || BIN_PATH;
  const binSlug = opts.tag ? ('-' + opts.tag) : '';
  let inited = false;
  let bin;

  /**
   * Runs the arduino binary
   *
   * @param {array}    [argv]
   * @param {function} callback
   * @api public
   */
  function run(argv, callback) {
    if (callback === undefined) {
      callback = argv;
      argv = [];
    }
    if (inited) {
      bin.run(argv, callback);
      return;
    }

    getFullVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      init(version);
      bin.run(argv, callback);
    });
  }

  /**
   * Load/download the current version of the binary
   *
   * @param {function} callback
   * @api public
   */
  function load(callback) {
    const opts = {
      extract: true,
      strip: 1
    };

    if (inited) {
      bin.load(opts, err => callback(err));
      return;
    }

    getFullVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      init(version);
      bin.load(opts, err => {
        if (err) {
          callback(err);
          return;
        }

        // HACK: remove the splash.png file because the arduino IDE does not
        // hide it in command line mode.
        // See https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc
        const splash = osFilterObj()(SPLASH_SCREEN);
        if (splash.length === 0) {
          callback();
          return;
        }
        const dirs = splash.map(s => {
          return join(bin.path(), s.img);
        });
        del()(dirs)
          .then(() => callback())
          .catch(err => callback(err));
      });
    });
  }

  /**
   * Removes the current version of the binary
   *
   * @param  {function} callback
   * @api public
   */
  function unload(callback) {
    if (inited) {
      bin.unload(err => callback(err));
      return;
    }

    getFullVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      init(version);
      bin.unload(err => callback(err));
    });
  }

  /**
   * Checks if a version is available.
   *
   * @param  {function} callback
   * @api private
   */
  function getFullVersion(callback) {
    getVersionsList((err, vers) => {
      if (err) {
        callback(err);
        return;
      }
      if (version === 'latest') {
        callback(null, vers[vers.length - 1]);
        return;
      }
      const valid = vers.some(v => v === version);
      if (!valid) {
        callback(new Error('The version provided is not available'));
        return;
      }
      callback(null, version);
    });
  }

  /**
   * Retrieves the list of arduino ide versions available
   *
   * @param  {function} callback
   * @api private
  */
  function getVersionsList(callback) {
    request()(VERSION_LIST_ENDPOINT, (err, res, body) => {
      if (err) {
        callback('Cannot get the version list: ' + err);
        return;
      }
      if (res.statusCode !== 200) {
        callback('Cannot get the version list: ' + res.statusCode);
        return;
      }
      const vers = body.split(',').map(v => semver().clean(v));
      callback(null, vers);
    });
  }

  /**
   * Initializes the binary mirrors
   *
   * @param {string} version
   * @api private
   */
  function init(version) {
    const slug = 'arduino-' + version + binSlug;
    bin = manager()(binPath, slug);
    MIRRORS.forEach(mirror => {
      bin.src(mirror.uri.replace(/{{version}}/g, version), mirror.os, mirror.arch);

      if (mirror.os === process.platform) {
        if (Array.isArray(mirror.bins)) {
          mirror.bins.some(b => {
            if (semver().satisfies(version, b.version)) {
              bin.use(b.bin.replace(/{{version}}/g, version));
              return true;
            }
            return false;
          });
          return;
        }
        bin.use(mirror.bin.replace(/{{version}}/g, version));
      }
    });

    inited = true;
  }

  /**
   * Gets the path to the binary
   *
   * @api public
   */
  function binary(callback) {
    if (inited) {
      callback(null, bin.bin());
      return;
    }
    getFullVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      init(version);
      callback(null, bin.bin());
    });
  }

  /**
   * Gets the path to the folder containing the Arduino IDE in use
   *
   * @api public
   */
  function path(callback) {
    if (inited) {
      callback(null, bin.path());
      return;
    }
    getFullVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      init(version);
      callback(null, bin.path());
    });
  }

  return {
    run,
    load,
    unload,
    binary,
    path
  };
}

module.exports = arduino;
<|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var debug = require('debug')

var root, dir

function tryReadPackageJson (dir) {
  var ok = fs.existsSync(path.resolve(dir, 'package.json'))
  if (ok) {
    root = dir
  }
  return ok
}

// remove self from require cache,
// so that next require call gets re-evaluated
delete require.cache[__filename]

var filename = module.parent.filename
if (!filename) {
  throw new Error('`autodebug` module can not be required in the REPL!')
}

dir = path.dirname(filename)
while (!tryReadPackageJson(dir)) {
  dir = path.dirname(dir)
}

if (!root) {
  throw new Error('could not find package root for ' + filename)
}

var packageName = require(path.resolve(dir, 'package.json')).name
var rel = path.relative(root, filename).replace(/\.js$/, '').split(/[\/\\]/g)
var name = packageName + ':' + rel.join(':')

module.exports = debug(name)
<commit_msg>never throw, always have a good default (so it works in interactive)<commit_after>var fs = require('fs')
var path = require('path')
var debug = require('debug')

var root, dir

function tryReadPackageJson (dir) {
  var ok = fs.existsSync(path.resolve(dir, 'package.json'))
  if (ok) {
    root = dir
  }
  return ok
}

// remove self from require cache,
// so that next require call gets re-evaluated
delete require.cache[__filename]

module.exports = (function () {
  if (!module.parent) {
    return debug(module.id)
  }
  var filename = module.parent.filename
  if (!filename) {
    return debug(module.parent.id || module.id)
  }

  dir = path.dirname(filename)
  while (!tryReadPackageJson(dir)) {
    dir = path.dirname(dir)
  }

  if (!root) {
    return debug(module.parent.id || module.id)
  }

  var packageName = require(path.resolve(dir, 'package.json')).name
  var rel = path.relative(root, filename).replace(/\.js$/, '').split(/[\/\\]/g)
  var name = packageName + ':' + rel.join(':')

  return debug(name)
})()
<|endoftext|>


<commit_before>/**
* @license AngularIO v0.0.0
* (c) Aleksandr Korolev
* License: MIT
*/
module.exports = function (angular, undefuned) {
	  /**
  * @ngdoc module
  * @name ngSocketIO
  * @description
  *
  * # ngSocketIO
  *
  * The `ngSocketIO` module provides work with socket.io library.
  *
  * ## Example
  *
  *
  */
  /* global -ngSocketIOModule */

  /**
	* Include socket.io client library
  **/
  var SocketClient = require('socket.io-client');
  var SocketIOProvider = function () {
    var _ = {
    	socket: SocketClient,
    	params: {
    		protocol: 'http',
    		host: 'localhost',
    		port: 80,
    		path: '',
    		sessionInit: '/auth/session'
    	},
    	socketUrl: function () {
    		_.socketURL = _.socketURL || _.params.protocol+"://"+_.params.host+(_.params.port>0?":"+_.params.port:"")+_.params.path;
    		return _.socketURL;
    	},
    	sessionUrl: function () {
    		_.sessionURL = _.sessionURL || _.params.protocol+"://"+_.params.host+(_.params.port>0?":"+_.params.port:"")+_.params.sessionInit;
    		return _.sessionURL;
    	},
    	io: false,
    	init: function (cb) {
    		if (_.io) {
            _.cb(cb, true);
        } else {
          if (_.sessionUrl()) {
	          _.$http.get(_.sessionUrl())
	            .success(function(data) {
	              _.io = _.socket.connect(_.socketUrl());
	              _.cb(cb, true);
	            })
	            .error(function(err) {
	              _.cb(cb, false)
	            });
	        } else {
            _.io = _.socket.connect(_.socketUrl());
            _.cb(cb, true);
	        }
        }
    	},
      cb: function (cb, result, args) {
      	var args = args || [];
        if (angular.isFunction(cb)) cb(result, (args[0]||undefined), (args[1]||undefined), (args[2]||undefined), (args[3]||undefined), (args[4]||undefined), (args[5]||undefined),
	                  (args[6]||undefined), (args[7]||undefined), (args[8]||undefined), (args[9]||undefined));
        console.log('"cb" is not a function, result: ', result);
      }
    };
		return {
			configure: function (params) {
				angular.extend(_.params, params);
			},
	    $get: ['$http', '$rootScope', function($http, $rootScope) {
	    	_.$http = $http;
	      var p = {
	        on: function (event, cb, args) {
	          _.init(function (connected) {
	            if(connected) {
	              _.io.on(event, function (data) {
	                _.cb(cb, data, args);
	                $rootScope.$apply();
	              });
	            } else {

	            }
	          });
	        },
	        send: function (event, data, cb) {
	          _.init(function (connected) {
	            if (connected) { // если подключены, отправляем событие
	              _.io.emit(event, data, cb);
	            } else { // иначе ставим в очередь
	            }
	          });
	        }
	      };
	      return p;
	    }]

	  };
	}
	SocketIOModule = angular.module('SocketIOModule', ['ng']).
   	provider('socketIO', SocketIOProvider);
}<commit_msg>Add some comments<commit_after>/**
* @license AngularIO v0.0.0
* (c) Aleksandr Korolev
* License: MIT
*/
module.exports = function (angular, undefuned) {
	  /**
  * @ngdoc module
  * @name ngSocketIO
  * @description
  *
  * # ngSocketIO
  *
  * The `ngSocketIO` module provides work with socket.io library.
  *
  * ## Example
  *
  *
  */

  /**
	* Include socket.io client library
  **/
  var SocketClient = require('socket.io-client');

    /**
  * @ngdoc provider
  * @name SocketIOProvider
  * @function
  *
  * @description
  *
  * Used for send events on socket.io server and listen server events.
  */
  var SocketIOProvider = function () {
    /*
    * Private variables and methods
    */
    var _ = {
    	socket: SocketClient,
    	params: {
    		protocol: 'http',
    		host: 'localhost',
    		port: 80,
    		path: '',
    		sessionInit: '/auth/session'
    	},
    	socketUrl: function () {
    		_.socketURL = _.socketURL || _.params.protocol+"://"+_.params.host+(_.params.port>0?":"+_.params.port:"")+_.params.path;
    		return _.socketURL;
    	},
    	sessionUrl: function () {
    		_.sessionURL = _.sessionURL || _.params.protocol+"://"+_.params.host+(_.params.port>0?":"+_.params.port:"")+_.params.sessionInit;
    		return _.sessionURL;
    	},
    	io: false,
    	init: function (cb) {
    		if (_.io) {
            _.cb(cb, true);
        } else {
          if (_.sessionUrl()) {
	          _.$http.get(_.sessionUrl())
	            .success(function(data) {
	              _.io = _.socket.connect(_.socketUrl());
	              _.cb(cb, true);
	            })
	            .error(function(err) {
	              _.cb(cb, false)
	            });
	        } else {
            _.io = _.socket.connect(_.socketUrl());
            _.cb(cb, true);
	        }
        }
    	},
      cb: function (cb, result, args) {
      	var args = args || [];
        if (angular.isFunction(cb)) cb(result, (args[0]||undefined), (args[1]||undefined), (args[2]||undefined), (args[3]||undefined), (args[4]||undefined), (args[5]||undefined),
	                  (args[6]||undefined), (args[7]||undefined), (args[8]||undefined), (args[9]||undefined));
        console.log('"cb" is not a function, result: ', result);
      }
    };
    /* Public methods */
		return {
      /**
      * @ngdoc method
      * @name SocketIOProvider#configure
      *
      * @description
      * Sets socket.io server params
      *   angular.module('myApp')
      *   .config(function(socketIOProvider) {
      *     var api = {
      *       protocol: 'http',
      *       host: 'localhost',
      *       port: 3000,
      *       path: '/basepath',
      *       sessionInit: '/auth/session'
      *     }
      *     socketIOProvider.configure(api);
      *   });
      *
      * @param {Object} params Mapping information about connection params.
      * @returns {Object} self
      */
			configure: function (params) {
				angular.extend(_.params, params);
        return this;
			},

	    $get: ['$http', '$rootScope', function($http, $rootScope) {
	    	_.$http = $http;
	      var p = {
	        on: function (event, cb, args) {
	          _.init(function (connected) {
	            if(connected) {
	              _.io.on(event, function (data) {
	                _.cb(cb, data, args);
	                if (!rootScope.$$phase) $rootScope.$apply();
	              });
	            } else {

	            }
	          });
	        },
	        send: function (event, data, cb) {
	          _.init(function (connected) {
	            if (connected) { // если подключены, отправляем событие
	              _.io.emit(event, data, cb);
	            } else { // иначе ставим в очередь
	            }
	          });
	        }
	      };
	      return p;
	    }]

	  };
	}
  /* SocketIOModule */
	angular.module('SocketIOModule', ['ng']).
   	provider('socketIO', SocketIOProvider);
}<|endoftext|>


<commit_before>var request = require('request');
var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('token world');
});

app.get('/helloworld', function (req, res) {
    var options = {
      method: 'POST',
      url: 'https://codehackdays.eu.auth0.com/oauth/token',
      headers: { 'content-type': 'application/json' },
      body: {
        "audience":"https://codehackdays-helloworld.herokuapp.com/",
        "client_id":process.env.CLIENT_ID,
        "client_secret":process.env.CLIENT_SECRET,
        "grant_type":"client_credentials"
      },
      json: true
    };

    request(options, function (err, response, body) {
      if (err) { throw err; }
      res.send(JSON.stringify(body));
  });
});

app.listen(process.env.PORT || 3000);
<commit_msg>Only interested in access_token<commit_after>var request = require('request');
var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('token world');
});

app.get('/helloworld', function (req, res) {
    var options = {
      method: 'POST',
      url: 'https://codehackdays.eu.auth0.com/oauth/token',
      headers: { 'content-type': 'application/json' },
      body: {
        "audience":"https://codehackdays-helloworld.herokuapp.com/",
        "client_id":process.env.CLIENT_ID,
        "client_secret":process.env.CLIENT_SECRET,
        "grant_type":"client_credentials"
      },
      json: true
    };

    request(options, function (err, response, body) {
      if (err) { throw err; }
      res.send(body.access_token);
  });
});

app.listen(process.env.PORT || 3000);
<|endoftext|>


<commit_before>var agent = require('superagent');
var util = require('./util');

var BASE_URL = 'https://oapi.dingtalk.com/service';
var TICKET_EXPIRES_IN = 1000 * 60 * 20 //20分钟
var TOKEN_EXPIRES_IN = 1000 * 60 * 60 * 2 - 10000 //1小时59分50秒.防止网络延迟

var Api = function(conf) {
  this.suite_key = conf.suiteid;
  this.suite_secret = conf.secret;
  this.ticket_expires_in = TICKET_EXPIRES_IN;
  this.token_expires_in = conf.token_expires_in || TOKEN_EXPIRES_IN;

  this.getTicket = conf.getTicket;
  this.getToken = conf.getToken;
  this.saveToken = conf.saveToken;

  this.ticket_cache = {
    expires: 0,
    value: null
  };
  this.token_cache = null;

}

Api.prototype.getLatestTicket = function(callback) {
  var now = Date.now();
  if (this.ticket_cache.expires + this.ticket_expires_in <= now) {
    this.getTicket(callback);
  } else {
    callback(null, this.ticket_cache);
  }
}

Api.prototype._get_access_token = function(callback) {
  var self = this;
  this.getLatestTicket(function(err, ticket) {

    var data = {
      suite_key: self.suite_key,
      suite_secret: self.suite_secret,
      suite_ticket: ticket.value
    };

    agent.post(BASE_URL + '/get_suite_token')
      .send(data).end(util.wrapper(callback));
  });
};

Api.prototype.getLatestToken = function(callback) {
  var self = this;

  console.log(self.token_cache);

  if (!self.token_cache) {
    self.getToken(function(err, token) {
      if (err) {
        return callback(err);
      } else {
        self.token_cache = token;
        self.getLatestToken(callback);
      }
    });
  } else {
    var now = Date.now();
    if (self.token_cache.expires + self.token_expires_in <= now) {
      self._get_access_token(function(err, token) {
        if (err) {
          return callback(err);
        } else {
          token = {
            value: token.suite_access_token,
            expires: now + self.token_expires_in
          }
          self.saveToken(token, function(err) {
            if (err) {
              return callback(err);
            }
            self.token_cache = token;
            callback(null, token);
          });
        }
      });
    } else {
      callback(null, this.token_cache);
    }
  }
}

Api.prototype.getPermanentCode = function(tmp_auth_code, callback) {
  var self = this;
  self.getLatestToken(function(err, token){

    if(err){
      return callback(err);
    };

    agent.post(BASE_URL + '/get_permanent_code')
      .query({suite_access_token:token.value})
      .send({tmp_auth_code : tmp_auth_code})
      .end(util.wrapper(callback));
  });

}

module.exports = Api;<commit_msg>增加了几个方法<commit_after>var agent = require('superagent');
var util = require('./util');

var BASE_URL = 'https://oapi.dingtalk.com/service';
var TICKET_EXPIRES_IN = 1000 * 60 * 20 //20分钟
var TOKEN_EXPIRES_IN = 1000 * 60 * 60 * 2 - 10000 //1小时59分50秒.防止网络延迟

var Api = function(conf) {
  this.suite_key = conf.suiteid;
  this.suite_secret = conf.secret;
  this.ticket_expires_in = TICKET_EXPIRES_IN;
  this.token_expires_in = conf.token_expires_in || TOKEN_EXPIRES_IN;

  this.getTicket = conf.getTicket;
  this.getToken = conf.getToken;
  this.saveToken = conf.saveToken;

  this.ticket_cache = {
    expires: 0,
    value: null
  };
  this.token_cache = null;

}

Api.prototype.getLatestTicket = function(callback) {
  var now = Date.now();
  if (this.ticket_cache.expires + this.ticket_expires_in <= now) {
    this.getTicket(callback);
  } else {
    callback(null, this.ticket_cache);
  }
}

Api.prototype._get_access_token = function(callback) {
  var self = this;
  this.getLatestTicket(function(err, ticket) {

    var data = {
      suite_key: self.suite_key,
      suite_secret: self.suite_secret,
      suite_ticket: ticket.value
    };

    agent.post(BASE_URL + '/get_suite_token')
      .send(data).end(util.wrapper(callback));
  });
};

Api.prototype.getLatestToken = function(callback) {
  var self = this;

  console.log(self.token_cache);

  if (!self.token_cache) {
    self.getToken(function(err, token) {
      if (err) {
        return callback(err);
      } else {
        self.token_cache = token;
        self.getLatestToken(callback);
      }
    });
  } else {
    var now = Date.now();
    if (self.token_cache.expires + self.token_expires_in <= now) {
      self._get_access_token(function(err, token) {
        if (err) {
          return callback(err);
        } else {
          token = {
            value: token.suite_access_token,
            expires: now + self.token_expires_in
          }
          self.saveToken(token, function(err) {
            if (err) {
              return callback(err);
            }
            self.token_cache = token;
            callback(null, token);
          });
        }
      });
    } else {
      callback(null, this.token_cache);
    }
  }
}

Api.prototype.getPermanentCode = function(tmp_auth_code, callback) {
  var self = this;
  self.getLatestToken(function(err, token){

    if(err){
      return callback(err);
    };

    agent.post(BASE_URL + '/get_permanent_code')
      .query({suite_access_token:token.value})
      .send({tmp_auth_code : tmp_auth_code})
      .end(util.wrapper(callback));
  });

}

Api.prototype.getCorpToken = function(auth_corpid, permanent_code, callback) {
  var self = this;
  self.getLatestToken(function(err, token){

    if(err){
      return callback(err);
    };

    agent.post(BASE_URL + '/get_corp_token')
      .query({suite_access_token:token.value})
      .send({auth_corpid : auth_corpid, permanent_code: permanent_code})
      .end(util.wrapper(callback));
  });
}

Api.prototype.getAuthInfo = function(auth_corpid, permanent_code, callback) {
  var self = this;
  self.getLatestToken(function(err, token){

    if(err){
      return callback(err);
    };
    agent.post(BASE_URL + '/get_auth_info')
      .query({suite_access_token:token.value})
      .send({suite_key: self.suite_key, auth_corpid : auth_corpid, permanent_code: permanent_code})
      .end(util.wrapper(callback));
  });
}

Api.prototype.getAgent = function(agentid, auth_corpid, permanent_code, callback) {
  var self = this;
  self.getLatestToken(function(err, token){

    if(err){
      return callback(err);
    };
    agent.post(BASE_URL + '/get_agent')
      .query({suite_access_token:token.value})
      .send({suite_key: self.suite_key, auth_corpid : auth_corpid, permanent_code: permanent_code, agentid: agentid})
      .end(util.wrapper(callback));
  });
}

Api.prototype.activateSuite = function(auth_corpid, permanent_code, callback) {
  var self = this;
  self.getLatestToken(function(err, token){

    if(err){
      return callback(err);
    };
    agent.post(BASE_URL + '/activate_suite')
      .query({suite_access_token:token.value})
      .send({suite_key: self.suite_key, auth_corpid : auth_corpid, permanent_code: permanent_code})
      .end(util.wrapper(callback));
  });
}

Api.prototype.setCorpIpwhitelist = function(auth_corpid, ip_whitelist, callback) {
  var self = this;
  self.getLatestToken(function(err, token){

    if(err){
      return callback(err);
    };
    agent.post(BASE_URL + '/set_corp_ipwhitelist')
      .query({suite_access_token:token.value})
      .send({suite_key: self.suite_key, auth_corpid : auth_corpid, ip_whitelist: permanent_code})
      .end(util.wrapper(callback));
  });
}

module.exports = Api;<|endoftext|>


<commit_before>'use strict';

let argv = require('yargs')
  .usage('Usage: $0 -input-path /path/to/beerlist')
  .example('$0 -input-path /path/to/beerlist', 'Scrape Ratebeer.com beers data')
  .default({'inputPath': './data/beers.txt'})
  .default({'outputPath': './data/'})
  .describe('input-path', 'Path where beers data is located')
  .describe('output-path', 'Path where beers extracted data is saved')
  .describe('data-range', 'Range of records that are processed')
  .argv;

let fs = require('fs');
let async = require('async');
let readline = require('readline');
let ratebeer = require('ratebeer');
var iconv = require('iconv');
var utf8 = require('utf8');
var ic = new iconv.Iconv('iso-8859-1', 'utf-8');
let Entities = require('html-entities').XmlEntities;

let entities = new Entities();
let count = 0;
let range = argv.dataRange ? argv.dataRange.split(':').map(function(part) {
  return parseInt(part);
}) : undefined;

function escapeBeerName(name) {
  return entities
    .decode(name)
    .replace(/\0/g, '')
    .trim();
}

function processSearchResult(query, result, done) {
  console.log(query);
  console.log(result);

  ratebeer.getBeerByUrl(result.url, { includeUserRatings: true }, (err, result) => {
    console.log(result);
    done();
  });
}

let searchCollection = [];
let reader = readline.createInterface({
  input: fs.createReadStream(argv.inputPath, { encoding: 'utf-16le' })
});

reader.on('line', function (line) {
  //line = utf8.decode(ic.convert(line).toString());

  // Only process valid records
  let details = line.split('\t');
  if (details.length < 6) {
    return;
  }
  count++;

  // If range is enabled
  if (range.length && (count < range[0] || count > range[1])) {
    if (count > range[1]) {
      reader.close();
    }

    return;
  }

  let name = escapeBeerName(details[1]);
  let variation = null;
  let variations = [ name ];

  // Generate variations
  // Remove brewery name
  variation = name.split(' ');
  variation.shift();
  variation = variation.join(' ');
  variations.push(variation);

  // Remove last word as it may describe beer style
  variation = name.split(' ');
  variation.pop();
  variation = variation.join(' ');
  variations.push(variation);

  searchCollection.push({
    name,
    variations,
    raw: details
  });
});

reader.on('close', function () {
  let queue = async.queue((item, callback) => {
    let response = null;

    async.eachSeries(item.variations, (variation, done) => {
      if (response) {
        done();
        return;
      }

      ratebeer.search(variation, function(err, data) {
        if (err) {
          console.error(err);
          done(err);
          return;
        }

        if (!data) {
          done();
          return;
        }

        response = {
          variation,
          data
        };

        done();
      });
    }, (err) => {
      if (err) {
        callback(new Error('Error while fetching data for ' + item.name));
        return;
      }

      if (!response || !response.data) {
        callback(new Error('No data for ' + item.name));
        return;
      }

      processSearchResult(response.variation, response.data, callback);
    })
  }, 1);

  queue.drain(() => {
    console.log('done');
  });

  searchCollection.forEach((item) => {
    queue.push(item, (err) => {
      console.log('done processing for', item.name);
    });
  });

  console.log('start processing');
});
<commit_msg>Initial scraper implementation<commit_after>'use strict';

let argv = require('yargs')
  .usage('Usage: $0 -input-path /path/to/beerlist')
  .example('$0 -input-path /path/to/beerlist', 'Scrape Ratebeer.com beers data')
  .default({'inputPath': './data/beers.txt'})
  .default({'outputPath': './data/'})
  .describe('input-path', 'Path where beers data is located')
  .describe('output-path', 'Path where beers extracted data is saved')
  .describe('data-range', 'Range of records that are processed')
  .argv;

let fs = require('fs');
let async = require('async');
let readline = require('readline');
let ratebeer = require('ratebeer');
var iconv = require('iconv');
var utf8 = require('utf8');
var ic = new iconv.Iconv('iso-8859-1', 'utf-8');
let Entities = require('html-entities').XmlEntities;

let entities = new Entities();
let count = 0;
let range = argv.dataRange ? argv.dataRange.split(':').map(function(part) {
  return parseInt(part);
}) : undefined;

function escapeBeerName(name) {
  return entities
    .decode(name)
    .replace(/\0/g, '')
    .trim();
}

function processSearchResult(query, result, done) {
  console.log(query);
  console.log(result);

  ratebeer.getBeerByUrl(result.url, { includeUserRatings: true }, (err, result) => {
    console.log(result);
    done();
  });
}

let searchCollection = [];
let reader = readline.createInterface({
  input: fs.createReadStream(argv.inputPath, { encoding: 'utf-16le' })
});

reader.on('line', function (line) {
  //line = utf8.decode(ic.convert(line).toString());

  // Only process valid records
  let details = line.split('\t');
  if (details.length < 6) {
    return;
  }
  count++;

  // If range is enabled
  if (range.length && (count < range[0] || count > range[1])) {
    if (count > range[1]) {
      reader.close();
    }

    return;
  }

  let name = escapeBeerName(details[1]);
  let variation = null;
  let variations = [ name ];

  // Generate variations
  // Remove brewery name
  variation = name.split(' ');
  variation.shift();
  variation = variation.join(' ');
  variations.push(variation);

  // Remove last word as it may describe beer style
  variation = name.split(' ');
  variation.pop();
  variation = variation.join(' ');
  variations.push(variation);

  console.log(details);
  searchCollection.push({
    name,
    variations,
    raw: details
  });
});

reader.on('close', function () {
  let queue = async.queue((item, callback) => {
    let response = null;

    async.eachSeries(item.variations, (variation, done) => {
      if (response) {
        done();
        return;
      }

      ratebeer.search(variation, function(err, data) {
        if (err) {
          console.error(err);
          done(err);
          return;
        }

        if (!data) {
          done();
          return;
        }

        response = {
          variation,
          data
        };

        done();
      });
    }, (err) => {
      if (err) {
        callback(new Error('Error while fetching data for ' + item.name));
        return;
      }

      if (!response || !response.data) {
        callback(new Error('No data for ' + item.name));
        return;
      }

      console.log(item);
      processSearchResult(response.variation, response.data, callback);
    })
  }, 1);

  queue.drain(() => {
    console.log('done');
  });

  searchCollection.forEach((item) => {
    queue.push(item, (err) => {
      console.log('done processing for', item.name);
    });
  });

  console.log('start processing');
});
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');

const reservedWords = require('./lib/reservedWords');
const requireLibrary = require('./lib/requireLibrary');

const sql = requireLibrary();
const Select = sql.select;

// Support proper Date conversion
sql.conversions.Date = function (value) {
  return '"' + value.toISOString() + '"';
};

Select.prototype.limit = function (val) {
  this._limit = val;
  return this;
};

Select.prototype.offset = function (val) {
  this._offset = val;
  return this;
};

Select.defineClause(
  'limit',
  '{{#ifNotNull _limit}}LIMIT {{_limit}}{{/ifNotNull}}',
  { after: 'orderBy' }
);

Select.defineClause(
  'offset',
  '{{#ifNotNull _offset}}OFFSET {{_offset}}{{/ifNotNull}}',
  { after: 'limit' }
);

// Add support for reserved words escaping
sql._autoQuoteChar = '`';

for (let word of reservedWords) {
  sql._reserved[word] = word;
}

module.exports = sql;
<commit_msg>Correct date formatting<commit_after>'use strict';

const _ = require('lodash');

const reservedWords = require('./lib/reservedWords');
const requireLibrary = require('./lib/requireLibrary');

const sql = requireLibrary();
const Select = sql.select;

// Support proper Date conversion
sql.conversions.Date = function (value) {
  return '"' + value.toISOString().slice(0, 19).replace('T', ' ') + '"';
};

Select.prototype.limit = function (val) {
  this._limit = val;
  return this;
};

Select.prototype.offset = function (val) {
  this._offset = val;
  return this;
};

Select.defineClause(
  'limit',
  '{{#ifNotNull _limit}}LIMIT {{_limit}}{{/ifNotNull}}',
  { after: 'orderBy' }
);

Select.defineClause(
  'offset',
  '{{#ifNotNull _offset}}OFFSET {{_offset}}{{/ifNotNull}}',
  { after: 'limit' }
);

// Add support for reserved words escaping
sql._autoQuoteChar = '`';

for (let word of reservedWords) {
  sql._reserved[word] = word;
}

module.exports = sql;
<|endoftext|>