<commit_before>/* global JSON */

(function(W) {
	'use strict';

	/**
	 * Setup initial variables
	 */
	var version = 1;

	W.fn.make('data', {
		/**
		 * Make Ajax request based on specified options
		 *
		 * @param {object} options
		 * @param {string} options.url - endpoint to request
		 * @param {(Array|function|string)} [options.send] - executed before Ajax call
		 * @param {(Array|function|string)} [options.success] - callback if request succeeds
		 * @param {(Array|function|string)} [options.error] - callback if request fails
		 * @param {(Array|function|string)} [options.complete] - callback on request completion
		 * @param {Array} [options.args] - callback arguments appended after default values
		 * @param {object} [options.data] - object to serialize and pass along with request
		 * @param {object} [options.headers] - request headers
		 * @param {boolean} [options.json=false] - evaluate the response as JSON and return object
		 * @param {(boolean|string)} [options.jsonp=false] - boolean or override name for callback query string parameter
		 * @param {string} [options.jsonpCallback] - override the name of the JSONP callback function
		 * @param {string} [options.method=get] - request verb
		 * @param {object} [options.scope] - callback scope
		 * @param {string} [options.template] - template string to parse response JSON
		 */
		request: function(options) {
			var conf = W.$extend({
					args: [],
					data: {},
					headers: {},
					method: 'get',
					root: ''
				}, options);

			if (conf.cache === false) {
				conf.data.dt = Date.now();
			}

			// Prefix root path to url
			if (conf.root) {
				conf.url = conf.root + conf.url;
			}

			// Process JSONP
			if (conf.jsonp) {
				return this.$private.jsonp(conf);
			}

			var scope = this,
				x = new XMLHttpRequest();

			if (conf.send) {
				W.$exec(conf.send, {
					args: conf.args,
					scope: conf.scope
				});
			}

			x.onreadystatechange = function() {
				scope.$private.change(x, conf);
			};

			var contentTypeHeader = 'Content-Type',
				method = conf.method.toUpperCase(),
				send = null,
				headers = [];

			// Format data based on specified verb
			if (method == 'GET') {
				conf.url = this.$private.getUrl(conf);
			} else {
				if (method == 'POST') {
					headers[contentTypeHeader] =
						'application/x-www-form-urlencoded; charset=UTF-8';
				}

				send = typeof conf.data == 'string' ?
					conf.data :
					JSON.stringify(conf.data);
			}

			x.open(method, conf.url, true);

			// Add JSON headers
			if (conf.json) {
				headers[contentTypeHeader] = 'application/json';
				headers.Accept = 'application/json, text/javascript, */*; q=0.01';
			}

			// Add X-Requested-With header for same domain requests
			var xrw = 'X-Requested-With',
				a = W._doc.createElement('a');
			a.href = conf.url;

			if (a.hostname == location.hostname) {
				headers[xrw] = 'XMLHttpRequest';
			}

			headers = W.$extend(headers, conf.headers);

			// Set request headers
			for (var key in headers) {
				var val = headers[key];

				if (val !== false) {
					x.setRequestHeader(key, val);
				}
			}

			x.send(send);
		}
	}, {
		/**
		 * Process the readyState change event
		 *
		 * @param {XMLHttpRequest} x
		 * @param {object} conf
		 * @returns {*}
		 */
		change: function(x, conf) {
			if (x.readyState === 4) {
				var status = x.status,
					exec = {
						args: conf.args,
						scope: conf.scope
					};

				exec.args.unshift(x);

				if (status >= 200 && status < 400) {
					if (conf.success) {
						this.success(x, conf);
					}
				} else if (conf.error) {
					W.$exec(conf.error, exec);
				}

				if (conf.complete) {
					W.$exec(conf.complete, exec);
				}
			}
		},

		/**
		 * Execute the request success callback
		 *
		 * @param {XMLHttpRequest} x
		 * @param {object} conf
		 * @returns {boolean}
		 */
		success: function(x, conf) {
			var resp = x.responseText,
				orig = resp,
				exec = {
					args: conf.args.slice(0),
					scope: conf.scope
				};

			// Parse JSON response if specified
			if (conf.json || conf.template) {
				try {
					resp = JSON.parse(resp);
				} catch (e) {
					resp = {};
				}

				if (conf.template) {
					resp = W.view.render(conf.template, resp);
					exec.args.unshift(orig);
				}
			}

			exec.args.unshift(resp);

			// Execute success callback if specified
			W.$exec(conf.success, exec);
		},

		/**
		 * Process JSONP request
		 *
		 * @param {object} conf
		 */
		jsonp: function(conf) {
			var head = W.$('head')[0];

			if (conf.success) {
				var fn = conf.jsonpCallback;

				if (! fn) {
					fn = 'jsonp' + version;
					version++;
				}

				W._win[fn] = function(data) {
					conf.args.unshift(data);

					W.$exec(conf.success, {
						args: conf.args,
						scope: conf.scope
					});
				};

				conf.data[
					conf.jsonp === true ?
						'callback' :
						conf.jsonp
				] = fn;
			}

			var el = W._doc.createElement('script');

			el.src = this.getUrl(conf);

			if (conf.error) {
				el.onerror = function() {
					W.$exec(conf.error, {
						args: conf.args,
						scope: conf.scope
					});
				};
			}

			head.appendChild(el);
		},

		/**
		 * Generate final URL
		 *
		 * @param {object} conf
		 */
		getUrl: function(conf) {
			var url = conf.url;

			if (conf.data && Object.keys(conf.data).length) {
				url += '?' + W.$serialize(conf.data);
			}

			return url;
		}
	});
})(Wee);<commit_msg>For relative URLs ensure the proper header still gets set in legacy IE<commit_after>/* global JSON */

(function(W) {
	'use strict';

	/**
	 * Setup initial variables
	 */
	var version = 1;

	W.fn.make('data', {
		/**
		 * Make Ajax request based on specified options
		 *
		 * @param {object} options
		 * @param {string} options.url - endpoint to request
		 * @param {(Array|function|string)} [options.send] - executed before Ajax call
		 * @param {(Array|function|string)} [options.success] - callback if request succeeds
		 * @param {(Array|function|string)} [options.error] - callback if request fails
		 * @param {(Array|function|string)} [options.complete] - callback on request completion
		 * @param {Array} [options.args] - callback arguments appended after default values
		 * @param {object} [options.data] - object to serialize and pass along with request
		 * @param {object} [options.headers] - request headers
		 * @param {boolean} [options.json=false] - evaluate the response as JSON and return object
		 * @param {(boolean|string)} [options.jsonp=false] - boolean or override name for callback query string parameter
		 * @param {string} [options.jsonpCallback] - override the name of the JSONP callback function
		 * @param {string} [options.method=get] - request verb
		 * @param {object} [options.scope] - callback scope
		 * @param {string} [options.template] - template string to parse response JSON
		 */
		request: function(options) {
			var conf = W.$extend({
					args: [],
					data: {},
					headers: {},
					method: 'get',
					root: ''
				}, options);

			if (conf.cache === false) {
				conf.data.dt = Date.now();
			}

			// Prefix root path to url
			if (conf.root) {
				conf.url = conf.root + conf.url;
			}

			// Process JSONP
			if (conf.jsonp) {
				return this.$private.jsonp(conf);
			}

			var scope = this,
				x = new XMLHttpRequest();

			if (conf.send) {
				W.$exec(conf.send, {
					args: conf.args,
					scope: conf.scope
				});
			}

			x.onreadystatechange = function() {
				scope.$private.change(x, conf);
			};

			var contentTypeHeader = 'Content-Type',
				method = conf.method.toUpperCase(),
				send = null,
				headers = [];

			// Format data based on specified verb
			if (method == 'GET') {
				conf.url = this.$private.getUrl(conf);
			} else {
				if (method == 'POST') {
					headers[contentTypeHeader] =
						'application/x-www-form-urlencoded; charset=UTF-8';
				}

				send = typeof conf.data == 'string' ?
					conf.data :
					JSON.stringify(conf.data);
			}

			x.open(method, conf.url, true);

			// Add JSON headers
			if (conf.json) {
				headers[contentTypeHeader] = 'application/json';
				headers.Accept = 'application/json, text/javascript, */*; q=0.01';
			}

			// Add X-Requested-With header for same domain requests
			var xrw = 'X-Requested-With',
				a = W._doc.createElement('a');
			a.href = conf.url;

			if (! a.hostname || a.hostname == location.hostname) {
				headers[xrw] = 'XMLHttpRequest';
			}

			headers = W.$extend(headers, conf.headers);

			// Set request headers
			for (var key in headers) {
				var val = headers[key];

				if (val !== false) {
					x.setRequestHeader(key, val);
				}
			}

			x.send(send);
		}
	}, {
		/**
		 * Process the readyState change event
		 *
		 * @param {XMLHttpRequest} x
		 * @param {object} conf
		 * @returns {*}
		 */
		change: function(x, conf) {
			if (x.readyState === 4) {
				var status = x.status,
					exec = {
						args: conf.args,
						scope: conf.scope
					};

				exec.args.unshift(x);

				if (status >= 200 && status < 400) {
					if (conf.success) {
						this.success(x, conf);
					}
				} else if (conf.error) {
					W.$exec(conf.error, exec);
				}

				if (conf.complete) {
					W.$exec(conf.complete, exec);
				}
			}
		},

		/**
		 * Execute the request success callback
		 *
		 * @param {XMLHttpRequest} x
		 * @param {object} conf
		 * @returns {boolean}
		 */
		success: function(x, conf) {
			var resp = x.responseText,
				orig = resp,
				exec = {
					args: conf.args.slice(0),
					scope: conf.scope
				};

			// Parse JSON response if specified
			if (conf.json || conf.template) {
				try {
					resp = JSON.parse(resp);
				} catch (e) {
					resp = {};
				}

				if (conf.template) {
					resp = W.view.render(conf.template, resp);
					exec.args.unshift(orig);
				}
			}

			exec.args.unshift(resp);

			// Execute success callback if specified
			W.$exec(conf.success, exec);
		},

		/**
		 * Process JSONP request
		 *
		 * @param {object} conf
		 */
		jsonp: function(conf) {
			var head = W.$('head')[0];

			if (conf.success) {
				var fn = conf.jsonpCallback;

				if (! fn) {
					fn = 'jsonp' + version;
					version++;
				}

				W._win[fn] = function(data) {
					conf.args.unshift(data);

					W.$exec(conf.success, {
						args: conf.args,
						scope: conf.scope
					});
				};

				conf.data[
					conf.jsonp === true ?
						'callback' :
						conf.jsonp
				] = fn;
			}

			var el = W._doc.createElement('script');

			el.src = this.getUrl(conf);

			if (conf.error) {
				el.onerror = function() {
					W.$exec(conf.error, {
						args: conf.args,
						scope: conf.scope
					});
				};
			}

			head.appendChild(el);
		},

		/**
		 * Generate final URL
		 *
		 * @param {object} conf
		 */
		getUrl: function(conf) {
			var url = conf.url;

			if (conf.data && Object.keys(conf.data).length) {
				url += '?' + W.$serialize(conf.data);
			}

			return url;
		}
	});
})(Wee);<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

const fs = require('fs');
const http = require('http');
const os = require('os');
const path = require('path');
const crypto = require('crypto');
const zlib = require('zlib');
const stream = require('stream');
const process = require('process');

const HttpsProxyAgent = require('https-proxy-agent');
const fetch = require('node-fetch');
const ProgressBar = require('progress');
const Proxy = require('proxy-from-env');
// NOTE: Can be dropped in favor of `fs.mkdirSync(path, { recursive: true })` once we stop supporting Node 8.x
const mkdirp = require('mkdirp');

const helper = require('../js/helper');
const pkgInfo = require('../package.json');

const CDN_URL =
  process.env.SENTRYCLI_LOCAL_CDNURL ||
  process.env.npm_config_sentrycli_cdnurl ||
  process.env.SENTRYCLI_CDNURL ||
  'https://downloads.sentry-cdn.com/sentry-cli';

function shouldRenderProgressBar() {
  const silentFlag = process.argv.some(v => v === '--silent');
  const silentConfig = process.env.npm_config_loglevel === 'silent';
  const silentEnv = process.env.SENTRY_NO_PROGRESS_BAR;
  // If any of possible options is set, skip rendering of progress bar
  return !(silentFlag || silentConfig || silentEnv);
}

