<commit_before>/**
 * module.js - The core of module loader
 */

var cachedMods = seajs.cache = {}
var anonymousMeta

var fetchingList = {}
var fetchedList = {}
var callbackList = {}

var STATUS = Module.STATUS = {
  // 1 - The `module.uri` is being fetched
  FETCHING: 1,
  // 2 - The meta data has been saved to cachedMods
  SAVED: 2,
  // 3 - The `module.dependencies` are being loaded
  LOADING: 3,
  // 4 - The module are ready to execute
  LOADED: 4,
  // 5 - The module is being executed
  EXECUTING: 5,
  // 6 - The `module.exports` is available
  EXECUTED: 6
}

function Module(uri, deps) {
  this.uri = uri
  this.dependencies = deps || []
  this.exports = null
  this.status = 0

  // Who depend on me
  this._waitings = {}

  // The number of unloaded dependencies
  this._remain = 0
}

// Resolve module.dependencies
Module.prototype.resolve = function() {
  var mod = this
  var ids = mod.dependencies
  var uris = []

  for (var i = 0, len = ids.length; i < len; i++) {
    uris[i] = resolve(ids[i], mod.uri)
  }
  return uris
}

// Load module.dependencies and fire onload when all done
Module.prototype.load = function() {
  var mod = this

  // If the module is being loaded, just wait it onload call
  if (mod.status >= STATUS.LOADING) {
    return
  }

  mod.status = STATUS.LOADING

  // Emit `load` event for plugins such as combo plugin
  var uris = mod.resolve()
  emit("load", uris)

  var len = mod._remain = uris.length
  var m

  // Initialize modules and register waitings
  for (var i = 0; i < len; i++) {
    m = Module.get(uris[i])

    if (m.status < STATUS.LOADED) {
      // Maybe duplicate
      m._waitings[mod.uri] = (m._waitings[mod.uri] || 0) + 1
    }
    else {
      mod._remain--
    }
  }

  if (mod._remain === 0) {
    mod.onload()
    return
  }

  // Begin parallel loading
  var requestCache = {}

  for (i = 0; i < len; i++) {
    m = cachedMods[uris[i]]

    if (m.status < STATUS.FETCHING) {
      m.fetch(requestCache)
    }
    else if (m.status === STATUS.SAVED) {
      m.load()
    }
  }

  // Send all requests at last to avoid cache bug in IE6-9. Issues#808
  for (var requestUri in requestCache) {
    if (requestCache.hasOwnProperty(requestUri)) {
      requestCache[requestUri]()
    }
  }
}

// Call this method when module is loaded
Module.prototype.onload = function() {
  var mod = this
  mod.status = STATUS.LOADED

  if (mod.callback) {
    mod.callback()
  }

  // Notify waiting modules to fire onload
  var waitings = mod._waitings
  var uri, m

  for (uri in waitings) {
    if (waitings.hasOwnProperty(uri)) {
      m = cachedMods[uri]
      m._remain -= waitings[uri]
      if (m._remain === 0) {
        m.onload()
      }
    }
  }

  // Reduce memory taken
  delete mod._waitings
  delete mod._remain
}

// Fetch a module
Module.prototype.fetch = function(requestCache) {
  var mod = this
  var uri = mod.uri

  mod.status = STATUS.FETCHING

  // Emit `fetch` event for plugins such as combo plugin
  var emitData = { uri: uri }
  emit("fetch", emitData)
  var requestUri = emitData.requestUri || uri

  // Empty uri or a non-CMD module
  if (!requestUri || fetchedList[requestUri]) {
    mod.load()
    return
  }

  if (fetchingList[requestUri]) {
    callbackList[requestUri].push(mod)
    return
  }

  fetchingList[requestUri] = true
  callbackList[requestUri] = [mod]

  // Emit `request` event for plugins such as text plugin
  emit("request", emitData = {
    uri: uri,
    requestUri: requestUri,
    onRequest: onRequest,
    charset: data.charset
  })

  if (!emitData.requested) {
    requestCache ?
        requestCache[emitData.requestUri] = sendRequest :
        sendRequest()
  }

  function sendRequest() {
    request(emitData.requestUri, emitData.onRequest, emitData.charset)
  }

  function onRequest() {
    delete fetchingList[requestUri]
    fetchedList[requestUri] = true

    // Save meta data of anonymous module
    if (anonymousMeta) {
      save(uri, anonymousMeta)
      anonymousMeta = null
    }

    // Call callbacks
    var m, mods = callbackList[requestUri]
    delete callbackList[requestUri]
    while ((m = mods.shift())) m.load()

    // Emit `requested` event
    emit("requested", emitData)
  }
}

// Execute a module
Module.prototype.exec = function () {
  var mod = this

  // When module is executed, DO NOT execute it again. When module
  // is being executed, just return `module.exports` too, for avoiding
  // circularly calling
  if (mod.status >= STATUS.EXECUTING) {
    return mod.exports
  }

  mod.status = STATUS.EXECUTING

  // Create require
  var uri = mod.uri

  function require(id) {
    return cachedMods[require.resolve(id)].exec()
  }

  require.resolve = function(id) {
    return resolve(id, uri)
  }

  require.async = function(ids, callback) {
    Module.use(ids, callback, uri + "_async_" + cid())
    return require
  }

  // Exec factory
  var factory = mod.factory

  var exports = isFunction(factory) ?
      factory(require, mod.exports = {}, mod) :
      factory

  if (exports === undefined) {
    exports = mod.exports
  }

  // Emit `error` event
  if (exports === null && !IS_CSS_RE.test(uri)) {
    emit("error", mod)
  }

  // Reduce memory leak
  delete mod.factory

  mod.exports = exports
  mod.status = STATUS.EXECUTED

  // Emit `exec` event
  emit("exec", mod)

  return exports
}

// Define a module
Module.define = function (id, deps, factory) {
  var argsLen = arguments.length

  // define(factory)
  if (argsLen === 1) {
    factory = id
    id = undefined
  }
  else if (argsLen === 2) {
    factory = deps

    // define(deps, factory)
    if (isArray(id)) {
      deps = id
      id = undefined
    }
    // define(id, factory)
    else {
      deps = undefined
    }
  }

  // Parse dependencies according to the module factory code
  if (!isArray(deps) && isFunction(factory)) {
    deps = parseDependencies(factory.toString())
  }

  var meta = {
    id: id,
    uri: resolve(id),
    deps: deps,
    factory: factory
  }

  // Try to derive uri in IE6-9 for anonymous modules
  if (!meta.uri && doc.attachEvent) {
    var script = getCurrentScript()

    if (script) {
      meta.uri = script.src
    }
    else {
      log("Failed to derive: " + factory)

      // NOTE: If the id-deriving methods above is failed, then falls back
      // to use onload event to get the uri
    }
  }

  // Emit `define` event, used in nocache plugin, seajs node version etc
  emit("define", meta)

  meta.uri ? save(meta.uri, meta) :
      // Save information for "saving" work in the script onload event
      anonymousMeta = meta
}

// Get an existed module or create a new one
Module.get = function(uri, deps) {
  return cachedMods[uri] || (cachedMods[uri] = new Module(uri, deps))
}

// Use function is equal to load a anonymous module
Module.use = function (ids, callback, uri) {
  var mod = Module.get(uri, isArray(ids) ? ids : [ids])

  mod.callback = function() {
    var exports = []
    var uris = mod.resolve()

    for (var i = 0, len = uris.length; i < len; i++) {
      exports[i] = cachedMods[uris[i]].exec()
    }

    if (callback) {
      callback.apply(global, exports)
    }

    delete mod.callback
  }

  mod.load()
}

// Load preload modules before all other modules
Module.preload = function(callback) {
  var preloadMods = data.preload
  var len = preloadMods.length

  if (len) {
    Module.use(preloadMods, function() {
      // Remove the loaded preload modules
      preloadMods.splice(0, len)

      // Allow preload modules to add new preload modules
      Module.preload(callback)
    }, data.cwd + "_preload_" + cid())
  }
  else {
    callback()
  }
}

// Helpers

function resolve(id, refUri) {
  // Emit `resolve` event for plugins such as text plugin
  var emitData = { id: id, refUri: refUri }
  emit("resolve", emitData)

  return emitData.uri || id2Uri(emitData.id, refUri)
}

function save(uri, meta) {
  var mod = Module.get(uri)

  // Do NOT override already saved modules
  if (mod.status < STATUS.SAVED) {
    mod.id = meta.id || uri
    mod.dependencies = meta.deps || []
    mod.factory = meta.factory
    mod.status = STATUS.SAVED
  }
}

// Public API

seajs.use = function(ids, callback) {
  Module.preload(function() {
    Module.use(ids, callback, data.cwd + "_use_" + cid())
  })
  return seajs
}

Module.define.cmd = {}
global.define = Module.define

// For Developers

seajs.Module = Module
data.fetchedList = fetchedList
data.cid = cid

seajs.resolve = id2Uri
seajs.require = function(id) {
  return (cachedMods[resolve(id)] || {}).exports
}

<commit_msg>Remove requested event<commit_after>/**
 * module.js - The core of module loader
 */

var cachedMods = seajs.cache = {}
var anonymousMeta

var fetchingList = {}
var fetchedList = {}
var callbackList = {}

var STATUS = Module.STATUS = {
  // 1 - The `module.uri` is being fetched
  FETCHING: 1,
  // 2 - The meta data has been saved to cachedMods
  SAVED: 2,
  // 3 - The `module.dependencies` are being loaded
  LOADING: 3,
  // 4 - The module are ready to execute
  LOADED: 4,
  // 5 - The module is being executed
  EXECUTING: 5,
  // 6 - The `module.exports` is available
  EXECUTED: 6
}

function Module(uri, deps) {
  this.uri = uri
  this.dependencies = deps || []
  this.exports = null
  this.status = 0

  // Who depend on me
  this._waitings = {}

  // The number of unloaded dependencies
  this._remain = 0
}

// Resolve module.dependencies
Module.prototype.resolve = function() {
  var mod = this
  var ids = mod.dependencies
  var uris = []

  for (var i = 0, len = ids.length; i < len; i++) {
    uris[i] = resolve(ids[i], mod.uri)
  }
  return uris
}

// Load module.dependencies and fire onload when all done
Module.prototype.load = function() {
  var mod = this

  // If the module is being loaded, just wait it onload call
  if (mod.status >= STATUS.LOADING) {
    return
  }

  mod.status = STATUS.LOADING

  // Emit `load` event for plugins such as combo plugin
  var uris = mod.resolve()
  emit("load", uris)

  var len = mod._remain = uris.length
  var m

  // Initialize modules and register waitings
  for (var i = 0; i < len; i++) {
    m = Module.get(uris[i])

    if (m.status < STATUS.LOADED) {
      // Maybe duplicate
      m._waitings[mod.uri] = (m._waitings[mod.uri] || 0) + 1
    }
    else {
      mod._remain--
    }
  }

  if (mod._remain === 0) {
    mod.onload()
    return
  }

  // Begin parallel loading
  var requestCache = {}

  for (i = 0; i < len; i++) {
    m = cachedMods[uris[i]]

    if (m.status < STATUS.FETCHING) {
      m.fetch(requestCache)
    }
    else if (m.status === STATUS.SAVED) {
      m.load()
    }
  }

  // Send all requests at last to avoid cache bug in IE6-9. Issues#808
  for (var requestUri in requestCache) {
    if (requestCache.hasOwnProperty(requestUri)) {
      requestCache[requestUri]()
    }
  }
}