function getDownloadUrl(platform, arch) {
  const releasesUrl = `${CDN_URL}/${pkgInfo.version}/sentry-cli`;
  let archString = '';
  switch (arch) {
    case 'x64':
      archString = 'x86_64';
      break;
    case 'x86':
    case 'ia32':
      archString = 'i686';
      break;
    default:
      archString = arch;
  }
  switch (platform) {
    case 'darwin':
      return `${releasesUrl}-Darwin-universal`;
    case 'win32':
      return `${releasesUrl}-Windows-${archString}.exe`;
    case 'linux':
    case 'freebsd':
      return `${releasesUrl}-Linux-${archString}`;
    default:
      return null;
  }
}

function createProgressBar(name, total) {
  if (process.stdout.isTTY) {
    return new ProgressBar(`fetching ${name} :bar :percent :etas`, {
      complete: '█',
      incomplete: '░',
      width: 20,
      total,
    });
  }

  let pct = null;
  let current = 0;
  return {
    tick: length => {
      current += length;
      const next = Math.round((current / total) * 100);
      if (next > pct) {
        pct = next;
        process.stdout.write(`fetching ${name} ${pct}%\n`);
      }
    },
  };
}

function npmCache() {
  const env = process.env;
  return (
    env.npm_config_cache ||
    env.npm_config_yarn_offline_mirror ||
    (env.APPDATA ? path.join(env.APPDATA, 'npm-cache') : path.join(os.homedir(), '.npm'))
  );
}

function getCachedPath(url) {
  const digest = crypto
    .createHash('md5')
    .update(url)
    .digest('hex')
    .slice(0, 6);

  return path.join(
    npmCache(),
    'sentry-cli',
    `${digest}-${path.basename(url).replace(/[^a-zA-Z0-9.]+/g, '-')}`
  );
}

function getTempFile(cached) {
  return `${cached}.${process.pid}-${Math.random()
    .toString(16)
    .slice(2)}.tmp`;
}

function downloadBinary() {
  const arch = os.arch();
  const platform = os.platform();
  const outputPath = helper.getPath();

  const downloadUrl = getDownloadUrl(platform, arch);
  if (!downloadUrl) {
    return Promise.reject(new Error(`Unsupported target ${platform}-${arch}`));
  }

  const cachedPath = getCachedPath(downloadUrl);
  if (fs.existsSync(cachedPath)) {
    fs.copyFileSync(cachedPath, outputPath);
    return Promise.resolve();
  }

  const proxyUrl = Proxy.getProxyForUrl(downloadUrl);
  const agent = proxyUrl ? new HttpsProxyAgent(proxyUrl) : null;

  return fetch(downloadUrl, {
    agent,
    compress: false,
    headers: {
      'accept-encoding': 'gzip, deflate, br',
    },
    redirect: 'follow',
  })
    .then(response => {
      if (!response.ok) {
        throw new Error(
          `Unable to download sentry-cli binary from ${downloadUrl}.\nServer returned ${response.status}: ${response.statusText}.`
        );
      }

      const contentEncoding = response.headers.get('content-encoding');
      let decompressor;
      if (/\bgzip\b/.test(contentEncoding)) {
        decompressor = zlib.createGunzip();
      } else if (/\bdeflate\b/.test(contentEncoding)) {
        decompressor = zlib.createInflate();
      } else if (/\bbr\b/.test(contentEncoding)) {
        decompressor = zlib.createBrotliDecompress();
      } else {
        decompressor = new stream.PassThrough();
      }
      const name = downloadUrl.match(/.*\/(.*?)$/)[1];
      const total = parseInt(response.headers.get('content-length'), 10);
      const progressBar = createProgressBar(name, total);
      const tempPath = getTempFile(cachedPath);
      mkdirp.sync(path.dirname(tempPath));

      return new Promise((resolve, reject) => {
        response.body
          .on('error', e => reject(e))
          .on('data', chunk => shouldRenderProgressBar() && progressBar.tick(chunk.length))
          .pipe(decompressor)
          .pipe(fs.createWriteStream(tempPath, { mode: '0755' }))
          .on('error', e => reject(e))
          .on('close', () => resolve());
      }).then(() => {
        fs.copyFileSync(tempPath, cachedPath);
        fs.copyFileSync(tempPath, outputPath);
        fs.unlinkSync(tempPath);
      });
    })
    .catch(error => {
      if (error instanceof fetch.FetchError) {
        throw new Error(
          `Unable to download sentry-cli binary from ${downloadUrl}.\nError code: ${error.code}`
        );
      } else {
        throw error;
      }
    });
}

function checkVersion() {
  return helper.execute(['--version']).then(output => {
    const version = output.replace('sentry-cli ', '').trim();
    const expected = process.env.SENTRYCLI_LOCAL_CDNURL ? 'DEV' : pkgInfo.version;
    if (version !== expected) {
      throw new Error(`Unexpected sentry-cli version "${version}", expected "${expected}"`);
    }
  });
}

if (process.env.SENTRYCLI_LOCAL_CDNURL) {
  // For testing, mock the CDN by spawning a local server
  const server = http.createServer((request, response) => {
    const contents = fs.readFileSync(path.join(__dirname, '../js/__mocks__/sentry-cli'));
    response.writeHead(200, {
      'Content-Type': 'application/octet-stream',
      'Content-Length': String(contents.byteLength),
    });
    response.end(contents);
  });

  server.listen(8999);
  process.on('exit', () => server.close());
}

downloadBinary()
  .then(() => checkVersion())
  .then(() => process.exit(0))
  .catch(e => {
    // eslint-disable-next-line no-console
    console.error(e.toString());
    process.exit(1);
  });
<commit_msg>fix: rename arm64 as aarch64 (#917)<commit_after>#!/usr/bin/env node

'use strict';

const fs = require('fs');
const http = require('http');
const os = require('os');
const path = require('path');
const crypto = require('crypto');
const zlib = require('zlib');
const stream = require('stream');
const process = require('process');

const HttpsProxyAgent = require('https-proxy-agent');
const fetch = require('node-fetch');
const ProgressBar = require('progress');
const Proxy = require('proxy-from-env');
// NOTE: Can be dropped in favor of `fs.mkdirSync(path, { recursive: true })` once we stop supporting Node 8.x
const mkdirp = require('mkdirp');

const helper = require('../js/helper');
const pkgInfo = require('../package.json');

const CDN_URL =
  process.env.SENTRYCLI_LOCAL_CDNURL ||
  process.env.npm_config_sentrycli_cdnurl ||
  process.env.SENTRYCLI_CDNURL ||
  'https://downloads.sentry-cdn.com/sentry-cli';

function shouldRenderProgressBar() {
  const silentFlag = process.argv.some(v => v === '--silent');
  const silentConfig = process.env.npm_config_loglevel === 'silent';
  const silentEnv = process.env.SENTRY_NO_PROGRESS_BAR;
  // If any of possible options is set, skip rendering of progress bar
  return !(silentFlag || silentConfig || silentEnv);
}

function getDownloadUrl(platform, arch) {
  const releasesUrl = `${CDN_URL}/${pkgInfo.version}/sentry-cli`;
  let archString = '';
  switch (arch) {
    case 'x64':
      archString = 'x86_64';
      break;
    case 'x86':
    case 'ia32':
      archString = 'i686';
      break;
    case 'arm64':
      archString = 'aarch64';
      break;
    default:
      archString = arch;
  }
  switch (platform) {
    case 'darwin':
      return `${releasesUrl}-Darwin-universal`;
    case 'win32':
      return `${releasesUrl}-Windows-${archString}.exe`;
    case 'linux':
    case 'freebsd':
      return `${releasesUrl}-Linux-${archString}`;
    default:
      return null;
  }
}

function createProgressBar(name, total) {
  if (process.stdout.isTTY) {
    return new ProgressBar(`fetching ${name} :bar :percent :etas`, {
      complete: '█',
      incomplete: '░',
      width: 20,
      total,
    });
  }

  let pct = null;
  let current = 0;
  return {
    tick: length => {
      current += length;
      const next = Math.round((current / total) * 100);
      if (next > pct) {
        pct = next;
        process.stdout.write(`fetching ${name} ${pct}%\n`);
      }
    },
  };
}

function npmCache() {
  const env = process.env;
  return (
    env.npm_config_cache ||
    env.npm_config_yarn_offline_mirror ||
    (env.APPDATA ? path.join(env.APPDATA, 'npm-cache') : path.join(os.homedir(), '.npm'))
  );
}

function getCachedPath(url) {
  const digest = crypto
    .createHash('md5')
    .update(url)
    .digest('hex')
    .slice(0, 6);

  return path.join(
    npmCache(),
    'sentry-cli',
    `${digest}-${path.basename(url).replace(/[^a-zA-Z0-9.]+/g, '-')}`
  );
}

function getTempFile(cached) {
  return `${cached}.${process.pid}-${Math.random()
    .toString(16)
    .slice(2)}.tmp`;
}

function downloadBinary() {
  const arch = os.arch();
  const platform = os.platform();
  const outputPath = helper.getPath();

  const downloadUrl = getDownloadUrl(platform, arch);
  if (!downloadUrl) {
    return Promise.reject(new Error(`Unsupported target ${platform}-${arch}`));
  }

  const cachedPath = getCachedPath(downloadUrl);
  if (fs.existsSync(cachedPath)) {
    fs.copyFileSync(cachedPath, outputPath);
    return Promise.resolve();
  }

  const proxyUrl = Proxy.getProxyForUrl(downloadUrl);
  const agent = proxyUrl ? new HttpsProxyAgent(proxyUrl) : null;

  return fetch(downloadUrl, {
    agent,
    compress: false,
    headers: {
      'accept-encoding': 'gzip, deflate, br',
    },
    redirect: 'follow',
  })
    .then(response => {
      if (!response.ok) {
        throw new Error(
          `Unable to download sentry-cli binary from ${downloadUrl}.\nServer returned ${response.status}: ${response.statusText}.`
        );
      }

      const contentEncoding = response.headers.get('content-encoding');
      let decompressor;
      if (/\bgzip\b/.test(contentEncoding)) {
        decompressor = zlib.createGunzip();
      } else if (/\bdeflate\b/.test(contentEncoding)) {
        decompressor = zlib.createInflate();
      } else if (/\bbr\b/.test(contentEncoding)) {
        decompressor = zlib.createBrotliDecompress();
      } else {
        decompressor = new stream.PassThrough();
      }
      const name = downloadUrl.match(/.*\/(.*?)$/)[1];
      const total = parseInt(response.headers.get('content-length'), 10);
      const progressBar = createProgressBar(name, total);
      const tempPath = getTempFile(cachedPath);
      mkdirp.sync(path.dirname(tempPath));

      return new Promise((resolve, reject) => {
        response.body
          .on('error', e => reject(e))
          .on('data', chunk => shouldRenderProgressBar() && progressBar.tick(chunk.length))
          .pipe(decompressor)
          .pipe(fs.createWriteStream(tempPath, { mode: '0755' }))
          .on('error', e => reject(e))
          .on('close', () => resolve());
      }).then(() => {
        fs.copyFileSync(tempPath, cachedPath);
        fs.copyFileSync(tempPath, outputPath);
        fs.unlinkSync(tempPath);
      });
    })
    .catch(error => {
      if (error instanceof fetch.FetchError) {
        throw new Error(
          `Unable to download sentry-cli binary from ${downloadUrl}.\nError code: ${error.code}`
        );
      } else {
        throw error;
      }
    });
}

function checkVersion() {
  return helper.execute(['--version']).then(output => {
    const version = output.replace('sentry-cli ', '').trim();
    const expected = process.env.SENTRYCLI_LOCAL_CDNURL ? 'DEV' : pkgInfo.version;
    if (version !== expected) {
      throw new Error(`Unexpected sentry-cli version "${version}", expected "${expected}"`);
    }
  });
}

if (process.env.SENTRYCLI_LOCAL_CDNURL) {
  // For testing, mock the CDN by spawning a local server
  const server = http.createServer((request, response) => {
    const contents = fs.readFileSync(path.join(__dirname, '../js/__mocks__/sentry-cli'));
    response.writeHead(200, {
      'Content-Type': 'application/octet-stream',
      'Content-Length': String(contents.byteLength),
    });
    response.end(contents);
  });

  server.listen(8999);
  process.on('exit', () => server.close());
}

downloadBinary()
  .then(() => checkVersion())
  .then(() => process.exit(0))
  .catch(e => {
    // eslint-disable-next-line no-console
    console.error(e.toString());
    process.exit(1);
  });
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2019 Google Inc. 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.
 * =============================================================================
 */

const cp = require('child_process');
const fs = require('fs');
const https = require('https');
const path = require('path');
const rimraf = require('rimraf');
const tar = require('tar');
const util = require('util');
const os = require('os');
const url = require('url');
const HttpsProxyAgent = require('https-proxy-agent');
const ProgressBar = require('progress');

const mkdir = util.promisify(fs.mkdir);
const exists = util.promisify(fs.exists);

// Determine which tarball to download based on the OS platform and arch:
const platform = os.platform().toLowerCase();
const platformArch = `${platform}-${os.arch().toLowerCase()}`;
let ANGLE_BINARY_URI = 'https://storage.googleapis.com/angle-builds/';
if (platform === 'darwin') {
  // TODO(add debug flag?)
  ANGLE_BINARY_URI += `angle-3626-debug-${platformArch}.tar.gz`
} else if (platform === 'linux') {
  // TODO(add debug flag?)
  ANGLE_BINARY_URI += `angle-3626-debug-${platformArch}.tar.gz`;
} else {
  throw new Error(`The platform ${platformArch} is not currently supported!`);
}

// Dependency storage paths:
const depsPath = path.join(__dirname, '..', 'deps');

//
// Ensures that a directory exists at a given path.
//
async function ensureDir(dirPath) {
  if (!await exists(dirPath)) {
    await mkdir(dirPath);
  }
}

//
// Downloads the ANGLE tarball set at `ANGLE_BINARY_URI` with an optional
// callback when downloading and extracting has finished.
//
async function downloadAngleLibs(callback) {
  console.error('* Downloading ANGLE');
  await ensureDir(depsPath);

  // If HTTPS_PROXY, https_proxy, HTTP_PROXY, or http_proxy is set
  const proxy = process.env['HTTPS_PROXY'] || process.env['https_proxy'] ||
      process.env['HTTP_PROXY'] || process.env['http_proxy'] || '';

  // Using object destructuring to construct the options object for the
  // http request.  the '...url.parse(ANGLE_BINARY_URI)' part fills in the host,
  // path, protocol, etc from the ANGLE_BINARY_URI and then we set the agent to
  // the default agent which is overridden a few lines down if there is a proxy
  const options = {...url.parse(ANGLE_BINARY_URI), agent: https.globalAgent};

  if (proxy !== '') {
    options.agent = new HttpsProxyAgent(proxy);
  }

  const request = https.get(options, response => {
    const bar = new ProgressBar('[:bar] :rate/bps :percent :etas', {
      complete: '=',
      incomplete: ' ',
      width: 30,
      total: parseInt(response.headers['content-length'], 10)
    });

    if (platform === 'win32') {
      //
      // TODO(kreeger): write me.
      //
    } else {
      // All other platforms use a tarball:
      response
          .on('data',
              (chunk) => {
                bar.tick(chunk.length);
              })
          .pipe(tar.x({C: depsPath, strict: true}))
          .on('close', () => {
            if (callback !== undefined) {
              callback();
            }
          });
    }
  });

  request.end();
}

//
// Wraps and executes a node-gyp rebuild command.
//
async function buildBindings() {
  console.error('* Building ANGLE bindings')
  cp.execSync('node-gyp rebuild', (err) => {
    if (err) {
      throw new Error('node-gyp failed with: ' + err);
    }
  });
}

//
// Main execution function for this script.
//
async function run() {
  await downloadAngleLibs(buildBindings);
}

run();
<commit_msg>Revert linux script<commit_after>/**
 * @license
 * Copyright 2019 Google Inc. 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.
 * =============================================================================
 */

const cp = require('child_process');
const fs = require('fs');
const https = require('https');
const path = require('path');
const rimraf = require('rimraf');
const tar = require('tar');
const util = require('util');
const os = require('os');
const url = require('url');
const HttpsProxyAgent = require('https-proxy-agent');
const ProgressBar = require('progress');

const mkdir = util.promisify(fs.mkdir);
const exists = util.promisify(fs.exists);

// Determine which tarball to download based on the OS platform and arch:
const platform = os.platform().toLowerCase();
const platformArch = `${platform}-${os.arch().toLowerCase()}`;
let ANGLE_BINARY_URI = 'https://storage.googleapis.com/angle-builds/';
if (platform === 'darwin') {
  // TODO(add debug flag?)
  ANGLE_BINARY_URI += `angle-3626-debug-${platformArch}.tar.gz`
} else if (platform === 'linux') {
  // TODO(add debug flag?)
  ANGLE_BINARY_URI += `angle-3578-debug-${platformArch}.tar.gz`;
} else {
  throw new Error(`The platform ${platformArch} is not currently supported!`);
}

// Dependency storage paths:
const depsPath = path.join(__dirname, '..', 'deps');

//
// Ensures that a directory exists at a given path.
//
async function ensureDir(dirPath) {
  if (!await exists(dirPath)) {
    await mkdir(dirPath);
  }
}

//
// Downloads the ANGLE tarball set at `ANGLE_BINARY_URI` with an optional
// callback when downloading and extracting has finished.
//
async function downloadAngleLibs(callback) {
  console.error('* Downloading ANGLE');
  await ensureDir(depsPath);

  // If HTTPS_PROXY, https_proxy, HTTP_PROXY, or http_proxy is set
  const proxy = process.env['HTTPS_PROXY'] || process.env['https_proxy'] ||
      process.env['HTTP_PROXY'] || process.env['http_proxy'] || '';

  // Using object destructuring to construct the options object for the
  // http request.  the '...url.parse(ANGLE_BINARY_URI)' part fills in the host,
  // path, protocol, etc from the ANGLE_BINARY_URI and then we set the agent to
  // the default agent which is overridden a few lines down if there is a proxy
  const options = {...url.parse(ANGLE_BINARY_URI), agent: https.globalAgent};

  if (proxy !== '') {
    options.agent = new HttpsProxyAgent(proxy);
  }

  const request = https.get(options, response => {
    const bar = new ProgressBar('[:bar] :rate/bps :percent :etas', {
      complete: '=',
      incomplete: ' ',
      width: 30,
      total: parseInt(response.headers['content-length'], 10)
    });

    if (platform === 'win32') {
      //
      // TODO(kreeger): write me.
      //
    } else {
      // All other platforms use a tarball:
      response
          .on('data',
              (chunk) => {
                bar.tick(chunk.length);
              })
          .pipe(tar.x({C: depsPath, strict: true}))
          .on('close', () => {
            if (callback !== undefined) {
              callback();
            }
          });
    }
  });

  request.end();
}

//
// Wraps and executes a node-gyp rebuild command.
//
async function buildBindings() {
  console.error('* Building ANGLE bindings')
  cp.execSync('node-gyp rebuild', (err) => {
    if (err) {
      throw new Error('node-gyp failed with: ' + err);
    }
  });
}

//
// Main execution function for this script.
//
async function run() {
  await downloadAngleLibs(buildBindings);
}

run();
<|endoftext|>


<commit_before>var current_page = 0;
var num_result = 0;

function handlePaginationClick(new_page_index, pagination_container) {
	if(new_page_index != current_page){
		var items_per_page = parseInt($("#num_hits").val());

		var cqp 	= $("#cqp_string").val();
		var corpus 	= getCorpus().toUpperCase();

		var start 	= new_page_index*items_per_page;
		var end 		= (start + items_per_page);

		makeRequest(cqp, corpus, start, end);
		current_page = new_page_index;
	}

   return false;
}

function makeRequest(cqp, corpus, start, end){
	var selected_corpus = settings.corpora[getCorpus()];
	var attributes = ['msd','lemma'];

	var data = {
					command:'query',
					corpus:corpus,
					cqp:cqp,
					start:start,
					end:end,
					context:'1 sentence',
					show:[],
					show_struct:[]
				};

	$.each(selected_corpus.attributes, function(key,val){
		data.show.push(key);
	});

	if (selected_corpus.struct_attributes) {
		$.each(selected_corpus.struct_attributes, function(key,val){
			data.show_struct.push(key);
		});
	}

	$.ajax({ url: settings.cgi_script+'?callback=?',
				dataType: "jsonp",
				data:data,
				traditional:true,
				success: corpus_results
	});

	setJsonLink(data);
}

function setJsonLink(data){
	$.ajaxSetup({ traditional: true });
	var url = settings.cgi_script+'?'+jQuery.param(data);
	$('#json-link').attr('href', url);
	$('#json-link').css('display', 'inline');
}

function onSubmit(evt) {
	var currentVisible = $("#tabs-container > div:visible");
	$.log("onSubmit", currentVisible, currentVisible.attr("id"))
	switch(currentVisible.attr("id")) {
	case "korp-simple":
		onSimpleChange();
		break;
	case "korp-extended":
		updateCQP();
		break;
//	case "korp-advanced":
//		break;
	}
	submitFormToServer();
}

function submitFormToServer(){
	num_result = 0;
//	TODO: loading text broken
	$('#results').append("
").find("p");

	var cqp 	= $("#cqp_string").val();
	var corpus 	= getCorpus().toUpperCase();

	var start 	= 0;
	var end 	= $("#num_hits").val()-1;

	makeRequest(cqp, corpus, start, end);

	$('#results-wraper').css('display', 'block');
}

function buildPager(number_of_hits){
	var items_per_page = $("#num_hits").val();

	if(number_of_hits > items_per_page){
		$("#Pagination").pagination(number_of_hits, {
			items_per_page:items_per_page,
			callback:handlePaginationClick,
			next_text: util.getLocaleString("next"),
			prev_text: util.getLocaleString("prev"),
			link_to:"#",
			num_edge_entries:2,
			ellipse_text: '..'
		});
		$(".next").attr("rel", "localize[next]");
		$(".prev").attr("rel", "localize[prev]");

	}else{
		$("#Pagination").html('');
	}
}

function selectLeft(sentence, offset) {
	return sentence.tokens.slice(offset, sentence.match.start);
}

function selectMatch(sentence) {
	var from = sentence.match.start;
	return sentence.tokens.slice(from, sentence.match.end);
}

function selectRight(sentence) {
	var from = sentence.match.end;
	var len=sentence.tokens.length;

	var to = len;
	if((len-sentence.match.end) > 12)
		to = sentence.match.end+12;

	return sentence.tokens.slice(sentence.match.end, to);
}

function corpus_results(data) {
	if(data.ERROR) {
		$.error("json fetch error: " + $.dump(data.ERROR));
		return;
	}
	var effectSpeed = 100;
	$('#results').find("p").remove();
	if($.trim($("#results-table").html()).length) {
		$("#results").fadeOut(effectSpeed, function() {
			$("#results-table").empty();
			corpus_results(data);
		});
	}
	else {
		$("#results").hide();
	}
	$("#sidebar:hidden").show("slide", {direction : "right"}, 400);

	var corpus = settings.corpora[getCorpus()];

	//if this is the first result-set
	if(num_result == 0){
		buildPager(data.hits);
	}
	$('#num-result').html(data.hits);
	num_result = data.hits;

	$.each(data.kwic, function(i,sentence){
		var offset = 0;
		if(sentence.match.start > 12)
			offset = sentence.match.start-12;
	    var splitObj = {
	    		"left" : selectLeft(sentence, offset),
	    		"match" : selectMatch(sentence),
	    		"right" : selectRight(sentence)
	    };

		$( "#sentenceTmpl" ).tmpl( splitObj, {rowIndex : i})
				.appendTo( "#results-table" )
				.find(".word").hover(
						function(){
							$(this).addClass('token_hover');
						},
						function(){
							$(this).removeClass('token_hover');
						}
				).click(
						function(event) {
							event.stopPropagation();
							util.SelectionManager.select($(this));
							var clickedWord = parseInt($(this).attr("name").split("-")[1]);
							var data = sentence.tokens[offset + clickedWord];
							updateSidebar(sentence.structs, data);
						}
				);

		$('.result_table tr:even').addClass('alt');
	});
//	make the first matched word selected by default.
	$(".match").children().first().click();
	$("#results").fadeIn(effectSpeed);
}

function renderSentence(tokens){
	//

}

function tooltipIn(object){
	//
	$.log('in'+$(object).html());
}

function tooltipOut(object){
	$.log('out');
}

function renderToken(token){
	var output = ''+token.word+''+token.word+''+tokens.lemma+' ';
	return output;
}

// Read a page's GET URL variables and return them as an associative array.
$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++){
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
  while(x<c.length){var m=r.exec(c.substr(x));
    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});

<commit_msg>support för att söka i alla korpusar<commit_after>var current_page = 0;
var num_result = 0;

function handlePaginationClick(new_page_index, pagination_container) {
	if(new_page_index != current_page){
		var items_per_page = parseInt($("#num_hits").val());

		var cqp 	= $("#cqp_string").val();
		var corpus 	= getCorpus().toUpperCase();

		var start 	= new_page_index*items_per_page;
		var end 		= (start + items_per_page);

		makeRequest(cqp, corpus, start, end);
		current_page = new_page_index;
	}

   return false;
}

function makeRequest(cqp, corpus, start, end){
	var selected_corpus = settings.corpora[getCorpus()];
	var attributes = ['msd','lemma'];

	var data = {}

	if(corpus == 'ALL'){

		data =	{
				command:'query',
				corpus:getAllCorpora(),
				cqp:cqp,
				start:start,
				end:end,
				context:'1 sentence',
				show:[],
				show_struct:[]
			};
	}else{
			data =	{
					command:'query',
					corpus:corpus,
					cqp:cqp,
					start:start,
					end:end,
					context:'1 sentence',
					show:[],
					show_struct:[]
				};
	}

	$.each(selected_corpus.attributes, function(key,val){
		data.show.push(key);
	});

	if (selected_corpus.struct_attributes) {
		$.each(selected_corpus.struct_attributes, function(key,val){
			data.show_struct.push(key);
		});
	}

	$.ajax({ url: settings.cgi_script+'?callback=?',
				dataType: "jsonp",
				data:data,
				traditional:true,
				success: corpus_results
	});

	setJsonLink(data);
}

function setJsonLink(data){
	$.ajaxSetup({ traditional: true });
	var url = settings.cgi_script+'?'+jQuery.param(data);
	$('#json-link').attr('href', url);
	$('#json-link').css('display', 'inline');
}

function onSubmit(evt) {
	var currentVisible = $("#tabs-container > div:visible");
	$.log("onSubmit", currentVisible, currentVisible.attr("id"))
	switch(currentVisible.attr("id")) {
	case "korp-simple":
		onSimpleChange();
		break;
	case "korp-extended":
		updateCQP();
		break;
//	case "korp-advanced":
//		break;
	}
	submitFormToServer();
}

function submitFormToServer(){
	num_result = 0;
//	TODO: loading text broken
	$('#results').append("
").find("p");

	var cqp 	= $("#cqp_string").val();
	var corpus 	= getCorpus().toUpperCase();

	var start 	= 0;
	var end 	= $("#num_hits").val()-1;

	makeRequest(cqp, corpus, start, end);

	$('#results-wraper').css('display', 'block');
}

function buildPager(number_of_hits){
	var items_per_page = $("#num_hits").val();

	if(number_of_hits > items_per_page){
		$("#Pagination").pagination(number_of_hits, {
			items_per_page:items_per_page,
			callback:handlePaginationClick,
			next_text: util.getLocaleString("next"),
			prev_text: util.getLocaleString("prev"),
			link_to:"#",
			num_edge_entries:2,
			ellipse_text: '..'
		});
		$(".next").attr("rel", "localize[next]");
		$(".prev").attr("rel", "localize[prev]");

	}else{
		$("#Pagination").html('');
	}
}

function selectLeft(sentence, offset) {
	return sentence.tokens.slice(offset, sentence.match.start);
}

function selectMatch(sentence) {
	var from = sentence.match.start;
	return sentence.tokens.slice(from, sentence.match.end);
}

function selectRight(sentence) {
	var from = sentence.match.end;
	var len=sentence.tokens.length;

	var to = len;
	if((len-sentence.match.end) > 12)
		to = sentence.match.end+12;

	return sentence.tokens.slice(sentence.match.end, to);
}

function corpus_results(data) {
	if(data.ERROR) {
		$.error("json fetch error: " + $.dump(data.ERROR));
		return;
	}
	var effectSpeed = 100;
	$('#results').find("p").remove();
	if($.trim($("#results-table").html()).length) {
		$("#results").fadeOut(effectSpeed, function() {
			$("#results-table").empty();
			corpus_results(data);
		});
	}
	else {
		$("#results").hide();
	}
	$("#sidebar:hidden").show("slide", {direction : "right"}, 400);

	var corpus = settings.corpora[getCorpus()];

	//if this is the first result-set
	if(num_result == 0){
		buildPager(data.hits);
	}
	$('#num-result').html(data.hits);
	num_result = data.hits;

	$.each(data.kwic, function(i,sentence){
		var offset = 0;
		if(sentence.match.start > 12)
			offset = sentence.match.start-12;
	    var splitObj = {
	    		"left" : selectLeft(sentence, offset),
	    		"match" : selectMatch(sentence),
	    		"right" : selectRight(sentence)
	    };

		$( "#sentenceTmpl" ).tmpl( splitObj, {rowIndex : i})
				.appendTo( "#results-table" )
				.find(".word").hover(
						function(){
							$(this).addClass('token_hover');
						},
						function(){
							$(this).removeClass('token_hover');
						}
				).click(
						function(event) {
							event.stopPropagation();
							util.SelectionManager.select($(this));
							var clickedWord = parseInt($(this).attr("name").split("-")[1]);
							var data = sentence.tokens[offset + clickedWord];
							updateSidebar(sentence.structs, data);
						}
				);

		$('.result_table tr:even').addClass('alt');
	});
//	make the first matched word selected by default.
	$(".match").children().first().click();
	$("#results").fadeIn(effectSpeed);
}

function renderSentence(tokens){
	//

}

function tooltipIn(object){
	//
	$.log('in'+$(object).html());
}

function tooltipOut(object){
	$.log('out');
}

function renderToken(token){
	var output = ''+token.word+''+token.word+''+tokens.lemma+' ';
	return output;
}

// Read a page's GET URL variables and return them as an associative array.
$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++){
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
  while(x<c.length){var m=r.exec(c.substr(x));
    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});

<|endoftext|>


<commit_before>(function(window) {
  var keyframes = sheet.add('@keyframes spin');
  var arrowStartPosition = Math.random();
  $('#arrow').css('transform', 'rotate(' + arrowStartPosition + 'turn)');

  $('.spinner').on('click', function() {
    var $arrow = $('#arrow');
    var $arrowClone = $arrow.clone(true);

    $arrow.replaceWith($arrowClone);
    $arrow = $('#arrow');

    // Set the start position using start data on the element and a random number.
    var startPosition = $arrow.data('start-pos') || arrowStartPosition;
    // Set the end position by adding a larger random number to the start value.
    var endPosition = startPosition + (Math.random() * 9 + 11);
    // Set the start data on the element at the end position to start at the same position on the next spin.
    $arrow.data('start-pos', endPosition);

    $arrow.css('transform', 'rotate(' + startPosition + 'turn)');

    keyframes.nested('from', { 'transform': 'rotate(' + startPosition + 'turn)' });
    keyframes.nested('to', { 'transform': 'rotate(' + endPosition + 'turn)' });
  });
})(window);
<commit_msg>Added lines to clear transform styles in @keyframes's 'from' and 'to' properties when clicking on Spinner button to prevent automatically spinning after switching options and coming back after spinning the spinner. Closes #5.<commit_after>(function(window) {
  var keyframes = sheet.add('@keyframes spin');
  keyframes.nested('from', { 'transform': '' });
  keyframes.nested('to', { 'transform': '' });
  var arrowStartPosition = Math.random();
  $('#arrow').css('transform', 'rotate(' + arrowStartPosition + 'turn)');

  $('.spinner').on('click', function() {
    var $arrow = $('#arrow');
    var $arrowClone = $arrow.clone(true);

    $arrow.replaceWith($arrowClone);
    $arrow = $('#arrow');

    // Set the start position using start data on the element and a random number.
    var startPosition = $arrow.data('start-pos') || arrowStartPosition;
    // Set the end position by adding a larger random number to the start value.
    var endPosition = startPosition + (Math.random() * 9 + 11);
    // Set the start data on the element at the end position to start at the same position on the next spin.
    $arrow.data('start-pos', endPosition);

    $arrow.css('transform', 'rotate(' + startPosition + 'turn)');

    keyframes.nested('from', { 'transform': 'rotate(' + startPosition + 'turn)' });
    keyframes.nested('to', { 'transform': 'rotate(' + endPosition + 'turn)' });
  });
})(window);
<|endoftext|>