// Call this method when module is loaded
Module.prototype.onload = function() {
  var mod = this
  mod.status = STATUS.LOADED

  if (mod.callback) {
    mod.callback()
  }

  // Notify waiting modules to fire onload
  var waitings = mod._waitings
  var uri, m

  for (uri in waitings) {
    if (waitings.hasOwnProperty(uri)) {
      m = cachedMods[uri]
      m._remain -= waitings[uri]
      if (m._remain === 0) {
        m.onload()
      }
    }
  }

  // Reduce memory taken
  delete mod._waitings
  delete mod._remain
}

// Fetch a module
Module.prototype.fetch = function(requestCache) {
  var mod = this
  var uri = mod.uri

  mod.status = STATUS.FETCHING

  // Emit `fetch` event for plugins such as combo plugin
  var emitData = { uri: uri }
  emit("fetch", emitData)
  var requestUri = emitData.requestUri || uri

  // Empty uri or a non-CMD module
  if (!requestUri || fetchedList[requestUri]) {
    mod.load()
    return
  }

  if (fetchingList[requestUri]) {
    callbackList[requestUri].push(mod)
    return
  }

  fetchingList[requestUri] = true
  callbackList[requestUri] = [mod]

  // Emit `request` event for plugins such as text plugin
  emit("request", emitData = {
    uri: uri,
    requestUri: requestUri,
    onRequest: onRequest,
    charset: data.charset
  })

  if (!emitData.requested) {
    requestCache ?
        requestCache[emitData.requestUri] = sendRequest :
        sendRequest()
  }

  function sendRequest() {
    request(emitData.requestUri, emitData.onRequest, emitData.charset)
  }

  function onRequest() {
    delete fetchingList[requestUri]
    fetchedList[requestUri] = true

    // Save meta data of anonymous module
    if (anonymousMeta) {
      save(uri, anonymousMeta)
      anonymousMeta = null
    }

    // Call callbacks
    var m, mods = callbackList[requestUri]
    delete callbackList[requestUri]
    while ((m = mods.shift())) m.load()
  }
}

// Execute a module
Module.prototype.exec = function () {
  var mod = this

  // When module is executed, DO NOT execute it again. When module
  // is being executed, just return `module.exports` too, for avoiding
  // circularly calling
  if (mod.status >= STATUS.EXECUTING) {
    return mod.exports
  }

  mod.status = STATUS.EXECUTING

  // Create require
  var uri = mod.uri

  function require(id) {
    return cachedMods[require.resolve(id)].exec()
  }

  require.resolve = function(id) {
    return resolve(id, uri)
  }

  require.async = function(ids, callback) {
    Module.use(ids, callback, uri + "_async_" + cid())
    return require
  }

  // Exec factory
  var factory = mod.factory

  var exports = isFunction(factory) ?
      factory(require, mod.exports = {}, mod) :
      factory

  if (exports === undefined) {
    exports = mod.exports
  }

  // Emit `error` event
  if (exports === null && !IS_CSS_RE.test(uri)) {
    emit("error", mod)
  }

  // Reduce memory leak
  delete mod.factory

  mod.exports = exports
  mod.status = STATUS.EXECUTED

  // Emit `exec` event
  emit("exec", mod)

  return exports
}

// Define a module
Module.define = function (id, deps, factory) {
  var argsLen = arguments.length

  // define(factory)
  if (argsLen === 1) {
    factory = id
    id = undefined
  }
  else if (argsLen === 2) {
    factory = deps

    // define(deps, factory)
    if (isArray(id)) {
      deps = id
      id = undefined
    }
    // define(id, factory)
    else {
      deps = undefined
    }
  }

  // Parse dependencies according to the module factory code
  if (!isArray(deps) && isFunction(factory)) {
    deps = parseDependencies(factory.toString())
  }

  var meta = {
    id: id,
    uri: resolve(id),
    deps: deps,
    factory: factory
  }

  // Try to derive uri in IE6-9 for anonymous modules
  if (!meta.uri && doc.attachEvent) {
    var script = getCurrentScript()

    if (script) {
      meta.uri = script.src
    }
    else {
      log("Failed to derive: " + factory)

      // NOTE: If the id-deriving methods above is failed, then falls back
      // to use onload event to get the uri
    }
  }

  // Emit `define` event, used in nocache plugin, seajs node version etc
  emit("define", meta)

  meta.uri ? save(meta.uri, meta) :
      // Save information for "saving" work in the script onload event
      anonymousMeta = meta
}

// Get an existed module or create a new one
Module.get = function(uri, deps) {
  return cachedMods[uri] || (cachedMods[uri] = new Module(uri, deps))
}

// Use function is equal to load a anonymous module
Module.use = function (ids, callback, uri) {
  var mod = Module.get(uri, isArray(ids) ? ids : [ids])

  mod.callback = function() {
    var exports = []
    var uris = mod.resolve()

    for (var i = 0, len = uris.length; i < len; i++) {
      exports[i] = cachedMods[uris[i]].exec()
    }

    if (callback) {
      callback.apply(global, exports)
    }

    delete mod.callback
  }

  mod.load()
}

// Load preload modules before all other modules
Module.preload = function(callback) {
  var preloadMods = data.preload
  var len = preloadMods.length

  if (len) {
    Module.use(preloadMods, function() {
      // Remove the loaded preload modules
      preloadMods.splice(0, len)

      // Allow preload modules to add new preload modules
      Module.preload(callback)
    }, data.cwd + "_preload_" + cid())
  }
  else {
    callback()
  }
}

// Helpers

function resolve(id, refUri) {
  // Emit `resolve` event for plugins such as text plugin
  var emitData = { id: id, refUri: refUri }
  emit("resolve", emitData)

  return emitData.uri || id2Uri(emitData.id, refUri)
}

function save(uri, meta) {
  var mod = Module.get(uri)

  // Do NOT override already saved modules
  if (mod.status < STATUS.SAVED) {
    mod.id = meta.id || uri
    mod.dependencies = meta.deps || []
    mod.factory = meta.factory
    mod.status = STATUS.SAVED
  }
}

// Public API

seajs.use = function(ids, callback) {
  Module.preload(function() {
    Module.use(ids, callback, data.cwd + "_use_" + cid())
  })
  return seajs
}

Module.define.cmd = {}
global.define = Module.define

// For Developers

seajs.Module = Module
data.fetchedList = fetchedList
data.cid = cid

seajs.resolve = id2Uri
seajs.require = function(id) {
  return (cachedMods[resolve(id)] || {}).exports
}

<|endoftext|>


<commit_before>import defaults from './modules/defaults'
import { isIgnored, ignoreSettings } from './modules/ignore'
import { getProps, has, reduceContent } from './modules/utils'

const { config } = hexo

const json = config.jsonContent || { meta: true }

const pages = has(json, 'pages') ? json.pages : defaults.pages

const posts = has(json, 'posts') ? json.posts : defaults.posts

const ignore = ignoreSettings(json)

let output = json.meta ? {
  meta: {
    title: config.title,
    subtitle: config.subtitle,
    description: config.description,
    author: config.author,
    url: config.url,
    root: config.root
  }
} : {}

hexo.extend.generator.register('json-content', site => {
  if (pages) {
    const pagesNames = getProps(pages)
    const pagesValid = site.pages.filter(page => !isIgnored(page, ignore))
    const pagesContent = pagesValid.map(page => reduceContent(pagesNames, page, json))

    if (posts || json.meta) {
      output.pages = pagesContent
    } else {
      output = pagesContent
    }
  }

  if (posts) {
    const postsNames = getProps(posts)
    const postsSorted = site.posts.sort('-date')
    const postsValid = postsSorted.filter(post => {
      const include = json.drafts || post.published
      return include && !isIgnored(post, ignore)
    })
    const postsContent = postsValid.map(post => reduceContent(postsNames, post, json))

    if (pages || json.meta) {
      output.posts = postsContent
    } else {
      output = postsContent
    }
  }

  return {
    path: json.file || 'content.json',
    data: JSON.stringify(output)
  }
})
<commit_msg>Better options assignment<commit_after>import defaults from './modules/defaults'
import { isIgnored, ignoreSettings } from './modules/ignore'
import { getProps, has, reduceContent } from './modules/utils'

const { config } = hexo
const defs = { meta: true }
const opts = config.jsonContent || {}
const json = { ...defs, ...opts }
const pages = has(json, 'pages') ? json.pages : defaults.pages
const posts = has(json, 'posts') ? json.posts : defaults.posts
const ignore = ignoreSettings(json)

let output = json.meta ? {
  meta: {
    title: config.title,
    subtitle: config.subtitle,
    description: config.description,
    author: config.author,
    url: config.url,
    root: config.root
  }
} : {}

hexo.extend.generator.register('json-content', site => {
  if (pages) {
    const pagesNames = getProps(pages)
    const pagesValid = site.pages.filter(page => !isIgnored(page, ignore))
    const pagesContent = pagesValid.map(page => reduceContent(pagesNames, page, json))

    if (posts || json.meta) {
      output.pages = pagesContent
    } else {
      output = pagesContent
    }
  }

  if (posts) {
    const postsNames = getProps(posts)
    const postsSorted = site.posts.sort('-date')
    const postsValid = postsSorted.filter(post => {
      const include = json.drafts || post.published
      return include && !isIgnored(post, ignore)
    })
    const postsContent = postsValid.map(post => reduceContent(postsNames, post, json))

    if (pages || json.meta) {
      output.posts = postsContent
    } else {
      output = postsContent
    }
  }

  return {
    path: json.file || 'content.json',
    data: JSON.stringify(output)
  }
})
<|endoftext|>


<commit_before>/**
 * This is the actual embed script that people put on their page. I use the
 * technique of passing in variables as function parameters, even if not
 * defined, to remove the need for a `var` statement.
 *
 * This script creates a window.branch object with a number of calls. When you
 * call them, it saves your call for later.
 */

(function(root, doc, scriptStr, branchStr, createCallback, branchSdk, funcs, i, scriptTag, firstScript) {
  if (!root[branchStr] || !root[branchStr]._q) {
    while (i < funcs.length) {
      createCallback(branchSdk, funcs[i++]);
    }

    scriptTag = doc.createElement(scriptStr);
    scriptTag.async = 1;
    scriptTag.src = "https://s3-us-west-1.amazonaws.com/branch-web-sdk/branch-0.x.min.js";
    firstScript = doc.getElementsByTagName(scriptStr)[0];
    firstScript.parentNode.insertBefore(scriptTag, firstScript);

    root[branchStr] = branchSdk;
  }
})(window, document, "script", 'branch', function(branch, name) {
  branch[name] = function() {
    branch._q.push([ name, arguments ]);
  };
}, { _q: [], _v: 1 }, // _q: the "queue" of calls, _v: the "version" of the embed script
'init;data;setIdentity;logout;track;link;linkClick;sendSMS;referrals;credits;redeem;banner'.split(';'), 0);
<commit_msg>We don't expose linkClick function<commit_after>/**
 * This is the actual embed script that people put on their page. I use the
 * technique of passing in variables as function parameters, even if not
 * defined, to remove the need for a `var` statement.
 *
 * This script creates a window.branch object with a number of calls. When you
 * call them, it saves your call for later.
 */