<commit_before>var getStorage = (function () {
	function StorageInfo(allStorages, storageId, elId, uri, title) {
		this._allStorages = allStorages;
		this._storageId = storageId;
		this._isAvailable = false;
		this._handler = null;
		this._elId = elId;
		this._uri = uri;
		this._title = title;
	}

	Object.defineProperty(StorageInfo.prototype, 'storageId', {
		get: function () { return this._storageId; }
	});

	Object.defineProperty(StorageInfo.prototype, 'isAvailable', {
		get: function () { return this._isAvailable; }
	});

	Object.defineProperty(StorageInfo.prototype, 'handler', {
		get: function () { return this._handler; }
	});

	Object.defineProperty(StorageInfo.prototype, 'elId', {
		get: function () { return this._elId; }
	});

	Object.defineProperty(StorageInfo.prototype, 'uri', {
		get: function () { return this._uri; }
	});

	Object.defineProperty(StorageInfo.prototype, 'title', {
		get: function () { return this._title; }
	});

	StorageInfo.prototype.setDeviceHandler = function (handler, isAvailable, onloaded) {
		this._handler = handler;
		this._isAvailable = isAvailable;

		if (this._allStorages.isLoaded()) {
			onloaded();
		}
	};

	// Storage configuration

	return function() {
		var storages = {}

		storages.SDCard = new StorageInfo(storages, 'sdcard', '#sdcard-storage', '#sdcard', 'SD Card');
		storages.Pictures = new StorageInfo(storages, 'pictures', '#pictires-storage', '#pictures', 'My Pictures');
		storages.Music = new StorageInfo(storages, 'music', '#music-storage', '#music', 'My Music');
		storages.Videos = new StorageInfo(storages, 'videos', '#videos-storage', '#videos', 'My Videos');

		storages.isLoaded = function () {
				return this.SDCard.handler !== null &&
						this.Pictures.handler !== null &&
						this.Music.handler !== null &&
						this.Videos.handler !== null;
			};

		storages.getDeviceStorages = function () {
			var deviceStorages = _.filter(this, function (storage) {
				return !_.isFunction(storage);
			});

			return deviceStorages;
		};

		storages.findStorageByUri = function (uri) {
			var storage = _.find(this, function (storage) {
				return !_.isFunction(storage) && storage.uri === uri;
			});

			return storage;
		};

		return storages;
	}
})();<commit_msg>Storage information initialization refactoring<commit_after>var getStorage = (function () {
	function StorageInfo(allStorages, parameters) {
		this._parameters = $.extend({
			isAvailable: false,
			handler: null
		}, parameters);

		this._allStorages = allStorages;
	}

	Object.defineProperty(StorageInfo.prototype, 'storageId', {
		get: function () { return this._parameters.storageId; }
	});

	Object.defineProperty(StorageInfo.prototype, 'isAvailable', {
		get: function () { return this._parameters.isAvailable; }
	});

	Object.defineProperty(StorageInfo.prototype, 'handler', {
		get: function () { return this._parameters.handler; }
	});

	Object.defineProperty(StorageInfo.prototype, 'elId', {
		get: function () { return this._parameters.elId; }
	});

	Object.defineProperty(StorageInfo.prototype, 'uri', {
		get: function () { return this._parameters.uri; }
	});

	Object.defineProperty(StorageInfo.prototype, 'title', {
		get: function () { return this._parameters.title; }
	});

	Object.defineProperty(StorageInfo.prototype, 'contentType', {
		get: function () { return this._parameters.contentType; }
	});

	StorageInfo.prototype.setDeviceHandler = function (handler, isAvailable, onloaded) {
		this._parameters.handler = handler;
		this._parameters.isAvailable = isAvailable;

		if (this._allStorages.isLoaded()) {
			onloaded();
		}
	};

	// Storage configuration

	return function() {
		var storages = {}

		storages.SDCard = new StorageInfo(storages, {
			storageId: 'sdcard',
			elId: '#sdcard-storage',
			uri: '#sdcard',
			title: 'SD Card',
			contentType: 'application/octet-stream'
		});

		storages.Pictures = new StorageInfo(storages, {
			storageId: 'pictures',
			elId: '#pictires-storage',
			uri: '#pictures',
			title: 'My Pictures',
			contentType: 'image/jpeg'
		});

		storages.Music = new StorageInfo(storages, {
			storageId: 'music',
			elId: '#music-storage',
			uri: '#music',
			title: 'My Music',
			contentType: 'audio/mpeg'
		});

		storages.Videos = new StorageInfo(storages, {
			storageId: 'videos',
			elId: '#videos-storage',
			uri: '#videos',
			title: 'My Videos',
			contentType: 'video/mpeg'
		});

		storages.isLoaded = function () {
				return this.SDCard.handler !== null &&
						this.Pictures.handler !== null &&
						this.Music.handler !== null &&
						this.Videos.handler !== null;
			};

		storages.getDeviceStorages = function () {
			var deviceStorages = _.filter(this, function (storage) {
				return !_.isFunction(storage);
			});

			return deviceStorages;
		};

		storages.findStorageByUri = function (uri) {
			var storage = _.find(this, function (storage) {
				return !_.isFunction(storage) && storage.uri === uri;
			});

			return storage;
		};

		return storages;
	}
})();<|endoftext|>


<commit_before>var x_timer;
var ip ='';
var geo ='';

$('#search').bind("keyup blur", function (event){

var exclud = [13,27,37,38,39,40];
clearTimeout(x_timer);

	x_timer = setTimeout(function(){
	if (exclud.indexOf(event.which) === -1) {

		var url = 'http://api.openweathermap.org/data/2.5/weather?q='+ $('#q').val()+'&units=metric&appid=2de143494c0b295cca9337e1e96b00e0';
		$('.var').empty();
	    $.get(url, function(data){
		  var temp = data.main.temp;
		  var winddir = degToCompass(data.wind.deg);
		  var speed = data.wind.speed;
		  var icon = data.weather[0].icon;
		  var city = data.name+','+data.sys.country;

		$('.icon').attr("src","http://openweathermap.org/img/w/"+icon+".png");
		$('.temp').html(temp);
		$('.wind').html(' Direction : '+winddir+' Speed: '+speed);
		$('.city').html(city);

	 });

}
}, 300);
});

    /*var urlip = 'https://api.ipify.org/?format=json';
    $.get(urlip, function(ipdata){
    	var ip = ipdata.ip;
    });
    if(ip!=''){
    var urlgeo = 'http://freegeoip.net/json/'+ip;
    $.get(urlgeo, function(geodata){
    	geo = geodata.city;
    	var code = geodata.country_code;
    	if(geo!=''){
    		$('.yourcity').html(geo);
    		$('.clic').html('<==== Just Click if this is your City!');
    		var newurl = 'http://api.openweathermap.org/data/2.5/weather?q='+geo+','+code+'&units=metric&appid=2de143494c0b295cca9337e1e96b00e0';
    		$('a').on("click",function(e){

    		$.get(url, function(data){
		  var temp = data.main.temp;
		  var winddir = degToCompass(data.wind.deg);
		  var speed = data.wind.speed;
		  var icon = data.weather[0].icon;

		$('.icon').attr("src","http://openweathermap.org/img/w/"+icon+".png");
		$('.temp').html(temp);
		$('.wind').html(' Direction : '+winddir+' Speed: '+speed);

	 });

    		});
    	}
    });
    }*/

window.onload = function() {
  document.getElementById("q").focus();
};

function degToCompass(num) {
    var val = Math.floor((num / 22.5) + 0.5);
    var arr = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"];
    return arr[(val % 16)];
}
<commit_msg>Update weather.js<commit_after>var x_timer;
var ip ='';
var geo ='';

$('#search').bind("keyup blur", function (event){

var exclud = [13,27,37,38,39,40];
clearTimeout(x_timer);

	x_timer = setTimeout(function(){
	if (exclud.indexOf(event.which) === -1) {

		var url = 'http://api.openweathermap.org/data/2.5/weather?q='+ $('#q').val()+'&units=metric&appid=44db6a862fba0b067b1930da0d769e98';
		$('.var').empty();
	    $.get(url, function(data){
		  var temp = data.main.temp;
		  var winddir = degToCompass(data.wind.deg);
		  var speed = data.wind.speed;
		  var icon = data.weather[0].icon;
		  var city = data.name+','+data.sys.country;

		$('.icon').attr("src","http://openweathermap.org/img/w/"+icon+".png");
		$('.temp').html(temp);
		$('.wind').html(' Direction : '+winddir+' Speed: '+speed);
		$('.city').html(city);

	 });

}
}, 300);
});

    /*var urlip = 'https://api.ipify.org/?format=json';
    $.get(urlip, function(ipdata){
    	var ip = ipdata.ip;
    });
    if(ip!=''){
    var urlgeo = 'http://freegeoip.net/json/'+ip;
    $.get(urlgeo, function(geodata){
    	geo = geodata.city;
    	var code = geodata.country_code;
    	if(geo!=''){
    		$('.yourcity').html(geo);
    		$('.clic').html('<==== Just Click if this is your City!');
    		var newurl = 'http://api.openweathermap.org/data/2.5/weather?q='+geo+','+code+'&units=metric&appid=2de143494c0b295cca9337e1e96b00e0';
    		$('a').on("click",function(e){

    		$.get(url, function(data){
		  var temp = data.main.temp;
		  var winddir = degToCompass(data.wind.deg);
		  var speed = data.wind.speed;
		  var icon = data.weather[0].icon;

		$('.icon').attr("src","http://openweathermap.org/img/w/"+icon+".png");
		$('.temp').html(temp);
		$('.wind').html(' Direction : '+winddir+' Speed: '+speed);

	 });

    		});
    	}
    });
    }*/

window.onload = function() {
  document.getElementById("q").focus();
};

function degToCompass(num) {
    var val = Math.floor((num / 22.5) + 0.5);
    var arr = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"];
    return arr[(val % 16)];
}
<|endoftext|>


<commit_before>var setupApn = function() {
  var apnOptions = Meteor.settings.apnOptions || {},
      alertSound = apnOptions.sound || "alert.aiff",
      root = process.env.PWD

  apnOptions = _.extend({
    cert: process.env.APNS_CERT,
    key: process.env.APNS_KEY,
    production: true
  }, apnOptions)

  return new Apn.Connection(apnOptions);
}

var setupGcm = function() {
  if(!process.env.GCM_SENDER_KEY) {
    console.log("Unable to load GCM_SENDER_KEY from env");
  }
  else {
    return new GCM.Sender(process.env.GCM_SENDER_KEY);
  }
}

var pusher = function() {
  var self = this;
  self.apns = setupApn();
  self.gcm = setupGcm();
}

_.extend(pusher.prototype, {
  pushAll: function(options) {
    var devices = Devices.find({});
    this.push(devices, options);
  },
  push: function(devices, options) {
    var apnsTokens = [];
    var gcmTokens = [];

    // extract the useful tokens from the device
    devices.forEach(function(device) {
      if(device.push && device.push.gcm) {
        gcmTokens.push(device.push.gcm);
      }
      if(device.push && device.push.apns) {
        apnsTokens.push(device.push.apns);
      }
    });

    if(gcmTokens.length > 0) this.pushGcm(gcmTokens, options);
    if(apnsTokens.length > 0) this.pushApns(apnsTokens, options);
  },
  pushGcm: function(tokens, options) {
    if(!options.text) throw Error("Must set options.text");
    if(Constants.disablePush) return;

    // set sound if available, otherwise send 'default'
    var sound = null;
    if(options.sound) {
      if(Constants.sounds.android[options.sound])
        sound = Constants.sounds.android[options.sound];
      else
        sound = 'default';
    }

    var data = options.payload || {};
    data.title = 'Lantern notification!';
    data.message = options.text;
    if(sound) data.sound = sound;
    var message = new GCM.Message({
      data: data
    });
    this.gcm.send(message, tokens, 3, function(error, result) {
      if(error) {
        console.log("Failed to send GCM: " + error);
        return;
      }
    });
  },
  pushApns: function(tokens, options) {
    var self = this;
    if(!options.text) throw Error("Must set options.text");
    if(Constants.disablePush) return;
    var notification = new Apn.Notification();
    notification.expiry = options.expiry || Math.floor(Date.now() / 1000) + 60;
    notification.alert = options.text;
    notification.payload = options.payload || {};
    if(options.sound) {
      if(Constants.sounds.ios[options.sound])
        notification.sound = Constants.sounds.ios[options.sound];
      else
        notification.sound = 'default'; // ios default sound
    }

    tokens = [].concat(tokens);
    _.each(tokens, function(token) {
      try {
        var device = new Apn.Device(token);
        self.apns.pushNotification(notification, device);
      } catch(e) {
        console.log("Unable to send APNS: " + e);
      }
    });
  }
});

Pusher = new pusher();
<commit_msg>Time out APNS connections before 4m<commit_after>var setupApn = function() {
  var apnOptions = Meteor.settings.apnOptions || {},
      alertSound = apnOptions.sound || "alert.aiff",
      root = process.env.PWD

  apnOptions = _.extend({
    cert: process.env.APNS_CERT,
    key: process.env.APNS_KEY,
    production: true,
    // Azure seems to time out connections after 4 mins :(
    connectionTimeout: 200000,
  }, apnOptions)

  return new Apn.Connection(apnOptions);
}

var setupGcm = function() {
  if(!process.env.GCM_SENDER_KEY) {
    console.log("Unable to load GCM_SENDER_KEY from env");
  }
  else {
    return new GCM.Sender(process.env.GCM_SENDER_KEY);
  }
}

var pusher = function() {
  var self = this;
  self.apns = setupApn();
  self.gcm = setupGcm();
}

_.extend(pusher.prototype, {
  pushAll: function(options) {
    var devices = Devices.find({});
    this.push(devices, options);
  },
  push: function(devices, options) {
    var apnsTokens = [];
    var gcmTokens = [];

    // extract the useful tokens from the device
    devices.forEach(function(device) {
      if(device.push && device.push.gcm) {
        gcmTokens.push(device.push.gcm);
      }
      if(device.push && device.push.apns) {
        apnsTokens.push(device.push.apns);
      }
    });

    if(gcmTokens.length > 0) this.pushGcm(gcmTokens, options);
    if(apnsTokens.length > 0) this.pushApns(apnsTokens, options);
  },
  pushGcm: function(tokens, options) {
    if(!options.text) throw Error("Must set options.text");
    if(Constants.disablePush) return;

    // set sound if available, otherwise send 'default'
    var sound = null;
    if(options.sound) {
      if(Constants.sounds.android[options.sound])
        sound = Constants.sounds.android[options.sound];
      else
        sound = 'default';
    }

    var data = options.payload || {};
    data.title = 'Lantern notification!';
    data.message = options.text;
    if(sound) data.sound = sound;
    var message = new GCM.Message({
      data: data
    });
    this.gcm.send(message, tokens, 3, function(error, result) {
      if(error) {
        console.log("Failed to send GCM: " + error);
        return;
      }
    });
  },
  pushApns: function(tokens, options) {
    var self = this;
    if(!options.text) throw Error("Must set options.text");
    if(Constants.disablePush) return;
    var notification = new Apn.Notification();
    notification.expiry = options.expiry || Math.floor(Date.now() / 1000) + 60;
    notification.alert = options.text;
    notification.payload = options.payload || {};
    if(options.sound) {
      if(Constants.sounds.ios[options.sound])
        notification.sound = Constants.sounds.ios[options.sound];
      else
        notification.sound = 'default'; // ios default sound
    }

    tokens = [].concat(tokens);
    _.each(tokens, function(token) {
      try {
        var device = new Apn.Device(token);
        self.apns.pushNotification(notification, device);
      } catch(e) {
        console.log("Unable to send APNS: " + e);
      }
    });
  }
});

Pusher = new pusher();
<|endoftext|>


<commit_before>var debug = require('debug')('instant:util')
var posix = require('posix')

var MAX_SOCKETS = 10000

exports.downgradeUid = function () {
  if (process.platform === 'linux' && process.env.NODE_ENV === 'production') {
    process.setuid('www-data')
    debug('downgraded uid to ' + process.getuid())
  }
}