(function(root, doc, scriptStr, branchStr, createCallback, branchSdk, funcs, i, scriptTag, firstScript) {
  if (!root[branchStr] || !root[branchStr]._q) {
    while (i < funcs.length) {
      createCallback(branchSdk, funcs[i++]);
    }

    scriptTag = doc.createElement(scriptStr);
    scriptTag.async = 1;
    scriptTag.src = "https://s3-us-west-1.amazonaws.com/branch-web-sdk/branch-0.x.min.js";
    firstScript = doc.getElementsByTagName(scriptStr)[0];
    firstScript.parentNode.insertBefore(scriptTag, firstScript);

    root[branchStr] = branchSdk;
  }
})(window, document, "script", 'branch', function(branch, name) {
  branch[name] = function() {
    branch._q.push([ name, arguments ]);
  };
}, { _q: [], _v: 1 }, // _q: the "queue" of calls, _v: the "version" of the embed script
'init;data;setIdentity;logout;track;link;sendSMS;referrals;credits;redeem;banner'.split(';'), 0);
<|endoftext|>


<commit_before>require('TraceKit')
var exceptionist = require('./lib/exceptionist')
var logger = require('./lib/logger')
var utils = require('./lib/utils')
var config = require('./lib/config')

function Opbeat () {
  this.isInstalled = false
  this.options = config.getConfig()

  this.onTraceKitReport = function (stackInfo) {
    logger.log('opbeat.onTraceKitReport', stackInfo)

    var exception = exceptionist.traceKitStackToOpbeatException(stackInfo, this.options)

    exceptionist.processException(exception, this.options)
  }

Opbeat.prototype.VERSION = '0.0.1'

Opbeat.prototype.isPlatformSupport = function () {
  return typeof Array.prototype.forEach === 'function' &&
    typeof JSON.stringify === 'function'
}

/*
 * Configure Opbeat with Opbeat.com credentials and other options
 *
 * @param {object} options Optional set of of global options
 * @return {Opbeat}
 */

Opbeat.prototype.config = function (options) {
  this.options = utils.mergeObject(this.options, options)
  return this
}

/*
 * Installs a global window.onerror error handler
 * to capture and report uncaught exceptions.
 * At this point, install() is required to be called due
 * to the way TraceKit is set up.
 *
 * @return {Opbeat}
 */

Opbeat.prototype.install = function () {
  if (this.isPlatformSupport() && !this.isInstalled) {
    window.TraceKit.report.subscribe(this.onTraceKitReport.bind(this))
    this.isInstalled = true
  }

  return this

}

/*
 * Uninstalls the global error handler.
 *
 * @return {Opbeat}
 */
Opbeat.prototype.uninstall = function () {
  window.TraceKit.report.uninstall()
  this.isInstalled = false

  return this
}

/*
 * Manually capture an exception and send it over to Opbeat.com
 *
 * @param {error} ex An exception to be logged
 * @param {object} options A specific set of options for this error [optional]
 * @return {Opbeat}
 */
Opbeat.prototype.captureException = function (ex, options) {
  if (!this.isInstalled) {
    throw new Error("Can't capture exception. Opbeat isn't intialized")
  }

  if (!(ex instanceof Error)) {
    throw new Error("Can't capture exception. Passed exception needs to be an instanceof Error")
  }

  // TraceKit.report will re-raise any exception passed to it,
  // which means you have to wrap it in try/catch. Instead, we
  // can wrap it here and only re-raise if TraceKit.report
  // raises an exception different from the one we asked to
  // report on.

  try {
    window.TraceKit.report(ex, options)
  } catch(ex1) {
    if (ex !== ex1) {
      throw ex1
    }
  }

  return this
}

/*
 * Set/clear a user to be sent along with the payload.
 *
 * @param {object} user An object representing user data [optional]
 * @return {Opbeat}
 */
Opbeat.prototype.setUserContext = function (user) {
  this.options.context.user = user

  return this
}

/*
 * Set extra attributes to be sent along with the payload.
 *
 * @param {object} extra An object representing extra data [optional]
 * @return {Opbeat}
 */
Opbeat.prototype.setExtraContext = function (extra) {
  this.options.context.extra = user

  return this
}

module.exports = new Opbeat()
<commit_msg>Validate config and install client if its valid upon initialization <commit_after>require('TraceKit')
var exceptionist = require('./lib/exceptionist')
var logger = require('./lib/logger')
var utils = require('./lib/utils')
var config = require('./lib/config')

function Opbeat () {
  this.isInstalled = false
  this.options = config.getConfig()

  this.onTraceKitReport = function (stackInfo) {
    logger.log('opbeat.onTraceKitReport', stackInfo)

    var exception = exceptionist.traceKitStackToOpbeatException(stackInfo, this.options)

    exceptionist.processException(exception, this.options)
  }

  if (config.isConfigValid(this.options)) {
    this.install()
  }

}

Opbeat.prototype.VERSION = '0.0.1'

Opbeat.prototype.isPlatformSupport = function () {
  return typeof Array.prototype.forEach === 'function' &&
    typeof JSON.stringify === 'function'
}

/*
 * Configure Opbeat with Opbeat.com credentials and other options
 *
 * @param {object} options Optional set of of global options
 * @return {Opbeat}
 */

Opbeat.prototype.config = function (options) {
  this.options = utils.mergeObject(this.options, options)
  return this
}

/*
 * Installs a global window.onerror error handler
 * to capture and report uncaught exceptions.
 * At this point, install() is required to be called due
 * to the way TraceKit is set up.
 *
 * @return {Opbeat}
 */

Opbeat.prototype.install = function () {
  if (this.isPlatformSupport() && !this.isInstalled) {
    window.TraceKit.report.subscribe(this.onTraceKitReport.bind(this))
    this.isInstalled = true
  }

  return this

}

/*
 * Uninstalls the global error handler.
 *
 * @return {Opbeat}
 */
Opbeat.prototype.uninstall = function () {
  window.TraceKit.report.uninstall()
  this.isInstalled = false

  return this
}

/*
 * Manually capture an exception and send it over to Opbeat.com
 *
 * @param {error} ex An exception to be logged
 * @param {object} options A specific set of options for this error [optional]
 * @return {Opbeat}
 */
Opbeat.prototype.captureException = function (ex, options) {
  if (!this.isInstalled) {
    throw new Error("Can't capture exception. Opbeat isn't intialized")
  }

  if (!(ex instanceof Error)) {
    throw new Error("Can't capture exception. Passed exception needs to be an instanceof Error")
  }

  // TraceKit.report will re-raise any exception passed to it,
  // which means you have to wrap it in try/catch. Instead, we
  // can wrap it here and only re-raise if TraceKit.report
  // raises an exception different from the one we asked to
  // report on.

  try {
    window.TraceKit.report(ex, options)
  } catch(ex1) {
    if (ex !== ex1) {
      throw ex1
    }
  }

  return this
}

/*
 * Set/clear a user to be sent along with the payload.
 *
 * @param {object} user An object representing user data [optional]
 * @return {Opbeat}
 */
Opbeat.prototype.setUserContext = function (user) {
  this.options.context.user = user

  return this
}

/*
 * Set extra attributes to be sent along with the payload.
 *
 * @param {object} extra An object representing extra data [optional]
 * @return {Opbeat}
 */
Opbeat.prototype.setExtraContext = function (extra) {
  this.options.context.extra = user

  return this
}

module.exports = new Opbeat()
<|endoftext|>


<commit_before>/**
 * @file
 * @author zdying
 */

'use strict';

var utils = require('./utils');

function Option (key, config) {
  config = config || {};

  var keyTokens = key.split(/\s+/);
  var optKey = keyTokens[0];
  var params = keyTokens.slice(1);
  var alias = config.alias;
  var validate = config.validate;

  if (params.length > 0) {
    config.params = params;
  }

  // this.name = key;
  // this.config = config;

  if (optKey.length === 1 && alias && alias.length > 1) {
    config.alias = optKey;
    optKey = alias;
  }

  if (validate && typeof validate !== 'function') {
    if (validate instanceof RegExp) {
      config.validate = function (val, result) {
        return validate.test(val);
      };
    }
  }

  this.name = utils.toCamelCase(optKey);
  this.originName = optKey;
  this.config = config;
}

Option.prototype = {
  constructor: Option,

  help: function () {

  }
};

module.exports = Option;
<commit_msg>delete unused code<commit_after>/**
 * @file
 * @author zdying
 */

'use strict';

var utils = require('./utils');

function Option (key, config) {
  config = config || {};

  var keyTokens = key.split(/\s+/);
  var optKey = keyTokens[0];
  var params = keyTokens.slice(1);
  var alias = config.alias;
  var validate = config.validate;

  if (params.length > 0) {
    config.params = params;
  }

  // this.name = key;
  // this.config = config;

  if (optKey.length === 1 && alias && alias.length > 1) {
    config.alias = optKey;
    optKey = alias;
  }

  if (validate && typeof validate !== 'function') {
    if (validate instanceof RegExp) {
      config.validate = function (val, result) {
        return validate.test(val);
      };
    }
  }

  this.name = utils.toCamelCase(optKey);
  this.originName = optKey;
  this.config = config;
}

// Option.prototype = {
//   constructor: Option,

//   help: function () {

//   }
// };

module.exports = Option;
<|endoftext|>


<commit_before>/**
 * Originally based on (public domain):
 * https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
 */

import {
  options, objectForEach
} from 'tko.utils';

import Expression from './expression';
import Identifier from './identifier';
import Arguments from './arguments';
import Node from './node';

var escapee = {
    "'": "'",
    '"':  '"',
    "`":  "`",
    '\\': '\\',
    '/':  '/',
    '$':  '$',
    b:    '\b',
    f:    '\f',
    n:    '\n',
    r:    '\r',
    t:    '\t'
  },
  operators = Node.operators;

/**
 * Construct a new Parser instance with new Parser(node, context)
 * @param {Node} node    The DOM element from which we parsed the
 *                         content.
 * @param {object} context The Knockout context.
 * @param {object} globals An object containing any desired globals.
 */
export default function Parser(node, context, globals) {
  this.node = node;
  this.context = context;
  this.globals = globals || {};
}

// Exposed for testing.
Parser.Expression = Expression;
Parser.Identifier = Identifier;
Parser.Arguments = Arguments;
Parser.Node = Node;

Parser.prototype.white = function () {
  var ch = this.ch;
  while (ch && ch <= ' ') {
    ch = this.next();
  }
  return ch;
};

Parser.prototype.next = function (c) {
  if (c && c !== this.ch) {
    this.error("Expected '" + c + "' but got '" + this.ch + "'");
  }
  this.ch = this.text.charAt(this.at);
  this.at += 1;
  return this.ch;
};

Parser.prototype.error = function (m) {
  throw {
    name:    'SyntaxError',
    message: m,
    at:      this.at,
    text:    this.text
  };
};

Parser.prototype.name = function () {
  // A name of a binding
  var name = '',
    enclosed_by;
  this.white();

  var ch = this.ch;

  if (ch === "'" || ch === '"') {
    enclosed_by = ch;
    ch = this.next();
  }

  while (ch) {
    if (enclosed_by && ch === enclosed_by) {
      this.white();
      ch = this.next();
      if (ch !== ':' && ch !== ',') {
        this.error(
          "Object name: " + name + " missing closing " + enclosed_by
        );
      }
      return name;
    } else if (ch === ':' || ch <= ' ' || ch === ',' ) {
      return name;
    }
    name += ch;
    ch = this.next();
  }

  return name;
};

Parser.prototype.number = function () {
  var number,
    string = '',
    ch = this.ch;

  if (ch === '-') {
    string = '-';
    ch = this.next('-');
  }
  while (ch >= '0' && ch <= '9') {
    string += ch;
    ch = this.next();
  }
  if (ch === '.') {
    string += '.';
    ch = this.next();
    while (ch && ch >= '0' && ch <= '9') {
      string += ch;
      ch = this.next();
    }
  }
  if (ch === 'e' || ch === 'E') {
    string += ch;
    ch = this.next();
    if (ch === '-' || ch === '+') {
      string += ch;
      ch = this.next();
    }
    while (ch >= '0' && ch <= '9') {
      string += ch;
      ch = this.next();
    }
  }
  number = +string;
  if (!isFinite(number)) {
    options.onError(new Error("Bad number: " + number + " in " + string));
  } else {
    return number;
  }
};

/**
 * Add a property to 'object' that equals the given value.
 * @param  {Object} object The object to add the value to.
 * @param  {String} key    object[key] is set to the given value.
 * @param  {mixed}  value  The value, may be a primitive or a function. If a
 *                         function it is unwrapped as a property.
 */
Parser.prototype.object_add_value = function (object, key, value) {
  if (value && value[Node.isExpressionOrIdentifierSymbol]) {
    Object.defineProperty(object, key, {
      get: function () {
        return value.get_value();
      },
      enumerable: true
    });
  } else {
    // primitives
    object[key] = value;
  }
};

Parser.prototype.object = function () {
  var key,
    object = {},
    ch = this.ch;

  if (ch === '{') {
    this.next('{');
    ch = this.white();
    if (ch === '}') {
      ch = this.next('}');
      return object;
    }
    while (ch) {
      if (ch === '"' || ch === "'" || ch === "`") {
        key = this.string();
      } else {
        key = this.name();
      }
      this.white();
      ch = this.next(':');
      if (Object.hasOwnProperty.call(object, key)) {
        this.error('Duplicate key "' + key + '"');
      }

      this.object_add_value(object, key, this.expression());

      ch = this.white();
      if (ch === '}') {
        ch = this.next('}');
        return object;
      }

      this.next(',');
      ch = this.white();
    }
  }
  this.error("Bad object");
};

/**
 * Read up to delim and return the string
 * @param  {string} delim The delimiter, either ' or "
 * @return {string}       The string read.
 */
Parser.prototype.read_string = function (delim) {
  var string = '',
    nodes = [''],
    plus_op = operators['+'],
    hex,
    i,
    uffff,
    interpolate = delim === "`",
    ch = this.next();

  while (ch) {
    if (ch === delim) {
      ch = this.next();
      if (interpolate) { nodes.push(plus_op); }
      nodes.push(string);
      return nodes;
    }
    if (ch === '\\') {
      ch = this.next();
      if (ch === 'u') {
        uffff = 0;
        for (i = 0; i < 4; i += 1) {
          hex = parseInt(ch = this.next(), 16);
          if (!isFinite(hex)) {
            break;
          }
          uffff = uffff * 16 + hex;
        }
        string += String.fromCharCode(uffff);
      } else if (typeof escapee[ch] === 'string') {
        string += escapee[ch];
      } else {
        break;
      }
    } else if (interpolate && ch === "$") {
      ch = this.next();
      if (ch === '{') {
        this.next('{');
        nodes.push(plus_op);
        nodes.push(string);
        nodes.push(plus_op);
        nodes.push(this.expression());
        string = '';
        // this.next('}');
      } else {
        string += "$" + ch;
      }
    } else {
      string += ch;
    }
    ch = this.next();
  }

  this.error("Bad string");
};

Parser.prototype.string = function () {
  var ch = this.ch;
  if (ch === '"') {
    return this.read_string('"').join('');
  } else if (ch === "'") {
    return this.read_string("'").join('');
  } else if (ch === "`") {
    return Node.create_root(this.read_string("`"));
  }

  this.error("Bad string");
};

Parser.prototype.array = function () {
  var array = [],
    ch = this.ch;

  if (ch === '[') {
    ch = this.next('[');
    this.white();
    if (ch === ']') {
      ch = this.next(']');
      return array;
    }
    while (ch) {
      array.push(this.expression());
      ch = this.white();
      if (ch === ']') {
        ch = this.next(']');
        return array;
      }
      this.next(',');
      ch = this.white();
    }
  }
  this.error("Bad array");
};

Parser.prototype.value = function () {
  var ch;
  this.white();
  ch = this.ch;
  switch (ch) {
  case '{': return this.object();
  case '[': return this.array();
  case '"': case "'": case "`": return this.string();
  case '-': return this.number();
  default:
    return ch >= '0' && ch <= '9' ? this.number() : this.identifier();
  }
};

/**
 * Get the function for the given operator.
 * A `.precedence` value is added to the function, with increasing
 * precedence having a higher number.
 * @return {function} The function that performs the infix operation
 */
Parser.prototype.operator = function () {
  var op = '',
    op_fn,
    ch = this.white();

  while (ch) {
    if (is_identifier_char(ch) || ch <= ' ' || ch === '' ||
        ch === '"' || ch === "'" || ch === '{' || ch === '[' ||
        ch === '(' || ch === "`") {
      break;
    }
    op += ch;
    ch = this.next();
  }

  if (op !== '') {
    op_fn = operators[op];

    if (!op_fn) {
      this.error("Bad operator: '" + op + "'.");
    }
  }

  return op_fn;
};

/**
 * Parse an expression – builds an operator tree, in something like
 * Shunting-Yard.
 *   See: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
 *
 * @return {function}   A function that computes the value of the expression
 *                      when called or a primitive.
 */
Parser.prototype.expression = function () {
  var op,
    nodes = [],
    node_value,
    ch = this.white();

  while (ch) {
    // unary prefix operators
    op = this.operator();
    if (op) {
      nodes.push(undefined);  // padding.
      nodes.push(op);
    }

    if (ch === '(') {
      this.next();
      nodes.push(this.expression());
      this.next(')');
    } else {
      node_value = this.value();
      nodes.push(node_value);
    }
    ch = this.white();
    if (ch === ':' || ch === '}' || ch === ',' || ch === ']' ||
        ch === ')' || ch === '' || ch === '`') {
      break;
    }
    // infix operators
    op = this.operator();
    if (op) {
      nodes.push(op);
    }
    ch = this.white();
  }

  if (nodes.length === 0) {
    return undefined;
  }

  if (nodes.length === 1) {
    return nodes[0];
  }

  return new Expression(nodes);
};

/**
 * Parse the arguments to a function, returning an Array.
 *
 */
Parser.prototype.func_arguments = function () {
  var args = [],
    ch = this.next('(');

  while(ch) {
    ch = this.white();
    if (ch === ')') {
      this.next(')');
      return new Arguments(this, args);
    } else {
      args.push(this.expression());
      ch = this.white();
    }
    if (ch !== ')') { this.next(','); }
  }

  this.error("Bad arguments to function");
};

/**
 * A dereference applies to an identifer, being either a function
 * call "()" or a membership lookup with square brackets "[member]".
 * @return {fn or undefined}  Dereference function to be applied to the
 *                            Identifier
 */
Parser.prototype.dereference = function () {
  var member,
    ch = this.white();

  while (ch) {
    if (ch === '(') {
      // a(...) function call
      return this.func_arguments();
    } else if (ch === '[') {
      // a[x] membership
      this.next('[');
      member = this.expression();
      this.white();
      this.next(']');

      return member;
    } else if (ch === '.') {
      // a.x membership
      member = '';
      this.next('.');
      ch = this.white();
      while (ch) {
        if (!is_identifier_char(ch)) {
          break;
        }
        member += ch;
        ch = this.next();
      }
      return member;
    } else {
      break;
    }
  }
  return;
};

Parser.prototype.identifier = function () {
  var token = '', ch, deref, dereferences = [];
  ch = this.white();
  while (ch) {
    if (!is_identifier_char(ch)) {
      break;
    }
    token += ch;
    ch = this.next();
  }
  switch (token) {
  case 'true': return true;
  case 'false': return false;
  case 'null': return null;
  case 'undefined': return void 0;
  default:
  }
  while (ch) {
    deref = this.dereference();
    if (deref !== undefined) {
      dereferences.push(deref);
    } else {
      break;
    }
  }
  return new Identifier(this, token, dereferences);
};

Parser.prototype.read_bindings = function () {
  var key,
    bindings = {},
    sep,
    ch = this.ch;

  while (ch) {
    key = this.name();
    sep = this.white();
    if (!sep || sep === ',') {
      if (sep) {
        ch = this.next(',');
      } else {
        ch = '';
      }
      // A "bare" binding e.g. "text"; substitute value of 'null'
      // so it becomes "text: null".
      bindings[key] = null;
    } else {
      ch = this.next(':');
      bindings[key] = this.expression();
      this.white();
      if (this.ch) {
        ch = this.next(',');
      } else {
        ch = '';
      }
    }
  }
  return bindings;
};

/**
* Convert result[name] from a value to a function (i.e. `valueAccessor()`)
* @param  {object} result [Map of top-level names to values]
* @return {object}        [Map of top-level names to functions]
*
* Accessors may be one of (below) constAccessor, identifierAccessor,
* expressionAccessor, or nodeAccessor.
*/
Parser.prototype.convert_to_accessors = function (result) {

  objectForEach(result, function (name, value) {
    if (value instanceof Identifier) {
      // Return a function that, with no arguments returns
      // the value of the identifier, otherwise sets the
      // value of the identifier to the first given argument.
      Object.defineProperty(result, name, {
        value: function (optionalValue, options) {
          if (arguments.length === 0) {
            return value.get_value();
          }
          if (options && options.onlyIfChanged && optionalValue === value.get_value()) {
            return;
          }
          return value.set_value(optionalValue);
        }
      });
    } else if (value instanceof Expression) {
      result[name] = function expressionAccessor() {
        return value.get_value();
      };
    } else if (value instanceof Node) {
      result[name] = function nodeAccessor() {
        return value.get_node_value();
      };
    } else if (typeof(value) != 'function') {
      result[name] = function constAccessor() {
        return value;
      };
    }
  });

  return result;
};

/**
 * Get the bindings as name: accessor()
 * @param  {string} source The binding string to parse.
 * @return {object}        Map of name to accessor function.
 */
Parser.prototype.parse = function (source) {
  this.text = (source || '').trim();
  this.at = 0;
  this.ch = ' ';

  if (!this.text) {
    return null;
  }

  try {
    var result = this.read_bindings();
  } catch (e) {
    options.onError(new Error(
      "Unable to parse bindings." +
      "\nBindings value: " + this.text +
      "\nMessage: <" + e.name + "> " + e.message
    ));
  }

  this.white();
  if (this.ch) {
    this.error("Syntax Error");
  }

  return this.convert_to_accessors(result);
};

/**
 * Determine if a character is a valid item in an identifier.
 * Note that we do not check whether the first item is a number, nor do we
 * support unicode identifiers here.
 *
 * See: http://docstore.mik.ua/orelly/webprog/jscript/ch02_07.htm
 * @param  {String}  ch  The character
 * @return {Boolean}     True if [A-Za-z0-9_]
 */
function is_identifier_char(ch) {
  return (ch >= 'A' && ch <= 'Z') ||
         (ch >= 'a' && ch <= 'z') ||
         (ch >= '0' && ch <= 9) ||
          ch === '_' || ch === '$';
}
<commit_msg>Clone constant accessors (for accessing plain objects defined in the data-bind string)<commit_after>/**
 * Originally based on (public domain):
 * https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
 */

import {
  options, objectForEach, clonePlainObjectDeep
} from 'tko.utils';

import Expression from './expression';
import Identifier from './identifier';
import Arguments from './arguments';
import Node from './node';

var escapee = {
    "'": "'",
    '"':  '"',
    "`":  "`",
    '\\': '\\',
    '/':  '/',
    '$':  '$',
    b:    '\b',
    f:    '\f',
    n:    '\n',
    r:    '\r',
    t:    '\t'
  },
  operators = Node.operators;

/**
 * Construct a new Parser instance with new Parser(node, context)
 * @param {Node} node    The DOM element from which we parsed the
 *                         content.
 * @param {object} context The Knockout context.
 * @param {object} globals An object containing any desired globals.
 */
export default function Parser(node, context, globals) {
  this.node = node;
  this.context = context;
  this.globals = globals || {};
}

// Exposed for testing.
Parser.Expression = Expression;
Parser.Identifier = Identifier;
Parser.Arguments = Arguments;
Parser.Node = Node;

Parser.prototype.white = function () {
  var ch = this.ch;
  while (ch && ch <= ' ') {
    ch = this.next();
  }
  return ch;
};

Parser.prototype.next = function (c) {
  if (c && c !== this.ch) {
    this.error("Expected '" + c + "' but got '" + this.ch + "'");
  }
  this.ch = this.text.charAt(this.at);
  this.at += 1;
  return this.ch;
};

Parser.prototype.error = function (m) {
  throw {
    name:    'SyntaxError',
    message: m,
    at:      this.at,
    text:    this.text
  };
};

Parser.prototype.name = function () {
  // A name of a binding
  var name = '',
    enclosed_by;
  this.white();

  var ch = this.ch;

  if (ch === "'" || ch === '"') {
    enclosed_by = ch;
    ch = this.next();
  }

  while (ch) {
    if (enclosed_by && ch === enclosed_by) {
      this.white();
      ch = this.next();
      if (ch !== ':' && ch !== ',') {
        this.error(
          "Object name: " + name + " missing closing " + enclosed_by
        );
      }
      return name;
    } else if (ch === ':' || ch <= ' ' || ch === ',' ) {
      return name;
    }
    name += ch;
    ch = this.next();
  }

  return name;
};

Parser.prototype.number = function () {
  var number,
    string = '',
    ch = this.ch;

  if (ch === '-') {
    string = '-';
    ch = this.next('-');
  }
  while (ch >= '0' && ch <= '9') {
    string += ch;
    ch = this.next();
  }
  if (ch === '.') {
    string += '.';
    ch = this.next();
    while (ch && ch >= '0' && ch <= '9') {
      string += ch;
      ch = this.next();
    }
  }
  if (ch === 'e' || ch === 'E') {
    string += ch;
    ch = this.next();
    if (ch === '-' || ch === '+') {
      string += ch;
      ch = this.next();
    }
    while (ch >= '0' && ch <= '9') {
      string += ch;
      ch = this.next();
    }
  }
  number = +string;
  if (!isFinite(number)) {
    options.onError(new Error("Bad number: " + number + " in " + string));
  } else {
    return number;
  }
};

/**
 * Add a property to 'object' that equals the given value.
 * @param  {Object} object The object to add the value to.
 * @param  {String} key    object[key] is set to the given value.
 * @param  {mixed}  value  The value, may be a primitive or a function. If a
 *                         function it is unwrapped as a property.
 */
Parser.prototype.object_add_value = function (object, key, value) {
  if (value && value[Node.isExpressionOrIdentifierSymbol]) {
    Object.defineProperty(object, key, {
      get: function () {
        return value.get_value();
      },
      enumerable: true
    });
  } else {
    // primitives
    object[key] = value;
  }
};

Parser.prototype.object = function () {
  var key,
    object = {},
    ch = this.ch;

  if (ch === '{') {
    this.next('{');
    ch = this.white();
    if (ch === '}') {
      ch = this.next('}');
      return object;
    }
    while (ch) {
      if (ch === '"' || ch === "'" || ch === "`") {
        key = this.string();
      } else {
        key = this.name();
      }
      this.white();
      ch = this.next(':');
      if (Object.hasOwnProperty.call(object, key)) {
        this.error('Duplicate key "' + key + '"');
      }

      this.object_add_value(object, key, this.expression());

      ch = this.white();
      if (ch === '}') {
        ch = this.next('}');
        return object;
      }

      this.next(',');
      ch = this.white();
    }
  }
  this.error("Bad object");
};

/**
 * Read up to delim and return the string
 * @param  {string} delim The delimiter, either ' or "
 * @return {string}       The string read.
 */
Parser.prototype.read_string = function (delim) {
  var string = '',
    nodes = [''],
    plus_op = operators['+'],
    hex,
    i,
    uffff,
    interpolate = delim === "`",
    ch = this.next();

  while (ch) {
    if (ch === delim) {
      ch = this.next();
      if (interpolate) { nodes.push(plus_op); }
      nodes.push(string);
      return nodes;
    }
    if (ch === '\\') {
      ch = this.next();
      if (ch === 'u') {
        uffff = 0;
        for (i = 0; i < 4; i += 1) {
          hex = parseInt(ch = this.next(), 16);
          if (!isFinite(hex)) {
            break;
          }
          uffff = uffff * 16 + hex;
        }
        string += String.fromCharCode(uffff);
      } else if (typeof escapee[ch] === 'string') {
        string += escapee[ch];
      } else {
        break;
      }
    } else if (interpolate && ch === "$") {
      ch = this.next();
      if (ch === '{') {
        this.next('{');
        nodes.push(plus_op);
        nodes.push(string);
        nodes.push(plus_op);
        nodes.push(this.expression());
        string = '';
        // this.next('}');
      } else {
        string += "$" + ch;
      }
    } else {
      string += ch;
    }
    ch = this.next();
  }

  this.error("Bad string");
};

Parser.prototype.string = function () {
  var ch = this.ch;
  if (ch === '"') {
    return this.read_string('"').join('');
  } else if (ch === "'") {
    return this.read_string("'").join('');
  } else if (ch === "`") {
    return Node.create_root(this.read_string("`"));
  }

  this.error("Bad string");
};

Parser.prototype.array = function () {
  var array = [],
    ch = this.ch;

  if (ch === '[') {
    ch = this.next('[');
    this.white();
    if (ch === ']') {
      ch = this.next(']');
      return array;
    }
    while (ch) {
      array.push(this.expression());
      ch = this.white();
      if (ch === ']') {
        ch = this.next(']');
        return array;
      }
      this.next(',');
      ch = this.white();
    }
  }
  this.error("Bad array");
};

Parser.prototype.value = function () {
  var ch;
  this.white();
  ch = this.ch;
  switch (ch) {
  case '{': return this.object();
  case '[': return this.array();
  case '"': case "'": case "`": return this.string();
  case '-': return this.number();
  default:
    return ch >= '0' && ch <= '9' ? this.number() : this.identifier();
  }
};

/**
 * Get the function for the given operator.
 * A `.precedence` value is added to the function, with increasing
 * precedence having a higher number.
 * @return {function} The function that performs the infix operation
 */
Parser.prototype.operator = function () {
  var op = '',
    op_fn,
    ch = this.white();

  while (ch) {
    if (is_identifier_char(ch) || ch <= ' ' || ch === '' ||
        ch === '"' || ch === "'" || ch === '{' || ch === '[' ||
        ch === '(' || ch === "`") {
      break;
    }
    op += ch;
    ch = this.next();
  }

  if (op !== '') {
    op_fn = operators[op];

    if (!op_fn) {
      this.error("Bad operator: '" + op + "'.");
    }
  }

  return op_fn;
};

/**
 * Parse an expression – builds an operator tree, in something like
 * Shunting-Yard.
 *   See: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
 *
 * @return {function}   A function that computes the value of the expression
 *                      when called or a primitive.
 */
Parser.prototype.expression = function () {
  var op,
    nodes = [],
    node_value,
    ch = this.white();

  while (ch) {
    // unary prefix operators
    op = this.operator();
    if (op) {
      nodes.push(undefined);  // padding.
      nodes.push(op);
    }

    if (ch === '(') {
      this.next();
      nodes.push(this.expression());
      this.next(')');
    } else {
      node_value = this.value();
      nodes.push(node_value);
    }
    ch = this.white();
    if (ch === ':' || ch === '}' || ch === ',' || ch === ']' ||
        ch === ')' || ch === '' || ch === '`') {
      break;
    }
    // infix operators
    op = this.operator();
    if (op) {
      nodes.push(op);
    }
    ch = this.white();
  }

  if (nodes.length === 0) {
    return undefined;
  }

  if (nodes.length === 1) {
    return nodes[0];
  }

  return new Expression(nodes);
};

/**
 * Parse the arguments to a function, returning an Array.
 *
 */
Parser.prototype.func_arguments = function () {
  var args = [],
    ch = this.next('(');

  while(ch) {
    ch = this.white();
    if (ch === ')') {
      this.next(')');
      return new Arguments(this, args);
    } else {
      args.push(this.expression());
      ch = this.white();
    }
    if (ch !== ')') { this.next(','); }
  }

  this.error("Bad arguments to function");
};

/**
 * A dereference applies to an identifer, being either a function
 * call "()" or a membership lookup with square brackets "[member]".
 * @return {fn or undefined}  Dereference function to be applied to the
 *                            Identifier
 */
Parser.prototype.dereference = function () {
  var member,
    ch = this.white();

  while (ch) {
    if (ch === '(') {
      // a(...) function call
      return this.func_arguments();
    } else if (ch === '[') {
      // a[x] membership
      this.next('[');
      member = this.expression();
      this.white();
      this.next(']');

      return member;
    } else if (ch === '.') {
      // a.x membership
      member = '';
      this.next('.');
      ch = this.white();
      while (ch) {
        if (!is_identifier_char(ch)) {
          break;
        }
        member += ch;
        ch = this.next();
      }
      return member;
    } else {
      break;
    }
  }
  return;
};

Parser.prototype.identifier = function () {
  var token = '', ch, deref, dereferences = [];
  ch = this.white();
  while (ch) {
    if (!is_identifier_char(ch)) {
      break;
    }
    token += ch;
    ch = this.next();
  }
  switch (token) {
  case 'true': return true;
  case 'false': return false;
  case 'null': return null;
  case 'undefined': return void 0;
  default:
  }
  while (ch) {
    deref = this.dereference();
    if (deref !== undefined) {
      dereferences.push(deref);
    } else {
      break;
    }
  }
  return new Identifier(this, token, dereferences);
};

Parser.prototype.read_bindings = function () {
  var key,
    bindings = {},
    sep,
    ch = this.ch;

  while (ch) {
    key = this.name();
    sep = this.white();
    if (!sep || sep === ',') {
      if (sep) {
        ch = this.next(',');
      } else {
        ch = '';
      }
      // A "bare" binding e.g. "text"; substitute value of 'null'
      // so it becomes "text: null".
      bindings[key] = null;
    } else {
      ch = this.next(':');
      bindings[key] = this.expression();
      this.white();
      if (this.ch) {
        ch = this.next(',');
      } else {
        ch = '';
      }
    }
  }
  return bindings;
};

/**
* Convert result[name] from a value to a function (i.e. `valueAccessor()`)
* @param  {object} result [Map of top-level names to values]
* @return {object}        [Map of top-level names to functions]
*
* Accessors may be one of (below) constAccessor, identifierAccessor,
* expressionAccessor, or nodeAccessor.
*/
Parser.prototype.convert_to_accessors = function (result) {

  objectForEach(result, function (name, value) {
    if (value instanceof Identifier) {
      // Return a function that, with no arguments returns
      // the value of the identifier, otherwise sets the
      // value of the identifier to the first given argument.
      Object.defineProperty(result, name, {
        value: function (optionalValue, options) {
          if (arguments.length === 0) {
            return value.get_value();
          }
          if (options && options.onlyIfChanged && optionalValue === value.get_value()) {
            return;
          }
          return value.set_value(optionalValue);
        }
      });
    } else if (value instanceof Expression) {
      result[name] = function expressionAccessor() {
        return value.get_value();
      };
    } else if (value instanceof Node) {
      result[name] = function nodeAccessor() {
        return value.get_node_value();
      };
    } else if (typeof(value) != 'function') {
      result[name] = function constAccessor() {
        return clonePlainObjectDeep(value);
      };
    }
  });

  return result;
};

/**
 * Get the bindings as name: accessor()
 * @param  {string} source The binding string to parse.
 * @return {object}        Map of name to accessor function.
 */
Parser.prototype.parse = function (source) {
  this.text = (source || '').trim();
  this.at = 0;
  this.ch = ' ';

  if (!this.text) {
    return null;
  }

  try {
    var result = this.read_bindings();
  } catch (e) {
    options.onError(new Error(
      "Unable to parse bindings." +
      "\nBindings value: " + this.text +
      "\nMessage: <" + e.name + "> " + e.message
    ));
  }

  this.white();
  if (this.ch) {
    this.error("Syntax Error");
  }

  return this.convert_to_accessors(result);
};

/**
 * Determine if a character is a valid item in an identifier.
 * Note that we do not check whether the first item is a number, nor do we
 * support unicode identifiers here.
 *
 * See: http://docstore.mik.ua/orelly/webprog/jscript/ch02_07.htm
 * @param  {String}  ch  The character
 * @return {Boolean}     True if [A-Za-z0-9_]
 */
function is_identifier_char(ch) {
  return (ch >= 'A' && ch <= 'Z') ||
         (ch >= 'a' && ch <= 'z') ||
         (ch >= '0' && ch <= 9) ||
          ch === '_' || ch === '$';
}
<|endoftext|>


<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2018 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

require('./polyfills');

var CONST = require('./const');
var Extend = require('./utils/object/Extend');

/**
* @namespace Phaser
*/

var Phaser = {

    Actions: require('./actions'),
    Animation: require('./animations'),
    Cache: require('./cache'),
    Cameras: require('./cameras'),
    Class: require('./utils/Class'),
    Create: require('./create'),
    Curves: require('./curves'),
    Data: require('./data'),
    Display: require('./display'),
    DOM: require('./dom'),
    EventEmitter: require('./events/EventEmitter'),
    Game: require('./boot/Game'),
    GameObjects: require('./gameobjects'),
    Geom: require('./geom'),
    Input: require('./input'),
    Loader: require('./loader'),
    Math: require('./math'),
    Physics: require('./physics'),
    Renderer: require('./renderer'),
    Scene: require('./scene/Scene'),
    Scenes: require('./scene'),
    Sound: require('./sound'),
    Structs: require('./structs'),
    Textures: require('./textures'),
    Tilemaps: require('./tilemaps'),
    Time: require('./time'),
    Tweens: require('./tweens'),
    Utils: require('./utils')

};

//   Merge in the consts

Phaser = Extend(false, Phaser, CONST);

//  Export it

module.exports = Phaser;

global.Phaser = Phaser;

/*
 * "Documentation is like pizza: when it is good, it is very, very good;
 * and when it is bad, it is better than nothing."
 *  -- Dick Brandon
 */
<commit_msg>Proper indent<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2018 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

require('./polyfills');

var CONST = require('./const');
var Extend = require('./utils/object/Extend');

/**
 * @namespace Phaser
 */

var Phaser = {

    Actions: require('./actions'),
    Animation: require('./animations'),
    Cache: require('./cache'),
    Cameras: require('./cameras'),
    Class: require('./utils/Class'),
    Create: require('./create'),
    Curves: require('./curves'),
    Data: require('./data'),
    Display: require('./display'),
    DOM: require('./dom'),
    EventEmitter: require('./events/EventEmitter'),
    Game: require('./boot/Game'),
    GameObjects: require('./gameobjects'),
    Geom: require('./geom'),
    Input: require('./input'),
    Loader: require('./loader'),
    Math: require('./math'),
    Physics: require('./physics'),
    Renderer: require('./renderer'),
    Scene: require('./scene/Scene'),
    Scenes: require('./scene'),
    Sound: require('./sound'),
    Structs: require('./structs'),
    Textures: require('./textures'),
    Tilemaps: require('./tilemaps'),
    Time: require('./time'),
    Tweens: require('./tweens'),
    Utils: require('./utils')

};

//   Merge in the consts

Phaser = Extend(false, Phaser, CONST);

//  Export it

module.exports = Phaser;

global.Phaser = Phaser;

/*
 * "Documentation is like pizza: when it is good, it is very, very good;
 * and when it is bad, it is better than nothing."
 *  -- Dick Brandon
 */
<|endoftext|>


<commit_before>/**
 *  Custom HTML fallback generator for chessmasterhong.github.io
 *  Author: Kevin Chan
 */

'use strict';

var fs = require('fs'),
    path = require('path');

var charset = 'utf8';

fs.readFile(path.join(__dirname, 'src', 'index.html'), charset, function(err, dataMain) {
    if(!err) {
        var index = dataMain.replace(/(ng-cloak|data-ng-cloak)\s*/gi, '')
                            .replace(/(\n.*?)*\n\s*/g, '')
                            .replace(/(\n.*?)*/gi, '<link rel=stylesheet href="../common/styles/site.min.css">')
                            .replace(/(\n.*?)*\n\s*/gi, '')

        var pages = ['about', 'contact', 'credits'];

        pages.forEach(function(page) {
            fs.readFile(path.join(__dirname, 'src', page, page + '.partial.html'), charset, function(err, dataView) {
                var dest = path.join(__dirname, page, 'index.html');
                fs.writeFile(
                    dest,
                    index.replace(/\sdata-ui-view(>)(?=<\/section>)/gi, '$1' + dataView)
                         .replace(new RegExp('data-ng-class="{\\s*active:\\s*isActive\\(\'' + page + '\'\\)\\s+}"', 'g'), 'class="active"'),
                    charset);
            });
        });
    } else {
        console.log(err);
    }
});

fs.readFile(path.join(__dirname, 'src', 'index.html'), charset, function(err, dataMain) {
    if(!err) {
        var index = dataMain.replace(/(ng-cloak|data-ng-cloak)\s*/gi, '')
                            .replace(/(\n.*?)*\n\s*/gi, '')
                            .replace(/(\n.*?)*/gi, '<link rel=stylesheet href="../common/styles/site.min.css">')
                            .replace(/(\n.*?)*\n\s*/gi, '')
                            .replace(/data-ng-class="{\s*active:\s*isActive\('projects'\)\s+}"/g, 'class="active"');

        fs.readFile(path.join(__dirname, 'src', 'projects', 'projectList.partial.html'), charset, function(err, dataView) {
            var showcaseTemplate = dataView.match(/<div\s+data-ng-repeat="project\s+in\s+projects(.*\n)*(?=<\/div>(\n.*)*
Other\sworks)/gi)[0],
                otherworksTemplate = dataView.match(/<span\s+data-ng-repeat="project\s+in\s+projects(.*\n)*(?=<\/div>)/gi)[0];

            var view = dataView.replace(/(<div\s+data-ng-repeat="project\s+in\s+projects)(.*\n)*(?=<\/div>(\n.*)*
Other\sworks)/gi, '')
                               .replace(/<span\s+data-ng-repeat="project\s+in\s+projects(.*\n)*(?=<\/div>)/gi, '');

            fs.readFile(path.join(__dirname, 'src', 'projects', 'projects.json'), charset, function(err, dataJSON) {
                var json = JSON.parse(dataJSON.replace(/\)]}',\n/, '')).reverse();

                var row = 0;
                json.forEach(function(project, projIndex) {
                    fs.readFile(path.join(__dirname, 'src', 'projects', projIndex.toString(), projIndex.toString() + '.partial.html'), charset, function(err, dataView) {
                        fs.writeFile(
                            path.join(__dirname, 'projects', projIndex.toString(), 'index.html'),
                            index.replace(/\sdata-ui-view(>)(?=<\/section>)/gi, '$1
Projects » ' + project.title + '
' + dataView)
                                 .replace(/(?=\.\.\/common)/gi, '../'),
                            charset
                        );
                    });

                    if(project.showcase === true) {
                        view = view.replace(/(
Showcase<\/h2>\n*
)/gi, '$1' +
                            showcaseTemplate.replace(/data-ng-class-even="'views-row\s+views-row-even'"\s+data-ng-class-odd="'views-row\s+views-row-odd'"/gi, 'class="views-row views-row-' + (row++ % 2 ? 'even' : 'odd') + '"')
                                            .replace(/\{\{\s*project\.projectIndex\s*}}/g, projIndex)
                                            .replace(/\{\{\s*project\.title\s*}}/g, project.title)
                                            .replace(/\{\{\s*project\.thumbnail\s*}}/g, project.thumbnail)
                                            .replace(/(href=")\/#(?=\/(.*?)")/gi, '$1')
                                            .replace(/\{\{\s*project\.urlDemo\s*}}/g, project.urlDemo)
                                            .replace(/\{\{\s*project\.urlSource\s*}}/g, project.urlSource)
                                            .replace(/\s*data-ng-bind="project\.title"(>)/g, '$1' + project.title)
                                            .replace(/\s*data-ng-bind="project\.excerpt"(>)/g, '$1' + project.excerpt)
                                            .replace(/data-ng-(?=src)/g, '')
                                            .replace(/<\/span>((\n.*?)*)<\/a>/gi, project.urlDemo ? '$1' : '')
                                            .replace(/<\/span>((\n.*?)*)<\/a>/gi, project.urlSource ? '$1' : '')
                            );
                    } else {
                        view = view.replace(/(
Other works<\/h2>\n*
)/gi, '$1' +
                            otherworksTemplate.replace(/data-ng-class="'views-row'"/gi, 'class="views-row"')
                                              .replace(/\{\{\s*project\.projectIndex\s*}}/g, projIndex)
                                              .replace(/\{\{\s*project\.title\s*}}/g, project.title)
                                              .replace(/\{\{\s*project\.thumbnail\s*}}/g, project.thumbnail)
                                              .replace(/data-ng-(?=src)/g, '')
                            );
                    }
                });

                var dest = path.join(__dirname, 'projects', 'index.html');
                fs.writeFile(dest, index.replace(/\sdata-ui-view(>)(?=<\/section>)/gi, '$1' + view), charset);
            });
        });
    } else {
        console.log(err);
    }
});

fs.readFile(path.join(__dirname, 'src', 'index.html'), charset, function(err, dataMain) {
    if(!err) {
        var index = dataMain.replace(/(ng-cloak|data-ng-cloak)\s*/gi, '')
                            .replace(/(\n.*?)*\n\s*/gi, '')
                            .replace(/(\n.*?)*/gi, '<link rel=stylesheet href="../common/styles/site.min.css">')
                            .replace(/(\n.*?)*\n\s*/gi, '')
                            .replace(/data-ng-class="{\s*active:\s*isActive\('resources'\)\s+}"/g, 'class="active"');

        fs.readFile(path.join(__dirname, 'src', 'resources', 'resourceList.partial.html'), charset, function(err, dataView) {
            var dest = path.join(__dirname, 'resources', 'index.html');
            fs.writeFile(dest, index.replace(/\sdata-ui-view(>)(?=<\/section>)/gi, '$1' + dataView), charset);
        });
    } else {
        console.log(err);
    }
});
<commit_msg>Added regexp matching for Angular attribute removal in HTML fallback.<commit_after>/**
 *  Custom HTML fallback generator for chessmasterhong.github.io
 *  Author: Kevin Chan
 */

'use strict';

var fs = require('fs'),
    path = require('path');

var charset = 'utf8';

fs.readFile(path.join(__dirname, 'src', 'index.html'), charset, function(err, dataMain) {
    if(!err) {
        var index = dataMain.replace(/(ng-cloak|data-ng-cloak)\s*/gi, '')
                            .replace(/(\n.*?)*\n\s*/g, '')
                            .replace(/(\n.*?)*/gi, '<link rel=stylesheet href="../common/styles/site.min.css">')
                            .replace(/(\n.*?)*\n\s*/gi, '')

        var pages = ['about', 'contact', 'credits'];

        pages.forEach(function(page) {
            fs.readFile(path.join(__dirname, 'src', page, page + '.partial.html'), charset, function(err, dataView) {
                var dest = path.join(__dirname, page, 'index.html');
                fs.writeFile(
                    dest,
                    index.replace(/\sdata-ui-view(>)(?=<\/section>)/gi, '$1' + dataView)
                         .replace(new RegExp('data-ng-class="{\\s*active:\\s*isActive\\(\'' + page + '\'\\)\\s+}"', 'g'), 'class="active"')
                         .replace(/\s+(data-ng|ng)-.*?".*?"/gi, ''),
                    charset);
            });
        });
    } else {
        console.log(err);
    }
});

fs.readFile(path.join(__dirname, 'src', 'index.html'), charset, function(err, dataMain) {
    if(!err) {
        var index = dataMain.replace(/(ng-cloak|data-ng-cloak)\s*/gi, '')
                            .replace(/(\n.*?)*\n\s*/gi, '')
                            .replace(/(\n.*?)*/gi, '<link rel=stylesheet href="../common/styles/site.min.css">')
                            .replace(/(\n.*?)*\n\s*/gi, '')
                            .replace(/data-ng-class="{\s*active:\s*isActive\('projects'\)\s+}"/g, 'class="active"');

        fs.readFile(path.join(__dirname, 'src', 'projects', 'projectList.partial.html'), charset, function(err, dataView) {
            var showcaseTemplate = dataView.match(/<div\s+data-ng-repeat="project\s+in\s+projects(.*\n)*(?=<\/div>(\n.*)*
Other\sworks)/gi)[0],
                otherworksTemplate = dataView.match(/<span\s+data-ng-repeat="project\s+in\s+projects(.*\n)*(?=<\/div>)/gi)[0];

            var view = dataView.replace(/(<div\s+data-ng-repeat="project\s+in\s+projects)(.*\n)*(?=<\/div>(\n.*)*
Other\sworks)/gi, '')
                               .replace(/<span\s+data-ng-repeat="project\s+in\s+projects(.*\n)*(?=<\/div>)/gi, '');

            fs.readFile(path.join(__dirname, 'src', 'projects', 'projects.json'), charset, function(err, dataJSON) {
                var json = JSON.parse(dataJSON.replace(/\)]}',\n/, '')).reverse();

                var row = 0;
                json.forEach(function(project, projIndex) {
                    projIndex = projIndex.toString();

                    fs.readFile(path.join(__dirname, 'src', 'projects', projIndex, projIndex + '.partial.html'), charset, function(err, dataView) {
                        fs.writeFile(
                            path.join(__dirname, 'projects', projIndex, 'index.html'),
                            index.replace(/\sdata-ui-view(>)(?=<\/section>)/gi, '$1
Projects » ' + project.title + '
' + dataView)
                                 .replace(/(?=\.\.\/common)/gi, '../')
                                 .replace(/\s+(data-ng|ng)-.*?".*?"/gi, ''),
                            charset
                        );
                    });

                    if(project.showcase === true) {
                        view = view.replace(/(
Showcase<\/h2>\n*
)/gi, '$1' +
                            showcaseTemplate.replace(/data-ng-class-even="'views-row\s+views-row-even'"\s+data-ng-class-odd="'views-row\s+views-row-odd'"/gi, 'class="views-row views-row-' + (row++ % 2 ? 'even' : 'odd') + '"')
                                            .replace(/\{\{\s*project\.projectIndex\s*}}/g, projIndex)
                                            .replace(/\{\{\s*project\.title\s*}}/g, project.title)
                                            .replace(/\{\{\s*project\.thumbnail\s*}}/g, project.thumbnail)
                                            .replace(/(href=")\/#(?=\/(.*?)")/gi, '$1')
                                            .replace(/\{\{\s*project\.urlDemo\s*}}/g, project.urlDemo)
                                            .replace(/\{\{\s*project\.urlSource\s*}}/g, project.urlSource)
                                            .replace(/\s*data-ng-bind="project\.title"(>)/g, '$1' + project.title)
                                            .replace(/\s*data-ng-bind="project\.excerpt"(>)/g, '$1' + project.excerpt)
                                            .replace(/data-ng-(?=src)/g, '')
                                            .replace(/<\/span>((\n.*?)*)<\/a>/gi, project.urlDemo ? '$1' : '')
                                            .replace(/<\/span>((\n.*?)*)<\/a>/gi, project.urlSource ? '$1' : '')
                            );
                    } else {
                        view = view.replace(/(
Other works<\/h2>\n*
)/gi, '$1' +
                            otherworksTemplate.replace(/data-ng-class="'views-row'"/gi, 'class="views-row"')
                                              .replace(/\{\{\s*project\.projectIndex\s*}}/g, projIndex)
                                              .replace(/\{\{\s*project\.title\s*}}/g, project.title)
                                              .replace(/\{\{\s*project\.thumbnail\s*}}/g, project.thumbnail)
                                              .replace(/data-ng-(?=src)/g, '')
                            );
                    }
                });

                var dest = path.join(__dirname, 'projects', 'index.html');
                fs.writeFile(
                    dest,
                    index.replace(/\sdata-ui-view(>)(?=<\/section>)/gi, '$1' + view)
                         .replace(/\s+(data-ng|ng)-.*?".*?"/gi, ''),
                    charset
                );
            });
        });
    } else {
        console.log(err);
    }
});

fs.readFile(path.join(__dirname, 'src', 'index.html'), charset, function(err, dataMain) {
    if(!err) {
        var index = dataMain.replace(/(ng-cloak|data-ng-cloak)\s*/gi, '')
                            .replace(/(\n.*?)*\n\s*/gi, '')
                            .replace(/(\n.*?)*/gi, '<link rel=stylesheet href="../common/styles/site.min.css">')
                            .replace(/(\n.*?)*\n\s*/gi, '')
                            .replace(/data-ng-class="{\s*active:\s*isActive\('resources'\)\s+}"/g, 'class="active"');

        fs.readFile(path.join(__dirname, 'src', 'resources', 'resourceList.partial.html'), charset, function(err, dataView) {
            var dest = path.join(__dirname, 'resources', 'index.html');
            fs.writeFile(
                dest,
                index.replace(/\sdata-ui-view(>)(?=<\/section>)/gi, '$1' + dataView)
                     .replace(/\s+(data-ng|ng)-.*?".*?"/gi, ''),
                charset
            );
        });
    } else {
        console.log(err);
    }
});
<|endoftext|>


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

const initTestsPath = [
  'test/_init_tests.js',
];

const fixturesExamplesPaths = [
  'test/fixtures/*.html',
  {
    pattern: 'test/fixtures/served/*.html',
    included: false,
    nocache: false,
    watched: true,
  },
  {
    pattern: 'examples/**/*',
    included: false,
    nocache: false,
    watched: true,
  },
];

const builtRuntimePaths = [
  {
    pattern: 'dist/**/*.js',
    included: false,
    nocache: false,
    watched: true,
  },
  {
    pattern: 'dist.3p/**/*',
    included: false,
    nocache: false,
    watched: true,
  },
  {
    pattern: 'dist.tools/**/*.js',
    included: false,
    nocache: false,
    watched: true,
  },
];

const commonUnitTestPaths = initTestsPath.concat(fixturesExamplesPaths);

const commonIntegrationTestPaths =
    initTestsPath.concat(fixturesExamplesPaths, builtRuntimePaths);

const testPaths = commonIntegrationTestPaths.concat([
  'test/**/*.js',
  'ads/**/test/test-*.js',
  'extensions/**/test/**/*.js',
]);

const a4aTestPaths = initTestsPath.concat([
  'extensions/amp-a4a/**/test/**/*.js',
  'extensions/amp-ad-network-*/**/test/**/*.js',
  'ads/google/a4a/test/*.js',
]);

const chaiAsPromised = [
  'test/chai-as-promised/chai-as-promised.js',
];

const unitTestPaths = [
  'test/unit/**/*.js',
  'ads/**/test/test-*.js',
  'extensions/**/test/*.js',
];

const unitTestOnSaucePaths = [
  'test/unit/**/*.js',
  'ads/**/test/test-*.js',
];

const integrationTestPaths = [
  'test/integration/**/*.js',
  'test/unit/test-error.js',
  'extensions/**/test/integration/**/*.js',
];

const e2eTestPaths = [
  'test/e2e/*.js',
  'extensions/**/test-e2e/*.js',
];

const devDashboardTestPaths = [
  'build-system/app-index/test/**/*.js',
];

const lintGlobs = [
  '**/*.js',
  // To ignore a file / directory, add it to .eslintignore.
];

/**
 * Array of 3p bootstrap urls
 * Defined by the following object schema:
 * basename: the name of the 3p frame without extension
 * max: the path of the readable html
 * min: the name of the minimized html
 */
const thirdPartyFrames = [
  {
    basename: 'frame',
    max: '3p/frame.max.html',
    min: 'frame.html',
  },
  {
    basename: 'nameframe',
    max: '3p/nameframe.max.html',
    min: 'nameframe.html',
  },
  {
    basename: 'recaptcha',
    max: '3p/recaptcha.max.html',
    min: 'recaptcha.html',
  },
];

/** @const  */
module.exports = {
  testPaths,
  a4aTestPaths,
  chaiAsPromised,
  commonUnitTestPaths,
  commonIntegrationTestPaths,
  unitTestPaths,
  unitTestOnSaucePaths,
  integrationTestPaths,
  e2eTestPaths,
  lintGlobs,
  devDashboardTestPaths,
  thirdPartyFrames,
  jsonGlobs: [
    '**/*.json',
    '!{node_modules,build,dist,dist.3p,dist.tools,' +
        'third_party,build-system}/**/*.*',
  ],
  presubmitGlobs: [
    '**/*.{css,js,go}',
    // This does match dist.3p/current, so we run presubmit checks on the
    // built 3p binary. This is done, so we make sure our special 3p checks
    // run against the entire transitive closure of deps.
    '!{node_modules,build,dist,dist.tools,' +
        'dist.3p/[0-9]*,dist.3p/current,dist.3p/current-min}/**/*.*',
    '!dist.3p/current/**/ampcontext-lib.js',
    '!dist.3p/current/**/iframe-transport-client-lib.js',
    '!out/**/*.*',
    '!validator/validator.pb.go',
    '!validator/dist/**/*.*',
    '!validator/node_modules/**/*.*',
    '!validator/nodejs/node_modules/**/*.*',
    '!validator/webui/dist/**/*.*',
    '!validator/webui/node_modules/**/*.*',
    '!build-system/tasks/presubmit-checks.js',
    '!build-system/tasks/visual-diff/node_modules/**/*.*',
    '!build-system/tasks/visual-diff/snippets/*.js',
    '!build/polyfills.js',
    '!build/polyfills/*.js',
    '!third_party/**/*.*',
    '!validator/chromeextension/*.*',
    // Files in this testdata dir are machine-generated and are not part
    // of the AMP runtime, so shouldn't be checked.
    '!extensions/amp-a4a/*/test/testdata/*.js',
    '!examples/**/*',
    '!examples/visual-tests/**/*',
    '!test/coverage/**/*.*',
    '!firebase/**/*.*',
  ],
  changelogIgnoreFileTypes: /\.md|\.json|\.yaml|LICENSE|CONTRIBUTORS$/,
};
<commit_msg>Exclude e2e tests when running yarn test (#20416)<commit_after>/**
 * Copyright 2015 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

const initTestsPath = [
  'test/_init_tests.js',
];

const fixturesExamplesPaths = [
  'test/fixtures/*.html',
  {
    pattern: 'test/fixtures/served/*.html',
    included: false,
    nocache: false,
    watched: true,
  },
  {
    pattern: 'examples/**/*',
    included: false,
    nocache: false,
    watched: true,
  },
];

const builtRuntimePaths = [
  {
    pattern: 'dist/**/*.js',
    included: false,
    nocache: false,
    watched: true,
  },
  {
    pattern: 'dist.3p/**/*',
    included: false,
    nocache: false,
    watched: true,
  },
  {
    pattern: 'dist.tools/**/*.js',
    included: false,
    nocache: false,
    watched: true,
  },
];

const commonUnitTestPaths = initTestsPath.concat(fixturesExamplesPaths);

const commonIntegrationTestPaths =
    initTestsPath.concat(fixturesExamplesPaths, builtRuntimePaths);

const testPaths = commonIntegrationTestPaths.concat([
  'test/*/!(e2e)/**/*.js',
  'ads/**/test/test-*.js',
  'extensions/**/test/**/*.js',
]);

const a4aTestPaths = initTestsPath.concat([
  'extensions/amp-a4a/**/test/**/*.js',
  'extensions/amp-ad-network-*/**/test/**/*.js',
  'ads/google/a4a/test/*.js',
]);

const chaiAsPromised = [
  'test/chai-as-promised/chai-as-promised.js',
];

const unitTestPaths = [
  'test/unit/**/*.js',
  'ads/**/test/test-*.js',
  'extensions/**/test/*.js',
];

const unitTestOnSaucePaths = [
  'test/unit/**/*.js',
  'ads/**/test/test-*.js',
];

const integrationTestPaths = [
  'test/integration/**/*.js',
  'test/unit/test-error.js',
  'extensions/**/test/integration/**/*.js',
];

const e2eTestPaths = [
  'test/e2e/*.js',
  'extensions/**/test-e2e/*.js',
];

const devDashboardTestPaths = [
  'build-system/app-index/test/**/*.js',
];

const lintGlobs = [
  '**/*.js',
  // To ignore a file / directory, add it to .eslintignore.
];

/**
 * Array of 3p bootstrap urls
 * Defined by the following object schema:
 * basename: the name of the 3p frame without extension
 * max: the path of the readable html
 * min: the name of the minimized html
 */
const thirdPartyFrames = [
  {
    basename: 'frame',
    max: '3p/frame.max.html',
    min: 'frame.html',
  },
  {
    basename: 'nameframe',
    max: '3p/nameframe.max.html',
    min: 'nameframe.html',
  },
  {
    basename: 'recaptcha',
    max: '3p/recaptcha.max.html',
    min: 'recaptcha.html',
  },
];

/** @const  */
module.exports = {
  testPaths,
  a4aTestPaths,
  chaiAsPromised,
  commonUnitTestPaths,
  commonIntegrationTestPaths,
  unitTestPaths,
  unitTestOnSaucePaths,
  integrationTestPaths,
  e2eTestPaths,
  lintGlobs,
  devDashboardTestPaths,
  thirdPartyFrames,
  jsonGlobs: [
    '**/*.json',
    '!{node_modules,build,dist,dist.3p,dist.tools,' +
        'third_party,build-system}/**/*.*',
  ],
  presubmitGlobs: [
    '**/*.{css,js,go}',
    // This does match dist.3p/current, so we run presubmit checks on the
    // built 3p binary. This is done, so we make sure our special 3p checks
    // run against the entire transitive closure of deps.
    '!{node_modules,build,dist,dist.tools,' +
        'dist.3p/[0-9]*,dist.3p/current,dist.3p/current-min}/**/*.*',
    '!dist.3p/current/**/ampcontext-lib.js',
    '!dist.3p/current/**/iframe-transport-client-lib.js',
    '!out/**/*.*',
    '!validator/validator.pb.go',
    '!validator/dist/**/*.*',
    '!validator/node_modules/**/*.*',
    '!validator/nodejs/node_modules/**/*.*',
    '!validator/webui/dist/**/*.*',
    '!validator/webui/node_modules/**/*.*',
    '!build-system/tasks/presubmit-checks.js',
    '!build-system/tasks/visual-diff/node_modules/**/*.*',
    '!build-system/tasks/visual-diff/snippets/*.js',
    '!build/polyfills.js',
    '!build/polyfills/*.js',
    '!third_party/**/*.*',
    '!validator/chromeextension/*.*',
    // Files in this testdata dir are machine-generated and are not part
    // of the AMP runtime, so shouldn't be checked.
    '!extensions/amp-a4a/*/test/testdata/*.js',
    '!examples/**/*',
    '!examples/visual-tests/**/*',
    '!test/coverage/**/*.*',
    '!firebase/**/*.*',
  ],
  changelogIgnoreFileTypes: /\.md|\.json|\.yaml|LICENSE|CONTRIBUTORS$/,
};
<|endoftext|>


<commit_before>$(function() {
    $.each($("tr.program-status"), function (index, row) {
        var path = $(row).attr("data-socket-path")
        url = 'ws://' + window.location.host + path;
        console.log('connecting to:' + url);
        var ws = new WebSocket(url);
        ws.onmessage = function(e) {
            var data = JSON.parse(e.data);
            $(row).find('td.execution-time a').replaceWith("" + data.executionTime + "");

            $(row).find('td.execution-status').empty();
            $("
" + data.executionStatusLabel + "
").appendTo($(row).find('td.execution-status'));
            var btn = $(row).find('button.program-run');
            if (data.executionStatus == "running") {
                btn.addClass("pure-button-disabled");
            } else {
                btn.removeClass("pure-button-disabled");
            }
            console.log(data)

            $('#succeeded h2').text($('td.execution-status div.succeeded').length)
            $('#retryable h2').text($('td.execution-status div.retryable').length)
            $('#failed h2').text($('td.execution-status div.failed').length)
        };
    });
});
<commit_msg>remove console.log<commit_after>$(function() {
    $.each($("tr.program-status"), function (index, row) {
        var path = $(row).attr("data-socket-path")
        url = 'ws://' + window.location.host + path;

        var ws = new WebSocket(url);
        ws.onmessage = function(e) {
            var data = JSON.parse(e.data);
            $(row).find('td.execution-time a').replaceWith("" + data.executionTime + "");

            $(row).find('td.execution-status').empty();
            $("
" + data.executionStatusLabel + "
").appendTo($(row).find('td.execution-status'));
            var btn = $(row).find('button.program-run');
            if (data.executionStatus == "running") {
                btn.addClass("pure-button-disabled");
            } else {
                btn.removeClass("pure-button-disabled");
            }

            $('#succeeded h2').text($('td.execution-status div.succeeded').length)
            $('#retryable h2').text($('td.execution-status div.retryable').length)
            $('#failed h2').text($('td.execution-status div.failed').length)
        };
    });
});
<|endoftext|>