exports.upgradeLimits = function () {
  posix.setrlimit('nofile', { soft: MAX_SOCKETS, hard: MAX_SOCKETS })
  var limits = posix.getrlimit('nofile')
  debug('upgraded resource limits to ' + limits.soft)
}
<commit_msg>downgrade gid<commit_after>var debug = require('debug')('instant:util')
var posix = require('posix')

var MAX_SOCKETS = 10000

exports.downgradeUid = function () {
  if (process.platform === 'linux' && process.env.NODE_ENV === 'production') {
    process.setgid('www-data')
    process.setuid('www-data')
    debug('downgraded gid (' + process.getgid() + ') uid (' + process.getuid() + ')')
  }
}

exports.upgradeLimits = function () {
  posix.setrlimit('nofile', { soft: MAX_SOCKETS, hard: MAX_SOCKETS })
  var limits = posix.getrlimit('nofile')
  debug('upgraded resource limits to ' + limits.soft)
}
<|endoftext|>


<commit_before>// common dependencies
var fs = require('fs');
var url = require('url');
var colors = require('colors');
var debug = require('debug')('hoardr:setup');

// express dependencies
var morgan = require('morgan');
var compress = require('compression');
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var methodOverride = require('method-override');
var errorHandler = require('errorhandler');
var flash = require('express-flash');

// configure express
module.exports.configureExpress = function(options, app, config) {
    // set view engine and parsers
    app.set('views', options.dir + '/views');
    app.set('view engine', 'html');
    app.engine('.html', options.handlebars.__express);

    // json pretty response
    app.set('json spaces', 2);

    // express common
    app.use(compress());
    app.use(options.express.static(options.dir + '/client/public'));
    app.use(morgan('dev'));
    app.use(options.cookieParser());
    app.use(bodyParser.urlencoded());
    app.use(bodyParser.json());
    app.use(methodOverride());
    app.use(options.session({
        secret: config.get('server.secret'),
        store: options.store,
        key: config.get('session.key')
    }));
    app.use(options.passport.initialize());
    app.use(options.passport.session());
    app.use(flash());
    app.use(favicon(options.dir + '/client/public/favicon.ico'));

    // express dev config
    if ('development' == config.get('env')) {
        app.use(errorHandler());
    }
};

// handle express errors
module.exports.handleExpressError = function(app) {
    // handle 404 not found
    app.use(function(req, res, next) {
        res.status(404);

        // respond with html page
        if (req.accepts('html')) {
            res.render('404', {
                url: req.url
            });
            return;
        }

        // respond with json
        if (req.accepts('json')) {
            res.send({
                error: 'Not found'
            });
            return;
        }

        // default to plain-text. send()
        res.type('txt').send('Not found');
    });

    // handling other errors
    app.use(function(err, req, res, next) {
        console.error(err.stack);
        res.send(500, 'Something broke!');
    });
};

// register handlebars partials
module.exports.registerPartials = function(path, handlebars) {
    var partials = path;
    fs.readdirSync(partials).forEach(function(folder) {
        var extension = folder.split('.')[1];
        if (extension != undefined) return;
        fs.readdirSync(partials + folder).forEach(function(file) {
            var extension = file.split('.')[1];
            if (extension != 'html') return;
            var source = fs.readFileSync(partials + folder + '/' + file, "utf8");
            var partial = folder + '-' + file.split('.')[0];
            handlebars.registerPartial(partial, source);
        });
    });
};

// register handlebars block helpers
module.exports.registerHelpers = function(helpers, handlebars) {
    for (var helper in helpers) {
        if (helpers.hasOwnProperty(helper)) {
            handlebars.registerHelper(helper, helpers[helper]);
        }
    }
    return;
};

// redis pubsub
module.exports.pubsub = function(redis, config) {
    var subscriber, publisher;

    if ('production' == config.get('env')) {
        var redisURL = url.parse(config.get('database.redis.url'));
        subscriber = redis.createClient(redisURL.port, redisURL.hostname, { no_ready_check: true });
        publisher = redis.createClient(redisURL.port, redisURL.hostname, { no_ready_check: true });
        if (redisURL.auth) subscriber.auth(redisURL.auth.split(":")[1]);
        if (redisURL.auth) publisher.auth(redisURL.auth.split(":")[1]);
    } else {
        subscriber = redis.createClient();
        publisher = redis.createClient();
    }

    return {
        subscriber: subscriber,
        publisher: publisher
    };
};

// create session store
module.exports.sessions = function(SessionStore, config) {
    var authObject;

    if (config.get('database.redis.url')) {
        var parsedUrl = url.parse(config.get('database.redis.url'));
        authObject = {
            prefix: config.get('database.redis.prefix'),
            host: parsedUrl.hostname,
            port: parsedUrl.port,
            db: config.get('database.redis.db'),
            pass: parsedUrl.auth ? parsedUrl.auth.split(":")[1] : null,
            secret: config.get('server.secret')
        };
    }

    return new SessionStore(authObject);
};

// connect to backend store (db)
module.exports.db = function(mongoose, config) {
    function connect() {
        mongoose.connect(config.get('database.mongo.url'));
    }

    // connection is open and ready
    mongoose.connection.on('open', function(ref) {
        debug('open connection to mongo server.');
    });

    // mongoose is connected to server
    mongoose.connection.on('connected', function(ref) {
        debug('connected to mongo server.');
    });

    // mongoose has disconnected
    mongoose.connection.on('disconnected', function(ref) {
        debug('disconnected from mongo server.');
        debug('retrying connection in 2 seconds..');

        setTimeout(function() {
            connect();
        }.bind(this), 2000);
    });

    // mongoose connection has closed
    mongoose.connection.on('close', function(ref) {
        debug('closed connection to mongo server');
    });

    // error has occured for mongoose connection
    mongoose.connection.on('error', function(err) {
        debug('error connection to mongo server!');
        debug(err);
    });

    // mongoose is reconnecting
    mongoose.connection.on('reconnect', function(ref) {
        debug('reconnect to mongo server.');
    });

    // initial connect
    connect();
};

// run application
module.exports.run = function(server, config) {
    server.listen(config.get('server.port'), function() {
        debug('listening on port %d'.green, server.address().port);
    });
};
<commit_msg>move icons into subfolder<commit_after>// common dependencies
var fs = require('fs');
var url = require('url');
var colors = require('colors');
var debug = require('debug')('hoardr:setup');

// express dependencies
var morgan = require('morgan');
var compress = require('compression');
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var methodOverride = require('method-override');
var errorHandler = require('errorhandler');
var flash = require('express-flash');

// configure express
module.exports.configureExpress = function(options, app, config) {
    // set view engine and parsers
    app.set('views', options.dir + '/views');
    app.set('view engine', 'html');
    app.engine('.html', options.handlebars.__express);

    // json pretty response
    app.set('json spaces', 2);

    // express common
    app.use(compress());
    app.use(options.express.static(options.dir + '/client/public'));
    app.use(morgan('dev'));
    app.use(options.cookieParser());
    app.use(bodyParser.urlencoded());
    app.use(bodyParser.json());
    app.use(methodOverride());
    app.use(options.session({
        secret: config.get('server.secret'),
        store: options.store,
        key: config.get('session.key')
    }));
    app.use(options.passport.initialize());
    app.use(options.passport.session());
    app.use(flash());
    app.use(favicon(options.dir + '/client/public/images/icon/favicon.ico'));

    // express dev config
    if ('development' == config.get('env')) {
        app.use(errorHandler());
    }
};

// handle express errors
module.exports.handleExpressError = function(app) {
    // handle 404 not found
    app.use(function(req, res, next) {
        res.status(404);

        // respond with html page
        if (req.accepts('html')) {
            res.render('404', {
                url: req.url
            });
            return;
        }

        // respond with json
        if (req.accepts('json')) {
            res.send({
                error: 'Not found'
            });
            return;
        }

        // default to plain-text. send()
        res.type('txt').send('Not found');
    });

    // handling other errors
    app.use(function(err, req, res, next) {
        console.error(err.stack);
        res.send(500, 'Something broke!');
    });
};

// register handlebars partials
module.exports.registerPartials = function(path, handlebars) {
    var partials = path;
    fs.readdirSync(partials).forEach(function(folder) {
        var extension = folder.split('.')[1];
        if (extension != undefined) return;
        fs.readdirSync(partials + folder).forEach(function(file) {
            var extension = file.split('.')[1];
            if (extension != 'html') return;
            var source = fs.readFileSync(partials + folder + '/' + file, "utf8");
            var partial = folder + '-' + file.split('.')[0];
            handlebars.registerPartial(partial, source);
        });
    });
};

// register handlebars block helpers
module.exports.registerHelpers = function(helpers, handlebars) {
    for (var helper in helpers) {
        if (helpers.hasOwnProperty(helper)) {
            handlebars.registerHelper(helper, helpers[helper]);
        }
    }
    return;
};

// redis pubsub
module.exports.pubsub = function(redis, config) {
    var subscriber, publisher;

    if ('production' == config.get('env')) {
        var redisURL = url.parse(config.get('database.redis.url'));
        subscriber = redis.createClient(redisURL.port, redisURL.hostname, { no_ready_check: true });
        publisher = redis.createClient(redisURL.port, redisURL.hostname, { no_ready_check: true });
        if (redisURL.auth) subscriber.auth(redisURL.auth.split(":")[1]);
        if (redisURL.auth) publisher.auth(redisURL.auth.split(":")[1]);
    } else {
        subscriber = redis.createClient();
        publisher = redis.createClient();
    }

    return {
        subscriber: subscriber,
        publisher: publisher
    };
};

// create session store
module.exports.sessions = function(SessionStore, config) {
    var authObject;

    if (config.get('database.redis.url')) {
        var parsedUrl = url.parse(config.get('database.redis.url'));
        authObject = {
            prefix: config.get('database.redis.prefix'),
            host: parsedUrl.hostname,
            port: parsedUrl.port,
            db: config.get('database.redis.db'),
            pass: parsedUrl.auth ? parsedUrl.auth.split(":")[1] : null,
            secret: config.get('server.secret')
        };
    }

    return new SessionStore(authObject);
};

// connect to backend store (db)
module.exports.db = function(mongoose, config) {
    function connect() {
        mongoose.connect(config.get('database.mongo.url'));
    }

    // connection is open and ready
    mongoose.connection.on('open', function(ref) {
        debug('open connection to mongo server.');
    });

    // mongoose is connected to server
    mongoose.connection.on('connected', function(ref) {
        debug('connected to mongo server.');
    });

    // mongoose has disconnected
    mongoose.connection.on('disconnected', function(ref) {
        debug('disconnected from mongo server.');
        debug('retrying connection in 2 seconds..');

        setTimeout(function() {
            connect();
        }.bind(this), 2000);
    });

    // mongoose connection has closed
    mongoose.connection.on('close', function(ref) {
        debug('closed connection to mongo server');
    });

    // error has occured for mongoose connection
    mongoose.connection.on('error', function(err) {
        debug('error connection to mongo server!');
        debug(err);
    });

    // mongoose is reconnecting
    mongoose.connection.on('reconnect', function(ref) {
        debug('reconnect to mongo server.');
    });

    // initial connect
    connect();
};

// run application
module.exports.run = function(server, config) {
    server.listen(config.get('server.port'), function() {
        debug('listening on port %d'.green, server.address().port);
    });
};
<|endoftext|>


<commit_before>	/*!
	 * JS Redirection Mobile
	 *
	 * Developed by
	 * Sebastiano Armeli-Battana (@sebarmeli) - http://sebarmeli.com
	 */

	/*
	 * This script will cover a basic scenario of full JS mobile redirection.
	 * The user will be redirected to the mobile version of the site (home page)
	 * if it's trying to access the site from a mobile device. This check is
	 * mainly done checking the User-Agent string.
	 * The mobile URL will be obtained appending a prefix (default is "m")) to
	 * the hostname of the current URL.
	 *
	 * In same case the user needs to be redirected to the Desktop version of
	 * the site from a mobile device. To achieve that, a possible solution is
	 * appending a parameter to the URL (default one is "isDesktopRedirection=true").
	 * In that case a cookie will be set up and until the cookie exists the user
	 * will access to the desktop version from a mobile device (default expiry
	 * time is one hour after he creation of the cookie) even without the
	 * parameter appended.
     *
	 * The function is attached to the window scope, mainly for testing purpose,
	 * but you can avoid that, creating an anonymous self-executing function.
	 *
	 * @param document
	 * @param navigator
	 * @param object containing two fields: param (parameter to be passed to avoid
	 *             mobile redirection), mobile_prefix (prefix appended to the
	 *             hostname)
	 * @author Sebastiano Armeli-Battana
	 * @version 0.1
	 *
	 */

	/*globals window, redirection_mobile, document, navigator, location */
	window.redirection_mobile = function(document, navigator, object) {

		// Retrieve the User Agent of the browser
		var agent = navigator.userAgent.toLowerCase(),

		// param value or default value
		param = object.param || "isDesktopRedirection=true",

		//"m" is the default mobile hostname prefix
		mobile_prefix = object.mobile_prefix || "m",

		// Retrieve the querystring
		search = document.location.search,

		// Check if the UA is a mobile one
		isUAMobile = !!(agent.match(/iPhone/i) || agent.match(/iPod/i) ||
						agent.match(/blackberry/i) || agent.match(/android/i)),

		// Check if the Cookie has been set up
		isCookieSet = document.cookie ?
						(document.cookie.indexOf(param) >= 0) :
						false,

		// Check that there is the parameter to redirect to desktop version
		isParameterSet = (search.indexOf(param) > 0);

		// Helper function
		var addTimeToDate = function(msec) {

			// Get the current date
			var exdate = new Date();

			// Add time to the date
			exdate.setTime(exdate.getTime() + msec);

			//Return the new Date
			return exdate;

		};

		// Check that User Agent is mobile, cookie is not set and parameter not present
		if (isUAMobile && !isCookieSet && !isParameterSet) {
		   document.location.href = document.location.protocol + "//" + mobile_prefix +
										"."+ document.location.host;
		}

		// Set the cookie in case the parameter is present
		else if (isParameterSet && isUAMobile && !isCookieSet) {
			document.cookie = param + ";expires="+
												addTimeToDate(3600*1000).toUTCString();
		}

	};	<commit_msg>Script taking care of the redirection<commit_after>	/*!
	 * JS Redirection Mobile
	 *
	 * Developed by
	 * Sebastiano Armeli-Battana (@sebarmeli) - http://sebarmeli.com
	 */

	/*
	 * This script will cover a basic scenario of full JS mobile redirection.
	 * The user will be redirected to the mobile version of the site (home page)
	 * if it's trying to access the site from a mobile device. This check is
	 * mainly done checking the User-Agent string.
	 * The mobile URL will be obtained appending a prefix (default is "m") to
	 * the hostname of the current URL.
	 *
	 * In same case the user needs to be redirected to the Desktop version of
	 * the site from a mobile device. To achieve that, a possible solution is
	 * appending a parameter to the URL (default one is "isDesktopRedirection=true").
	 * In that case a cookie will be set up and until the cookie exists the user
	 * will access to the desktop version from a mobile device (default expiry
	 * time is one hour after he creation of the cookie) even without the
	 * parameter appended.
     *
	 * The function is attached to the window scope, mainly for testing purpose,
	 * but you can avoid that, creating an anonymous self-executing function.
	 *
	 * @param document
	 * @param navigator
	 * @param object containing two fields: param (parameter to be passed to avoid
	 *             mobile redirection), mobile_prefix (prefix appended to the
	 *             hostname)
	 * @author Sebastiano Armeli-Battana
	 * @version 0.1
	 *
	 */

	/*globals window, redirection_mobile, document, navigator, location */
	window.redirection_mobile = function(document, navigator, object) {

		// Retrieve the User Agent of the browser
		var agent = navigator.userAgent.toLowerCase(),

		// param value or default value
		param = object.param || "isDesktopRedirection=true",

		//"m" is the default mobile hostname prefix
		mobile_prefix = object.mobile_prefix || "m",

		// Retrieve the querystring
		search = document.location.search,

		// Check if the UA is a mobile one
		isUAMobile = !!(agent.match(/iPhone/i) || agent.match(/iPod/i) ||
						agent.match(/blackberry/i) || agent.match(/android/i)),

		// Check if the Cookie has been set up
		isCookieSet = document.cookie ?
						(document.cookie.indexOf(param) >= 0) :
						false,

		// Check that there is the parameter to redirect to desktop version
		isParameterSet = (search.indexOf(param) > 0);

		// Helper function
		var addTimeToDate = function(msec) {

			// Get the current date
			var exdate = new Date();

			// Add time to the date
			exdate.setTime(exdate.getTime() + msec);

			//Return the new Date
			return exdate;

		};

		// Check that User Agent is mobile, cookie is not set and parameter not present
		if (isUAMobile && !isCookieSet && !isParameterSet) {
		   document.location.href = document.location.protocol + "//" + mobile_prefix +
										"."+ document.location.host;
		}

		// Set the cookie in case the parameter is present
		else if (isParameterSet && isUAMobile && !isCookieSet) {
			document.cookie = param + ";expires="+
												addTimeToDate(3600*1000).toUTCString();
		}

	};	<|endoftext|>


<commit_before>/*
 * Allow you smoothly surf on many websites blocking non-mainland visitors.
 * Copyright (C) 2012, 2013 Bo Zhu http://zhuzhu.org
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

var unblock_youku = unblock_youku || {};  // namespace

// for both chrome extension and server
unblock_youku.common_urls = [
    'http://v.youku.com/player/*',
    'http://api.youku.com/player/*',
    'http://v2.tudou.com/*',
    'http://www.tudou.com/a/*',
    'http://www.tudou.com/v/*',
    'http://s.plcloud.music.qq.com/fcgi-bin/p.fcg*',
    'http://hot.vrs.sohu.com/*',
    'http://live.tv.sohu.com/live/player*',
    'http://hot.vrs.letv.com/*',
    //'http://g3.letv.cn/*',
    'http://data.video.qiyi.com/*',

    // cause oversea servers unusable?
    // 'http://interface.bilibili.tv/player*',

    'http://220.181.61.229/*',
    'http://61.135.183.45/*',
    'http://61.135.183.46/*',
    'http://220.181.19.218/*',
    'http://220.181.61.213/*',
    'http://220.181.118.181/*',
    'http://123.126.48.47/*',
    'http://123.126.48.48/*',

    'http://vv.video.qq.com/*',
    'http://tt.video.qq.com/getinfo*',
    'http://ice.video.qq.com/getinfo*',
    'http://tjsa.video.qq.com/getinfo*',
    'http://a10.video.qq.com/getinfo*',
    'http://xyy.video.qq.com/getinfo*',
    'http://vcp.video.qq.com/getinfo*',
    'http://vsh.video.qq.com/getinfo*',
    'http://vbj.video.qq.com/getinfo*',
    'http://bobo.video.qq.com/getinfo*',
    'http://flvs.video.qq.com/getinfo*',

    'http://geo.js.kankan.xunlei.com/*',
    'http://web-play.pptv.com/*',
    'http://web-play.pplive.cn/*',
    // 'http://c1.pptv.com/*',
    'http://dyn.ugc.pps.tv/*',
    'http://inner.kandian.com/*',
    'http://ipservice.163.com/*',
    'http://zb.s.qq.com/*',
    'http://ip.kankan.xunlei.com/*',
    'http://vxml.56.com/json/*',

    'http://music.sina.com.cn/yueku/intro/*',
    //'http://ting.baidu.com/data/music/songlink*',
    //'http://ting.baidu.com/data/music/songinfo*',
    //'http://ting.baidu.com/song/*/download*',
    'http://music.sina.com.cn/radio/port/webFeatureRadioLimitList.php*',
    'http://play.baidu.com/data/music/songlink*',

    'http://v.iask.com/v_play.php*',
    'http://v.iask.com/v_play_ipad.cx.php*',
    'http://tv.weibo.com/player/*',

    //'http://kandian.com/player/getEpgInfo*',  // !!!
    //'http://cdn.kandian.com/*',
    'http://www.yinyuetai.com/insite/*',
    'http://www.yinyuetai.com/main/get-video-info*',

    'http://*.dpool.sina.com.cn/iplookup*',
    'http://*/vrs_flash.action*',
    'http://*/?prot=2&type=1*',
    'http://*/?prot=2&file=/*',
    'http://api.letv.com/streamblock*',
    'http://api.letv.com/mms/out/video/play*',
    'http://live.gslb.letv.com/gslb?*',
    'http://vdn.apps.cntv.cn/api/get*'
];

// only for chrome extension
unblock_youku.chrome_extra_urls = [
    // 'http://www.tudou.com/programs/view/*',
    // 'http://www.tudou.com/albumplay/*',
    // 'http://www.tudou.com/listplay/*',

    'http://live.video.sina.com.cn/room/*',
    'http://edge.v.iask.com/*',  // may be large files

    'http://pay.youku.com/buy/redirect.html*',
    'http://pay.video.qq.com/fcgi-bin/paylimit*',

    'http://play.baidu.com/*',
    'http://zhangmenshiting.baidu.com/*',
    'http://music.baidu.com/box*',
    'http://music.baidu.com/data/music/songlink*',
    'http://music.baidu.com/data/music/songinfo*',
    'http://music.baidu.com/data/music/fmlink*',
    'http://music.baidu.com/song/*/download*',
    'http://fm.baidu.com/*',
    'http://www.kugou.com/*',
    'http://music.baidu.com/data/user/collect*',

    'http://d.dxy.cn/*',
    'http://ac.qq.com/*/v/cid/*',
    'http://v.pptv.com/show/*.html',
    'http://www.songtaste.com/*',
    'http://songtaste.com/*',
    'http://www.yyets.com/*',
    'http://imanhua.com/comic/*',
    'http://www.imanhua.com/comic/*',
    'http://imanhua.com/v2*',
    'http://www.imanhua.com/v2*'
];

// only for server
unblock_youku.server_extra_urls = [
    // for Mobile apps    // Video apps
    'http://api.3g.youku.com/layout*',
    'http://api.3g.youku.com/v3/play/address*',
    'http://api.3g.youku.com/openapi-wireless/videos/*/download*',
    'http://api.3g.youku.com/videos/*/download*',
    'http://api.3g.youku.com/common/v3/play*',
    'http://play.api.3g.tudou.com/v*',
    'http://api.3g.tudou.com/*',
    'http://api.tv.sohu.com/mobile_user/device/clientconf.json?*',
    'http://access.tv.sohu.com/*',
    'http://iface2.iqiyi.com/php/xyz/iface/*',
    'http://dynamic.app.m.letv.com/*/dynamic.php?*playid*',
    'http://listso.m.areainfo.ppstream.com/ip/q.php*',
    'http://api.letv.com/getipgeo',
    'http://m.letv.com/api/geturl?*',
    // Music apps
    'http://3g.music.qq.com/*',
    'http://mqqplayer.3g.qq.com/*',
    'http://proxy.music.qq.com/*',
    'http://ip2.kugou.com/check/isCn/*',
    'http://ip.kugou.com/check/isCn/*',
    'http://client.api.ttpod.com/global*',
    'http://mobi.kuwo.cn/*',
    'http://mobilefeedback.kugou.com/*',
    'http://tingapi.ting.baidu.com/v1/restserver/ting?*method=baidu.ting.song*',
    'http://serviceinfo.sdk.duomi.com/api/serviceinfo/getserverlist*',
    // for PC Clients only
    'http://iplocation.geo.qiyi.com/cityjson',
    'http://sns.video.qq.com/tunnel/fcgi-bin/tunnel*',
    'http://v5.pc.duomi.com/single-ajaxsingle-isban*',
    'https://openapi.youku.com/*',  // see issue #118
    'https://61.135.196.99/*', //n-openapi.youku.com
    'https://220.181.185.150/*', //zw-openapi.youku.com
    'https://httpbin.org/get',  // for testing
    // for 3rd party's DNS for Apple TV (see pull request #78)
    'http://180.153.225.136/*',
    'http://118.244.244.124/*',
    'http://210.129.145.150/*',
];

function urls2regexs(url_list) {
    "use strict";

    var regex_list = [];

    var i, re_str;
    for (i = 0; i < url_list.length; i++) {
        re_str = url_list[i].replace(/\//g, '\\/');
        re_str = re_str.replace(/\./g, '\\.');
        re_str = re_str.replace(/\*/g, '.*');
        // make the first * matches only domain names or ip addresses
        // just as http://developer.chrome.com/extensions/match_patterns.html
        re_str = re_str.replace(/^http:\\\/\\\/\.\*/i, 'http:\/\/[^\/]*');
        regex_list.push(new RegExp('^' + re_str, 'i'));
    }

    return regex_list;
}

// also export as a node.js module
var exports = exports || {};
exports.url_list = unblock_youku.common_urls.concat(unblock_youku.server_extra_urls);
exports.url_regex_list = urls2regexs(exports.url_list);
<commit_msg>Fix #143 youku mobile app<commit_after>/*
 * Allow you smoothly surf on many websites blocking non-mainland visitors.
 * Copyright (C) 2012, 2013 Bo Zhu http://zhuzhu.org
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

var unblock_youku = unblock_youku || {};  // namespace

// for both chrome extension and server
unblock_youku.common_urls = [
    'http://v.youku.com/player/*',
    'http://api.youku.com/player/*',
    'http://v2.tudou.com/*',
    'http://www.tudou.com/a/*',
    'http://www.tudou.com/v/*',
    'http://s.plcloud.music.qq.com/fcgi-bin/p.fcg*',
    'http://hot.vrs.sohu.com/*',
    'http://live.tv.sohu.com/live/player*',
    'http://hot.vrs.letv.com/*',
    //'http://g3.letv.cn/*',
    'http://data.video.qiyi.com/*',

    // cause oversea servers unusable?
    // 'http://interface.bilibili.tv/player*',

    'http://220.181.61.229/*',
    'http://61.135.183.45/*',
    'http://61.135.183.46/*',
    'http://220.181.19.218/*',
    'http://220.181.61.213/*',
    'http://220.181.118.181/*',
    'http://123.126.48.47/*',
    'http://123.126.48.48/*',

    'http://vv.video.qq.com/*',
    'http://tt.video.qq.com/getinfo*',
    'http://ice.video.qq.com/getinfo*',
    'http://tjsa.video.qq.com/getinfo*',
    'http://a10.video.qq.com/getinfo*',
    'http://xyy.video.qq.com/getinfo*',
    'http://vcp.video.qq.com/getinfo*',
    'http://vsh.video.qq.com/getinfo*',
    'http://vbj.video.qq.com/getinfo*',
    'http://bobo.video.qq.com/getinfo*',
    'http://flvs.video.qq.com/getinfo*',

    'http://geo.js.kankan.xunlei.com/*',
    'http://web-play.pptv.com/*',
    'http://web-play.pplive.cn/*',
    // 'http://c1.pptv.com/*',
    'http://dyn.ugc.pps.tv/*',
    'http://inner.kandian.com/*',
    'http://ipservice.163.com/*',
    'http://zb.s.qq.com/*',
    'http://ip.kankan.xunlei.com/*',
    'http://vxml.56.com/json/*',

    'http://music.sina.com.cn/yueku/intro/*',
    //'http://ting.baidu.com/data/music/songlink*',
    //'http://ting.baidu.com/data/music/songinfo*',
    //'http://ting.baidu.com/song/*/download*',
    'http://music.sina.com.cn/radio/port/webFeatureRadioLimitList.php*',
    'http://play.baidu.com/data/music/songlink*',

    'http://v.iask.com/v_play.php*',
    'http://v.iask.com/v_play_ipad.cx.php*',
    'http://tv.weibo.com/player/*',

    //'http://kandian.com/player/getEpgInfo*',  // !!!
    //'http://cdn.kandian.com/*',
    'http://www.yinyuetai.com/insite/*',
    'http://www.yinyuetai.com/main/get-video-info*',

    'http://*.dpool.sina.com.cn/iplookup*',
    'http://*/vrs_flash.action*',
    'http://*/?prot=2&type=1*',
    'http://*/?prot=2&file=/*',
    'http://api.letv.com/streamblock*',
    'http://api.letv.com/mms/out/video/play*',
    'http://live.gslb.letv.com/gslb?*',
    'http://vdn.apps.cntv.cn/api/get*'
];

// only for chrome extension
unblock_youku.chrome_extra_urls = [
    // 'http://www.tudou.com/programs/view/*',
    // 'http://www.tudou.com/albumplay/*',
    // 'http://www.tudou.com/listplay/*',

    'http://live.video.sina.com.cn/room/*',
    'http://edge.v.iask.com/*',  // may be large files

    'http://pay.youku.com/buy/redirect.html*',
    'http://pay.video.qq.com/fcgi-bin/paylimit*',

    'http://play.baidu.com/*',
    'http://zhangmenshiting.baidu.com/*',
    'http://music.baidu.com/box*',
    'http://music.baidu.com/data/music/songlink*',
    'http://music.baidu.com/data/music/songinfo*',
    'http://music.baidu.com/data/music/fmlink*',
    'http://music.baidu.com/song/*/download*',
    'http://fm.baidu.com/*',
    'http://www.kugou.com/*',
    'http://music.baidu.com/data/user/collect*',

    'http://d.dxy.cn/*',
    'http://ac.qq.com/*/v/cid/*',
    'http://v.pptv.com/show/*.html',
    'http://www.songtaste.com/*',
    'http://songtaste.com/*',
    'http://www.yyets.com/*',
    'http://imanhua.com/comic/*',
    'http://www.imanhua.com/comic/*',
    'http://imanhua.com/v2*',
    'http://www.imanhua.com/v2*'
];

// only for server
unblock_youku.server_extra_urls = [
    // for Mobile apps    // Video apps
    'http://api.3g.youku.com/layout*',
    'http://api.3g.youku.com/v3/play/address*',
    'http://api.3g.youku.com/openapi-wireless/videos/*/download*',
    'http://api.3g.youku.com/videos/*/download*',
    'http://api.3g.youku.com/common/v3/play*',
    'http://play.api.3g.youku.com/v3/play/address*',
    'http://play.api.3g.tudou.com/v*',
    'http://api.3g.tudou.com/*',
    'http://api.tv.sohu.com/mobile_user/device/clientconf.json?*',
    'http://access.tv.sohu.com/*',
    'http://iface2.iqiyi.com/php/xyz/iface/*',
    'http://dynamic.app.m.letv.com/*/dynamic.php?*playid*',
    'http://listso.m.areainfo.ppstream.com/ip/q.php*',
    'http://api.letv.com/getipgeo',
    'http://m.letv.com/api/geturl?*',
    // Music apps
    'http://3g.music.qq.com/*',
    'http://mqqplayer.3g.qq.com/*',
    'http://proxy.music.qq.com/*',
    'http://ip2.kugou.com/check/isCn/*',
    'http://ip.kugou.com/check/isCn/*',
    'http://client.api.ttpod.com/global*',
    'http://mobi.kuwo.cn/*',
    'http://mobilefeedback.kugou.com/*',
    'http://tingapi.ting.baidu.com/v1/restserver/ting?*method=baidu.ting.song*',
    'http://serviceinfo.sdk.duomi.com/api/serviceinfo/getserverlist*',
    // for PC Clients only
    'http://iplocation.geo.qiyi.com/cityjson',
    'http://sns.video.qq.com/tunnel/fcgi-bin/tunnel*',
    'http://v5.pc.duomi.com/single-ajaxsingle-isban*',
    'https://openapi.youku.com/*',  // see issue #118
    'https://61.135.196.99/*', //n-openapi.youku.com
    'https://220.181.185.150/*', //zw-openapi.youku.com
    'https://httpbin.org/get',  // for testing
    // for 3rd party's DNS for Apple TV (see pull request #78)
    'http://180.153.225.136/*',
    'http://118.244.244.124/*',
    'http://210.129.145.150/*',
];

function urls2regexs(url_list) {
    "use strict";

    var regex_list = [];

    var i, re_str;
    for (i = 0; i < url_list.length; i++) {
        re_str = url_list[i].replace(/\//g, '\\/');
        re_str = re_str.replace(/\./g, '\\.');
        re_str = re_str.replace(/\*/g, '.*');
        // make the first * matches only domain names or ip addresses
        // just as http://developer.chrome.com/extensions/match_patterns.html
        re_str = re_str.replace(/^http:\\\/\\\/\.\*/i, 'http:\/\/[^\/]*');
        regex_list.push(new RegExp('^' + re_str, 'i'));
    }

    return regex_list;
}

// also export as a node.js module
var exports = exports || {};
exports.url_list = unblock_youku.common_urls.concat(unblock_youku.server_extra_urls);
exports.url_regex_list = urls2regexs(exports.url_list);
<|endoftext|>


<commit_before>module.exports = {
    "globals": {
        "ts-jest": {
            "diagnostics": true,
            "tsConfig": "<rootDir>/tsconfig.spec.json"
        },
    },
    "testPathIgnorePatterns": [
        "<rootDir>/.c9/", "<rootDir>/node_modules/"
    ],
    "transform": {
        "^.+\\.tsx?$": "ts-jest"
    },
    "testRegex": "(/spec/.*|(\\.|/)(test|spec))\\.ts?$",
    "moduleFileExtensions": [
        "ts",
        "tsx",
        "js",
        "jsx",
        "json",
        "node"
    ],
    "collectCoverage": true,
    "coverageReporters": ["text-summary"],
    "verbose": true,
    "transformIgnorePatterns": [
        "/node_modules/(?!@tsed/testing).+\\.js$"
    ]
}
<commit_msg>fixing ts-jest warning message<commit_after>module.exports = {
    "globals": {
        "ts-jest": {
            "diagnostics": true,
            "tsconfig": "<rootDir>/tsconfig.spec.json"
        },
    },
    "testPathIgnorePatterns": [
        "<rootDir>/.c9/", "<rootDir>/node_modules/"
    ],
    "transform": {
        "^.+\\.tsx?$": "ts-jest"
    },
    "testRegex": "(/spec/.*|(\\.|/)(test|spec))\\.ts?$",
    "moduleFileExtensions": [
        "ts",
        "tsx",
        "js",
        "jsx",
        "json",
        "node"
    ],
    "collectCoverage": true,
    "coverageReporters": ["text-summary"],
    "verbose": true,
    "transformIgnorePatterns": [
        "/node_modules/(?!@tsed/testing).+\\.js$"
    ]
}
<|endoftext|>


<commit_before>module.exports = {
  verbose: true,
  transform: {
    '^.+\\.(ts|tsx)?$': 'ts-jest',
    '^.+\\.(js|jsx)?$': 'babel-jest',
  },
  moduleDirectories: ['node_modules', 'src'],
  globals: {
    'ts-jest': {
      babelConfig: true,
    },
  },
};
<commit_msg>Updated Jest config<commit_after>module.exports = {
  verbose: true,
  transform: {
    '^.+\\.(ts|tsx)?$': 'ts-jest',
    '^.+\\.(js|jsx)?$': 'babel-jest',
  },
  moduleDirectories: ['node_modules', 'src'],
  globals: {
    'ts-jest': {
      babelConfig: true,
    },
  },
  coverageDirectory: "./coverage/",
  collectCoverage: true
};
<|endoftext|>


<commit_before>module.exports = {
  rootDir: '.',
  setupFilesAfterEnv: ['<rootDir>/src/__helpers__/setup.ts'],
  transform: {
    '\\.ts$': '<rootDir>/dist/index.js',
  },
  testMatch: ['<rootDir>/src/**/?(*.)+(spec|test).ts?(x)'],
  collectCoverageFrom: [
    '<rootDir>/src/**/*.ts',
    '!<rootDir>/src/**/*.d.ts',
    '!<rootDir>/src/**/*.spec.ts',
    '!<rootDir>/src/**/*.test.ts',
    '!<rootDir>/src/**/__*__/*',
  ],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
  testEnvironment: 'node',
  snapshotSerializers: ['<rootDir>/src/__serializers__/processed-source.ts'],
  cacheDirectory: '<rootDir>/.cache/unit',
}
<commit_msg>fix: test path for windows (attempt 2)<commit_after>module.exports = {
  rootDir: '.',
  setupFilesAfterEnv: ['<rootDir>/src/__helpers__/setup.ts'],
  transform: {
    '\\.ts$': '<rootDir>/dist/index.js',
  },
  testMatch: ['<rootDir>/src/**/*.spec.ts'],
  collectCoverageFrom: [
    '<rootDir>/src/**/*.ts',
    '!<rootDir>/src/**/*.d.ts',
    '!<rootDir>/src/**/*.spec.ts',
    '!<rootDir>/src/**/*.test.ts',
    '!<rootDir>/src/**/__*__/*',
  ],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
  testEnvironment: 'node',
  snapshotSerializers: ['<rootDir>/src/__serializers__/processed-source.ts'],
  cacheDirectory: '<rootDir>/.cache/unit',
}
<|endoftext|>