text
stringlengths 2
1.05M
|
|---|
/*
* Copyright (c) 2015, Groupon, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of GROUPON nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
var rc = require('rc');
var _ = require('lodash');
var getDefaults = require('./defaults');
function Config(settings) {
_.assign(this, settings);
}
Config.prototype.get = function get(path, defaultValue) {
var value = _.get(this, path, defaultValue);
if (value === undefined) {
throw new Error('Missing required config setting ' + JSON.stringify(path));
}
return value;
};
Config.prototype.getBool = function getBool(path, defaultValue) {
var value = this.get(path, defaultValue);
return value !== '0' && value !== 'false' && !!value;
};
Config.prototype.has = function has(path) {
return _.get(this, path) !== undefined;
};
Config.prototype.set = function set(path, value) {
_.set(this, path, value);
return this;
};
Config.prototype.createShallowChild = function createShallowChild(options) {
return _.extend(Object.create(this), options || {});
};
function loadConfig() {
var settings = rc('testium', getDefaults());
if (settings.app === 'null') {
settings.app = null;
}
return new Config(settings);
}
Config.default = Config;
Config.load = loadConfig;
module.exports = Config;
|
/**
* Matcher that checks to see if the actual, a Jasmine spy, was called with a
* set of parameters for each expected call.
*
* @augments jasmine.Matchers
* @example toHaveBeenCalledSequentiallyWith(
* [
* [CallOneArgOne, CallOneArgTwo],
* [CallTwoArgOne, CallTwoArgTwo],
* ...
* ]
* )
* @return bool TRUE if the match succeeded, FALSE otherwise.
*/
jasmine.Matchers.prototype.toHaveBeenCalledSequentiallyWith = function() {
var actualArgs = this.actual.argsForCall;
var expectedArgs = jasmine.util.argsToArray(arguments);
expectedArgs = expectedArgs[0];
if (!jasmine.isSpy(this.actual)) {
throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
}
var response = true;
var positiveMessage = "";
if (actualArgs.length < expectedArgs.length) {
// Function not called sufficient times
positiveMessage = "Expected spy " + this.actual.identity;
positiveMessage += " to have been called " + expectedArgs.length;
positiveMessage += " times but it was only called " + actualArgs.length + " times.";
response = false;
} else if (actualArgs.length > expectedArgs.length) {
// Function called more times than expected
positiveMessage = "Expected spy " + this.actual.identity;
positiveMessage += " to have been called " + expectedArgs.length;
positiveMessage += " time but it was actually called " + actualArgs.length + " times.";
response = false;
} else {
// For each actual arguments used in the function
for (var i = 0, length = actualArgs.length; i < length; i++) {
// And each expected argument
for (var j = 0, expectedLength = expectedArgs.length; j < expectedLength; j++) {
// If the actual argument isn't *exactly* what's expected
// then set response to FALSE, and break out of the loop.
// Sets the positive message to say which argument was wrong.
if (typeof(actualArgs[i][j]) === typeof(expectedArgs)) {
if (typeof(actualArgs) == 'function') {
continue;
} else if (typeof(actualArgs[i][j]) == 'object' && typeof(expectedArgs[i][j]) == 'object') {
if (JSON.stringify(actualArgs[i][j]) != JSON.stringify(expectedArgs[i][j])) {
response = response && false;
positiveMessage = "Expected argument set " + i + " part " + j;
positiveMessage += " to be object: " + JSON.stringify(actualArgs[i][j]);
positiveMessage += " but got: " + JSON.stringify(expectedArgs[i][j]);
}
} else if (actualArgs[i][j] !== expectedArgs[i][j]) {
response = response && false;
positiveMessage = "Expected argument set " + i + " part " + j;
positiveMessage += " to be " + expectedArgs[i][j];
positiveMessage += " but got: " + actualArgs[i][j];
break;
}
}
}
// If we've had a negative response at this point then break again.
if (response === false) {
break;
}
}
}
this.message = function() {
var invertedMessage = "Expected spy " + this.actual.identity +
" not to have been called with " + jasmine.pp(expectedArgs) +
" but it was.";
if (this.actual.callCount === 0) {
positiveMessage = "Expected spy " + this.actual.identity;
positiveMessage += " to have been called with " + jasmine.pp(expectedArgs);
positiveMessage += " but it was never called.";
}
return [positiveMessage, invertedMessage];
};
return response;
};
|
$( document ).ready(function() {
//eyes animation when page loaded
$(".bob .sponge .eye.right .pupil").animate({
left: "+=35"
}, 1000, function() {
$(this).animate({
left:10
}, 1000)
})
$(".bob .sponge .eye.left .pupil").animate({
left: "+=10"
}, 1000, function() {
$(this).animate({
left:25
}, 1000)
})
$(".all_right_hand").rotate({bind:{
click: function(){
$(this).rotate({
angle: 0,
animateTo:-80,
center: ["100%", "100%"],
duration:1000,
callback: function(){
$(this).rotate({
animateTo:0
})
}
})
}
}
});
$(".all_left_hand").rotate({bind:{
click: function(){
$(this).rotate({
angle: 0,
animateTo:80,
center: ["0%", "0%"],
duration:1000,
callback: function(){
$(this).rotate({
animateTo:0
})
}
})
}
}
});
});
|
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users');
var restaurants = require('../../app/controllers/restaurants');
// Restaurants Routes
app.route('/restaurants')
.get(restaurants.list)
.post(users.requiresLogin, restaurants.create);
app.route('/restaurants/:restaurantId')
.get(restaurants.read)
.put(users.requiresLogin, restaurants.hasAuthorization, restaurants.update)
.delete(users.requiresLogin, restaurants.hasAuthorization, restaurants.delete);
// Finish by binding the Restaurant middleware
app.param('restaurantId', restaurants.restaurantByID);
};
|
webpackJsonp([99219681209289],{434:function(t,e,n){"use strict";function u(t){return t&&t.__esModule?t:{default:t}}e.__esModule=!0;var r=n(29),l=u(r),f=n(38),o=u(f),a=n(37),d=u(a),i=n(1),c=u(i),s=function(t){function e(){return(0,l.default)(this,e),(0,o.default)(this,t.apply(this,arguments))}return(0,d.default)(e,t),e.prototype.render=function(){return c.default.createElement("div",null)},e}(c.default.Component);e.default=s}});
//# sourceMappingURL=component---node-modules-gatsby-plugin-offline-app-shell-js-5c4c5a0f7af9dc69d6d7.js.map
|
import React from 'react';
import {Breadcrumb, IconHome} from 'react-windy-ui';
export default function Bc2() {
return <>
<Breadcrumb hasBackground>
<Breadcrumb.Item>
<IconHome/> Home
</Breadcrumb.Item>
<Breadcrumb.Item>
Main
</Breadcrumb.Item>
<Breadcrumb.Item active>
Application
</Breadcrumb.Item>
</Breadcrumb>
</>;
}
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[140],{563:function(s,t,a){"use strict";a.r(t);var e=a(15),n=Object(e.a)({},(function(){var s=this,t=s.$createElement,a=s._self._c||t;return a("ContentSlotsDistributor",{attrs:{"slot-key":s.$parent.slotKey}},[a("h1",{attrs:{id:"_01-jsx简介"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_01-jsx简介"}},[s._v("#")]),s._v(" 01. JSX简介")]),s._v(" "),a("h2",{attrs:{id:"什么是jsx"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#什么是jsx"}},[s._v("#")]),s._v(" 什么是JSX?")]),s._v(" "),a("div",{staticClass:"language-js line-numbers-mode"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[s._v("const")]),s._v(" element "),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("=")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("<")]),s._v("h1"),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v(">")]),s._v("Hello"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(",")]),s._v(" world"),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("!")]),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("<")]),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("/")]),s._v("h1"),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v(">")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(";")]),s._v("\n")])]),s._v(" "),a("div",{staticClass:"line-numbers-wrapper"},[a("span",{staticClass:"line-number"},[s._v("1")]),a("br")])]),a("p",[s._v("以类似模板语法的方式描述UI的一种语法。它是JS的"),a("strong",[s._v("语法糖")]),s._v(","),a("strong",[s._v("本质上也是JS")]),s._v("。可以在其中使用"),a("strong",[s._v("变量或表达式、函数等")]),s._v("。")]),s._v(" "),a("h2",{attrs:{id:"为什么使用jsx"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#为什么使用jsx"}},[s._v("#")]),s._v(" 为什么使用JSX?")]),s._v(" "),a("p",[s._v("将"),a("em",[s._v("标记与逻辑")]),s._v(" 共同存放在称之为“组件”的松散耦合单元之中,来实现"),a("a",{attrs:{href:"https://en.wikipedia.org/wiki/Separation_of_concerns",target:"_blank",rel:"noopener noreferrer"}},[a("em",[s._v("关注点分离")]),a("OutboundLink")],1),s._v("。")]),s._v(" "),a("p",[s._v("React不强制使用JSX,但在 JavaScript 代码中将 JSX 和 UI 放在一起时,会在"),a("strong",[s._v("视觉上有辅助作用")]),s._v("。")]),s._v(" "),a("h2",{attrs:{id:"在-jsx-中嵌入表达式"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#在-jsx-中嵌入表达式"}},[s._v("#")]),s._v(" 在 JSX 中嵌入表达式")]),s._v(" "),a("div",{staticClass:"language-js line-numbers-mode"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[s._v("const")]),s._v(" element "),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("=")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("<")]),s._v("h1"),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v(">")]),s._v("Hello"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(",")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("{")]),a("span",{pre:!0,attrs:{class:"token number"}},[s._v("2")]),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("+")]),a("span",{pre:!0,attrs:{class:"token number"}},[s._v("2")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("}")]),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("<")]),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("/")]),s._v("h1"),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v(">")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(";")]),s._v("\n")])]),s._v(" "),a("div",{staticClass:"line-numbers-wrapper"},[a("span",{staticClass:"line-number"},[s._v("1")]),a("br")])]),a("p",[s._v("在 JSX 语法中,你可以在大括号内放置任何有效的 "),a("a",{attrs:{href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Expressions",target:"_blank",rel:"noopener noreferrer"}},[s._v("JavaScript 表达式"),a("OutboundLink")],1),s._v("。")]),s._v(" "),a("h2",{attrs:{id:"jsx-也是一个表达式"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#jsx-也是一个表达式"}},[s._v("#")]),s._v(" JSX 也是一个表达式")]),s._v(" "),a("p",[s._v("在编译之后,JSX 表达式会被转为普通 JavaScript 函数调用,并且对其取值后"),a("strong",[s._v("得到 JavaScript 对象")])]),s._v(" "),a("blockquote",[a("p",[s._v("可以把JSX当初一个对象来对待,可以使用它赋值给变量、当参数输入函数、返回JSX等。")])]),s._v(" "),a("h2",{attrs:{id:"jsx-特定属性"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#jsx-特定属性"}},[s._v("#")]),s._v(" JSX 特定属性")]),s._v(" "),a("p",[s._v("通过使用引号,来将属性值指定为字符串字面量:")]),s._v(" "),a("div",{staticClass:"language-js line-numbers-mode"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[s._v("const")]),s._v(" element "),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("=")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("<")]),s._v("div tabIndex"),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("=")]),a("span",{pre:!0,attrs:{class:"token string"}},[s._v('"0"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v(">")]),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("<")]),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("/")]),s._v("div"),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v(">")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(";")]),s._v("\n")])]),s._v(" "),a("div",{staticClass:"line-numbers-wrapper"},[a("span",{staticClass:"line-number"},[s._v("1")]),a("br")])]),a("blockquote",[a("p",[s._v("JSX中的属性名使用camelCase(小驼峰)命名。如上面例子中的"),a("code",[s._v("tabIndex")])])]),s._v(" "),a("p",[s._v("使用大括号,来在属性值中插入一个 JavaScript 表达式:")]),s._v(" "),a("div",{staticClass:"language-js line-numbers-mode"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[s._v("const")]),s._v(" element "),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("=")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("<")]),s._v("img src"),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("{")]),s._v("user"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(".")]),s._v("avatarUrl"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("}")]),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v(">")]),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("<")]),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("/")]),s._v("img"),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v(">")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(";")]),s._v("\n")])]),s._v(" "),a("div",{staticClass:"line-numbers-wrapper"},[a("span",{staticClass:"line-number"},[s._v("1")]),a("br")])]),a("h2",{attrs:{id:"使用-jsx-指定子元素"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#使用-jsx-指定子元素"}},[s._v("#")]),s._v(" 使用 JSX 指定子元素")]),s._v(" "),a("p",[s._v("JSX 标签里能够包含很多子元素:")]),s._v(" "),a("div",{staticClass:"language-jsx line-numbers-mode"},[a("pre",{pre:!0,attrs:{class:"language-jsx"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[s._v("const")]),s._v(" element "),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("=")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("(")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("<")]),s._v("div")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(">")])]),a("span",{pre:!0,attrs:{class:"token plain-text"}},[s._v("\n ")]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("<")]),s._v("h1")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(">")])]),a("span",{pre:!0,attrs:{class:"token plain-text"}},[s._v("Hello!")]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("</")]),s._v("h1")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(">")])]),a("span",{pre:!0,attrs:{class:"token plain-text"}},[s._v("\n ")]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("<")]),s._v("h2")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(">")])]),a("span",{pre:!0,attrs:{class:"token plain-text"}},[s._v("Good to see you here.")]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("</")]),s._v("h2")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(">")])]),a("span",{pre:!0,attrs:{class:"token plain-text"}},[s._v("\n ")]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("</")]),s._v("div")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(">")])]),s._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(";")]),s._v("\n")])]),s._v(" "),a("div",{staticClass:"line-numbers-wrapper"},[a("span",{staticClass:"line-number"},[s._v("1")]),a("br"),a("span",{staticClass:"line-number"},[s._v("2")]),a("br"),a("span",{staticClass:"line-number"},[s._v("3")]),a("br"),a("span",{staticClass:"line-number"},[s._v("4")]),a("br"),a("span",{staticClass:"line-number"},[s._v("5")]),a("br"),a("span",{staticClass:"line-number"},[s._v("6")]),a("br")])]),a("h2",{attrs:{id:"jsx-防止注入攻击"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#jsx-防止注入攻击"}},[s._v("#")]),s._v(" JSX 防止注入攻击")]),s._v(" "),a("p",[s._v("React DOM 在渲染所有输入内容之前,默认会进行"),a("a",{attrs:{href:"https://stackoverflow.com/questions/7381974/which-characters-need-to-be-escaped-on-html",target:"_blank",rel:"noopener noreferrer"}},[s._v("转义"),a("OutboundLink")],1),s._v("。它可以确保在你的应用中,"),a("strong",[s._v("永远不会注入那些并非自己明确编写的内容")]),s._v("。所有的内容在渲染之前都被转换成了字符串。这样可以有效地防止 "),a("a",{attrs:{href:"https://en.wikipedia.org/wiki/Cross-site_scripting",target:"_blank",rel:"noopener noreferrer"}},[s._v("XSS(cross-site-scripting, 跨站脚本)"),a("OutboundLink")],1),s._v("攻击。")]),s._v(" "),a("h2",{attrs:{id:"jsx-表示对象"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#jsx-表示对象"}},[s._v("#")]),s._v(" JSX 表示对象")]),s._v(" "),a("p",[s._v("Babel 会把 JSX 转译成一个名为 "),a("code",[s._v("React.createElement()")]),s._v(" 函数调用。")]),s._v(" "),a("p",[s._v("以下两种示例代码完全等效:")]),s._v(" "),a("div",{staticClass:"language-jsx line-numbers-mode"},[a("pre",{pre:!0,attrs:{class:"language-jsx"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[s._v("const")]),s._v(" element "),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("=")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("(")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("<")]),s._v("h1")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[s._v("className")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[s._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v('"')]),s._v("greeting"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(">")])]),a("span",{pre:!0,attrs:{class:"token plain-text"}},[s._v("\n Hello, world!\n ")]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("</")]),s._v("h1")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(">")])]),s._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(";")]),s._v("\n\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[s._v("const")]),s._v(" element "),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v("=")]),s._v(" React"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[s._v("createElement")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("(")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token string"}},[s._v("'h1'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(",")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[s._v("// 标签名")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("{")]),s._v("className"),a("span",{pre:!0,attrs:{class:"token operator"}},[s._v(":")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[s._v("'greeting'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(",")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[s._v("// 属性对象")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token string"}},[s._v("'Hello, world!'")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[s._v("// 内容")]),s._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v(";")]),s._v("\n")])]),s._v(" "),a("div",{staticClass:"line-numbers-wrapper"},[a("span",{staticClass:"line-number"},[s._v("1")]),a("br"),a("span",{staticClass:"line-number"},[s._v("2")]),a("br"),a("span",{staticClass:"line-number"},[s._v("3")]),a("br"),a("span",{staticClass:"line-number"},[s._v("4")]),a("br"),a("span",{staticClass:"line-number"},[s._v("5")]),a("br"),a("span",{staticClass:"line-number"},[s._v("6")]),a("br"),a("span",{staticClass:"line-number"},[s._v("7")]),a("br"),a("span",{staticClass:"line-number"},[s._v("8")]),a("br"),a("span",{staticClass:"line-number"},[s._v("9")]),a("br"),a("span",{staticClass:"line-number"},[s._v("10")]),a("br"),a("span",{staticClass:"line-number"},[s._v("11")]),a("br")])])])}),[],!1,null,null,null);t.default=n.exports}}]);
|
global.fetch = require('cross-fetch')
const Logger = require('../utils/logger')
const dotenv = require('dotenv')
dotenv.config()
const moment = require('moment')
const {
getProposalsSelectQuery,
getRoundsSelectQuery,
updateRoundRecord
} = require('../airtable/airtable_utils')
const {
RoundState,
getCurrentRound,
completeEarstructuresValues,
calculateWinningProposalsForEarmark
} = require('../airtable/rounds/funding_rounds')
const {
processAirtableNewProposals
} = require('../airtable/process_airtable_new_proposals')
const {
processFundingRoundComplete,
computeBurnedFunds
} = require('../airtable/process_airtable_funding_round_complete')
const {
prepareProposalsForSnapshot
} = require('../snapshot/prepare_snapshot_received_proposals_airtable')
const {
submitProposalsToSnaphotGranular,
submitProposalsToSnaphotBatch
} = require('../snapshot/submit_snapshot_accepted_proposals_airtable')
const {
syncAirtableActiveProposalVotes
} = require('../airtable/sync_airtable_active_proposal_votes_snapshot')
const {
syncGSheetsActiveProposalVotes
} = require('../gsheets/sync_gsheets_active_proposal_votes_snapshot')
const { BallotType } = require('../snapshot/snapshot_utils')
const { sleep } = require('../functions/utils')
const { getTokenPrice } = require('../functions/chainlink')
const {
processAirtableProposalStandings
} = require('../airtable/process_airtable_all_proposal_standings')
const {
checkAndGenerateNextRoundOpsSchedule
} = require('../scripts/ops/generate_issues')
const prepareNewProposals = async (curRound, curRoundNumber) => {
// Prepare proposals for Snapshot (Check token balance, calc snapshot height)
await processAirtableNewProposals(curRoundNumber)
// Review all standings for Snapshot
sleep(1000)
await prepareProposalsForSnapshot(curRound)
}
// Split up functionality
// Make it easy to debug/trigger events
// DONE - End voting periods
// DONE - Kickoff new round
// DONE - Update existing round
const main = async () => {
const curRound = await getCurrentRound()
let curRoundNumber
let curRoundState
let curRoundStartDate
let curRoundProposalsDueBy
let curRoundProposalsDueBy_plus15
let curRoundVoteStart
let curRoundVoteEnd
let curRoundVoteType
let curRoundBallotType
if (curRound !== undefined) {
curRoundNumber = curRound.get('Round')
curRoundState = curRound.get('Round State')
curRoundStartDate = curRound.get('Start Date')
curRoundProposalsDueBy = moment(curRound.get('Proposals Due By'))
.utc()
.toISOString()
curRoundProposalsDueBy_plus15 = moment(curRound.get('Proposals Due By'))
.add(15, 'minutes')
.utc()
.toISOString()
curRoundVoteStart = curRound.get('Voting Starts')
curRoundVoteEnd = curRound.get('Voting Ends')
curRoundVoteType = curRound.get('Vote Type')
curRoundBallotType = curRound.get('Ballot Type')
// TODO-RA: This function will take longer and longer to process
await processAirtableProposalStandings(curRoundNumber) // process proposal standings
await checkAndGenerateNextRoundOpsSchedule(curRoundNumber)
}
const lastRoundNumber = parseInt(curRoundNumber, 10) - 1
let lastRound = await getRoundsSelectQuery(`{Round} = ${lastRoundNumber}`)
let lastRoundState
let lastRoundVoteEnd
let lastRoundBallotType
if (lastRound !== undefined && lastRound.length > 0) {
;[lastRound] = lastRound
lastRoundState = lastRound.get('Round State')
lastRoundVoteEnd = lastRound.get('Voting Ends')
lastRoundBallotType = lastRound.get('Ballot Type')
}
const now = moment().utc().toISOString()
if (curRoundState === undefined) {
// this is when the round is ending => switching to the next funding round
if (lastRoundState === RoundState.Voting && now >= lastRoundVoteEnd) {
const oceanPrice = await getTokenPrice() // get the latest Ocean price
const earmarkStructure = await completeEarstructuresValues(
lastRound,
oceanPrice,
lastRound.get('Basis Currency')
) // calculate the earmark values based on the updated Ocean price
const roundUpdateData = {
'OCEAN Price': oceanPrice,
Earmarks: JSON.stringify(earmarkStructure),
'Funding Available USD': lastRound.get('Funding Available') * oceanPrice
}
await lastRound.updateFields(roundUpdateData) // update the round record
Logger.log('Start next round.')
// Update votes and compute funds burned
const fundsBurned = await computeBurnedFunds(lastRound, lastRoundNumber)
await syncAirtableActiveProposalVotes(
lastRoundNumber,
lastRoundBallotType
)
try {
await syncGSheetsActiveProposalVotes(
lastRoundNumber,
lastRoundBallotType
)
} catch (err) {
Logger.error(`Error syncing GSheets Active Proposal Votes: ${err}`)
}
// Complete round calculations
const proposalsFunded = await processFundingRoundComplete(
lastRound,
lastRoundNumber
)
// Start the next round
const roundUpdate = [
{
id: lastRound.id,
fields: {
'Round State': RoundState.Ended,
'Proposals Granted': proposalsFunded,
'OCEAN Burned': fundsBurned
}
},
{
id: curRound.id,
fields: {
'Round State': RoundState.Started
}
}
]
await updateRoundRecord(roundUpdate)
} else if (now >= curRoundStartDate) {
Logger.log('Start current round.')
// Start the current round
const roundUpdate = [
{
id: curRound.id,
fields: {
'Round State': RoundState.Started
}
}
]
await updateRoundRecord(roundUpdate)
}
} else {
// this is logic for the current funding round, and the states within it
if (curRoundState === RoundState.Started && now < curRoundProposalsDueBy) {
Logger.log('Update active round.')
await prepareNewProposals(curRound, curRoundNumber)
} else if (
curRoundState === RoundState.Started &&
now >= curRoundProposalsDueBy
) {
Logger.log('Start DD period.')
await prepareNewProposals(curRound, curRoundNumber)
const allProposals = await getProposalsSelectQuery(
`{Round} = ${curRoundNumber}`
)
const tokenPrice = await getTokenPrice()
const basisCurrency = curRound.get('Basis Currency')
let fundingAvailable = 0
let fundingAvailableUSD = 0
switch (basisCurrency) {
case 'USD': {
fundingAvailableUSD = curRound.get('Funding Available USD')
fundingAvailable = fundingAvailableUSD / tokenPrice
break
}
case 'OCEAN': {
const fundingAvailableOCEAN = curRound.get('Funding Available')
fundingAvailable = fundingAvailableOCEAN
fundingAvailableUSD = fundingAvailableOCEAN * tokenPrice
break
}
default:
Logger.log('No Basis Currency was selected for this round.')
}
const roundUpdate = [
{
id: curRound.id,
fields: {
'Round State': RoundState.DueDiligence,
Proposals: allProposals.length,
'OCEAN Price': tokenPrice,
Earmarks: JSON.stringify(
completeEarstructuresValues(curRound, tokenPrice, basisCurrency)
),
'Funding Available': fundingAvailable,
'Funding Available USD': fundingAvailableUSD
}
}
]
// Enter Due Diligence period
calculateWinningProposalsForEarmark(
allProposals,
fundingAvailableUSD,
tokenPrice
)
await updateRoundRecord(roundUpdate)
} else if (
curRoundState === RoundState.DueDiligence &&
now >= curRoundVoteStart
) {
Logger.log('Start Voting period.')
// Submit to snapshot + Enter voting state
if (curRoundBallotType === BallotType.Granular) {
await submitProposalsToSnaphotGranular(curRoundNumber, curRoundVoteType)
} else if (curRoundBallotType === BallotType.Batch) {
await submitProposalsToSnaphotBatch(curRoundNumber, curRoundVoteType)
}
const roundUpdate = [
{
id: curRound.id,
fields: {
'Round State': RoundState.Voting
}
}
]
await updateRoundRecord(roundUpdate)
} else if (
curRoundState === RoundState.DueDiligence &&
now <= curRoundProposalsDueBy_plus15
) {
// 15 minute grace period from DD to allow Alex to update proposals
Logger.log('Update Proposals - Grace Period.')
await prepareNewProposals(curRound, curRoundNumber)
const allProposals = await getProposalsSelectQuery(
`{Round} = ${curRoundNumber}`
)
// Update proposal count
const roundUpdate = [
{
id: curRound.id,
fields: {
Proposals: allProposals.length
}
}
]
await updateRoundRecord(roundUpdate)
} else if (curRoundState === RoundState.Voting && now < curRoundVoteEnd) {
Logger.log('Update vote count.')
// Update votes
await syncAirtableActiveProposalVotes(curRoundNumber, curRoundBallotType)
await syncGSheetsActiveProposalVotes(curRoundNumber, curRoundBallotType)
}
}
}
main()
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z" />
, 'Cancel');
|
/**
* Creates a new admin app.
*/
function AdminApp() {
this._defaults = { operatorId: RapidContext.App.user().id };
this._types = {};
this._cxnIds = null;
this._cxnCount = 0;
this._currentProc = null;
this._batch = { running: false, delay: 5, queue: [],
stat: { success: 0, failed: 0 },
func: MochiKit.Base.bind("_processBatch", this) };
}
/**
* Starts the app and initializes the UI.
*/
AdminApp.prototype.start = function () {
// Create procedure callers
this.proc = RapidContext.Procedure.mapAll({
typeList: "System.Type.List",
cxnList: "System.Connection.List",
cxnValidate: "System.Connection.Validate",
appList: "System.App.List",
plugInList: "System.PlugIn.List",
procList: "System.Procedure.List",
procDelete: "System.Procedure.Delete",
procTypes: "System.Procedure.Types",
userList: "System.User.List",
userChange: "System.User.Change"
});
// All views
MochiKit.Signal.connect(this.ui.root, "onenter", MochiKit.Base.bind("selectChild", this.ui.tabContainer, null));
MochiKit.Signal.connect(this.proc.typeList, "onsuccess", this, "_updateTypeCache");
// Connection view
RapidContext.UI.connectProc(this.proc.cxnList, this.ui.cxnLoading, this.ui.cxnReload);
MochiKit.Signal.connect(this.proc.cxnList, "onsuccess", this.ui.cxnTable, "setData");
MochiKit.Signal.connect(this.proc.cxnList, "onsuccess", this, "_showConnection");
MochiKit.Signal.connect(this.ui.cxnTable, "onselect", this, "_showConnection");
MochiKit.Signal.connect(this.ui.cxnValidate, "onclick", this, "_validateConnections");
MochiKit.Signal.connect(this.ui.cxnAdd, "onclick", this, "_addConnection");
MochiKit.Signal.connect(this.ui.cxnRemove, "onclick", this, "_removeConnection");
MochiKit.Signal.connect(this.ui.cxnEdit, "onclick", this, "_editConnection");
MochiKit.Signal.connect(this.ui.cxnEditType, "onchange", this, "_updateConnectionEdit");
MochiKit.Signal.connect(this.ui.cxnEditShowAll, "onchange", this, "_updateConnectionEdit");
MochiKit.Signal.connect(this.ui.cxnEditForm, "onclick", this, "_addRemoveConnectionProps")
MochiKit.Signal.connect(this.ui.cxnEditCancel, "onclick", this.ui.cxnEditDialog, "hide");
MochiKit.Signal.connect(this.ui.cxnEditSave, "onclick", this, "_storeConnection");
var statusRenderer = function (td, value, data) {
if (data._error || data._lastError) {
td.appendChild(RapidContext.Widget.Icon({ ref: "ERROR" }));
} else if (!data._openChannels) {
td.appendChild(RapidContext.Widget.Icon({ ref: "WARNING", tooltip: "Unknown" }));
} else {
td.appendChild(RapidContext.Widget.Icon({ ref: "OK" }));
}
};
var typeRenderer = function (td, value, data) {
if (/^connection\//.test(value)) {
td.appendChild(RapidContext.Util.createTextNode(value.substr(11)));
}
};
this.ui.cxnTable.getChildNodes()[1].setAttrs({ renderer: statusRenderer });
this.ui.cxnTable.getChildNodes()[2].setAttrs({ renderer: typeRenderer });
// App view
MochiKit.Signal.connectOnce(this.ui.appTab, "onenter", this, "loadApps");
RapidContext.UI.connectProc(this.proc.appList, this.ui.appLoading, this.ui.appReload);
MochiKit.Signal.connect(this.proc.appList, "onsuccess", this, "_callbackLoadApps");
MochiKit.Signal.connect(this.ui.appTable, "onselect", this, "_showApp");
MochiKit.Signal.connect(this.ui.appLaunch, "onclick", this, "_launchApp");
MochiKit.Signal.connect(this.ui.appLaunchWindow, "onclick", this, "_launchAppWindow");
var urlRenderer = function (td, value, data) {
if (value) {
var styles = { marginLeft: "3px" };
var attrs = { ref: "EXPAND", tooltip: "Open in new window", style: styles };
var ico = RapidContext.Widget.Icon(attrs);
var link = MochiKit.DOM.A({ href: value, target: "_blank" }, value, ico);
td.appendChild(link);
}
};
this.ui.appResourceTable.getChildNodes()[1].setAttrs({ renderer: urlRenderer });
// Plug-in view
MochiKit.Signal.connectOnce(this.ui.pluginTab, "onenter", this, "loadPlugins");
MochiKit.Signal.connect(this.ui.pluginTab, "onenter", this, "_pluginUploadInit");
MochiKit.Signal.connect(this.ui.pluginFile, "onselect", this, "_pluginUploadStart");
MochiKit.Signal.connect(this.ui.pluginInstall, "onclick", this, "_pluginInstall");
MochiKit.Signal.connect(this.ui.pluginReset, "onclick", this, "resetServer");
MochiKit.Signal.connect(this.ui.pluginFileDelete, "onclick", this, "_pluginUploadInit");
RapidContext.UI.connectProc(this.proc.plugInList, this.ui.pluginLoading, this.ui.pluginReload);
MochiKit.Signal.connect(this.proc.plugInList, "onsuccess", this.ui.pluginTable, "setData");
MochiKit.Signal.connect(this.proc.plugInList, "onsuccess", this, "_showPlugin");
MochiKit.Signal.connect(this.ui.pluginTable, "onselect", this, "_showPlugin");
MochiKit.Signal.connect(this.ui.pluginLoad, "onclick", this, "_togglePlugin");
MochiKit.Signal.connect(this.ui.pluginUnload, "onclick", this, "_togglePlugin");
// Procedure view
MochiKit.Signal.connectOnce(this.ui.procTab, "onenter", this, "loadProcedures");
RapidContext.UI.connectProc(this.proc.procList, this.ui.procTreeLoading, this.ui.procTreeReload);
MochiKit.Signal.connect(this.proc.procList, "onsuccess", this, "_callbackProcedures");
RapidContext.UI.connectProc(this.proc.procDelete);
MochiKit.Signal.connect(this.proc.procDelete, "oncall", this.ui.overlay, "show");
MochiKit.Signal.connect(this.proc.procDelete, "onresponse", this.ui.overlay, "hide");
MochiKit.Signal.connect(this.proc.procDelete, "onsuccess", this.proc.procList, "recall");
MochiKit.Signal.connect(this.ui.procTree, "onselect", this, "_showProcedure");
MochiKit.Signal.connect(this.ui.procAdd, "onclick", this, "_addProcedure");
MochiKit.Signal.connect(this.ui.procRemove, "onclick", this, "_removeProcedure");
MochiKit.Signal.connect(this.ui.procEdit, "onclick", this, "_editProcedure");
MochiKit.Signal.connect(this.ui.procEditType, "onchange", this, "_updateProcEdit");
MochiKit.Signal.connect(this.ui.procEditAdd, "onclick", this, "_addProcBinding");
MochiKit.Signal.connect(this.ui.procEditCancel, "onclick", this.ui.procEditDialog, "hide");
MochiKit.Signal.connect(this.ui.procEditSave, "onclick", this, "_saveProcedure");
MochiKit.Signal.connect(this.ui.procReload, "onclick", this, "_showProcedure");
MochiKit.Signal.connect(this.ui.procExec, "onclick", this, "_executeProcedure");
MochiKit.Signal.connect(this.ui.procBatch, "onclick", this, "_createBatch");
MochiKit.Signal.connect(this.ui.procExecResult, "onexpand", this, "_showExecData");
MochiKit.Signal.connect(this.ui.procArgCancel, "onclick", this.ui.procArgDialog, "hide");
MochiKit.Signal.connect(this.ui.procArgSave, "onclick", this, "_updateProcArg");
this.ui.procExecLoading.hide();
this.ui.procExecResult.resizeContent = function () {
var pos = MochiKit.Style.getElementPosition(this, this.parentNode);
var dim = MochiKit.Style.getElementDimensions(this.parentNode);
MochiKit.Style.setElementDimensions(this, { w: dim.w - 2, h: dim.h - pos.y - 2 });
}
// Batch view
MochiKit.Signal.connect(this.ui.batchDelete, "onclick", this, "_clearBatch");
MochiKit.Signal.connect(this.ui.batchDelay, "onclick", this, "_configBatchDelay");
MochiKit.Signal.connect(this.ui.batchPlay, "onclick", this, "_toggleBatch");
MochiKit.Signal.connect(this.ui.batchPause, "onclick", this, "_toggleBatch");
// User view
MochiKit.Signal.connectOnce(this.ui.userTab, "onenter", this, "loadUsers");
RapidContext.UI.connectProc(this.proc.userList, this.ui.userLoading, this.ui.userReload);
MochiKit.Signal.connect(this.proc.userList, "onsuccess", this.ui.userTable, "setData");
MochiKit.Signal.connect(this.ui.userTable, "onselect", this, "_editUser");
MochiKit.Signal.connect(this.ui.userAdd, "onclick", this, "_addUser");
MochiKit.Signal.connect(this.ui.userSave, "onclick", this, "_saveUser");
RapidContext.UI.connectProc(this.proc.userChange);
MochiKit.Signal.connect(this.proc.userChange, "onsuccess", this.proc.userList, "recall");
// Log view
MochiKit.Signal.connect(this.ui.logTab, "onenter", this, "_showLogs");
MochiKit.Signal.connect(this.ui.logError, "onclick", MochiKit.Base.bind("setLogLevel", this, "error"));
MochiKit.Signal.connect(this.ui.logWarning, "onclick", MochiKit.Base.bind("setLogLevel", this, "warn"));
MochiKit.Signal.connect(this.ui.logInfo, "onclick", MochiKit.Base.bind("setLogLevel", this, "info"));
MochiKit.Signal.connect(this.ui.logTrace, "onclick", MochiKit.Base.bind("setLogLevel", this, "log"));
MochiKit.Signal.connect(this.ui.logClear, "onclick", this, "_clearLogs");
MochiKit.Signal.connect(this.ui.logReload, "onclick", this, "_showLogs");
MochiKit.Signal.connect(this.ui.logTable, "onselect", this, "_showLogDetails");
// TODO: Security test should be made on access, not role name
var user = RapidContext.App.user();
if (!user || !user.role || MochiKit.Base.findValue(user.role, "admin") < 0) {
this.ui.procAdd.hide();
this.ui.procRemove.addClass("hidden");
this.ui.tabContainer.removeChildNode(this.ui.cxnTab);
this.ui.tabContainer.removeChildNode(this.ui.pluginTab);
this.ui.tabContainer.removeChildNode(this.ui.userTab);
RapidContext.Widget.destroyWidget(this.ui.cxnTab);
RapidContext.Widget.destroyWidget(this.ui.pluginTab);
RapidContext.Widget.destroyWidget(this.ui.userTab);
this.ui.cxnTab = null;
this.ui.pluginTab = null;
this.ui.userTab = null;
}
// Initialize data
if (this.ui.cxnTab) {
this.proc.cxnList();
} else {
this.loadApps();
}
this._showProcedure();
this._stopBatch();
}
/**
* Stops the app.
*/
AdminApp.prototype.stop = function () {
for (var name in this.proc) {
MochiKit.Signal.disconnectAll(this.proc[name]);
}
}
/**
* Updates the type cache.
*/
AdminApp.prototype._updateTypeCache = function (res) {
this._types = {};
for (var i = 0; i < res.length; i++) {
var type = res[i];
this._types[type.id] = type;
type.property = type.property || [];
type.properties = {};
for (var j = 0; j < type.property.length; j++) {
var prop = type.property[j];
type.properties[prop.name] = prop;
}
delete type.property;
}
for (var id in this._types) {
var type = this._types[id];
var parts = id.split("/");
while (parts.length > 1) {
parts.pop();
var baseId = parts.join("/");
var baseType = this._types[baseId];
if (baseType && baseType.properties) {
MochiKit.Base.setdefault(type.properties, baseType.properties);
}
}
}
}
/**
* Validates all connections. The connection list is updated before
* the validation starts.
*/
AdminApp.prototype._validateConnections = function () {
this.ui.overlay.setAttrs({ message: "Validating..." });
this.ui.overlay.show();
var d = this.proc.cxnList();
d.addBoth(MochiKit.Base.bind("_validateCallback", this));
}
/**
* Connection validation callback handler. This method will iterate
* over all the connections in the connection table one by one. This
* callback method will be called between each validation.
*
* @return {Deferred} a MochiKit.Async.Deferred that will callback
* when the validation is complete
*/
AdminApp.prototype._validateCallback = function () {
if (this._cxnIds == null) {
var data = this.ui.cxnTable.getData();
this._cxnIds = MochiKit.Base.map(MochiKit.Base.itemgetter("id"), data);
this._cxnCount = this._cxnIds.length;
}
if (this._cxnIds.length == 0) {
this._cxnIds = null;
this.ui.overlay.hide();
return this.proc.cxnList();
} else {
var id = this._cxnIds.shift();
var pos = this._cxnCount - this._cxnIds.length;
var msg = "Validating " + pos + " of " + this._cxnCount + "...";
this.ui.overlay.setAttrs({ message: msg });
var d = this.proc.cxnValidate(id);
d.addBoth(MochiKit.Base.method(this, "_validateCallback"));
return d;
}
}
/**
* Shows the specified connection in the Admin UI. This method will
* show the connection pane (if not already displaying), validate
* the connection specified, update the connection list and finally
* display the connection details.
*
* @param {String} id the connection identifier
*/
AdminApp.prototype.showConnection = function (id) {
this.ui.tabContainer.selectChild(this.ui.cxnTab);
var cxnList = this.proc.cxnList;
var cxnTable = this.ui.cxnTable;
var d = this.proc.cxnValidate(id);
d.addBoth(function () { return cxnList(); });
d.addCallback(function () { cxnTable.setSelectedIds(id); });
}
/**
* Shows detailed connection information.
*/
AdminApp.prototype._showConnection = function () {
var data = this.ui.cxnTable.getSelectedData();
data = MochiKit.Base.update({}, data);
if (/^@\d+$/.test(data._lastUsedTime)) {
var dttm = new Date(+data._lastUsedTime.substr(1));
data.lastAccess = MochiKit.DateTime.toISOTimestamp(dttm);
}
this.ui.cxnForm.reset();
this.ui.cxnForm.update(data);
if (data.plugin == "local") {
this.ui.cxnRemove.show();
} else {
this.ui.cxnRemove.hide();
}
if (data.plugin && data.id) {
this.ui.cxnEdit.show();
var url = "rapidcontext/storage/connection/" + data.id;
MochiKit.DOM.setNodeAttribute(this.ui.cxnLink, "href", url);
MochiKit.DOM.removeElementClass(this.ui.cxnLink, "hidden");
} else {
this.ui.cxnEdit.hide();
MochiKit.DOM.addElementClass(this.ui.cxnLink, "hidden");
}
while (this.ui.cxnTemplate.previousSibling.className == "template") {
RapidContext.Widget.destroyWidget(this.ui.cxnTemplate.previousSibling);
}
var hidden = ["lastAccess", "id", "type", "plugin", "maxOpen", "_maxOpen",
"_usedChannels", "_openChannels", "_lastUsedTime"];
RapidContext.Util.mask(data, hidden);
for (var k in data) {
if (!/^_/.test(k) || !(k.substr(1) in data)) {
var title = RapidContext.Util.toTitleCase(k);
var value = data[k];
if (value == null) {
value = "";
}
if (/error$/i.test(k)) {
value = MochiKit.DOM.SPAN({ "class": "important" }, value);
} else if (/password$/i.test(k)) {
value = RapidContext.Widget.Field({ name: k, value: value, mask: true });
}
var tr = this.ui.cxnTemplate.cloneNode(true);
tr.className = "template";
MochiKit.DOM.appendChildNodes(tr.firstChild, title + ":");
MochiKit.DOM.appendChildNodes(tr.lastChild, value);
MochiKit.DOM.insertSiblingNodesBefore(this.ui.cxnTemplate, tr);
}
}
}
/**
* Opens the connection editing dialog for a new connection.
*/
AdminApp.prototype._addConnection = function () {
this._initConnectionEdit({});
}
/**
* Removes a connection (after user confirmation).
*/
AdminApp.prototype._removeConnection = function () {
var data = this.ui.cxnTable.getSelectedData();
var msg = "Delete the connection '" + data.id + "'?";
if (confirm(msg)) {
var path = "connection/" + data.id;
var d = AdminApp.storageDelete(path);
d.addErrback(RapidContext.UI.showError);
d.addCallback(MochiKit.Base.method(this.proc.cxnList, "recall"));
}
}
/**
* Opens the connection editing dialog for an existing connection.
*/
AdminApp.prototype._editConnection = function () {
var data = this.ui.cxnTable.getSelectedData();
this._initConnectionEdit(data);
}
/**
* Initializes the connection editing dialog.
*/
AdminApp.prototype._initConnectionEdit = function (data) {
this.ui.cxnEditDialog.data = data;
this.ui.cxnEditForm.reset();
this.ui.cxnEditForm.update(data);
var self = this;
var d = this.proc.typeList();
d.addCallback(function () {
var select = self.ui.cxnEditType;
while (select.firstChild.nextSibling) {
RapidContext.Widget.destroyWidget(select.firstChild.nextSibling);
}
for (var k in self._types) {
if (/connection\//.test(k)) {
var attrs = { value: k };
if (data.type === k) {
attrs.selected = true;
}
select.appendChild(MochiKit.DOM.OPTION(attrs, k));
}
}
});
d.addCallback(MochiKit.Base.bind("_updateConnectionEdit", this));
d.addCallback(MochiKit.Base.bind("show", this.ui.cxnEditDialog));
d.addErrback(RapidContext.UI.showError);
return d;
}
/**
* Updates the connection editing dialog.
*/
AdminApp.prototype._updateConnectionEdit = function () {
var data = this.ui.cxnEditForm.valueMap();
var showAll = (data._showAll == "yes");
this.ui.cxnEditForm.reset();
MochiKit.Base.setdefault(data, this.ui.cxnEditDialog.data);
while (this.ui.cxnEditTemplate.previousSibling.className == "template") {
RapidContext.Widget.destroyWidget(this.ui.cxnEditTemplate.previousSibling);
}
var hiddenProps = { id: true, type: true, plugin: true };
var props = {};
if (this._types[data.type]) {
var type = this._types[data.type];
MochiKit.Base.update(props, type.properties);
MochiKit.DOM.replaceChildNodes(this.ui.cxnEditTypeDescr, type.description);
} else {
MochiKit.DOM.replaceChildNodes(this.ui.cxnEditTypeDescr);
}
for (var name in data) {
var value = MochiKit.Format.strip(data[name]);
if (!/^_/.test(name) && !(name in props) && !(name in hiddenProps) && value) {
props[name] = { name: name, title: name, custom: true,
description: "User-specified parameter." };
if (/password$/i.test(name)) {
props[name].format = "password";
}
}
}
for (var name in props) {
var p = props[name];
var title = p.title || RapidContext.Util.toTitleCase(name);
var value = (data[name] != null) ? "" + data[name] : "";
var defaultValue = (data["_" + name] != null) ? "" + data["_" + name] : "";
var valueLines = AdminApp.splitLines(value, 58);
var tr = this.ui.cxnEditTemplate.cloneNode(true);
tr.className = "template";
MochiKit.DOM.appendChildNodes(tr.firstChild, title + ":");
var attrs = { name: name, cols: 58, size: 60 };
if (defaultValue) {
attrs.placeholder = defaultValue;
}
var input = null;
if (p.format == "text" || valueLines.length > 1) {
attrs.rows = Math.min(Math.max(2, valueLines.length), 20);
input = RapidContext.Widget.TextArea(attrs);
} else if (p.format == "password") {
attrs.type = "password";
input = RapidContext.Widget.TextField(attrs);
} else {
input = RapidContext.Widget.TextField(attrs);
}
MochiKit.DOM.appendChildNodes(tr.lastChild, input);
if (p.custom) {
var style = { "margin-left": "3px" };
var icon = RapidContext.Widget.Icon({ ref: "REMOVE", style: style });
icon["data-remove"] = true;
MochiKit.DOM.appendChildNodes(tr.lastChild, icon);
}
if (p.required && p.format != "password") {
var attrs = { name: name, display: "icon" };
var validator = RapidContext.Widget.FormValidator(attrs);
MochiKit.DOM.appendChildNodes(tr.lastChild, validator);
}
if (p.description) {
var help = MochiKit.DOM.DIV({ "class": "helptext preformatted" }, p.description);
MochiKit.DOM.appendChildNodes(tr.lastChild, help);
}
if (!showAll && !p.required && !p.custom && !value) {
tr.style.display = "none";
}
MochiKit.DOM.insertSiblingNodesBefore(this.ui.cxnEditTemplate, tr);
}
this.ui.cxnEditForm.update(data);
}
/**
* Handles addition and removal of custom connection parameters.
*/
AdminApp.prototype._addRemoveConnectionProps = function (evt) {
var elem = evt.target();
if (elem === this.ui.cxnEditAdd) {
var name = MochiKit.Format.strip(this.ui.cxnEditAddParam.value);
if (/[a-z0-9_-]+/i.test(name)) {
this.ui.cxnEditAddParam.setAttrs({ name: name, value: "value" });
this._updateConnectionEdit();
this.ui.cxnEditAddParam.setAttrs({ name: "_add", value: "" });
} else {
alert("Invalid parameter name.");
}
} else if (elem["data-remove"] === true) {
var tr = MochiKit.DOM.getFirstParentByTagAndClassName(elem, "TR");
RapidContext.Widget.destroyWidget(tr);
}
}
/**
* Stores the edited or new connection to the RapidContext storage.
*/
AdminApp.prototype._storeConnection = function () {
this.ui.cxnEditForm.validateReset();
if (this.ui.cxnEditForm.validate()) {
var data = this.ui.cxnEditForm.valueMap();
var prevData = this.ui.cxnEditDialog.data;
var path = "connection/" + data.id;
for (var name in data) {
var value = MochiKit.Format.strip(data[name]);
if (/^_/.test(name) || value == "") {
delete data[name];
}
}
var d = AdminApp.storageWrite(path, data);
if (prevData.id && prevData.id != data.id) {
var oldPath = "connection/" + prevData.id;
d.addCallback(MochiKit.Base.partial(AdminApp.storageDelete, oldPath));
}
d.addErrback(RapidContext.UI.showError);
d.addCallback(MochiKit.Base.method(this.ui.cxnEditDialog, "hide"));
d.addCallback(MochiKit.Base.method(this, "showConnection", data.id));
}
}
/**
* Loads the app list.
*/
AdminApp.prototype.loadApps = function () {
this.proc.appList();
}
/**
* Callback for the app list loading.
*/
AdminApp.prototype._callbackLoadApps = function () {
// Procedure call triggered an update of the cached app list,
// so the procedure results can be ignored here
this.ui.appTable.setData(RapidContext.App.apps());
this._showApp();
}
/**
* Shows detailed app information.
*/
AdminApp.prototype._showApp = function () {
var data = this.ui.appTable.getSelectedData();
this.ui.appForm.reset();
if (data) {
this.ui.appForm.update(data);
var iconNode = data.icon ? data.icon.cloneNode(true) : null;
MochiKit.DOM.replaceChildNodes(this.ui.appIcon, iconNode);
var url = "rapidcontext/storage/app/" + data.id;
MochiKit.DOM.setNodeAttribute(this.ui.appLink, "href", url);
MochiKit.DOM.removeElementClass(this.ui.appLink, "hidden");
this.ui.appResourceTable.show();
this.ui.appResourceTable.setData(data.resources);
} else {
MochiKit.DOM.replaceChildNodes(this.ui.appIcon);
MochiKit.DOM.addElementClass(this.ui.appLink, "hidden");
this.ui.appResourceTable.hide();
}
this.ui.appLaunch.setAttrs({ disabled: !data });
this.ui.appLaunchWindow.setAttrs({ disabled: !data });
}
/**
* Launches the currently selected app.
*/
AdminApp.prototype._launchApp = function () {
var data = this.ui.appTable.getSelectedData();
RapidContext.App.startApp(data.id);
}
/**
* Launches the currently selected app in separate window.
*/
AdminApp.prototype._launchAppWindow = function () {
var data = this.ui.appTable.getSelectedData();
RapidContext.App.startApp(data.id, window.open());
}
/**
* Loads the table of available plug-ins.
*/
AdminApp.prototype.loadPlugins = function () {
return this.proc.plugInList();
}
/**
* Shows the details for the currently selected plug-in.
*/
AdminApp.prototype._showPlugin = function () {
var data = this.ui.pluginTable.getSelectedData();
this.ui.pluginForm.reset();
if (data) {
this.ui.pluginForm.update(data);
MochiKit.DOM.removeElementClass(this.ui.pluginLink, "hidden");
var path = "/storage/plugin/" + data.id + "/";
var url = "rapidcontext/storage" + path;
MochiKit.DOM.setNodeAttribute(this.ui.pluginLink, "href", url);
if (data.loaded) {
this.ui.pluginLoad.hide();
this.ui.pluginUnload.show();
} else {
this.ui.pluginLoad.show();
this.ui.pluginUnload.hide();
}
if (data.id === "system" || data.id === "local") {
this.ui.pluginUnload.hide();
}
} else {
MochiKit.DOM.addElementClass(this.ui.pluginLink, "hidden");
this.ui.pluginLoad.hide();
this.ui.pluginUnload.hide();
}
}
/**
* Loads or unloads the currently selected plug-in.
*/
AdminApp.prototype._togglePlugin = function () {
this.ui.pluginReload.hide();
this.ui.pluginLoading.show();
var data = this.ui.pluginTable.getSelectedData();
var proc = data.loaded ? "System.PlugIn.Unload" : "System.PlugIn.Load";
var d = RapidContext.App.callProc(proc, [data.id]);
d.addErrback(RapidContext.UI.showError);
if (data.loaded && data.className) {
d.addCallback(function () {
alert("Note: Unloading Java resources requires a full server restart.");
});
}
// TODO: This should be handled internally on the server...
d.addBoth(MochiKit.Base.bind("resetServer", this));
d.addBoth(MochiKit.Base.bind("loadPlugins", this))
}
/**
* Initializes the plug-in file upload and installation interface.
*/
AdminApp.prototype._pluginUploadInit = function () {
this.ui.pluginFile.show();
this.ui.pluginProgress.hide();
this.ui.pluginFileInfo.hide();
this.ui.pluginInstall.disable();
}
/**
* Handles the plug-in file upload init.
*/
AdminApp.prototype._pluginUploadStart = function () {
this.ui.pluginFile.hide();
this.ui.pluginProgress.show();
this.ui.pluginProgress.setAttrs({ min: 0, max: 100, ratio: 0 });
this._pluginUploadProgress();
}
/**
* Shows the progress for the plug-in file upload.
*
* @param {Object} [res] the optional session data object
*/
AdminApp.prototype._pluginUploadProgress = function (res) {
var selfCallback = MochiKit.Base.bind("_pluginUploadProgress", this);
function pluginLoadStatus() {
var d = RapidContext.App.callProc("System.Session.Current");
d.addBoth(selfCallback);
}
if (res && res.files && res.files.plugin) {
this._pluginUploadInfo(res.files.plugin);
} else {
MochiKit.Async.callLater(1, pluginLoadStatus);
if (res && res.files && res.files.progress) {
this.ui.pluginProgress.setAttrs({ ratio: res.files.progress });
}
}
}
/**
* Shows the information for an uploaded plug-in file.
*
* @param {Object} file the session file data object
*/
AdminApp.prototype._pluginUploadInfo = function (file) {
this.ui.pluginFile.hide();
this.ui.pluginProgress.hide();
this.ui.pluginFileInfo.show();
var value = parseInt(file.size);
if (value > 1000000) {
file.approxSize = MochiKit.Format.roundToFixed(value / 1048576, 1) + " MiB";
} else if (value > 2000) {
file.approxSize = MochiKit.Format.roundToFixed(value / 1024, 1) + " KiB";
} else {
file.approxSize = file.size + " bytes";
}
this.ui.pluginUploadForm.update(file);
this.ui.pluginInstall.enable();
}
/**
* Performs a plug-in installation.
*/
AdminApp.prototype._pluginInstall = function () {
var self = this;
var id;
this.ui.overlay.setAttrs({ message: "Installing..." });
this.ui.overlay.show();
var d = RapidContext.App.callProc("System.PlugIn.Install", ["plugin"]);
d.addCallback(function (res) {
id = res;
});
// TODO: This should be handled internally on the server...
d.addCallback(MochiKit.Base.bind("resetServer", this));
d.addCallback(MochiKit.Base.bind("loadPlugins", this));
d.addCallback(function () {
self.ui.pluginTable.setSelectedIds(id);
self._pluginUploadInit();
self._showPlugin();
});
d.addErrback(RapidContext.UI.showError);
d.addBoth(function () {
self.ui.overlay.hide();
});
}
/**
* Sends a server reset (restart) request.
*/
AdminApp.prototype.resetServer = function (e) {
var d = RapidContext.App.callProc("System.Reset");
if (e instanceof MochiKit.Signal.Event) {
d.addCallback(function (data) { alert("Server reset complete"); });
d.addErrback(RapidContext.UI.showError);
}
return d;
}
/**
* Loads the procedures for the procedure tree.
*/
AdminApp.prototype.loadProcedures = function () {
this.proc.procList();
}
/**
* Callback function for loading the procedure tree.
*
* @param {Object} res the result object
*/
AdminApp.prototype._callbackProcedures = function (res) {
this.ui.procTree.markAll();
for (var i = 0; i < res.length; i++) {
var path = res[i].split(".");
var node = this.ui.procTree.addPath(path);
node.data = res[i];
}
this.ui.procTree.removeAllMarked();
this._showProcedure();
}
/**
* Shows the specified procedure in the procedure tree and in the
* details area.
*
* @param {String} name the procedure name
*/
AdminApp.prototype.showProcedure = function (name) {
var node = this.ui.procTree.findByPath(name.split("."));
if (node == null) {
throw new Error("failed to find procedure '" + name + "'");
} else if (node.isSelected()) {
this._showProcedure();
} else {
node.select();
}
}
/**
* Loads detailed procedure information.
*/
AdminApp.prototype._showProcedure = function () {
var node = this.ui.procTree.selectedChild();
this.ui.procForm.reset();
this.ui.procRemove.hide();
this.ui.procEdit.hide();
this.ui.procReload.hide();
this.ui.procLoading.hide();
MochiKit.DOM.replaceChildNodes(this.ui.procArgTable);
this.ui.procExec.disable();
this.ui.procBatch.disable();
this.ui.procExecResult.removeAll();
RapidContext.Util.resizeElements(this.ui.procExecResult);
if (node != null && node.data != null) {
var args = [node.data];
var d = RapidContext.App.callProc("System.Procedure.Read", args);
d.addBoth(MochiKit.Base.bind("_callbackShowProcedure", this));
this.ui.procLoading.show();
}
}
/**
* Callback function for showing detailed procedure information.
*
* @param {Object} res the result object or error
*/
AdminApp.prototype._callbackShowProcedure = function (res) {
this.ui.procReload.show();
this.ui.procLoading.hide();
if (res instanceof Error) {
RapidContext.UI.showError(res);
} else {
this._currentProc = res;
if (res.plugin == "local") {
this.ui.procRemove.show();
}
if (res.type != "built-in") {
this.ui.procEdit.show();
}
this.ui.procForm.update(res);
MochiKit.DOM.replaceChildNodes(this.ui.procArgTable);
var count = 0;
for (var i = 0; i < res.bindings.length; i++) {
var b = res.bindings[i];
if (b.type == "argument") {
var attrs = { "class": "label", style: "padding-top: 4px; padding-right: 6px;" };
var text = RapidContext.Util.toTitleCase(b.name).replace(" ", "\u00A0") + ":";
var col1 = MochiKit.DOM.TD(attrs, text);
var value = this._defaults[b.name] || "";
var attrs = { name: "arg" + count, value: value, style: "margin-right: 6px;" };
var field = RapidContext.Widget.TextField(attrs);
var icon = RapidContext.Widget.Icon({ ref: "EDIT", style: { "verticalAlign": "middle", "fontSize": "1.6em" } });
icon.onclick = MochiKit.Base.bind("_editProcArg", this, count);
var col2 = MochiKit.DOM.TD({ style: "padding-right: 6px; white-space: nowrap;" }, field, icon);
var col3 = MochiKit.DOM.TD({ style: "padding-top: 4px; white-space: pre-line;" }, b.description);
var tr = MochiKit.DOM.TR({}, col1, col2, col3);
this.ui.procArgTable.appendChild(tr);
count++;
}
}
this.ui.procExec.enable();
this.ui.procBatch.enable();
this.ui.procExecResult.removeAll();
RapidContext.Util.resizeElements(this.ui.procExecResult);
}
}
/**
* Returns the current procedure arguments array. Each argument in
* the array is a data object containing a "type" and a "value"
* property. Both have string values.
*
* @return {Array} the procedure arguments
*/
AdminApp.prototype._getProcArgs = function () {
var args = [];
var rows = this.ui.procArgTable.childNodes;
for (var i = 0; i < rows.length; i++) {
var td = rows[i].childNodes[1];
var field = td.firstChild;
var type = field.dataType || "string";
var value = field.dataValue || field.getValue();
args.push({ type: type, value: value });
}
return args;
}
/**
* Opens the procedure argument editor for a specific argument.
*
* @param {Number} idx the argument index
*/
AdminApp.prototype._editProcArg = function (idx) {
var args = this._getProcArgs();
this.ui.procArgForm.update(args[idx]);
this.ui.procArgForm.argumentIndex = idx;
this.ui.procArgDialog.show();
}
/**
* Updates a procedure argument after editing in the dialog.
*/
AdminApp.prototype._updateProcArg = function () {
var form = this.ui.procArgForm.valueMap();
var idx = this.ui.procArgForm.argumentIndex;
var tr = this.ui.procArgTable.childNodes[idx];
var td = tr.childNodes[1];
var field = td.firstChild;
field.dataType = form.type;
var lines = form.value.split("\n");
if (form.type === "string" && lines.length <= 1) {
field.disabled = false;
field.dataValue = undefined;
field.setAttrs({ value: form.value });
} else if (form.type === "json") {
field.disabled = true;
field.dataValue = form.value;
var text = "JSON object";
try {
var o = MochiKit.Base.evalJSON(form.value);
if (o instanceof Array) {
text = "JSON array, " + o.length + " rows";
}
} catch (e) {
text = "Invalid JSON string";
}
field.setAttrs({ value: text });
} else {
field.disabled = true;
field.dataValue = form.value;
var text = lines.length + " lines, " + form.value.length + " chars";
field.setAttrs({ value: text });
}
this.ui.procArgDialog.hide();
}
/**
* Opens the procedure editing dialog for a new procedure.
*/
AdminApp.prototype._addProcedure = function () {
var data = { name: "", type: "javascript", description: "",
bindings: {}, defaults: {} };
var d = this._initProcEdit(data);
d.addCallback(MochiKit.Base.bind("_updateProcEdit", this));
}
/**
* Removes the currently shown procedure (if in the local plug-in).
*/
AdminApp.prototype._removeProcedure = function () {
var p = this._currentProc;
var msg = "Do you really want to delete the\nprocedure '" + p.name + "'?";
if (confirm(msg)) {
this.ui.overlay.setAttrs({ message: "Deleting..." });
this.proc.procDelete(p.name);
}
}
/**
* Opens the procedure editing dialog for an existing procedure.
*/
AdminApp.prototype._editProcedure = function () {
var p = this._currentProc;
var data = { name: p.name, type: p.type, description: p.description,
bindings: {}, defaults: {} };
for (var i = 0; i < p.bindings.length; i++) {
var b = MochiKit.Base.clone(p.bindings[i]);
if (b.type === "argument") {
b.value = b.description;
b.description = "";
}
data.bindings[b.name] = b;
}
this._initProcEdit(data);
}
/**
* Initializes the procedure editing dialog.
*/
AdminApp.prototype._initProcEdit = function (data) {
this.ui.procEditDialog.data = data;
var select = this.ui.procEditType;
var d = this.proc.procTypes();
d.addCallback(function (res) {
MochiKit.DOM.replaceChildNodes(select);
var types = MochiKit.Base.keys(res).sort();
for (var i = 0; i < types.length; i++) {
var k = types[i];
select.appendChild(MochiKit.DOM.OPTION({ value: k }, k));
var values = res[k].bindings
var keys = MochiKit.Base.map(MochiKit.Base.itemgetter("name"), values);
data.defaults[k] = RapidContext.Util.dict(keys, values);
}
});
d.addCallback(MochiKit.Base.bind("_renderProcEdit", this));
d.addCallback(MochiKit.Base.bind("show", this.ui.procEditDialog));
d.addErrback(RapidContext.UI.showError);
return d;
}
/**
* Renders the procedure editing form from the data object stored in
* the dialog.
*/
AdminApp.prototype._renderProcEdit = function () {
var data = this.ui.procEditDialog.data;
RapidContext.Widget.destroyWidget(this.ui.procEditConns.childNodes);
RapidContext.Widget.destroyWidget(this.ui.procEditData.childNodes);
RapidContext.Widget.destroyWidget(this.ui.procEditProcs.childNodes);
RapidContext.Widget.destroyWidget(this.ui.procEditArgs.childNodes);
var parents = { connection: this.ui.procEditConns,
data: this.ui.procEditData,
procedure: this.ui.procEditProcs,
argument: this.ui.procEditArgs };
for (var k in data.bindings) {
var b = data.bindings[k];
var defaults = data.defaults[data.type][b.name];
var strong = MochiKit.DOM.STRONG({}, b.name + ": ");
var icon = (defaults == null) ? RapidContext.Widget.Icon({ ref: "REMOVE" }) : null;
var style = { "padding-top": icon ? "0px" : "3px", "padding-bottom": "4px", "white-space": "pre-line" };
var div = MochiKit.DOM.DIV({ style: style }, strong, icon, b.description);
var attrs = { name: "binding." + b.name, value: b.value,
style: { "width": "100%", "margin-bottom": "8px" } };
if (b.value.indexOf("\n") < 0) {
var field = RapidContext.Widget.TextField(attrs);
} else {
attrs.rows = Math.min(20, b.value.match(/\n/g).length + 2);
attrs.wrap = "off";
var field = RapidContext.Widget.TextArea(attrs);
}
var container = MochiKit.DOM.DIV({}, div, field);
if (icon) {
var func = function (name) {
delete data.bindings[name];
this._updateProcEdit();
};
MochiKit.Signal.connect(icon, "onclick", MochiKit.Base.bind(func, this, b.name));
}
parents[b.type].appendChild(container);
}
for (var k in parents) {
var node = parents[k];
if (node.childNodes.length == 0) {
var style = { "padding-top": "3px" };
var div = MochiKit.DOM.DIV({ style: style }, "< None >");
node.appendChild(div);
}
}
var className = (data.type == "javascript") ? "" : "hidden";
this.ui.procEditProcs.parentNode.className = className;
var opts = this.ui.procEditAddType.getElementsByTagName("option");
opts[0].disabled = (data.type != "javascript");
opts[1].disabled = (data.type != "javascript");
opts[2].disabled = (data.type != "javascript");
if (data.type != "javascript") {
this.ui.procEditAddType.selectedIndex = 3;
}
this.ui.procEditForm.update(data);
}
/**
* Adds a procedure binding from the input control.
*/
AdminApp.prototype._addProcBinding = function () {
var data = this.ui.procEditDialog.data;
var type = this.ui.procEditAddType.value;
var name = MochiKit.Format.strip(this.ui.procEditAddName.getValue());
if (name == "") {
RapidContext.UI.showError("Procedure binding name cannot be empty.");
this.ui.procEditAddName.focus();
} else if (data.bindings[name] != null) {
RapidContext.UI.showError("Procedure binding name already exists.");
this.ui.procEditAddName.focus();
} else {
var b = { name: name, type: type, description: "" };
b.value = (type == "data") ? "\n" : "";
data.bindings[name] = b;
this.ui.procEditAddName.setAttrs({ value: "" });
this._updateProcEdit();
}
}
/**
* Updates the procedure editing data from the form values. This
* method will automatically handle removed bindings, added bindings
* or modification of the procedure type. It will also trigger
* re-rendering of the form.
*/
AdminApp.prototype._updateProcEdit = function () {
var data = this.ui.procEditDialog.data;
var values = this.ui.procEditForm.valueMap();
data.name = values.name;
data.type = values.type;
data.description = values.description;
for (var k in values) {
if (k.indexOf("binding.") == 0) {
var name = k.substring(8);
if (data.bindings[name]) {
data.bindings[name].value = values[k];
}
}
}
var defaults = data.defaults[data.type];
for (var k in defaults) {
if (data.bindings[k] == null) {
var b = MochiKit.Base.clone(defaults[k]);
b.value = (b.type == "data") ? "\n" : "";
data.bindings[k] = b;
}
}
for (var k in data.bindings) {
var b = data.bindings[k];
var v = MochiKit.Format.strip(b.value);
if (defaults[k] == null && v == "" && b.description != "") {
delete data.bindings[k];
}
}
this._renderProcEdit();
}
/**
* Saves the procedure from the procedure edit dialog.
*/
AdminApp.prototype._saveProcedure = function () {
var data = this.ui.procEditDialog.data;
this._updateProcEdit();
var bindings = [];
for (var k in data.bindings) {
var b = data.bindings[k];
var res = { name: b.name, type: b.type };
if (b.type == "argument") {
res.description = b.value;
} else {
res.value = b.value;
}
bindings.push(res);
}
var args = [data.name, data.type, data.description, bindings];
var d = RapidContext.App.callProc("System.Procedure.Write", args);
d.addCallback(MochiKit.Base.bind("hide", this.ui.procEditDialog));
d.addCallback(MochiKit.Base.bind("recall", this.proc.procList));
d.addCallback(MochiKit.Base.bind("showProcedure", this, data.name));
d.addErrback(RapidContext.UI.showError);
}
/**
* Executes a procedure call for the current procedure.
*/
AdminApp.prototype._executeProcedure = function () {
var proc = this._currentProc;
var args = [];
var values = this._getProcArgs();
for (var i = 0; i < proc.bindings.length; i++) {
var b = proc.bindings[i];
if (b.type == "argument") {
var value = values[args.length].value;
if (values[args.length].type === "json") {
try {
value = MochiKit.Base.evalJSON(value);
} catch (e) {
RapidContext.UI.showError("Invalid JSON: " + value);
return;
}
} else if (value.length < 50) {
this._defaults[b.name] = value;
}
args.push(value);
}
}
this.ui.procExecLoading.show();
this.ui.procExec.disable();
this.ui.procBatch.disable();
this.ui.procExecResult.removeAll();
var d = RapidContext.App.callProc(proc.name, args);
d.addBoth(MochiKit.Base.bind("_callbackExecute", this));
}
/**
* Callback function for procedure execution.
*
* @param {Object} res the response data or error
*/
AdminApp.prototype._callbackExecute = function (res) {
this.ui.procExecLoading.hide();
this.ui.procExec.enable();
this.ui.procBatch.enable();
if (res instanceof Error) {
RapidContext.UI.showError(res);
} else {
this._showExecData(this.ui.procExecResult, res);
}
}
/**
* Expands a procedure result tree node by adding child data nodes.
* The node data can be retrieved from the node or by using a
* specified value.
*
* @param {Node} node the tree node (or tree) widget
* @param {Object} [data] the data object to add
*/
AdminApp.prototype._showExecData = function (node, data) {
function typeName(value) {
if (typeof(value) == "object") {
if (value == null) {
return "null";
} else if (value instanceof Number) {
return "Number";
} else if (value instanceof Boolean) {
return "Boolean";
} else if (value instanceof String) {
return "String";
} else if (value instanceof Array) {
return "Array";
} else if (value instanceof Date) {
return "Date";
} else if (value instanceof RegExp) {
return "RegExp";
} else {
return "Object";
}
} else {
return typeof(value);
}
}
function dataLabel(type, value, truncate) {
if (value == null) {
return "<null>";
} else if (type === "Array") {
return "[Array, length: " + value.length + "]";
} else if (type !== "Object") {
try {
var str = "[" + type + "] " + value.toString();
return truncate ? MochiKit.Text.truncate(str, 50, "...") : str;
} catch (e) {
return "[" + type + "]";
}
} else {
try {
if (value.hasOwnProperty("toString")) {
var str = value.toString();
return truncate ? MochiKit.Text.truncate(str, 50, "...") : str;
}
} catch (ignore) {
// Fallback to key enumeration
}
var keys = MochiKit.Base.keys(value);
return "[Object, " + keys.length + " properties]";
}
}
data = (typeof(data) !== "undefined") ? data : node.data;
var type = typeName(data);
if (node.getChildNodes().length > 0) {
// Do nothing
} else if (type === "Array" || type === "Object") {
for (var k in data) {
var v = data[k];
if (typeof(v) === "undefined") {
v = data[parseInt(k)];
}
var vt = typeName(v);
var attrs = { name: k + ": " + dataLabel(vt, v, true) };
if (vt === "Array" || vt === "Object") {
attrs.folder = true;
} else if (v != null) {
attrs.tooltip = dataLabel(vt, v, false);
}
var child = RapidContext.Widget.TreeNode(attrs);
if (vt === "Array" || vt === "Object") {
child.data = v;
}
node.addAll(child);
}
} else {
var attrs = { name: dataLabel(type, data, true),
tooltip: dataLabel(type, data, false) };
node.addAll(RapidContext.Widget.TreeNode(attrs));
}
}
/**
* Creates a new set of batch calls for the current procedure.
*/
AdminApp.prototype._createBatch = function () {
var proc = this._currentProc;
var args = [];
var count = null;
var values = this._getProcArgs();
for (var i = 0; i < proc.bindings.length; i++) {
var b = proc.bindings[i];
if (b.type == "argument") {
var value = values[args.length].value;
if (values[args.length].type === "json") {
try {
value = MochiKit.Base.evalJSON(value);
} catch (e) {
RapidContext.UI.showError("Invalid JSON: " + value);
return;
}
} else {
value = MochiKit.Base.map(MochiKit.Format.strip, value.split("\n"));
if (value.length <= 1) {
value = value[0];
}
}
if (value instanceof Array) {
if (count == null) {
count = value.length;
} else if (value.length != count) {
var msg = "Mismatching line count for field " + name +
": expected " + count + ", but found " +
value.length;
RapidContext.UI.showError(msg);
return;
}
}
args.push(value);
}
}
if (count == null) {
RapidContext.UI.showError("Multiple argument values required for batch creation");
return;
}
for (var i = 0; i < count; i++) {
var callArgs = [];
for (var j = 0; j < args.length; j++) {
var value = args[j];
if (value instanceof Array) {
callArgs.push(value[i]);
} else {
callArgs.push(value);
}
}
this._batch.queue.push({ proc: proc.name, args: callArgs });
}
this.ui.tabContainer.selectChild(this.ui.batchTab);
this._startBatch();
}
/**
* Configure the batch delay.
*/
AdminApp.prototype._configBatchDelay = function () {
var value;
value = prompt("Enter order processing delay (in seconds):",
"" + this._batch.delay);
if (value != null) {
value = parseInt(value, 10);
if (!isNaN(value)) {
this._batch.delay = Math.max(value, 0);
}
}
}
/**
* Starts the batch processing if not already running.
*/
AdminApp.prototype._startBatch = function () {
if (!this._batch.running) {
this._batch.running = true;
this._batch.stat.success = 0;
this._batch.stat.failed = 0;
this.ui.batchProgress.setAttrs({ min: 0, max: this._batch.queue.length, text: null });
this.ui.batchPlay.hide();
this.ui.batchPause.show();
this.ui.batchLoading.show();
this._processBatch();
}
}
/**
* Stops the batch processing if running.
*/
AdminApp.prototype._stopBatch = function () {
this._batch.running = false;
this.ui.batchPlay.show();
this.ui.batchPause.hide();
this.ui.batchLoading.hide();
}
/**
* Toggles the batch processing.
*/
AdminApp.prototype._toggleBatch = function () {
if (this._batch.running) {
this._stopBatch();
} else {
this._startBatch();
}
}
/**
* Stops the batch processing and clears the queue.
*/
AdminApp.prototype._clearBatch = function () {
this._stopBatch();
this._batch.queue = [];
this._batch.stat.success = 0;
this._batch.stat.failed = 0;
this.ui.batchForm.reset();
this.ui.batchProgress.setAttrs({ min: 0, max: 0, text: "Stopped" });
}
/**
* Processes the first item in the batch queue.
*/
AdminApp.prototype._processBatch = function () {
var item;
if (this._batch.running) {
item = this._batch.queue.shift();
if (item == null) {
this._stopBatch();
} else {
var d = RapidContext.App.callProc(item.proc, item.args);
d.addBoth(MochiKit.Base.bind("_callbackBatch", this));
}
}
}
/**
* Callback function for batch processing.
*
* @param {Object} res the call result data or error
*/
AdminApp.prototype._callbackBatch = function (res) {
var delay;
if (res instanceof Error) {
this._batch.stat.failed++;
} else {
this._batch.stat.success++;
}
this.ui.batchForm.update(this._batch.stat);
var done = this._batch.stat.success + this._batch.stat.failed;
var total = this._batch.queue.length + done;
if (this.ui.batchProgress.max != total) {
this.ui.batchProgress.setAttrs({ min: 0, max: total });
}
this.ui.batchProgress.setAttrs({ value: done });
if (this._batch.queue.length > 0) {
setTimeout(this._batch.func, this._batch.delay * 1000);
} else {
this._stopBatch();
}
}
/**
* Loads the list of users.
*/
AdminApp.prototype.loadUsers = function () {
this.proc.userList();
}
/**
* Modifies the user form for adding a new user.
*/
AdminApp.prototype._addUser = function () {
this.ui.userForm.reset();
this.ui.userForm.update({ enabled: true,
passwordHint: "Minimum 5 characters" });
this.ui.userId.enable();
}
/**
* Modifies the user form for editing an existing user.
*/
AdminApp.prototype._editUser = function () {
var data = this.ui.userTable.getSelectedData();
this.ui.userForm.reset();
var extra = { roles: (data.role) ? data.role.join(" ") : "",
passwordHint: "Leave blank for unmodified" };
this.ui.userForm.update(MochiKit.Base.update(extra, data));
this.ui.userId.disable();
}
/**
* Saves the user modification form.
*/
AdminApp.prototype._saveUser = function () {
var data = this.ui.userForm.valueMap();
if (this.ui.userForm.validate()) {
this.proc.userChange(data.id,
data.name,
data.email,
data.description,
data.enabled ? "1" : "0",
data.password,
data.roles);
}
}
/**
* Sets a new log level.
*/
AdminApp.prototype.setLogLevel = function (level) {
level = RapidContext.Log.level(level);
this.ui.logForm.update({ level: level });
};
/**
* Clears the log.
*/
AdminApp.prototype._clearLogs = function () {
RapidContext.Log.clear();
this.ui.logTable.setData([]);
MochiKit.DOM.replaceChildNodes(this.ui.logData);
};
/**
* Refreshes the log levels and table.
*/
AdminApp.prototype._showLogs = function () {
this.ui.logForm.update({ level: RapidContext.Log.level() });
this.ui.logTable.setData(RapidContext.Log.history());
};
/**
* Show log details for the selected log data.
*/
AdminApp.prototype._showLogDetails = function () {
var data = this.ui.logTable.getSelectedData();
var text;
if (data == null || data.data == null) {
text = "<no additional data>";
} else {
// TODO: Replace this string splitting with something more dynamic
var list = data.data.split("\n");
for (var i = 0; i < list.length; i++) {
var str = list[i];
var res = "";
while (str.length > 1000) {
var pos = str.lastIndexOf(" ", 1000);
pos = (pos < 500) ? 1000 : pos + 1;
res += str.substring(0, pos) + "\n ";
str = str.substring(pos);
}
list[i] = res + str;
}
text = MochiKit.DOM.PRE(null, list.join("\n"));
}
MochiKit.DOM.replaceChildNodes(this.ui.logData, text);
};
/**
* Stores an object to the RapidContext storage. Note that only
* read-write storages can be used for storage (typically the local
* plug-in). If the storage path does not point to a single mounted
* storage, the first writable overlay storage will be used (always
* the local plug-in).
*
* @param {String} path the storage path
* @param {Object} data the data object to store (JSON data)
*
* @return {Deferred} a MochiKit.Async.Deferred object that will
* callback when the data has been stored
*/
AdminApp.storageWrite = function (path, data) {
if (MochiKit.Text.startsWith("/", path)) {
path = path.substring(1);
}
var options = { method: "POST", timeout: 60, headers: {} };
options.headers["Content-Type"] = "application/json";
options.sendContent = MochiKit.Base.serializeJSON(data);
var d = RapidContext.App.loadXHR("rapidcontext/storage/" + path, null, options);
d.addCallback(function (xhr) {
if (xhr.status == 200 || xhr.status == 201) {
return path;
} else {
throw new MochiKit.Async.XMLHttpRequestError(xhr, "unrecognized response code");
}
});
d.addErrback(function (err) {
if (err instanceof MochiKit.Async.XMLHttpRequestError) {
var xhr = err.req;
var msg = xhr.responseText || xhr.statusText || err.message;
msg = msg.replace(/^HTTP \d+\s/i, "");
msg = msg.replace(/^.*:\s*([\s\S]+)/, "$1");
err.message = msg;
return err;
} else {
return err;
}
});
return d;
}
/**
* Removes an object from the RapidContext storage. Note that only
* objects in read-write storages can be removed (typically the local
* plug-in).
*
* @param {String} path the storage path
*
* @return {Deferred} a MochiKit.Async.Deferred object that will
* callback when the data has been removed
*/
AdminApp.storageDelete = function (path) {
if (MochiKit.Text.startsWith("/", path)) {
path = path.substring(1);
}
var options = { method: "DELETE", timeout: 60 };
var d = RapidContext.App.loadXHR("rapidcontext/storage/" + path, null, options);
d.addCallback(function (res) {
if (res.status == 204) {
return null;
} else {
throw new Error(res.statusText.substr(4));
}
});
return d;
}
/**
* Splits a text string into multiple lines. Existing line breaks
* will be preserved (recognizing "\n", "\r" or "\r\n"), but
* additional line breaks may be added by specifying a maximum line
* length. If the keepspace flag is set, the newlines and space
* characters at the end of each line will be preserved.
*
* @param {String} str the string to split
* @param {Number} [maxlen] the maximum line length, or zero for
* unlimited (defaults to 0)
* @param {Boolean} [keepspace] the boolean flag to keep
* trailing whitespace (defaults to false)
*
* @return {Array} an array of string for each line
*
* @example
*
*/
AdminApp.splitLines = function (str, maxlen, keepspace) {
var lines = [];
str = str || "";
maxlen = maxlen || 0;
function splitPush(str) {
if (!keepspace) {
str = str.replace(/\s+$/, "");
}
while (maxlen > 0 && str.length > maxlen) {
var line = str.substring(0, maxlen);
var m = /^\s+/.exec(str.substring(maxlen));
if (!keepspace && m) {
line += m[0];
} else {
m = /[^\s\).:,;=-]*$/.exec(line);
if (m && m.index > 0) {
line = line.substring(0, m.index);
}
}
str = str.substring(line.length);
if (!keepspace) {
line = line.replace(/\s+$/, "");
}
lines.push(line);
}
if (str.length > 0 || line == null) {
lines.push(str);
}
}
var re = /\n|\r\n|\r/g;
var m;
var pos = 0;
while ((m = re.exec(str)) != null) {
splitPush(str.substring(pos, re.lastIndex));
pos = re.lastIndex;
}
splitPush(str.substring(pos));
return lines;
}
|
import React from 'react';
export const CardNumber = ({ cardNumber }) => {
return (<div className='card-number'>
{cardNumber}
</div>);
};
|
var bson = require('bson'),
fs = require('fs'),
Q = require('q');
module.exports = binary;
function binary(store) {
var put = store.put,
get = store.get;
if (put) {
store.put = function (value) {
value.contents = new bson.Binary(fs.readFileSync(value.path));
return put.apply(this, arguments);
};
}
if (get) {
store.get = function () {
return Q.when(get.apply(this, arguments))
.then(convertObjectToStream);
};
}
return store;
}
function convertObjectToStream(object) {
var contents,
disposition,
metadata;
if (object) {
contents = object.contents;
object.forEach = function (each) {
each(contents.buffer);
};
object[ 'content-type' ] = object.type;
disposition = 'attachment';
if (object.name) {
disposition += ';filename="' + object.name + '"';
}
metadata = {
'content-type': object.type,
'content-length': contents.buffer.length,
'content-disposition': disposition,
filename: object.name,
alternates: [ object ]
};
object.forEach.binary = true;
object.getMetadata = function () {
return metadata;
};
}
return object;
}
|
import React from 'react';
import _ from 'lodash';
import styled, { css } from 'styled-components'
import PropTypes from 'prop-types';
import RectangleShape from '../Shape/RectangleShape';
class Element extends React.Component{
constructor(props){
super(props);
this.state = {
activeOption: this.props.initialOption,
}
}
handleClick = (id) => {
this.setState({activeOption: id})
_.invoke(this.props, 'onClick', id, this.props)
}
render(){
const {
className,
options,
} = this.props
return (
<ul className={className}>
{ _.values(options).map(option => (
// Replace <li/> with a component for better state handling and generic code
<li
key={option.id}
onClick={() => this.handleClick( option.id )}
>
<RectangleShape
background={`${ option.id === this.state.activeOption ? option.background : 'rgba(0,0,0,0.1)'}`}
raised={option.id === this.state.activeOption ? 1 : 0}
>
<input
type="hidden"
name={option.name}
value={option.value}
autoComplete="off"
/>
<div>
<span>
{option.label}
</span>
</div>
</RectangleShape>
</li>
))}
</ul>
)
};
};
Element.propTypes = {
/**
* The children of the component.
*/
children: PropTypes.node,
/**
* Additonal classes.
*/
className: PropTypes.string,
/**
* Description of the intreval the range.
*/
description: PropTypes.bool,
/**
* Description of the intreval the range.
*/
initialOption: PropTypes.string,
/**
* The range of the grades options 1-5 or 1-10
*/
options: PropTypes.arrayOf(PropTypes.shape(
{
value: PropTypes.string,
label: PropTypes.string,
name: PropTypes.string,
id: PropTypes.string,
}
))
}
Element.defaultProps = {
initialOption: undefined,
}
const Multiple = styled(Element)`
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 0;
list-style: none;
display: flex;
margin: 0;
font-weight: bold;
font-size: 0.9em;
li {
margin-bottom: 0.4em
div {
width: 100%
max-width: 100%;
display: flex;
justify-content: center;
align-items: center;
transition: all 0.3s ease
flex: 1;
}
}
li:last-child {
margin: 0;
}
${props => props.range === 10 && css`
font-size: 0.8em;
`}
`;
export default Multiple;
|
var WIDTH = 25;
var HEIGHT = 25;
function bind(callerObj, method) {
return function() {
return method.apply(callerObj, arguments);
};
}
// http://stackoverflow.com/questions/1740700/how-to-get-hex-color-value-rather-than-rgb-value
function rgb2hex(rgb) {
if(!rgb) return "#000000";
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
function Editor() {
Editor.prototype.start = function() {
this.x = 0;
this.y = 0;
this.sx = -1;
this.sy = -1;
this.teleport = -1;
this.rooms = [];
this.doors = [];
this.objects = [];
this.teleporters = [];
this.cursor = $("#cursor");
this.size = this.cursor.width();
this.viewport = $("#visual");
this.roomsChanged = false;
$(".swatch").first().addClass("active");
this.roomColor = rgb2hex($(".swatch").first().css("background-color"));
$("#visual").mousedown(bind(this, function(event) {
this.x = (event.clientX / this.size)|0;
this.y = (event.clientY / this.size)|0;
$("#cursor").css({
left: (this.x * this.size) + "px",
top: (this.y * this.size) + "px"
});
this.render();
}));
$(document).keydown(bind(this, function(event) {
if(event.target.id && event.target.id == "editor") return true;
//console.log(event.which, event.keyCode, event.target);
var handled = true;
switch(event.which) {
case 38: this.y--; break;
case 40: this.y++; break;
case 37: this.x--; break;
case 39: this.x++; break;
case 82: this.startRoom(); break;
case 27: this.deleteRoom(); break;
case 13: this.createRoom(); break;
case 84: this.createTeleporter(); break;
default: handled = false;
}
if(this.x < 0) this.x = 0;
if(this.y < 0) this.y = 0;
$("#cursor").css({
left: (this.x * this.size) + "px",
top: (this.y * this.size) + "px"
});
this.render();
this.scrollCursorIntoView();
if(handled) event.preventDefault();
return !handled;
}));
$("#load").click(bind(this, function(event) {
var d = JSON.parse($("#editor").val());
this.rooms = d.rooms || [];
this.doors = d.doors || [];
this.objects = d.objects || [];
this.teleporters = d.teleporters || [];
this.roomsChanged = true;
this.render();
return false;
}));
$(".swatch").click(bind(this, function(event) {
$(".swatch").removeClass("active");
$(event.currentTarget).addClass("active");
this.roomColor = rgb2hex($(event.currentTarget).css("background-color"));
var index = this.getRoomIndex();
if(index > -1) {
this.rooms[index].color = this.roomColor;
this.roomsChanged = true;
}
this.render();
}));
$("#add_object").click(bind(this, function(event) {
var index = this.getRoomIndex();
if(index > -1) {
var rot = $("#rot").val();
try {
rot = parseFloat(rot, 10);
} catch(exc) {
rot = 0;
}
this.objects.push({x:this.x, y:this.y, object:$("#objects").val(), room: index, rot: rot});
this.roomsChanged = true;
this.render();
}
}));
$("#set_door_type").click(bind(this, function(event) {
var index = this.getDoorIndex();
if(index > -1) {
this.doors[index].key = $("#doors").val();
this.roomsChanged = true;
this.render();
}
}));
$("#cave").click(bind(this, function(event) {
var index = this.getRoomIndex();
if(index > -1) {
this.rooms[index].cave = $("#cave").is(":checked");
this.roomsChanged = true;
this.render();
}
}));
};
Editor.prototype.getDoorIndex = function() {
for(var i = 0; i < this.doors.length; i++) {
if(this.x == this.doors[i].x && this.y == this.doors[i].y) {
return i;
}
}
return -1;
};
Editor.prototype.getRoomIndex = function() {
for(var i = 0; i < this.rooms.length; i++) {
var r = this.rooms[i];
if (this.x >= r.x && this.y >= r.y && this.x < r.x + r.w && this.y < r.y + r.h) {
return i;
}
}
return -1;
};
Editor.prototype.deleteRoom = function() {
this.sx = this.sy = -1;
var done = false;
for(var i = 0; i < this.objects.length; i++) {
if(this.objects[i].x == this.x && this.objects[i].y == this.y) {
this.objects.splice(i, 1);
this.roomsChanged = true;
done = true;
break;
}
}
if(!done) {
var index = this.getRoomIndex();
if (index > -1) {
var a = [];
for(var i = 0; i < this.teleporters.length; i++) {
if(this.teleporters[i].roomA != index && this.teleporters[i].roomB != index) a.push(this.teleporters[i]);
if(this.teleporters[i].roomA > index) this.teleporters[i].roomA--;
if(this.teleporters[i].roomB > index) this.teleporters[i].roomB--;
}
this.teleporters = a;
a = [];
for (var i = 0; i < this.objects.length; i++) {
if (this.objects[i].room != index) a.push(this.objects[i]);
}
this.objects = a;
this.rooms.splice(index, 1);
this.roomsChanged = true;
}
}
};
Editor.prototype.startRoom = function() {
this.sx = this.x;
this.sy = this.y;
};
Editor.prototype.createTeleporter = function() {
if(this.teleport == -1) {
this.teleport = this.getRoomIndex();
this.teleporters.push({ roomA: this.teleport, roomB: null });
} else {
this.teleporters[this.teleporters.length - 1].roomB = this.getRoomIndex();
this.teleport = -1;
}
this.roomsChanged = true;
};
Editor.prototype.createRoom = function() {
if(this.sx > -1) {
var sx = Math.min(this.x, this.sx);
var sy = Math.min(this.y, this.sy);
var w = Math.abs(this.x - this.sx) + 1;
var h = Math.abs(this.y - this.sy) + 1;
this.rooms.push({
x: sx,
y: sy,
w: w,
h: h,
color: this.roomColor,
cave: $("#cave").is(":checked")
});
this.sx = this.sy = -1;
this.roomsChanged = true;
}
};
Editor.prototype.render = function() {
if(this.roomsChanged) {
$(".room", this.viewport).remove();
for (var i = 0; i < this.rooms.length; i++) {
var room = this.rooms[i];
var teleporter = false;
for(var t = 0; t < this.teleporters.length; t++) {
if(this.teleporters[t].roomA == i || this.teleporters[t].roomB == i) {
teleporter = true;
break;
}
}
this.viewport.append("<div class='room" + (room.cave ? ' cave' : '') + (teleporter ? ' teleporter' : '') + "'></div>");
$(".room", this.viewport).last().css({
left: (room.x * this.size) + "px",
top: (room.y * this.size) + "px",
width: (room.w * this.size) + "px",
height: (room.h * this.size) + "px",
background: room.color
});
}
this.findDoors();
$(".door", this.viewport).remove();
for (var i = 0; i < this.doors.length; i++) {
var door = this.doors[i];
this.viewport.append("<div class='door'></div>");
if(door.key != "") $(".door", this.viewport).last().addClass(door.key);
$(".door", this.viewport).last().css({
left: (door.x * this.size + this.getDoorDx(door.dir)) + "px",
top: (door.y * this.size + this.getDoorDy(door.dir)) + "px"
});
}
$(".object", this.viewport).remove();
for(var i = 0; i < this.objects.length; i++) {
var o = this.objects[i];
this.viewport.append("<div class='object " + o.object + "'></div>");
$(".object", this.viewport).last().css({
left: (o.x * this.size) + "px",
top: (o.y * this.size) + "px"
});
}
$("#editor").val(JSON.stringify({rooms: this.rooms, doors: this.doors, objects: this.objects, teleporters: this.teleporters }));
}
if(this.sx > -1) {
if($(".room.active").length == 0) {
this.viewport.append("<div class='room active'></div>");
}
var sx = Math.min(this.x, this.sx);
var sy = Math.min(this.y, this.sy);
var w = Math.abs(this.x - this.sx) + 1;
var h = Math.abs(this.y - this.sy) + 1;
$(".room.active", this.viewport).last().css({
left: (sx * this.size) + "px",
top: (sy * this.size) + "px",
width: (w * this.size) + "px",
height: (h * this.size) + "px",
background: this.roomColor
});
} else {
if($(".room.active").length > 0) {
$(".room.active").remove();
}
}
};
Editor.prototype.findDoors = function() {
var seen = {};
// remember the keys
var keys = {};
for(var i = 0; i < this.doors.length; i++) {
var door = this.doors[i];
keys[door.roomA + ":" + door.roomB] = door.key;
}
// reset the doors
this.doors = [];
for(var i = 0; i < this.rooms.length; i++) {
var a = this.rooms[i];
for(var t = 0; t < this.rooms.length; t++) {
if(i != t) {
// only process each a:b rooms combo once
var key = Math.min(i, t) + ":" + Math.max(i, t);
if(!seen[key]) {
seen[key] = true;
var b = this.rooms[t];
var x, y, dir;
dir = null;
if (a.y == b.y + b.h) {
dir = "n";
y = a.y;
x = this.getCommonValue(a.x, a.w, b.x, b.w);
}
if (a.y + a.h == b.y) {
dir = "s";
y = a.y + a.h - 1;
x = this.getCommonValue(a.x, a.w, b.x, b.w);
}
if (a.x == b.x + b.w) {
dir = "w";
x = a.x;
y = this.getCommonValue(a.y, a.h, b.y, b.h);
}
if (a.x + a.w == b.x) {
dir = "e";
x = a.x + a.w - 1;
y = this.getCommonValue(a.y, a.h, b.y, b.h);
}
if(dir && x > -1 && y > -1) {
this.doors.push({x: x, y: y, dir: dir, roomA: i, roomB: t, key: keys[key] == null ? "" : keys[key]});
}
}
}
}
}
};
Editor.prototype.getCommonValue = function(a, aw, b, bw) {
if(b < a) {
var tmp = b; b = a; a = tmp;
tmp = bw; bw = aw; aw = tmp;
}
return a <= b && a + aw > b ? b + ((.5 * Math.min(bw, (a + aw - b)))|0) : -1;
};
Editor.prototype.getDoorDx = function(dir) {
//if(dir == "n" || dir == "s") return 0;
//return dir == "w" ? -this.size/2 : this.size/2;
return this.size * .25;
};
Editor.prototype.getDoorDy = function(dir) {
//if(dir == "e" || dir == "w") return 0;
//return dir == "n" ? -this.size/2 : this.size/2;
return this.size * .25;
};
Editor.prototype.scrollCursorIntoView = function() {
var cursorRect = this.cursor[0].getBoundingClientRect();
var viewportRect = this.viewport[0].getBoundingClientRect();
if(cursorRect.left < viewportRect.left || cursorRect.right > viewportRect.right ||
cursorRect.top < viewportRect.top || cursorRect.bottom > viewportRect.bottom) {
this.cursor[0].scrollIntoView();
}
};
}
|
const express = require('express');
const Methodic = require('../models/methodic');
const router = express.Router();
router.post('/', async (req, res, next) => {
const { email } = req.body;
const methodics = await Methodic.find({ doctorEmail: email });
res.json(methodics);
});
module.exports = router;
|
// @ts-check
/**
* @type {NodeListOf<HTMLInputElement>}
*/
const themeSwitch = document.querySelectorAll("input[name='themeSwitch']")
themeSwitch.forEach((radio) => {
radio.addEventListener("change", () => {
document.documentElement.dataset.theme = radio.value
})
})
const view = document.querySelector("[data-view]")
const keys = document.querySelectorAll(".Key")
keys.forEach((key) => {
key.addEventListener("click", (e) => {
e.preventDefault()
view.textContent = [...view.textContent.split(" "), key.textContent.trim()].join(" ")
// console.log(key.textContent.trim())
})
})
/**
* Format a numeric string into a comma-separated one.
* @param {string} numStr
*/
function formatNum(numStr) {
let formatted = ""
// TODO: what if the numstr begins with a sign or is a float?
const len = numStr.length
for (let i = 1; i <= len; i++) {
const nextDigit = numStr[len - i]
// Add a comma if i is a multiple of 3 and there's more digits in front
formatted = (i % 3 === 0 && i < len ? "," : "") + nextDigit + formatted
}
return formatted
}
window.play = function (num) {
const fmtted = formatNum(num)
const pattern = /^(\d{1,3})(,\d{3})*$/
console.log(fmtted)
console.log(pattern.test(fmtted))
}
|
!function(e,_){"object"==typeof exports&&"undefined"!=typeof module&&"function"==typeof require?_(require("../moment")):"function"==typeof define&&define.amd?define(["../moment"],_):_(e.moment)}(this,function(e){"use strict";function _(e,_,t){return"m"===t?_?"хвіліна":"хвіліну":"h"===t?_?"гадзіна":"гадзіну":e+" "+(e=+e,t=(t={mm:_?"хвіліна_хвіліны_хвілін":"хвіліну_хвіліны_хвілін",hh:_?"гадзіна_гадзіны_гадзін":"гадзіну_гадзіны_гадзін",dd:"дзень_дні_дзён",MM:"месяц_месяцы_месяцаў",yy:"год_гады_гадоў"}[t]).split("_"),e%10==1&&e%100!=11?t[0]:2<=e%10&&e%10<=4&&(e%100<10||20<=e%100)?t[1]:t[2])}return e.defineLocale("be",{months:{format:"студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня".split("_"),standalone:"студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань".split("_")},monthsShort:"студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж".split("_"),weekdays:{format:"нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу".split("_"),standalone:"нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота".split("_"),isFormat:/\[ ?[Вв] ?(?:мінулую|наступную)? ?\] ?dddd/},weekdaysShort:"нд_пн_ат_ср_чц_пт_сб".split("_"),weekdaysMin:"нд_пн_ат_ср_чц_пт_сб".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY г.",LLL:"D MMMM YYYY г., HH:mm",LLLL:"dddd, D MMMM YYYY г., HH:mm"},calendar:{sameDay:"[Сёння ў] LT",nextDay:"[Заўтра ў] LT",lastDay:"[Учора ў] LT",nextWeek:function(){return"[У] dddd [ў] LT"},lastWeek:function(){switch(this.day()){case 0:case 3:case 5:case 6:return"[У мінулую] dddd [ў] LT";case 1:case 2:case 4:return"[У мінулы] dddd [ў] LT"}},sameElse:"L"},relativeTime:{future:"праз %s",past:"%s таму",s:"некалькі секунд",m:_,mm:_,h:_,hh:_,d:"дзень",dd:_,M:"месяц",MM:_,y:"год",yy:_},meridiemParse:/ночы|раніцы|дня|вечара/,isPM:function(e){return/^(дня|вечара)$/.test(e)},meridiem:function(e,_,t){return e<4?"ночы":e<12?"раніцы":e<17?"дня":"вечара"},ordinalParse:/\d{1,2}-(і|ы|га)/,ordinal:function(e,_){switch(_){case"M":case"d":case"DDD":case"w":case"W":return e%10!=2&&e%10!=3||e%100==12||e%100==13?e+"-ы":e+"-і";case"D":return e+"-га";default:return e}},week:{dow:1,doy:7}})});
|
/** @module management */
var util = require('util');
var utils = require('../utils');
var jsonToBase64 = utils.jsonToBase64;
var generateClientInfo = utils.generateClientInfo;
var ArgumentError = require('rest-facade').ArgumentError;
// Managers.
var ClientsManager = require('./ClientsManager');
var ClientGrantsManager = require('./ClientGrantsManager');
var GrantsManager = require('./GrantsManager');
var UsersManager = require('./UsersManager');
var UserBlocksManager = require('./UserBlocksManager');
var ConnectionsManager = require('./ConnectionsManager');
var BlacklistedTokensManager = require('./BlacklistedTokensManager');
var RulesManager = require('./RulesManager');
var DeviceCredentialsManager = require('./DeviceCredentialsManager');
var EmailProviderManager = require('./EmailProviderManager');
var StatsManager = require('./StatsManager');
var TenantManager = require('./TenantManager');
var JobsManager = require('./JobsManager');
var TicketsManager = require('./TicketsManager');
var LogsManager = require('./LogsManager');
var LogStreamsManager = require('./LogStreamsManager');
var ResourceServersManager = require('./ResourceServersManager');
var ManagementTokenProvider = require('./ManagementTokenProvider');
var RulesConfigsManager = require('./RulesConfigsManager');
var EmailTemplatesManager = require('./EmailTemplatesManager');
var GuardianManager = require('./GuardianManager');
var CustomDomainsManager = require('./CustomDomainsManager');
var RolesManager = require('./RolesManager');
var HooksManager = require('./HooksManager');
var BrandingManager = require('./BrandingManager');
var MigrationsManager = require('./MigrationsManager');
var PromptsManager = require('./PromptsManager');
var BASE_URL_FORMAT = 'https://%s/api/v2';
var MANAGEMENT_API_AUD_FORMAT = 'https://%s/api/v2/';
/**
* @class ManagementClient
* Management API SDK.
*
* The Auth0 Management API is meant to be used by back-end servers or trusted
* parties performing administrative tasks. Generally speaking, anything that
* can be done through the Auth0 dashboard (and more) can also be done through
* this API.
* @constructor
* @memberOf module:management
*
* @example <caption>
* Initialize your client class with an API v2 token (you can generate one
* <a href="https://auth0.com/docs/apiv2">here</a>) and a domain.
* </caption>
*
* var ManagementClient = require('auth0').ManagementClient;
* var auth0 = new ManagementClient({
* domain: '{YOUR_ACCOUNT}.auth0.com',
* token: '{YOUR_API_V2_TOKEN}'
* });
*
*
* @example <caption>
* Initialize your client class, by using a Non Interactive Client to fetch an access_token
* via the Client Credentials Grant.
* </caption>
*
* var ManagementClient = require('auth0').ManagementClient;
* var auth0 = new ManagementClient({
* domain: '{YOUR_ACCOUNT}.auth0.com',
* clientId: '{YOUR_NON_INTERACTIVE_CLIENT_ID}',
* clientSecret: '{YOUR_NON_INTERACTIVE_CLIENT_SECRET}',
* scope: "read:users write:users",
* audience: 'https://{YOUR_TENANT_NAME}.auth0.com/api/v2/',
* tokenProvider: {
* enableCache: true,
* cacheTTLInSeconds: 10
* }
* });
*
* @param {Object} options Options for the ManagementClient SDK.
* If a token is provided only the domain is required, other parameters are ignored.
* If no token is provided domain, clientId, clientSecret and scopes are required
* @param {String} options.domain ManagementClient server domain.
* @param {String} [options.token] API access token.
* @param {String} [options.clientId] Management API Non Interactive Client Id.
* @param {String} [options.clientSecret] Management API Non Interactive Client Secret.
* @param {String} [options.audience] Management API Audience. By default is your domain's, e.g. the domain is `tenant.auth0.com` and the audience is `http://tenant.auth0.com/api/v2/`
* @param {String} [options.scope] Management API Scopes.
* @param {Boolean} [options.tokenProvider.enableCache=true] Enabled or Disable Cache.
* @param {Number} [options.tokenProvider.cacheTTLInSeconds] By default the `expires_in` value will be used to determine the cached time of the token, this can be overridden.
* @param {Boolean} [options.retry.enabled=true] Enabled or Disable Retry Policy functionality.
* @param {Number} [options.retry.maxRetries=10] Retry failed requests X times.
* @param {Object} [options.headers] Additional headers that will be added to the outgoing requests.
*
*/
var ManagementClient = function(options) {
if (!options || typeof options !== 'object') {
throw new ArgumentError('Management API SDK options must be an object');
}
if (!options.domain || options.domain.length === 0) {
throw new ArgumentError('Must provide a domain');
}
var baseUrl = util.format(BASE_URL_FORMAT, options.domain);
var userAgent = options.userAgent || 'node.js/' + process.version.replace('v', '');
var defaultHeaders = {
'User-Agent': 'node.js/' + process.version.replace('v', ''),
'Content-Type': 'application/json'
};
var managerOptions = {
headers: Object.assign(defaultHeaders, options.headers || {}),
baseUrl: baseUrl
};
if (options.token === undefined) {
var config = Object.assign(
{ audience: util.format(MANAGEMENT_API_AUD_FORMAT, options.domain) },
options
);
if (options.tokenProvider) {
config.enableCache = options.tokenProvider.enableCache;
config.cacheTTLInSeconds = options.tokenProvider.cacheTTLInSeconds;
delete config.tokenProvider;
}
this.tokenProvider = new ManagementTokenProvider(config);
managerOptions.tokenProvider = this.tokenProvider;
} else if (typeof options.token !== 'string' || options.token.length === 0) {
throw new ArgumentError('Must provide a token');
} else {
this.tokenProvider = {
getAccessToken: function() {
return Promise.resolve(options.token);
}
};
managerOptions.headers['Authorization'] = 'Bearer ' + options.token;
}
if (options.telemetry !== false) {
var clientInfo = options.clientInfo || generateClientInfo();
if ('string' === typeof clientInfo.name && clientInfo.name.length > 0) {
var telemetry = jsonToBase64(clientInfo);
managerOptions.headers['Auth0-Client'] = telemetry;
}
}
managerOptions.retry = options.retry;
/**
* Simple abstraction for performing CRUD operations on the
* clients endpoint.
*
* @type {ClientsManager}
*/
this.clients = new ClientsManager(managerOptions);
/**
* Simple abstraction for performing CRUD operations on the client grants
* endpoint.
*
* @type {ClientGrantsManager}
*/
this.clientGrants = new ClientGrantsManager(managerOptions);
/**
* Simple abstraction for performing CRUD operations on the grants
* endpoint.
*
* @type {GrantsManager}
*/
this.grants = new GrantsManager(managerOptions);
/**
* Simple abstraction for performing CRUD operations on the
* users endpoint.
*
* @type {UsersManager}
*/
this.users = new UsersManager(managerOptions);
/**
* Simple abstraction for performing CRUD operations on the
* user-blocks endpoint.
*
* @type {UserBlocksManager}
*/
this.userBlocks = new UserBlocksManager(managerOptions);
/**
* Simple abstraction for performing CRUD operations on the
* guardian endpoint.
*
* @type {GuardianManager}
*/
this.guardian = new GuardianManager(managerOptions);
/**
* Simple abstraction for performing CRUD operations on the
* custom domains endpoint.
*
* @type {CustomDomainsManager}
*/
this.customDomains = new CustomDomainsManager(managerOptions);
/**
* Simple abstraction for performing CRUD operations on the
* connections endpoint.
*
* @type {ConnectionsManager}
*/
this.connections = new ConnectionsManager(managerOptions);
/**
* Simple abstraction for performing CRUD operations on the
* device credentials endpoint.
*
* @type {DeviceCredentialsManager}
*/
this.deviceCredentials = new DeviceCredentialsManager(managerOptions);
/**
* Simple abstraction for performing CRUD operations on the
* rules endpoint.
*
* @type {RulesManager}
*/
this.rules = new RulesManager(managerOptions);
/**
* Simple abstraction for performing CRUD operations on the
* blacklisted tokens endpoint.
*
* @type {BlacklistedtokensManager}
*/
this.blacklistedTokens = new BlacklistedTokensManager(managerOptions);
/**
* Simple abstraction for performing CRUD operations on the
* email provider endpoint.
*
* @type {EmailProviderManager}
*/
this.emailProvider = new EmailProviderManager(managerOptions);
/**
* ManagementClient account statistics manager.
*
* @type {StatsManager}
*/
this.stats = new StatsManager(managerOptions);
/**
* ManagementClient tenant settings manager.
*
* @type {TenantManager}
*/
this.tenant = new TenantManager(managerOptions);
/**
* Jobs manager.
*
* @type {JobsManager}
*/
this.jobs = new JobsManager(managerOptions);
/**
* Tickets manager.
*
* @type {TicketsManager}
*/
this.tickets = new TicketsManager(managerOptions);
/**
* Logs manager.
*
* @type {LogsManager}
*/
this.logs = new LogsManager(managerOptions);
/**
* Log Streams manager.
*
* @type {LogStreamsManager}
*/
this.logStreams = new LogStreamsManager(managerOptions);
/**
* Simple abstraction for performing CRUD operations on the
* resource servers endpoint.
*
* @type {ResourceServersManager}
*/
this.resourceServers = new ResourceServersManager(managerOptions);
/**
* Simple abstraction for performing CRUD operations on
* Auth0's Email Templates
*
* @type {EmailTemplatesManager}
*/
this.emailTemplates = new EmailTemplatesManager(managerOptions);
/**
* RulesConfigs manager.
*
* @type {RulesConfigsManager}
*/
this.rulesConfigs = new RulesConfigsManager(managerOptions);
/**
* Simple abstraction for performing CRUD operations on the
* roles endpoint.
*
* @type {RolesManager}
*/
this.roles = new RolesManager(managerOptions);
/**
* Simple abstraction for performing CRUD operations on the
* hooks endpoint.
*
* @type {HooksManager}
*/
this.hooks = new HooksManager(managerOptions);
/**
* Simple abstraction for performing CRUD operations on the
* branding endpoint.
*
* @type {HooksManager}
*/
this.branding = new BrandingManager(managerOptions);
/**
* ManagementClient migrations manager.
*
* @type {MigrationsManager}
*/
this.migrations = new MigrationsManager(managerOptions);
/**
* Prompts Manager
*
* @type {PromptsManager}
*/
this.prompts = new PromptsManager(managerOptions);
};
/**
* Get all connections.
*
* @method getConnections
* @memberOf module:management.ManagementClient.prototype
*
* @example <caption>
* This method takes an optional object as first argument that may be used to
* specify pagination settings. If pagination options are not present,
* the first page of a limited number of results will be returned.
* </caption>
*
* // Pagination settings.
* var params = {
* per_page: 10,
* page: 0
* };
*
* management.getConnections(params, function (err, connections) {
* console.log(connections.length);
* });
*
* @param {Object} [params] Connections params.
* @param {Number} [params.per_page] Number of results per page.
* @param {Number} [params.page] Page number, zero indexed.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getConnections', 'connections.getAll');
/**
* Create a new connection.
*
* @method createConnection
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.createConnection(data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Connection created.
* });
*
* @param {Object} data Connection data object.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'createConnection', 'connections.create');
/**
* Get an Auth0 connection.
*
* @method getConnection
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getConnection({ id: CONNECTION_ID }, function (err, connection) {
* if (err) {
* // Handle error.
* }
*
* console.log(connection);
* });
*
* @param {Object} params Connection parameters.
* @param {String} params.id Connection ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getConnection', 'connections.get');
/**
* Delete an existing connection.
*
* @method deleteConnection
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.deleteConnection({ id: CONNECTION_ID }, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Connection deleted.
* });
*
* @param {Object} params Connection parameters.
* @param {String} params.id Connection ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'deleteConnection', 'connections.delete');
/**
* Update an existing connection.
*
* @method updateConnection
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var data = { name: 'newConnectionName' };
* var params = { id: CONNECTION_ID };
*
* management.updateConnection(params, data, function (err, connection) {
* if (err) {
* // Handle error.
* }
*
* console.log(connection.name); // 'newConnectionName'
* });
*
* @param {Object} params Connection parameters.
* @param {String} params.id Connection ID.
* @param {Object} data Updated connection data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateConnection', 'connections.update');
/**
* Get all Auth0 clients.
*
* @method getClients
* @memberOf module:management.ManagementClient.prototype
*
* @example <caption>
* This method takes an optional object as first argument that may be used to
* specify pagination settings. If pagination options are not present,
* the first page of a limited number of results will be returned.
* </caption>
*
* // Pagination settings.
* var params = {
* per_page: 10,
* page: 0
* };
*
* management.getClients(params, function (err, clients) {
* console.log(clients.length);
* });
*
* @param {Object} [params] Clients parameters.
* @param {Number} [params.per_page] Number of results per page.
* @param {Number} [params.page] Page number, zero indexed.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getClients', 'clients.getAll');
/**
* Get an Auth0 client.
*
* @method getClient
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getClient({ client_id: CLIENT_ID }, function (err, client) {
* if (err) {
* // Handle error.
* }
*
* console.log(client);
* });
*
* @param {Object} params Client parameters.
* @param {String} params.client_id Application client ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getClient', 'clients.get');
/**
* Create an Auth0 client.
*
* @method createClient
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.createClient(data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Client created.
* });
*
* @param {Object} data The client data object.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'createClient', 'clients.create');
/**
* Update an Auth0 client.
*
* @method updateClient
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var data = { name: 'newClientName' };
* var params = { client_id: CLIENT_ID };
*
* management.updateClient(params, data, function (err, client) {
* if (err) {
* // Handle error.
* }
*
* console.log(client.name); // 'newClientName'
* });
*
* @param {Object} params Client parameters.
* @param {String} params.client_id Application client ID.
* @param {Object} data Updated client data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateClient', 'clients.update');
/**
* Delete an Auth0 client.
*
* @method deleteClient
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.deleteClient({ client_id: CLIENT_ID }, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Client deleted.
* });
*
* @param {Object} params Client parameters.
* @param {String} params.client_id Application client ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'deleteClient', 'clients.delete');
/**
* Get all Auth0 Client Grants.
*
* @method getClientGrants
* @memberOf module:management.ManagementClient.prototype
*
* @example <caption>
* This method takes an optional object as first argument that may be used to
* specify pagination settings. If pagination options are not present,
* the first page of a limited number of results will be returned.
* </caption>
*
* // Pagination settings.
* var params = {
* per_page: 10,
* page: 0
* };
*
* management.getClientGrants(params, function (err, grants) {
* console.log(grants.length);
* });
*
* @param {Object} [params] Client Grants parameters.
* @param {Number} [params.per_page] Number of results per page.
* @param {Number} [params.page] Page number, zero indexed.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getClientGrants', 'clientGrants.getAll');
/**
* Create an Auth0 client grant.
*
* @method createClientGrant
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.clientGrants.create(data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Client grant created.
* });
*
* @param {Object} data The client data object.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'createClientGrant', 'clientGrants.create');
/**
* Update an Auth0 client grant.
*
* @method updateClientGrant
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var data = {
* client_id: CLIENT_ID,
* audience: AUDIENCE,
* scope: []
* };
* var params = { id: CLIENT_GRANT_ID };
*
* management.clientGrants.update(params, data, function (err, grant) {
* if (err) {
* // Handle error.
* }
*
* console.log(grant.id);
* });
*
* @param {Object} params Client parameters.
* @param {String} params.id Client grant ID.
* @param {Object} data Updated client data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateClientGrant', 'clientGrants.update');
/**
* Delete an Auth0 client grant.
*
* @method deleteClientGrant
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.clientGrants.delete({ id: GRANT_ID }, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Grant deleted.
* });
*
* @param {Object} params Client parameters.
* @param {String} params.id Client grant ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'deleteClientGrant', 'clientGrants.delete');
/**
* Get all Auth0 Grants.
*
* @method getGrants
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = {
* per_page: 10,
* page: 0,
* include_totals: true,
* user_id: USER_ID,
* client_id: CLIENT_ID,
* audience: AUDIENCE
* };
*
* management.getGrants(params, function (err, grants) {
* console.log(grants.length);
* });
*
* @param {Object} params Grants parameters.
* @param {Number} params.per_page Number of results per page.
* @param {Number} params.page Page number, zero indexed.
* @param {Boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false;
* @param {String} params.user_id The user_id of the grants to retrieve.
* @param {String} params.client_id The client_id of the grants to retrieve.
* @param {String} params.audience The audience of the grants to retrieve.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getGrants', 'grants.getAll');
/**
* Delete an Auth0 grant.
*
* @method deleteGrant
* @memberOf module:management.GrantsManager.prototype
*
* @example
* var params = {
* id: GRANT_ID,
* user_id: USER_ID
* };
*
* management.deleteGrant(params, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Grant deleted.
* });
*
* @param {Object} params Grant parameters.
* @param {String} params.id Grant ID.
* @param {String} params.user_id The user_id of the grants to delete.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'deleteGrant', 'grants.delete');
/**
* Create an Auth0 credential.
*
* @method createDevicePublicKey
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.createConnection(data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Credential created.
* });
*
* @param {Object} data The device credential data object.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'createDevicePublicKey',
'deviceCredentials.createPublicKey'
);
/**
* Get all Auth0 credentials.
*
* @method getDeviceCredentials
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = {user_id: "USER_ID"};
*
* management.getDeviceCredentials(params, function (err, credentials) {
* console.log(credentials.length);
* });
*
* @param {Object} params Credential parameters.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getDeviceCredentials', 'deviceCredentials.getAll');
/**
* Delete an Auth0 device credential.
*
* @method deleteDeviceCredential
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: CREDENTIAL_ID };
*
* management.deleteDeviceCredential(params, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Credential deleted.
* });
*
* @param {Object} params Credential parameters.
* @param {String} params.id Device credential ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'deleteDeviceCredential', 'deviceCredentials.delete');
/**
* Get all rules.
*
* @method getRules
* @memberOf module:management.ManagementClient.prototype
*
* @example <caption>
* This method takes an optional object as first argument that may be used to
* specify pagination settings. If pagination options are not present,
* the first page of a limited number of results will be returned.
* </caption>
*
* // Pagination settings.
* var params = {
* per_page: 10,
* page: 0
* };
*
* management.getRules(params, function (err, rules) {
* console.log(rules.length);
* });
*
* @param {Object} [params] Rules parameters.
* @param {Number} [params.per_page] Number of results per page.
* @param {Number} [params.page] Page number, zero indexed.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getRules', 'rules.getAll');
/**
* Create a new rule.
*
* @method createRule
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.createRule(data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Rule created.
* });
*
* @param {Object} data Rule data object.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'createRule', 'rules.create');
/**
* Get an Auth0 rule.
*
* @method getRule
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getRule({ id: RULE_ID }, function (err, rule) {
* if (err) {
* // Handle error.
* }
*
* console.log(rule);
* });
*
* @param {Object} params Rule parameters.
* @param {String} params.id Rule ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getRule', 'rules.get');
/**
* Delete an existing rule.
*
* @method deleteRule
* @memberOf module:management.ManagementClient.prototype
*
* @example
* auth0.deleteRule({ id: RULE_ID }, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Rule deleted.
* });
*
* @param {Object} params Rule parameters.
* @param {String} params.id Rule ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'deleteRule', 'rules.delete');
/**
* Update an existing rule.
*
* @method updateRule
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: RULE_ID };
* var data = { name: 'my-rule'};
* management.updateRule(params, data, function (err, rule) {
* if (err) {
* // Handle error.
* }
*
* console.log(rule.name); // 'my-rule'.
* });
*
* @param {Object} params Rule parameters.
* @param {String} params.id Rule ID.
* @param {Object} data Updated rule data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateRule', 'rules.update');
/**
* Get all users.
*
* @method getUsers
* @memberOf module:management.ManagementClient.prototype
*
* @example <caption>
* This method takes an optional object as first argument that may be used to
* specify pagination settings. If pagination options are not present,
* the first page of a limited number of results will be returned.
* </caption>
*
* // Pagination settings.
* var params = {
* search_engine: 'v3',
* q: 'name:*jane*',
* per_page: 10,
* page: 0
* };
*
* auth0.getUsers(params, function (err, users) {
* console.log(users.length);
* });
*
* @param {Object} [params] Users params.
* @param {Number} [params.search_engine] The version of the search engine to use.
* @param {String} [params.q] User Search string to filter which users are returned. Follows Lucene query string syntax as documented at https://auth0.com/docs/api/management/v2#!/Users/get_users.
* @param {Number} [params.per_page] Number of results per page.
* @param {Number} [params.page] Page number, zero indexed.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getUsers', 'users.getAll');
/**
* Get users for a given email address
*
* @method getUsersByEmail
* @memberOf module:management.ManagementClient.prototype
*
* @example <caption>
* This method takes an email address as the first argument,
* and returns all users with that email address
* </caption>
*
* auth0.getUsersByEmail(email, function (err, users) {
* console.log(users);
* });
*
* @param {String} [email] Email Address of users to locate
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getUsersByEmail', 'users.getByEmail');
/**
* Get a user by its id.
*
* @method getUser
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getUser({ id: USER_ID }, function (err, user) {
* console.log(user);
* });
*
* @param {Object} data The user data object.
* @param {String} data.id The user id.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getUser', 'users.get');
/**
* Delete all users.
*
* @method deleteAllUsers
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.deleteAllUsers(function (err) {
* if (err) {
* // Handle error.
* }
*
* // Users deleted
* });
*
* @param {Function} [cb] Callback function
*
* @return {Promise|undefined}
*
* @deprecated This method will be removed in the next major release.
*/
utils.wrapPropertyMethod(ManagementClient, 'deleteAllUsers', 'users.deleteAll');
/**
* Delete a user by its id.
*
* @method deleteUser
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.deleteUser({ id: USER_ID }, function (err) {
* if (err) {
* // Handle error.
* }
*
* // User deleted.
* });
*
* @param {Object} params The user data object..
* @param {String} params.id The user id.
* @param {Function} [cb] Callback function
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'deleteUser', 'users.delete');
/**
* Create a new user.
*
* @method createUser
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.createUser(data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // User created.
* });
*
* @param {Object} data User data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'createUser', 'users.create');
/**
* Update a user by its id.
*
* @method updateUser
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: USER_ID };
*
* management.updateUser(params, data, function (err, user) {
* if (err) {
* // Handle error.
* }
*
* // Updated user.
* console.log(user);
* });
*
* @param {Object} params The user parameters.
* @param {String} params.id The user id.
* @param {Object} data New user data.
* @param {Function} [cb] Callback function
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateUser', 'users.update');
/**
* Update the user metadata for a user.
*
* @method updateUserMetadata
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: USER_ID };
* var metadata = {
* address: '123th Node.js Street'
* };
*
* management.updateUserMetadata(params, metadata, function (err, user) {
* if (err) {
* // Handle error.
* }
*
* // Updated user.
* console.log(user);
* });
*
* @param {Object} params The user data object..
* @param {String} params.id The user id.
* @param {Object} metadata New user metadata.
* @param {Function} [cb] Callback function
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateUserMetadata', 'users.updateUserMetadata');
/**
* Update the app metadata for a user.
*
* @method updateAppMetadata
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: USER_ID };
* var metadata = {
* foo: 'bar'
* };
*
* management.updateAppMetadata(params, metadata, function (err, user) {
* if (err) {
* // Handle error.
* }
*
* // Updated user.
* console.log(user);
* });
*
* @param {Object} params The user data object..
* @param {String} params.id The user id.
* @param {Object} metadata New app metadata.
* @param {Function} [cb] Callback function
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateAppMetadata', 'users.updateAppMetadata');
/**
* Delete a multifactor provider for a user.
*
* @method deleteUserMultifactor
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: USER_ID, provider: MULTIFACTOR_PROVIDER };
*
* management.deleteUserMultifactor(params, function (err, user) {
* if (err) {
* // Handle error.
* }
*
* // Users accounts unlinked.
* });
*
* @param {Object} params Data object.
* @param {String} params.id The user id.
* @param {String} params.provider Multifactor provider.
* @param {Function} [cb] Callback function
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'deleteUserMultifactor',
'users.deleteMultifactorProvider'
);
/**
* Delete a multifactor provider for a user.
*
* @method deleteUserMultifcator
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: USER_ID, provider: MULTIFACTOR_PROVIDER };
*
* management.deleteUserMultifcator(params, function (err, user) {
* if (err) {
* // Handle error.
* }
*
* // Users accounts unlinked.
* });
*
* @param {Object} params Data object.
* @param {String} params.id The user id.
* @param {String} params.provider Multifactor provider.
* @param {Function} [cb] Callback function
*
* @return {Promise|undefined}
*
* @deprecated The function name has a typo.
* We're shipping this so it doesn't break compatibility.
* Use {@link deleteUserMultifactor} instead.
*/
utils.wrapPropertyMethod(
ManagementClient,
'deleteUserMultifcator',
'users.deleteMultifactorProvider'
);
/**
* Unlink the given accounts.
*
* @method unlinkUsers
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: USER_ID, provider: 'auht0', user_id: OTHER_USER_ID };
*
* management.unlinkUsers(params, function (err, user) {
* if (err) {
* // Handle error.
* }
*
* // Users accounts unlinked.
* });
*
* @param {Object} params Linked users data.
* @param {String} params.id Primary user ID.
* @param {String} params.provider Identity provider in use.
* @param {String} params.user_id Secondary user ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'unlinkUsers', 'users.unlink');
/**
* Link the user with another account.
*
* @method linkUsers
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var userId = 'USER_ID';
* var params = {
* user_id: 'OTHER_USER_ID',
* connection_id: 'CONNECTION_ID'
* };
*
* management.linkUsers(userId, params, function (err, user) {
* if (err) {
* // Handle error.
* }
*
* // Users linked.
* });
*
* @param {String} userId ID of the primary user.
* @param {Object} params Secondary user data.
* @param {String} params.user_id ID of the user to be linked.
* @param {String} params.connection_id ID of the connection to be used.
* @param {String} params.provider Identity provider of the secondary user account being linked.
* @param {String} params.link_with JWT for the secondary account being linked. If sending this parameter, provider, user_id, and connection_id must not be sent.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'linkUsers', 'users.link');
/**
* Get user's log events.
*
* @method getUserLogs
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: USER_ID, page: 0, per_page: 50, sort: 'date:-1', include_totals: true };
*
* management.getUserLogs(params, function (err, logs) {
* if (err) {
* // Handle error.
* }
*
* console.log(logs);
* });
*
* @param {Object} params Get logs data.
* @param {String} params.id User id.
* @param {Number} params.per_page Number of results per page.
* @param {Number} params.page Page number, zero indexed.
* @param {String} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1.
* @param {Boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false;
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getUserLogs', 'users.logs');
/**
* Get user's roles
*
* @method getUserRoles
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: USER_ID, page: 0, per_page: 50, sort: 'date:-1', include_totals: true };
*
* management.getUserRoles(params, function (err, logs) {
* if (err) {
* // Handle error.
* }
*
* console.log(logs);
* });
*
* @param {Object} params Get roles data.
* @param {String} params.id User id.
* @param {Number} params.per_page Number of results per page.
* @param {Number} params.page Page number, zero indexed.
* @param {String} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1.
* @param {Boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false;
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getUserRoles', 'users.getRoles');
/**
* Assign roles to a user
*
* @method assignRolestoUser
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var parms = { id : 'USER_ID'};
* var data = { "roles" :["role1"]};
*
* management.assignRolestoUser(params, data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // User assigned roles.
* });
*
* @param {Object} params params object
* @param {String} params.id user_id
* @param {Object} data data object containing list of role IDs
* @param {String} data.roles Array of role IDs
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'assignRolestoUser', 'users.assignRoles');
/**
* Assign users to a role
*
* @method assignUsersToRole
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id :'ROLE_ID'};
* var data = { "users" : ["userId1","userId2"]};
*
* management.roles.assignUsers(params, data, function (err, user) {
* if (err) {
* // Handle error.
* }
*
* // permissions added.
* });
*
* @param {String} params.id ID of the Role.
* @param {Object} data permissions data
* @param {String} data.permissions Array of permissions
* @param {String} data.permissions.permission_name Name of a permission
* @param {String} data.permissions.resource_server_identifier Identifier for a resource
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'assignUsersToRole', 'roles.assignUsers');
/**
* Remove roles from a user
*
* @method removeRolesFromUser
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var parms = { id : 'USER_ID'};
* var data = { "roles" :["role1"]};
*
* management.removeRolesFromUser(params, data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // User assigned roles.
* });
*
* @param {Object} params params object
* @param {String} params.id user_id
* @param {String} data data object containing list of role IDs
* @param {String} data.roles Array of role IDs
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'removeRolesFromUser', 'users.removeRoles');
/**
* Get user's permissions
*
* @method getUserPermissions
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: USER_ID, page: 0, per_page: 50, sort: 'date:-1', include_totals: true };
*
* management.getUserPermissions(params, function (err, logs) {
* if (err) {
* // Handle error.
* }
*
* console.log(logs);
* });
*
* @param {Object} params Get permissions data.
* @param {String} params.id User id.
* @param {Number} params.per_page Number of results per page.
* @param {Number} params.page Page number, zero indexed.
* @param {String} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1.
* @param {Boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false;
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getUserPermissions', 'users.getPermissions');
/**
* Assign permissions to a user
*
* @method assignPermissionsToUser
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var parms = { id : 'USER_ID'};
* var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]};
*
* management.assignPermissionsToUser(params, data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // User assigned permissions.
* });
*
* @param {Object} params params object
* @param {String} params.id user_id
* @param {String} data data object containing list of permissions
* @param {String} data.permissions Array of permission IDs
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'assignPermissionsToUser', 'users.assignPermissions');
/**
* Remove permissions from a user
*
* @method removePermissionsFromUser
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var parms = { id : 'USER_ID'};
* var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]};
*
* management.removePermissionsFromUser(params, data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // User assigned permissions.
* });
*
* @param {Object} params params object
* @param {String} params.id user_id
* @param {String} data data object containing list of permission IDs
* @param {String} data.permissions Array of permission IDs
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'removePermissionsFromUser', 'users.removePermissions');
/**
* Get a list of a user's Guardian enrollments.
*
* @method getGuardianEnrollments
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getGuardianEnrollments({ id: USER_ID }, function (err, enrollments) {
* console.log(enrollments);
* });
*
* @param {Object} data The user data object.
* @param {String} data.id The user id.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'getGuardianEnrollments',
'users.getGuardianEnrollments'
);
/**
* Generate new Guardian recovery code.
*
* @method regenerateRecoveryCode
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.regenerateRecoveryCode({ id: USER_ID }, function (err, newRecoveryCode) {
* console.log(newRecoveryCode);
* });
*
* @param {Object} data The user data object.
* @param {String} data.id The user id.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'regenerateRecoveryCode',
'users.regenerateRecoveryCode'
);
/**
* Invalidate all remembered browsers for MFA.
*
* @method invalidateRememberBrowser
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.invalidateRememberBrowser({ id: USER_ID }, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Invalidated all remembered browsers.
* });
*
* @param {Object} data The user data object.
* @param {String} data.id The user id.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'invalidateRememberBrowser',
'users.invalidateRememberBrowser'
);
/**
* Get user blocks by its id.
*
* @method getUserBlocks
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getUserBlocks({ id: USER_ID }, function (err, blocks) {
* if (err) {
* // Handle error.
* }
*
* console.log(blocks);
* });
*
* @param {Object} params The user data object..
* @param {String} params.id The user id.
* @param {Function} [cb] Callback function
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getUserBlocks', 'userBlocks.get');
/**
* Unblock an user by its id.
*
* @method unblockUser
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.unblockUser({ id: USER_ID }, function (err) {
* if (err) {
* // Handle error.
* }
*
* // User unblocked.
* });
*
* @param {Object} params The user data object..
* @param {String} params.id The user id.
* @param {Function} [cb] Callback function
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'unblockUser', 'userBlocks.delete');
/**
* Get user blocks by its identifier.
*
* @method getUserBlocksByIdentifier
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getUserBlocksByIdentifier({ identifier: USER_ID }, function (err, blocks) {
* if (err) {
* // Handle error.
* }
*
* console.log(blocks);
* });
*
* @param {Object} params The user data object..
* @param {String} params.identifier The user identifier, any of: username, phone_number, email.
* @param {Function} [cb] Callback function
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'getUserBlocksByIdentifier',
'userBlocks.getByIdentifier'
);
/**
* Unblock an user by its id.
*
* @method unblockUser
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.unblockUserByIdentifier({ identifier: USER_ID }, function (err) {
* if (err) {
* // Handle error.
* }
*
* // User unblocked.
* });
*
* @param {Object} params The user data object..
* @param {String} params.identifier The user identifier, any of: username, phone_number, email.
* @param {Function} [cb] Callback function
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'unblockUserByIdentifier',
'userBlocks.deleteByIdentifier'
);
/**
* Get a single Guardian enrollment.
*
* @method getGuardianEnrollment
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getGuardianEnrollment({ id: ENROLLMENT_ID }, function (err, enrollment) {
* console.log(enrollment);
* });
*
* @param {Object} data The Guardian enrollment data object.
* @param {String} data.id The Guardian enrollment id.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'getGuardianEnrollment',
'guardian.getGuardianEnrollment'
);
/**
* Delete a user's Guardian enrollment.
*
* @method deleteGuardianEnrollment
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.deleteGuardianEnrollment({ id: ENROLLMENT_ID }, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Email provider deleted.
* });
*
* @param {Object} data The Guardian enrollment data object.
* @param {String} data.id The Guardian enrollment id.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'deleteGuardianEnrollment',
'guardian.deleteGuardianEnrollment'
);
/**
* Get all blacklisted tokens.
*
* @method getBlacklistedTokens
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getBlacklistedTokens(function (err, tokens) {
* console.log(tokens.length);
* });
*
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getBlacklistedTokens', 'blacklistedTokens.getAll');
/**
* Blacklist a new token.
*
* @method blacklistToken
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var token = {
* aud: 'aud',
* jti: 'jti'
* };
*
* management.blacklistToken(token, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Token blacklisted.
* });
*
* @param {Object} token Token data.
* @param {String} token.aud Audience (your app client ID).
* @param {String} token.jti The JWT ID claim.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'blacklistToken', 'blacklistedTokens.add');
/**
* Create a new Email Template.
*
* @method createEmailTemplate
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.createEmailTemplate(data, function (err) {
* if (err) {
* // Handle error.
* // Email Template created.
* });
*
* @param {Object} data Email Template data object.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'createEmailTemplate', 'emailTemplates.create');
/**
* Get an Auth0 Email Template.
*
* @method getEmailTemplate
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getEmailTemplate({ name: EMAIL_TEMPLATE_NAME }, function (err, emailTemplate) {
* if (err) {
* // Handle error.
* }
*
* console.log(emailTemplate);
* });
*
* @param {Object} params Email Template parameters.
* @param {String} params.name Template Name
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getEmailTemplate', 'emailTemplates.get');
/**
* Update an existing Email Template.
*
* @method updateEmailTemplates
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var data = { from: 'new@email.com' };
* var params = { name: EMAIL_TEMPLATE_NAME };
*
* management.updateEmailTemplates(params, data, function (err, emailTemplate) {
* if (err) {
* // Handle error.
* }
*
* console.log(emailTemplate.from); // 'new@email.com'
* });
*
* @param {Object} params Email Template parameters.
* @param {String} params.name Template Name
* @param {Object} data Updated Email Template data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateEmailTemplate', 'emailTemplates.update');
/**
* Get the email provider.
*
* @method getEmailProvider
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getEmailProvider(function (err, provider) {
* console.log(provider.length);
* });
*
* @param {Function} [cb] Callback function.
* @param {Object} [params] Clients parameters.
* @param {Number} [params.fields] A comma separated list of fields to include or exclude (depending on include_fields) from the result, empty to retrieve: name, enabled, settings fields.
* @param {Number} [params.include_fields] true if the fields specified are to be excluded from the result, false otherwise (defaults to true)
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getEmailProvider', 'emailProvider.get');
/**
* Configure the email provider.
*
* @method configureEmailProvider
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.configureEmailProvider(data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Email provider configured.
* });
*
* @param {Object} data The email provider data object.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'configureEmailProvider', 'emailProvider.configure');
/**
* Delete email provider.
*
* @method deleteEmailProvider
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.deleteEmailProvider(function (err) {
* if (err) {
* // Handle error.
* }
*
* // Email provider deleted.
* });
*
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'deleteEmailProvider', 'emailProvider.delete');
/**
* Update the email provider.
*
* @method updateEmailProvider
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.updateEmailProvider(params, data, function (err, provider) {
* if (err) {
* // Handle error.
* }
*
* // Updated email provider.
* console.log(provider);
* });
*
* @param {Object} params Email provider parameters.
* @param {Object} data Updated email provider data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateEmailProvider', 'emailProvider.update');
/**
* Get a the active users count.
*
* @method getActiveUsersCount
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getActiveUsersCount(function (err, usersCount) {
* if (err) {
* // Handle error.
* }
*
* console.log(usersCount);
* });
*
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getActiveUsersCount', 'stats.getActiveUsersCount');
/**
* Get the daily stats.
*
* @method getDailyStats
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = {
* from: '{YYYYMMDD}', // First day included in the stats.
* to: '{YYYYMMDD}' // Last day included in the stats.
* };
*
* management.getDaily(params, function (err, stats) {
* if (err) {
* // Handle error.
* }
*
* console.log(stats);
* });
*
* @param {Object} params Stats parameters.
* @param {String} params.from The first day in YYYYMMDD format.
* @param {String} params.to The last day in YYYYMMDD format.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getDailyStats', 'stats.getDaily');
/**
* Get the tenant settings..
*
* @method getTenantSettings
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getSettings(function (err, settings) {
* if (err) {
* // Handle error.
* }
*
* console.log(settings);
* });
*
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getTenantSettings', 'tenant.getSettings');
/**
* Update the tenant settings.
*
* @method updateTenantSettings
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.updateTenantSettings(data, function (err) {
* if (err) {
* // Handle error.
* }
* });
*
* @param {Object} data The new tenant settings.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateTenantSettings', 'tenant.updateSettings');
/**
* Get a job by its ID.
*
* @method getJob
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = {
* id: '{JOB_ID}'
* };
*
* management.getJob(params, function (err, job) {
* if (err) {
* // Handle error.
* }
*
* // Retrieved job.
* console.log(job);
* });
*
* @param {Object} params Job parameters.
* @param {String} params.id Job ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getJob', 'jobs.get');
/**
* Given a path to a file and a connection id, create a new job that imports the
* users contained in the file or JSON string and associate them with the given
* connection.
*
* @method importUsers
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = {
* connection_id: '{CONNECTION_ID}',
* users: '{PATH_TO_USERS_FILE}' // or users_json: '{USERS_JSON_STRING}'
* };
*
* management.importUsers(params, function (err) {
* if (err) {
* // Handle error.
* }
* });
*
* @param {Object} data Users import data.
* @param {String} data.connection_id connection_id of the connection to which users will be imported.
* @param {String} [data.users] Path to the users data file. Either users or users_json is mandatory.
* @param {String} [data.users_json] JSON data for the users.
* @param {Boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false).
* @param {Boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false).
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'importUsers', 'jobs.importUsers');
/**
* Given a path to a file and a connection id, create a new job that imports the
* users contained in the file or JSON string and associate them with the given
* connection.
*
* @method importUsersJob
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = {
* connection_id: '{CONNECTION_ID}',
* users: '{PATH_TO_USERS_FILE}' // or users_json: '{USERS_JSON_STRING}'
* };
*
* management.importUsersJob(params, function (err) {
* if (err) {
* // Handle error.
* }
* });
*
* @param {Object} data Users import data.
* @param {String} data.connection_id connection_id of the connection to which users will be imported.
* @param {String} [data.users] Path to the users data file. Either users or users_json is mandatory.
* @param {String} [data.users_json] JSON data for the users.
* @param {Boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false).
* @param {Boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false).
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'importUsersJob', 'jobs.importUsersJob');
/**
* Export all users to a file using a long running job.
*
* @method exportUsers
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var data = {
* connection_id: 'con_0000000000000001',
* format: 'csv',
* limit: 5,
* fields: [
* {
* "name": "user_id"
* },
* {
* "name": "name"
* },
* {
* "name": "email"
* },
* {
* "name": "identities[0].connection",
* "export_as": "provider"
* },
* {
* "name": "user_metadata.some_field"
* }
* ]
* }
*
* management.exportUsers(data, function (err, results) {
* if (err) {
* // Handle error.
* }
*
* // Retrieved job.
* console.log(results);
* });
*
* @param {Object} data Users export data.
* @param {String} [data.connection_id] The connection id of the connection from which users will be exported
* @param {String} [data.format] The format of the file. Valid values are: "json" and "csv".
* @param {Number} [data.limit] Limit the number of records.
* @param {Object[]} [data.fields] A list of fields to be included in the CSV. If omitted, a set of predefined fields will be exported.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'exportUsers', 'jobs.exportUsers');
/**
* Given a job ID, retrieve the failed/errored items
*
* @method errors
* @memberOf module:management.JobsManager.prototype
*
* @example
* var params = {
* id: '{JOB_ID}'
* };
*
* management.jobs.errors(params, function (err, job) {
* if (err) {
* // Handle error.
* }
*
* // Retrieved job.
* console.log(job);
* });
*
* @param {Object} params Job parameters.
* @param {String} params.id Job ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getJobErrors', 'jobs.errors');
/**
* Send a verification email to a user.
*
* @method sendEmailVerification
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = {
* user_id: '{USER_ID}'
* };
*
* management.sendEmailVerification(params, function (err) {
* if (err) {
* // Handle error.
* }
* });
*
* @param {Object} data User data object.
* @param {String} data.user_id ID of the user to be verified.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'sendEmailVerification', 'jobs.verifyEmail');
/**
* Create a new password change ticket.
*
* @method createPasswordChangeTicket
* @memberOf module:management.ManagementClient.prototype
*
* @example
*
* var params = {
* result_url: '{REDIRECT_URL}', // Redirect after using the ticket.
* user_id: '{USER_ID}'
* };
*
* // or
*
* var params = {
* result_url: '{REDIRECT_URL}', // Redirect after using the ticket.
* email: '{USER_EMAIL}',
* connection_id: '{CONNECTION}' // eg. con_00000000001
* };
*
* auth0.createPasswordChangeTicket(params, function (err) {
* if (err) {
* // Handle error.
* }
* });
*
* @param {Function} [cb] Callback function.
* @return {Promise}
*/
utils.wrapPropertyMethod(ManagementClient, 'createPasswordChangeTicket', 'tickets.changePassword');
/**
* Create an email verification ticket.
*
* @method createEmailVerificationTicket
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var data = {
* user_id: '{USER_ID}',
* result_url: '{REDIRECT_URL}' // Optional redirect after the ticket is used.
* };
*
* auth0.createEmailVerificationTicket(data, function (err) {
* if (err) {
* // Handle error.
* }
* });
*
* @param {Function} [cb] Callback function.
* @return {Promise}
*/
utils.wrapPropertyMethod(ManagementClient, 'createEmailVerificationTicket', 'tickets.verifyEmail');
/**
* Get an Auth0 log.
*
* @method getLog
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getLog({ id: EVENT_ID }, function (err, log) {
* if (err) {
* // Handle error.
* }
*
* console.log(log);
* });
*
* @param {Object} params Log parameters.
* @param {String} params.id Event ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getLog', 'logs.get');
/**
* Get all logs.
*
* @method getLogs
* @memberOf module:management.ManagementClient.prototype
*
* @example <caption>
* This method takes an optional object as first argument that may be used to
* specify pagination settings and the search query. If pagination options are
* not present, the first page of a limited number of results will be returned.
* </caption>
*
* // Pagination settings.
* var params = {
* per_page: 10,
* page: 2
* };
*
* management.getLogs(params, function (err, logs) {
* console.log(logs.length);
* });
*
* @param {Object} [params] Logs params.
* @param {String} [params.q] Search Criteria using Query String Syntax
* @param {Number} [params.page] Page number. Zero based
* @param {Number} [params.per_page] The amount of entries per page
* @param {String} [params.sort] The field to use for sorting.
* @param {String} [params.fields] A comma separated list of fields to include or exclude
* @param {Boolean} [params.include_fields] true if the fields specified are to be included in the result, false otherwise.
* @param {Boolean} [params.include_totals] true if a query summary must be included in the result, false otherwise. Default false
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getLogs', 'logs.getAll');
/**
* Get all Log Streams.
*
* @method getLogStreams
* @memberOf module:management.ManagementClient.prototype
*
*
*
* management.getLogStreams( function (err, logStreams) {
* console.log(logStreams.length);
* });
*
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getLogStreams', 'logStreams.getAll');
/**
* Create a new Log Stream.
*
* @method createLogStream
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.createLogStream(data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Log Stream created.
* });
*
* @param {Object} data Log Stream data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'createLogStream', 'logStreams.create');
/**
* Get an Auth0 Log Stream.
*
* @method getLogStream
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getLogStream({ id: LOG_STREAM_ID }, function (err, logStream) {
* if (err) {
* // Handle error.
* }
*
* console.log(logStream);
* });
*
* @param {Object} params Log Stream parameters.
* @param {String} params.id Log Stream ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getLogStream', 'logStreams.get');
/**
* Delete an existing Log Stream.
*
* @method deleteLogStream
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.deleteLogStream({ id: LOG_STREAM_ID }, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Log Stream deleted.
* });
*
* @param {Object} params Log Stream parameters.
* @param {String} params.id Log Stream ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'deleteLogStream', 'logStreams.delete');
/**
* Update an existing Log Stream.
*
* @method updateLogStream
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: LOG_STREAM_ID };
* var data = { name: 'my-log-stream'};
* management.updateLogStream(params, data, function (err, logStream) {
* if (err) {
* // Handle error.
* }
*
* console.log(logStream.name); // 'my-log-stream'.
* });
*
* @param {Object} params Rule parameters.
* @param {String} params.id Rule ID.
* @param {Object} data Updated rule data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateLogStream', 'logStreams.update');
/**
* Create a new resource server.
*
* @method createResourceServer
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.createResourceServer(data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Resource Server created.
* });
*
* @param {Object} data Resource Server data object.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'createResourceServer', 'resourceServers.create');
/**
* Get all resource servers.
*
* @method getResourceServers
* @memberOf module:management.ManagementClient.prototype
*
* @example <caption>
* This method takes an optional object as first argument that may be used to
* specify pagination settings. If pagination options are not present,
* the first page of a limited number of results will be returned.
* </caption>
*
* // Pagination settings.
* var params = {
* per_page: 10,
* page: 0
* };
*
* management.getResourceServers(params, function (err, resourceServers) {
* console.log(resourceServers.length);
* });
*
* @param {Object} [params] Resource Servers parameters.
* @param {Number} [params.per_page] Number of results per page.
* @param {Number} [params.page] Page number, zero indexed.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getResourceServers', 'resourceServers.getAll');
/**
* Get a Resource Server.
*
* @method getResourceServer
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getResourceServer({ id: RESOURCE_SERVER_ID }, function (err, resourceServer) {
* if (err) {
* // Handle error.
* }
*
* console.log(resourceServer);
* });
*
* @param {Object} params Resource Server parameters.
* @param {String} params.id Resource Server ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getResourceServer', 'resourceServers.get');
/**
* Delete an existing resource server.
*
* @method deleteResourceServer
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.deleteResourceServer({ id: RESOURCE_SERVER_ID }, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Resource Server deleted.
* });
*
* @param {Object} params Resource Server parameters.
* @param {String} params.id Resource Server ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'deleteResourceServer', 'resourceServers.delete');
/**
* Update an existing resource server.
*
* @method updateResourceServer
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var data = { name: 'newResourceServerName' };
* var params = { id: RESOURCE_SERVER_ID };
*
* management.updateResourceServer(params, data, function (err, resourceServer) {
* if (err) {
* // Handle error.
* }
*
* console.log(resourceServer.name); // 'newResourceServerName'
* });
*
* @param {Object} params Resource Server parameters.
* @param {String} params.id Resource Server ID.
* @param {Object} data Updated Resource Server data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateResourceServer', 'resourceServers.update');
/**
* Set a new rules config.
*
* @method setRulesConfig
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { key: RULE_CONFIG_KEY };
* var data = { value: RULES_CONFIG_VALUE };
*
* management.setRulesConfig(params, data, function (err, rulesConfig) {
* if (err) {
* // Handle error.
* }
*
* // Rules Config set.
* });
*
* @param {Object} params Rule Config parameters.
* @param {String} params.key Rule Config key.
* @param {Object} data Rule Config Data parameters.
* @param {String} data.value Rule Config Data value.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'setRulesConfig', 'rulesConfigs.set');
/**
* Get rules config.
*
* @method getRulesConfigs
* @memberOf module:management.ManagementClient.prototype
* @param {Function} [cb] Callback function.
*
* @example
*
* management.getRulesConfigs(function (err, rulesConfigs) {
* if (err) {
* // Handle error.
* }
*
* // Get Rules Configs.
* });
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getRulesConfigs', 'rulesConfigs.getAll');
/**
* Delete rules config.
*
* @method deleteRulesConfig
* @memberOf module:management.ManagementClient.prototype
*
* @example
*
* management.deleteRulesConfig({ key: RULE_CONFIG_KEY }, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Rules Config deleted.
* });
*
* @param {Object} params Rule Configs parameters.
* @param {String} params.key Rule Configs key.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'deleteRulesConfig', 'rulesConfigs.delete');
/**
* Create an Auth0 Custom Domain.
*
* @method createCustomDomain
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.createCustomDomain(data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // CustomDomain created.
* });
*
* @param {Object} data The custom domain data object.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'createCustomDomain', 'customDomains.create');
/**
* Get all Auth0 CustomDomains.
*
* @method getCustomDomains
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getCustomDomains(function (err, customDomains) {
* console.log(customDomains.length);
* });
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getCustomDomains', 'customDomains.getAll');
/**
* Get a Custom Domain.
*
* @method getCustomDomain
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getCustomDomain({ id: CUSTOM_DOMAIN_ID }, function (err, customDomain) {
* if (err) {
* // Handle error.
* }
*
* console.log(customDomain);
* });
*
* @param {Object} params Custom Domain parameters.
* @param {String} params.id Custom Domain ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getCustomDomain', 'customDomains.get');
/**
* Verify a Custom Domain.
*
* @method verifyCustomDomain
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.verifyCustomDomain({ id: CUSTOM_DOMAIN_ID }, function (err, customDomain) {
* if (err) {
* // Handle error.
* }
*
* console.log(customDomain);
* });
*
* @param {Object} params Custom Domain parameters.
* @param {String} params.id Custom Domain ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'verifyCustomDomain', 'customDomains.verify');
/**
* Delete a Custom Domain.
*
* @method deleteCustomDomain
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.deleteCustomDomain({ id: CUSTOM_DOMAIN_ID }, function (err) {
* if (err) {
* // Handle error.
* }
*
* // CustomDomain deleted.
* });
*
* @param {Object} params Custom Domain parameters.
* @param {String} params.id Custom Domain ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'deleteCustomDomain', 'customDomains.delete');
/**
* Create a Guardian enrollment ticket.
*
* @method createGuardianEnrollmentTicket
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.createGuardianEnrollmentTicket(function (err, ticket) {
* console.log(ticket);
* });
*
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'createGuardianEnrollmentTicket',
'guardian.createEnrollmentTicket'
);
/**
* Get a list of Guardian factors and statuses.
*
* @method getGuardianFactors
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getGuardianFactors(function (err, factors) {
* console.log(factors.length);
* });
*
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getGuardianFactors', 'guardian.getFactors');
/**
* Get Guardian factor provider configuration
*
* @method getGuardianFactorProvider
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getFactorProvider({ name: 'sms', provider: 'twilio'}, function (err, provider) {
* console.log(provider);
* });
*
* @param {Object} params Factor provider parameters.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'getGuardianFactorProvider',
'guardian.getFactorProvider'
);
/**
* Update Guardian's factor provider
*
* @method updateFactorProvider
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.updateGuardianFactorProvider({ name: 'sms', provider: 'twilio' }, {
* messaging_service_sid: 'XXXXXXXXXXXXXX',
* auth_token: 'XXXXXXXXXXXXXX',
* sid: 'XXXXXXXXXXXXXX'
* }, function (err, provider) {
* console.log(provider);
* });
*
* @param {Object} params Factor provider parameters.
* @param {Object} data Updated Factor provider data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'updateGuardianFactorProvider',
'guardian.updateFactorProvider'
);
/**
* Get Guardian enrollment and verification factor templates
*
* @method getGuardianFactorTemplates
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getGuardianFactorTemplates({ name: 'sms' }, function (err, templates) {
* console.log(templates);
* });
*
* @param {Object} params Factor parameters.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'getGuardianFactorTemplates',
'guardian.getFactorTemplates'
);
/**
* Update Guardian enrollment and verification factor templates
*
* @method updateGuardianFactorTemplates
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.updateGuardianFactorTemplates({ name: 'sms' }, {
* enrollment_message: "{{code}} is your verification code for {{tenant.friendly_name}}. Please enter this code to verify your enrollment.",
* verification_message: "{{code}} is your verification code for {{tenant.friendly_name}}"
* }, function (err, templates) {
* console.log(templates);
* });
*
* @param {Object} params Factor parameters.
* @param {Object} data Updated factor templates data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'updateGuardianFactorTemplates',
'guardian.updateFactorTemplates'
);
/**
* Update Guardian Factor
*
* @method updateGuardianFactor
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.updateGuardianFactor({ name: 'sms' }, {
* enabled: true
* }, function (err, factor) {
* console.log(factor);
* });
*
* @param {Object} params Factor parameters.
* @param {Object} data Updated factor data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateGuardianFactor', 'guardian.updateFactor');
/**
* Get enabled Guardian policies
*
* @method getGuardianPolicies
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getGuardianPolicies(function (err, policies) {
* console.log(policies);
* });
*
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getGuardianPolicies', 'guardian.getPolicies');
/**
* Update enabled Guardian policies
*
* @method updateGuardianPolicies
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.updateGuardianPolicies({}, [
* 'all-applications'
* ], function (err, policies) {
* console.log(policies);
* });
*
* @param {Object} params Parameters.
* @param {String[]} data Policies to enable. Empty array disables all policies.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateGuardianPolicies', 'guardian.updatePolicies');
/**
* Get the Guardian phone factor's selected provider
*
* @method getGuardianPhoneFactorSelectedProvider
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getGuardianPhoneFactorSelectedProvider(function (err, selectedProvider) {
* console.log(selectedProvider);
* });
*
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'getGuardianPhoneFactorSelectedProvider',
'guardian.getPhoneFactorSelectedProvider'
);
/**
* Update the Guardian phone factor's selected provider
*
* @method updateGuardianPhoneFactorSelectedProvider
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.updateGuardianPhoneFactorSelectedProvider({}, {
* provider: 'twilio'
* }, function (err, factor) {
* console.log(factor);
* });
*
* @param {Object} params Parameters.
* @param {Object} data Updated selected provider data.
* @param {String} data.provider Name of the selected provider
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'updateGuardianPhoneFactorSelectedProvider',
'guardian.updatePhoneFactorSelectedProvider'
);
/**
* Get the Guardian phone factor's message types
*
* @method getGuardianPhoneFactorMessageTypes
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getGuardianPhoneFactorMessageTypes(function (err, messageTypes) {
* console.log(messageTypes);
* });
*
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'getGuardianPhoneFactorMessageTypes',
'guardian.getPhoneFactorMessageTypes'
);
/**
* Update the Guardian phone factor's message types
*
* @method updateGuardianPhoneFactorMessageTypes
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.updateGuardianPhoneFactorMessageTypes({}, {
* message_types: ['sms', 'voice']
* }, function (err, factor) {
* console.log(factor);
* });
*
* @param {Object} params Parameters.
* @param {Object} data Updated selected provider data.
* @param {String[]} data.message_types Message types (only `"sms"` and `"voice"` are supported).
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'updateGuardianPhoneFactorMessageTypes',
'guardian.updatePhoneFactorMessageTypes'
);
/**
* Get all roles.
*
* @method getRoles
* @memberOf module:management.ManagementClient.prototype
*
* @example <caption>
* This method takes an optional object as first argument that may be used to
* specify pagination settings. If pagination options are not present,
* the first page of a limited number of results will be returned.
* </caption>
*
* // Pagination settings.
* var params = {
* per_page: 10,
* page: 0
* };
*
* management.getRoles(params, function (err, roles) {
* console.log(roles.length);
* });
*
* @param {Object} [params] Roles parameters.
* @param {Number} [params.per_page] Number of results per page.
* @param {Number} [params.page] Page number, zero indexed.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getRoles', 'roles.getAll');
/**
* Create a new role.
*
* @method createRole
* @memberOf module:management.ManagementClient.prototype
*
* @example
* data = {"name": "test1","description": "123"}
* management.createRole(data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Role created.
* });
*
* @param {Object} data Role data object.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'createRole', 'roles.create');
/**
* Get an Auth0 role.
*
* @method getRole
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getRole({ id: ROLE_ID }, function (err, role) {
* if (err) {
* // Handle error.
* }
*
* console.log(role);
* });
*
* @param {Object} params Role parameters.
* @param {String} params.id Role ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getRole', 'roles.get');
/**
* Delete an existing role.
*
* @method deleteRole
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.deleteRole({ id: ROLE_ID }, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Role deleted.
* });
*
* @param {Object} params Role parameters.
* @param {String} params.id Role ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'deleteRole', 'roles.delete');
/**
* Update an existing role.
*
* @method updateRole
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: ROLE_ID };
* var data = { name: 'my-role'};
* management.updateRole(params, data, function (err, role) {
* if (err) {
* // Handle error.
* }
*
* console.log(role.name); // 'my-role'.
* });
*
* @param {Object} params Role parameters.
* @param {String} params.id Role ID.
* @param {Object} data Updated role data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateRole', 'roles.update');
/**
* Get permissions for a given role
*
* @method getPermissionsInRole
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id :'ROLE_ID'};
* @example <caption>
* This method takes a roleId and
* returns all permissions within that role
*
* </caption>
*
* management.getPermissionsInRole(params, function (err, permissions) {
* console.log(permissions);
* });
*
* @param {String} [roleId] Id of the role
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getPermissionsInRole', 'roles.getPermissions');
/**
* Add permissions in a role
*
* @method addPermissionsInRole
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id :'ROLE_ID'};
* var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]};
*
* management.addPermissionsInRole(params, data, function (err, permissions) {
* console.log(permissions);
* });
*
* @param {String} params.id ID of the Role.
* @param {Object} data permissions data
* @param {String} data.permissions Array of permissions
* @param {String} data.permissions.permission_name Name of a permission
* @param {String} data.permissions.resource_server_identifier Identifier for a resource
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'addPermissionsInRole', 'roles.addPermissions');
/**
* Remove permissions from a role
*
* @method removePermissionsFromRole
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id :'ROLE_ID'};
* var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]};
*
* management.removePermissionsFromRole(params, data, function (err, permissions) {
* console.log(permissions);
* });
*
* @param {String} params.id ID of the Role.
* @param {Object} data permissions data
* @param {String} data.permissions Array of permissions
* @param {String} data.permissions.permission_name Name of a permission
* @param {String} data.permissions.resource_server_identifier Identifier for a resource
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'removePermissionsFromRole', 'roles.removePermissions');
/**
* Get users in a given role
*
* @method getUsersInRole
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = {
* id: 'ROLE_ID'
* per_page: 50,
* page: 0
* };
*
* @example <caption>
* This method takes a roleId and returns all users within that role
* </caption>
*
* management.getUsersInRole(params, function (err, users) {
* console.log(users);
* });
*
* @param {String} [id] Id of the role
* @param {Number} [params.per_page] Number of results per page.
* @param {Number} [params.page] Page number, zero indexed.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getUsersInRole', 'roles.getUsers');
/**
* Get all hooks.
*
* @method getHooks
* @memberOf module:management.ManagementClient.prototype
*
* @example <caption>
* This method takes an optional object as first argument that may be used to
* specify pagination settings. If pagination options are not present,
* the first page of a limited number of results will be returned.
* </caption>
*
* // Pagination settings.
* var params = {
* per_page: 10,
* page: 0
* };
*
* management.getHooks(params, function (err, hooks) {
* console.log(hooks.length);
* });
*
* @param {Object} [params] Hooks parameters.
* @param {Number} [params.per_page] Number of results per page.
* @param {Number} [params.page] Page number, zero indexed.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getHooks', 'hooks.getAll');
/**
* Get an Auth0 hook.
*
* @method getHook
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getHook({ id: HOOK_ID }, function (err, hook) {
* if (err) {
* // Handle error.
* }
*
* console.log(hook);
* });
*
* @param {Object} params Hook parameters.
* @param {String} params.id Hook ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getHook', 'hooks.get');
/**
* Create a new hook.
*
* @method createHook
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.createHook(data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Hook created.
* });
*
* @param {Object} data Hook data object.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'createHook', 'hooks.create');
/**
* Update an existing hook.
*
* @method updateHook
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: HOOK_ID };
* var data = { name: 'my-hook'};
* management.updateHook(params, data, function (err, hook) {
* if (err) {
* // Handle error.
* }
*
* console.log(hook.name); // 'my-hook'.
* });
*
* @param {Object} params Hook parameters.
* @param {String} params.id Hook ID.
* @param {Object} data Updated hook data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateHook', 'hooks.update');
/**
* Delete an existing hook.
*
* @method deleteHook
* @memberOf module:management.ManagementClient.prototype
*
* @example
* auth0.deleteHook({ id: HOOK_ID }, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Hook deleted.
* });
*
* @param {Object} params Hook parameters.
* @param {String} params.id Hook ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'deleteHook', 'hooks.delete');
/**
* Get an Auth0 hook's secrets.
*
* @method getHookSecrets
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: HOOK_ID }
* management.getHookSecrets(params, function (err, secrets) {
* if (err) {
* // Handle error.
* }
*
* console.log(secrets);
* });
*
* @param {Object} params Hook parameters.
* @param {String} params.id Hook ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getHookSecrets', 'hooks.getSecrets');
/**
* Add hook screts.
*
* @method addHookScrets
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: 'HOOK_ID' }
* var data = { DB_PASSWORD: 'password1', API_TOKEN: 'secret' }
* management.addHookScrets(params, data, function (err, secrets) {
* if (err) {
* // Handle error.
* }
*
* // Hook secrets created.
* });
*
* @param {Object} params Hook parameters.
* @param {String} params.id Hook ID.
* @param {Object} data Secrets key/value pairs
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'addHookSecrets', 'hooks.addSecrets');
/**
* Update an existing hook.
*
* @method updateHookSecrets
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: HOOK_ID };
* var data = { API_TOKEN: 'updated-secret'};
* management.updateHookSecrets(params, data, function (err, secrets) {
* if (err) {
* // Handle error.
* }
*
* console.log(secrets)
* });
*
* @param {Object} params Hook parameters.
* @param {String} params.id Hook ID.
* @param {Object} data Secrets key/value pairs
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateHookSecrets', 'hooks.updateSecrets');
/**
* Delete an existing hook.
*
* @method removeHookSecrets
* @memberOf module:management.ManagementClient.prototype
*
* @example
* var params = { id: HOOK_ID }
* var data = ['API_TOKEN', 'DB_PASSWORD']
* auth0.removeHookSecrets(params, data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Hook deleted.
* });
*
* @param {Object} params Hook parameters.
* @param {String} params.id Hook ID.
* @param {Object} data Secrets key/value pairs
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'removeHookSecrets', 'hooks.removeSecrets');
/**
* Returns the access_token.
*
* @method getAccessToken
* @memberOf module:management.ManagementClient.prototype
*
* @return {Promise} Promise returning an access_token.
*/
utils.wrapPropertyMethod(ManagementClient, 'getAccessToken', 'tokenProvider.getAccessToken');
/**
* Update the branding settings.
*
* @method updateBrandingSettings
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.updateBrandingSettings(data, function (err, branding) {
* if (err) {
* // Handle error.
* }
*
* // Updated branding
* console.log(branding);
* });
*
* @param {Object} params Branding parameters.
* @param {Object} data Updated branding data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateBrandingSettings', 'branding.updateSettings');
/**
* Get the branding settings..
*
* @method getBrandingSettings
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getBrandingSettings(data, function (err, branding) {
* if (err) {
* // Handle error.
* }
*
* // Branding
* console.log(branding);
* });
*
* @param {Object} params Branding parameters.
* @param {Object} data Branding data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getBrandingSettings', 'branding.getSettings');
/**
* Update the tenant migrations.
*
* @method updateMigrations
* @memberOf module:management.ManagementClient.prototype
*
* @example
* data = { flags: { migration: true } };
* management.updateMigrations(data, function (err, migrations) {
* if (err) {
* // Handle error.
* }
*
* // Updated migrations flags
* console.log(migrations.flags);
* });
*
* @param {Object} data Updated migrations data.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updateMigrations', 'migrations.updateMigrations');
/**
* Get migrations flags
*
* @method getMigrations
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getMigrations(function (err, migrations) {
* if (err) {
* // Handle error.
* }
*
* // Migration flags
* console.log(migrations.flags);
* });
*
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getMigrations', 'migrations.getMigrations');
/**
* Get prompts settings..
*
* @method getPromptsSettings
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.getPromptsSettings(function (err, settings) {
* if (err) {
* // Handle error.
* }
*
* console.log(settings);
* });
*
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'getPromptsSettings', 'prompts.getSettings');
/**
* Update prompts settings.
*
* @method updatePromptsSettings
* @memberOf module:management.ManagementClient.prototype
*
* @example
* management.updatePromptsSettings(data, function (err) {
* if (err) {
* // Handle error.
* }
* });
*
* @param {Object} data The new prompts settings.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(ManagementClient, 'updatePromptsSettings', 'prompts.updateSettings');
/**
* Retrieve custom text for a specific prompt and language.
*
* @method getCustomTextByLanguage
* @memberOf module:management.PromptsManager.prototype
*
* @example
* var params = { prompt: PROMPT_NAME, language: LANGUAGE };
*
* management.prompts.getCustomTextByLanguage(params, function (err, customText) {
* if (err) {
* // Handle error.
* }
*
* console.log('CustomText', customText);
* });
*
* @param {Object} params Data object.
* @param {String} params.prompt Name of the prompt.
* @param {String} params.language Language to retrieve.
* @param {Function} [cb] Callback function
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'getCustomTextByLanguage',
'prompts.getCustomTextByLanguage'
);
/**
* Set custom text for a specific prompt.
*
* @method updateCustomTextByLanguage
* @memberOf module:management.PromptsManager.prototype
*
* @example
* var params = { prompt: PROMPT_NAME, language: LANGUAGE, body: BODY_OBJECT };
*
* management.prompts.updateCustomTextByLanguage(params, function (err, customText) {
* if (err) {
* // Handle error.
* }
*
* console.log('CustomText', customText);
* });
*
* @param {Object} params Data object.
* @param {String} params.prompt Name of the prompt.
* @param {String} params.language Language to retrieve.
* @param {Object} params.body An object containing custom dictionaries for a group of screens.
* @param {Function} [cb] Callback function
*
* @return {Promise|undefined}
*/
utils.wrapPropertyMethod(
ManagementClient,
'updateCustomTextByLanguage',
'prompts.updateCustomTextByLanguage'
);
module.exports = ManagementClient;
|
// miniprogram/pages/navigator/navigator.js
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
enter:[
{
name:'borrowClassroom',
name_zh:'教室借用'
},
{
name:'progressCheck',
name_zh: '进度查询'
}
]
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {//如果是管理员,则渲染审批界面**存在bug,用户点击过快时,尚未同步数据库而已开始鉴权,导致管理员用户仍无法渲染出审批**
const isAdmin = app.globalData.isAdmin;
let enter = this.data.enter;
enter.push({
name: 'admin',
name_zh: '审批'
});
if(isAdmin){
this.setData({enter})
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
|
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[17],{
/***/ "./resources/js/lang/en.json":
/*!***********************************!*\
!*** ./resources/js/lang/en.json ***!
\***********************************/
/*! exports provided: no_projects, see_more, score, upload, ranking, gallery, game, play, back, introduction_text, games_played, categories, users, Hello, projects, ok, cancel, error_alert_title, error_alert_text, token_expired_alert_title, token_expired_alert_text, login, register, page_not_found, go_home, logout, email, remember_me, password, forgot_password, confirm_password, name, toggle_navigation, home, you_are_logged_in, reset_password, send_password_reset_link, settings, profile, your_info, info_updated, update, your_password, password_updated, new_password, login_with, register_with, verify_email, send_verification_link, resend_verification_link, failed_to_verify_email, verify_email_address, default */
/***/ (function(module) {
eval("module.exports = {\"no_projects\":\"No projects to display.\",\"see_more\":\"See more\",\"score\":\"Score\",\"upload\":\"Upload\",\"ranking\":\"Ranking\",\"gallery\":\"Gallery\",\"game\":\"Game\",\"play\":\"Play\",\"back\":\"Go back\",\"introduction_text\":\"This is an introduction text\",\"games_played\":\"games played\",\"categories\":\"categories\",\"users\":\"users\",\"Hello\":\"Hello\",\"projects\":\"projects\",\"ok\":\"Ok\",\"cancel\":\"Cancel\",\"error_alert_title\":\"Oops...\",\"error_alert_text\":\"Something went wrong! Please try again.\",\"token_expired_alert_title\":\"Session Expired!\",\"token_expired_alert_text\":\"Please log in again to continue.\",\"login\":\"Log In\",\"register\":\"Register\",\"page_not_found\":\"Page Not Found\",\"go_home\":\"Go Home\",\"logout\":\"Logout\",\"email\":\"Email\",\"remember_me\":\"Remember Me\",\"password\":\"Password\",\"forgot_password\":\"Forgot Your Password?\",\"confirm_password\":\"Confirm Password\",\"name\":\"Name\",\"toggle_navigation\":\"Toggle navigation\",\"home\":\"Home\",\"you_are_logged_in\":\"you are logged in!\",\"reset_password\":\"Reset Password\",\"send_password_reset_link\":\"Send Password Reset Link\",\"settings\":\"Settings\",\"profile\":\"Profile\",\"your_info\":\"Your Info\",\"info_updated\":\"Your info has been updated!\",\"update\":\"Update\",\"your_password\":\"Your Password\",\"password_updated\":\"Your password has been updated!\",\"new_password\":\"New Password\",\"login_with\":\"Login with\",\"register_with\":\"Register with\",\"verify_email\":\"Verify Email\",\"send_verification_link\":\"Send Verification Link\",\"resend_verification_link\":\"Resend Verification Link ?\",\"failed_to_verify_email\":\"Failed to verify email.\",\"verify_email_address\":\"We sent you an email with an the verification link.\"};//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiIuL3Jlc291cmNlcy9qcy9sYW5nL2VuLmpzb24uanMiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./resources/js/lang/en.json\n");
/***/ })
}]);
|
$(document).ready(function(){
$("h2").click(function(){
if ($(this).hasClass('panda')) {
$("p#panda").show();
$("img.panda").show();
} else {
$("p#panda").hide();
$("img.panda").hide();
}
if ($(this).hasClass('dog')) {
$("p#dog").show();
$("img.dog").show();
} else {
$("p#dog").hide();
$("img.dog").hide();
}
if ($(this).hasClass('bear')) {
$("p#bear").show();
$("img.bear").show();
} else {
$("p#bear").hide();
$("img.bear").hide();
}
});
});
|
import isFunction from 'lodash.isfunction';
import Core from '../core/core';
/**
* @class Twitter
* @description Twitter class
* @example
* const twitter = new Twitter({
* consumerKey: 'your-app-consumer-key',
* consumerSecret: 'your-app-consumer-secret',
* accessToken: 'your-app-access-token',
* accessTokenSecret: 'your-app-access-token-secret',
* });
*
* twitter.get('some-twitter-route').then((data) => {
* console.log(data);
* });
*/
class Twitter extends Core {
/**
* @constructs Twitter
* @description Constructs an instance of Twitter.
*
* @param {object} config - Config of class.
* @param {string} config.consumerKey - consumerKey of Twitter app.
* @param {string} config.consumerSecret - consumerSecret of Twitter app.
* @param {string} config.accessToken - accessToken of Twitter app.
* @param {string} config.accessTokenSecret - accessTokenSecret of Twitter app.
* @param {object} [options] - Options of class.
*
*/
constructor(config = {}, options = {}) {
super(options);
this.name = 'twitter';
this.checkValidConfig(
['consumerKey', 'consumerSecret', 'accessToken', 'accessTokenSecret'],
config,
);
this.oauth = {
consumer_key: config.consumerKey,
consumer_secret: config.consumerSecret,
token: config.accessToken,
token_secret: config.accessTokenSecret,
};
this.url = 'https://api.twitter.com';
this.version = options.version || '1.1';
this.baseApiUrl = `${this.url}/${this.version}`;
}
/**
* @memberof Twitter
* @function get
* @description Make a get request to twitter api.
*
* @param {string} url - Url of route.
* @param {object} [options] - Options to pass in request.
* @param {function} [callback] - Callback to call when the request finish.
* @return {promise}
*/
get(url, options = {}, callback) {
if (isFunction(options)) {
callback = options;
options = {};
}
return this.request({
method: 'GET',
json: true,
uri: `${this.baseApiUrl}/${url}.json`,
oauth: this.oauth,
qs: options,
}, callback);
}
/**
* @memberof Twitter
* @function post
* @description Make a post request to twitter api.
*
* @param {string} url - Url of route.
* @param {object} [options] - Options to pass in request.
* @param {function} [callback] - Callback to call when the request finish.
* @return {promise}
*/
post(url, options = {}, callback) {
if (isFunction(options)) {
callback = options;
options = {};
}
return this.request({
method: 'POST',
json: true,
uri: `${this.baseApiUrl}/${url}.json`,
oauth: this.oauth,
form: options,
}, callback);
}
/**
* @memberof Twitter
* @function delete
* @description Make a get request to twitter api.
*
* @param {string} url - Url of route.
* @param {object} [options] - Options to pass in request.
* @param {function} [callback] - Callback to call when the request finish.
* @return {promise}
*/
delete(url, options = {}, callback) {
if (isFunction(options)) {
callback = options;
options = {};
}
return this.request({
method: 'DELETE',
json: true,
uri: `${this.baseApiUrl}/${url}.json`,
oauth: this.oauth,
qs: options,
}, callback);
}
}
export default Twitter;
|
var Module={};onmessage=(function(event){switch(event.data.type){case"run":try{var data_offset=[Module._get_static_buffer(),Module._get_dynamic_buffer()];for(var i=0;i<event.data.inputs.length;i++){var var_alloc=event.data.inputs[i];var data_buf=new Float32Array(Module.buffer,data_offset[var_alloc.space]+var_alloc.offset*Float32Array.BYTES_PER_ELEMENT,var_alloc.size);data_buf.set(var_alloc.data)}Module._run();var outputs=[];var output_buffers=[];for(var i=0;i<event.data.outputs.length;i++){var var_alloc=event.data.outputs[i];var data_buf_view=new Float32Array(Module.buffer,data_offset[var_alloc.space]+var_alloc.offset*Float32Array.BYTES_PER_ELEMENT,var_alloc.size);var data_buf_copy=new Float32Array(data_buf_view.length);data_buf_copy.set(data_buf_view);outputs.push(data_buf_copy);output_buffers.push(data_buf_copy.buffer)}postMessage(outputs,output_buffers)}catch(ex){postMessage({"error":ex.message})}break;case"weight":try{var weight_buf=new Float32Array(Module.buffer,Module._get_static_buffer(),event.data.data.length);weight_buf.set(event.data.data);postMessage(0)}catch(ex){postMessage({"error":ex.message})}break;case"set_dynamic_buffer":try{var dynamic_ptr=Module._allocate_dynamic_buffer(event.data.size);if(dynamic_ptr===0){throw Error("Dynamic buffer cannot be allocated")}var data_to_set=event.data.data;var data_idx=0;while(data_idx<data_to_set.length){Module._set_placeholder_value(data_to_set[data_idx],data_to_set[data_idx+1],data_to_set[data_idx+2]);data_idx+=3}postMessage(0)}catch(ex){postMessage({"error":ex.message})}break;default:postMessage({"error":"Unknown message"});break}});Module.quit=(function(status,toThrow){postMessage({"error":toThrow,"status":status})});Module.onRuntimeInitialized=(function(){postMessage(0)});var Module;if(!Module)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;if(Module["ENVIRONMENT"]){if(Module["ENVIRONMENT"]==="WEB"){ENVIRONMENT_IS_WEB=true}else if(Module["ENVIRONMENT"]==="WORKER"){ENVIRONMENT_IS_WORKER=true}else if(Module["ENVIRONMENT"]==="NODE"){ENVIRONMENT_IS_NODE=true}else if(Module["ENVIRONMENT"]==="SHELL"){ENVIRONMENT_IS_SHELL=true}else{throw new Error("The provided Module['ENVIRONMENT'] value is not valid. It must be one of: WEB|WORKER|NODE|SHELL.")}}else{ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER}if(ENVIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=console.log;if(!Module["printErr"])Module["printErr"]=console.warn;var nodeFS;var nodePath;Module["read"]=function shell_read(filename,binary){if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);var ret=nodeFS["readFileSync"](filename);return binary?ret:ret.toString()};Module["readBinary"]=function readBinary(filename){var ret=Module["read"](filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};Module["load"]=function load(f){globalEval(read(f))};if(!Module["thisProgram"]){if(process["argv"].length>1){Module["thisProgram"]=process["argv"][1].replace(/\\/g,"/")}else{Module["thisProgram"]="unknown-program"}}Module["arguments"]=process["argv"].slice(2);if(typeof module!=="undefined"){module["exports"]=Module}process["on"]("uncaughtException",(function(ex){if(!(ex instanceof ExitStatus)){throw ex}}));Module["inspect"]=(function(){return"[Emscripten Module object]"})}else if(ENVIRONMENT_IS_SHELL){if(!Module["print"])Module["print"]=print;if(typeof printErr!="undefined")Module["printErr"]=printErr;if(typeof read!="undefined"){Module["read"]=read}else{Module["read"]=function shell_read(){throw"no read() available"}}Module["readBinary"]=function readBinary(f){if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}var data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){Module["arguments"]=scriptArgs}else if(typeof arguments!="undefined"){Module["arguments"]=arguments}if(typeof quit==="function"){Module["quit"]=(function(status,toThrow){quit(status)})}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){Module["read"]=function shell_read(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){Module["readBinary"]=function readBinary(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}Module["readAsync"]=function readAsync(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function xhr_onload(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response)}else{onerror()}};xhr.onerror=onerror;xhr.send(null)};if(typeof arguments!="undefined"){Module["arguments"]=arguments}if(typeof console!=="undefined"){if(!Module["print"])Module["print"]=function shell_print(x){console.log(x)};if(!Module["printErr"])Module["printErr"]=function shell_printErr(x){console.warn(x)}}else{var TRY_USE_DUMP=false;if(!Module["print"])Module["print"]=TRY_USE_DUMP&&typeof dump!=="undefined"?(function(x){dump(x)}):(function(x){})}if(ENVIRONMENT_IS_WORKER){Module["load"]=importScripts}if(typeof Module["setWindowTitle"]==="undefined"){Module["setWindowTitle"]=(function(title){document.title=title})}}else{throw"Unknown runtime environment. Where are we?"}function globalEval(x){eval.call(null,x)}if(!Module["load"]&&Module["read"]){Module["load"]=function load(f){globalEval(Module["read"](f))}}if(!Module["print"]){Module["print"]=(function(){})}if(!Module["printErr"]){Module["printErr"]=Module["print"]}if(!Module["arguments"]){Module["arguments"]=[]}if(!Module["thisProgram"]){Module["thisProgram"]="./this.program"}if(!Module["quit"]){Module["quit"]=(function(status,toThrow){throw toThrow})}Module.print=Module["print"];Module.printErr=Module["printErr"];Module["preRun"]=[];Module["postRun"]=[];for(var key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=undefined;var Runtime={setTempRet0:(function(value){tempRet0=value;return value}),getTempRet0:(function(){return tempRet0}),stackSave:(function(){return STACKTOP}),stackRestore:(function(stackTop){STACKTOP=stackTop}),getNativeTypeSize:(function(type){switch(type){case"i1":case"i8":return 1;case"i16":return 2;case"i32":return 4;case"i64":return 8;case"float":return 4;case"double":return 8;default:{if(type[type.length-1]==="*"){return Runtime.QUANTUM_SIZE}else if(type[0]==="i"){var bits=parseInt(type.substr(1));assert(bits%8===0);return bits/8}else{return 0}}}}),getNativeFieldSize:(function(type){return Math.max(Runtime.getNativeTypeSize(type),Runtime.QUANTUM_SIZE)}),STACK_ALIGN:16,prepVararg:(function(ptr,type){if(type==="double"||type==="i64"){if(ptr&7){assert((ptr&7)===4);ptr+=4}}else{assert((ptr&3)===0)}return ptr}),getAlignSize:(function(type,size,vararg){if(!vararg&&(type=="i64"||type=="double"))return 8;if(!type)return Math.min(size,8);return Math.min(size||(type?Runtime.getNativeFieldSize(type):0),Runtime.QUANTUM_SIZE)}),dynCall:(function(sig,ptr,args){if(args&&args.length){return Module["dynCall_"+sig].apply(null,[ptr].concat(args))}else{return Module["dynCall_"+sig].call(null,ptr)}}),functionPointers:[],addFunction:(function(func){for(var i=0;i<Runtime.functionPointers.length;i++){if(!Runtime.functionPointers[i]){Runtime.functionPointers[i]=func;return 2*(1+i)}}throw"Finished up all reserved function pointers. Use a higher value for RESERVED_FUNCTION_POINTERS."}),removeFunction:(function(index){Runtime.functionPointers[(index-2)/2]=null}),warnOnce:(function(text){if(!Runtime.warnOnce.shown)Runtime.warnOnce.shown={};if(!Runtime.warnOnce.shown[text]){Runtime.warnOnce.shown[text]=1;Module.printErr(text)}}),funcWrappers:{},getFuncWrapper:(function(func,sig){assert(sig);if(!Runtime.funcWrappers[sig]){Runtime.funcWrappers[sig]={}}var sigCache=Runtime.funcWrappers[sig];if(!sigCache[func]){if(sig.length===1){sigCache[func]=function dynCall_wrapper(){return Runtime.dynCall(sig,func)}}else if(sig.length===2){sigCache[func]=function dynCall_wrapper(arg){return Runtime.dynCall(sig,func,[arg])}}else{sigCache[func]=function dynCall_wrapper(){return Runtime.dynCall(sig,func,Array.prototype.slice.call(arguments))}}}return sigCache[func]}),getCompilerSetting:(function(name){throw"You must build with -s RETAIN_COMPILER_SETTINGS=1 for Runtime.getCompilerSetting or emscripten_get_compiler_setting to work"}),stackAlloc:(function(size){var ret=STACKTOP;STACKTOP=STACKTOP+size|0;STACKTOP=STACKTOP+15&-16;return ret}),staticAlloc:(function(size){var ret=STATICTOP;STATICTOP=STATICTOP+size|0;STATICTOP=STATICTOP+15&-16;return ret}),dynamicAlloc:(function(size){var ret=HEAP32[DYNAMICTOP_PTR>>2];var end=(ret+size+15|0)&-16;HEAP32[DYNAMICTOP_PTR>>2]=end;if(end>=TOTAL_MEMORY){var success=enlargeMemory();if(!success){HEAP32[DYNAMICTOP_PTR>>2]=ret;return 0}}return ret}),alignMemory:(function(size,quantum){var ret=size=Math.ceil(size/(quantum?quantum:16))*(quantum?quantum:16);return ret}),makeBigInt:(function(low,high,unsigned){var ret=unsigned?+(low>>>0)+ +(high>>>0)*+4294967296:+(low>>>0)+ +(high|0)*+4294967296;return ret}),GLOBAL_BASE:8,QUANTUM_SIZE:4,__dummy__:0};Module["Runtime"]=Runtime;var ABORT=0;var EXITSTATUS=0;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}function getCFunc(ident){var func=Module["_"+ident];if(!func){try{func=eval("_"+ident)}catch(e){}}assert(func,"Cannot call unknown function "+ident+" (perhaps LLVM optimizations or closure removed it?)");return func}var cwrap,ccall;((function(){var JSfuncs={"stackSave":(function(){Runtime.stackSave()}),"stackRestore":(function(){Runtime.stackRestore()}),"arrayToC":(function(arr){var ret=Runtime.stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}),"stringToC":(function(str){var ret=0;if(str!==null&&str!==undefined&&str!==0){var len=(str.length<<2)+1;ret=Runtime.stackAlloc(len);stringToUTF8(str,ret,len)}return ret})};var toC={"string":JSfuncs["stringToC"],"array":JSfuncs["arrayToC"]};ccall=function ccallFunc(ident,returnType,argTypes,args,opts){var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=Runtime.stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func.apply(null,cArgs);if(returnType==="string")ret=Pointer_stringify(ret);if(stack!==0){if(opts&&opts.async){EmterpreterAsync.asyncFinalizers.push((function(){Runtime.stackRestore(stack)}));return}Runtime.stackRestore(stack)}return ret};var sourceRegex=/^function\s*[a-zA-Z$_0-9]*\s*\(([^)]*)\)\s*{\s*([^*]*?)[\s;]*(?:return\s*(.*?)[;\s]*)?}$/;function parseJSFunc(jsfunc){var parsed=jsfunc.toString().match(sourceRegex).slice(1);return{arguments:parsed[0],body:parsed[1],returnValue:parsed[2]}}var JSsource=null;function ensureJSsource(){if(!JSsource){JSsource={};for(var fun in JSfuncs){if(JSfuncs.hasOwnProperty(fun)){JSsource[fun]=parseJSFunc(JSfuncs[fun])}}}}cwrap=function cwrap(ident,returnType,argTypes){argTypes=argTypes||[];var cfunc=getCFunc(ident);var numericArgs=argTypes.every((function(type){return type==="number"}));var numericRet=returnType!=="string";if(numericRet&&numericArgs){return cfunc}var argNames=argTypes.map((function(x,i){return"$"+i}));var funcstr="(function("+argNames.join(",")+") {";var nargs=argTypes.length;if(!numericArgs){ensureJSsource();funcstr+="var stack = "+JSsource["stackSave"].body+";";for(var i=0;i<nargs;i++){var arg=argNames[i],type=argTypes[i];if(type==="number")continue;var convertCode=JSsource[type+"ToC"];funcstr+="var "+convertCode.arguments+" = "+arg+";";funcstr+=convertCode.body+";";funcstr+=arg+"=("+convertCode.returnValue+");"}}var cfuncname=parseJSFunc((function(){return cfunc})).returnValue;funcstr+="var ret = "+cfuncname+"("+argNames.join(",")+");";if(!numericRet){var strgfy=parseJSFunc((function(){return Pointer_stringify})).returnValue;funcstr+="ret = "+strgfy+"(ret);"}if(!numericArgs){ensureJSsource();funcstr+=JSsource["stackRestore"].body.replace("()","(stack)")+";"}funcstr+="return ret})";return eval(funcstr)}}))();Module["ccall"]=ccall;Module["cwrap"]=cwrap;function setValue(ptr,value,type,noSafe){type=type||"i8";if(type.charAt(type.length-1)==="*")type="i32";switch(type){case"i1":HEAP8[ptr>>0]=value;break;case"i8":HEAP8[ptr>>0]=value;break;case"i16":HEAP16[ptr>>1]=value;break;case"i32":HEAP32[ptr>>2]=value;break;case"i64":tempI64=[value>>>0,(tempDouble=value,+Math_abs(tempDouble)>=+1?tempDouble>+0?(Math_min(+Math_floor(tempDouble/+4294967296),+4294967295)|0)>>>0:~~+Math_ceil((tempDouble- +(~~tempDouble>>>0))/+4294967296)>>>0:0)],HEAP32[ptr>>2]=tempI64[0],HEAP32[ptr+4>>2]=tempI64[1];break;case"float":HEAPF32[ptr>>2]=value;break;case"double":HEAPF64[ptr>>3]=value;break;default:abort("invalid type for setValue: "+type)}}Module["setValue"]=setValue;function getValue(ptr,type,noSafe){type=type||"i8";if(type.charAt(type.length-1)==="*")type="i32";switch(type){case"i1":return HEAP8[ptr>>0];case"i8":return HEAP8[ptr>>0];case"i16":return HEAP16[ptr>>1];case"i32":return HEAP32[ptr>>2];case"i64":return HEAP32[ptr>>2];case"float":return HEAPF32[ptr>>2];case"double":return HEAPF64[ptr>>3];default:abort("invalid type for setValue: "+type)}return null}Module["getValue"]=getValue;var ALLOC_NORMAL=0;var ALLOC_STACK=1;var ALLOC_STATIC=2;var ALLOC_DYNAMIC=3;var ALLOC_NONE=4;Module["ALLOC_NORMAL"]=ALLOC_NORMAL;Module["ALLOC_STACK"]=ALLOC_STACK;Module["ALLOC_STATIC"]=ALLOC_STATIC;Module["ALLOC_DYNAMIC"]=ALLOC_DYNAMIC;Module["ALLOC_NONE"]=ALLOC_NONE;function allocate(slab,types,allocator,ptr){var zeroinit,size;if(typeof slab==="number"){zeroinit=true;size=slab}else{zeroinit=false;size=slab.length}var singleType=typeof types==="string"?types:null;var ret;if(allocator==ALLOC_NONE){ret=ptr}else{ret=[typeof _malloc==="function"?_malloc:Runtime.staticAlloc,Runtime.stackAlloc,Runtime.staticAlloc,Runtime.dynamicAlloc][allocator===undefined?ALLOC_STATIC:allocator](Math.max(size,singleType?1:types.length))}if(zeroinit){var ptr=ret,stop;assert((ret&3)==0);stop=ret+(size&~3);for(;ptr<stop;ptr+=4){HEAP32[ptr>>2]=0}stop=ret+size;while(ptr<stop){HEAP8[ptr++>>0]=0}return ret}if(singleType==="i8"){if(slab.subarray||slab.slice){HEAPU8.set(slab,ret)}else{HEAPU8.set(new Uint8Array(slab),ret)}return ret}var i=0,type,typeSize,previousType;while(i<size){var curr=slab[i];if(typeof curr==="function"){curr=Runtime.getFunctionIndex(curr)}type=singleType||types[i];if(type===0){i++;continue}if(type=="i64")type="i32";setValue(ret+i,curr,type);if(previousType!==type){typeSize=Runtime.getNativeTypeSize(type);previousType=type}i+=typeSize}return ret}Module["allocate"]=allocate;function getMemory(size){if(!staticSealed)return Runtime.staticAlloc(size);if(!runtimeInitialized)return Runtime.dynamicAlloc(size);return _malloc(size)}Module["getMemory"]=getMemory;function Pointer_stringify(ptr,length){if(length===0||!ptr)return"";var hasUtf=0;var t;var i=0;while(1){t=HEAPU8[ptr+i>>0];hasUtf|=t;if(t==0&&!length)break;i++;if(length&&i==length)break}if(!length)length=i;var ret="";if(hasUtf<128){var MAX_CHUNK=1024;var curr;while(length>0){curr=String.fromCharCode.apply(String,HEAPU8.subarray(ptr,ptr+Math.min(length,MAX_CHUNK)));ret=ret?ret+curr:curr;ptr+=MAX_CHUNK;length-=MAX_CHUNK}return ret}return Module["UTF8ToString"](ptr)}Module["Pointer_stringify"]=Pointer_stringify;function AsciiToString(ptr){var str="";while(1){var ch=HEAP8[ptr++>>0];if(!ch)return str;str+=String.fromCharCode(ch)}}Module["AsciiToString"]=AsciiToString;function stringToAscii(str,outPtr){return writeAsciiToMemory(str,outPtr,false)}Module["stringToAscii"]=stringToAscii;var UTF8Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(u8Array,idx){var endPtr=idx;while(u8Array[endPtr])++endPtr;if(endPtr-idx>16&&u8Array.subarray&&UTF8Decoder){return UTF8Decoder.decode(u8Array.subarray(idx,endPtr))}else{var u0,u1,u2,u3,u4,u5;var str="";while(1){u0=u8Array[idx++];if(!u0)return str;if(!(u0&128)){str+=String.fromCharCode(u0);continue}u1=u8Array[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}u2=u8Array[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u3=u8Array[idx++]&63;if((u0&248)==240){u0=(u0&7)<<18|u1<<12|u2<<6|u3}else{u4=u8Array[idx++]&63;if((u0&252)==248){u0=(u0&3)<<24|u1<<18|u2<<12|u3<<6|u4}else{u5=u8Array[idx++]&63;u0=(u0&1)<<30|u1<<24|u2<<18|u3<<12|u4<<6|u5}}}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}}}Module["UTF8ArrayToString"]=UTF8ArrayToString;function UTF8ToString(ptr){return UTF8ArrayToString(HEAPU8,ptr)}Module["UTF8ToString"]=UTF8ToString;function stringToUTF8Array(str,outU8Array,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127){if(outIdx>=endIdx)break;outU8Array[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;outU8Array[outIdx++]=192|u>>6;outU8Array[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;outU8Array[outIdx++]=224|u>>12;outU8Array[outIdx++]=128|u>>6&63;outU8Array[outIdx++]=128|u&63}else if(u<=2097151){if(outIdx+3>=endIdx)break;outU8Array[outIdx++]=240|u>>18;outU8Array[outIdx++]=128|u>>12&63;outU8Array[outIdx++]=128|u>>6&63;outU8Array[outIdx++]=128|u&63}else if(u<=67108863){if(outIdx+4>=endIdx)break;outU8Array[outIdx++]=248|u>>24;outU8Array[outIdx++]=128|u>>18&63;outU8Array[outIdx++]=128|u>>12&63;outU8Array[outIdx++]=128|u>>6&63;outU8Array[outIdx++]=128|u&63}else{if(outIdx+5>=endIdx)break;outU8Array[outIdx++]=252|u>>30;outU8Array[outIdx++]=128|u>>24&63;outU8Array[outIdx++]=128|u>>18&63;outU8Array[outIdx++]=128|u>>12&63;outU8Array[outIdx++]=128|u>>6&63;outU8Array[outIdx++]=128|u&63}}outU8Array[outIdx]=0;return outIdx-startIdx}Module["stringToUTF8Array"]=stringToUTF8Array;function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}Module["stringToUTF8"]=stringToUTF8;function lengthBytesUTF8(str){var len=0;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127){++len}else if(u<=2047){len+=2}else if(u<=65535){len+=3}else if(u<=2097151){len+=4}else if(u<=67108863){len+=5}else{len+=6}}return len}Module["lengthBytesUTF8"]=lengthBytesUTF8;var UTF16Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf-16le"):undefined;function demangle(func){var __cxa_demangle_func=Module["___cxa_demangle"]||Module["__cxa_demangle"];if(__cxa_demangle_func){try{var s=func.substr(1);var len=lengthBytesUTF8(s)+1;var buf=_malloc(len);stringToUTF8(s,buf,len);var status=_malloc(4);var ret=__cxa_demangle_func(buf,0,0,status);if(getValue(status,"i32")===0&&ret){return Pointer_stringify(ret)}}catch(e){}finally{if(buf)_free(buf);if(status)_free(status);if(ret)_free(ret)}return func}Runtime.warnOnce("warning: build with -s DEMANGLE_SUPPORT=1 to link in libcxxabi demangling");return func}function demangleAll(text){var regex=/__Z[\w\d_]+/g;return text.replace(regex,(function(x){var y=demangle(x);return x===y?x:x+" ["+y+"]"}))}function jsStackTrace(){var err=new Error;if(!err.stack){try{throw new Error(0)}catch(e){err=e}if(!err.stack){return"(no stack trace available)"}}return err.stack.toString()}function stackTrace(){var js=jsStackTrace();if(Module["extraStackTrace"])js+="\n"+Module["extraStackTrace"]();return demangleAll(js)}Module["stackTrace"]=stackTrace;var HEAP,buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferViews(){Module["HEAP8"]=HEAP8=new Int8Array(buffer);Module["HEAP16"]=HEAP16=new Int16Array(buffer);Module["HEAP32"]=HEAP32=new Int32Array(buffer);Module["HEAPU8"]=HEAPU8=new Uint8Array(buffer);Module["HEAPU16"]=HEAPU16=new Uint16Array(buffer);Module["HEAPU32"]=HEAPU32=new Uint32Array(buffer);Module["HEAPF32"]=HEAPF32=new Float32Array(buffer);Module["HEAPF64"]=HEAPF64=new Float64Array(buffer)}var STATIC_BASE,STATICTOP,staticSealed;var STACK_BASE,STACKTOP,STACK_MAX;var DYNAMIC_BASE,DYNAMICTOP_PTR;STATIC_BASE=STATICTOP=STACK_BASE=STACKTOP=STACK_MAX=DYNAMIC_BASE=DYNAMICTOP_PTR=0;staticSealed=false;function abortOnCannotGrowMemory(){abort("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+TOTAL_MEMORY+", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime but prevents some optimizations, (3) set Module.TOTAL_MEMORY to a higher value before the program runs, or (4) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ")}function enlargeMemory(){abortOnCannotGrowMemory()}var TOTAL_STACK=Module["TOTAL_STACK"]||5242880;var TOTAL_MEMORY=Module["TOTAL_MEMORY"]||385875968;if(TOTAL_MEMORY<TOTAL_STACK)Module.printErr("TOTAL_MEMORY should be larger than TOTAL_STACK, was "+TOTAL_MEMORY+"! (TOTAL_STACK="+TOTAL_STACK+")");if(Module["buffer"]){buffer=Module["buffer"]}else{{buffer=new ArrayBuffer(TOTAL_MEMORY)}}updateGlobalBufferViews();function getTotalMemory(){return TOTAL_MEMORY}HEAP32[0]=1668509029;HEAP16[1]=25459;if(HEAPU8[2]!==115||HEAPU8[3]!==99)throw"Runtime error: expected the system to be little-endian!";Module["HEAP"]=HEAP;Module["buffer"]=buffer;Module["HEAP8"]=HEAP8;Module["HEAP16"]=HEAP16;Module["HEAP32"]=HEAP32;Module["HEAPU8"]=HEAPU8;Module["HEAPU16"]=HEAPU16;Module["HEAPU32"]=HEAPU32;Module["HEAPF32"]=HEAPF32;Module["HEAPF64"]=HEAPF64;function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback();continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===undefined){Module["dynCall_v"](func)}else{Module["dynCall_vi"](func,callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATEXIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeExited=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function ensureInitRuntime(){if(runtimeInitialized)return;runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function exitRuntime(){callRuntimeCallbacks(__ATEXIT__);runtimeExited=true}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}Module["addOnPreRun"]=addOnPreRun;function addOnInit(cb){__ATINIT__.unshift(cb)}Module["addOnInit"]=addOnInit;function addOnPreMain(cb){__ATMAIN__.unshift(cb)}Module["addOnPreMain"]=addOnPreMain;function addOnExit(cb){__ATEXIT__.unshift(cb)}Module["addOnExit"]=addOnExit;function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}Module["addOnPostRun"]=addOnPostRun;function intArrayFromString(stringy,dontAddNull,length){var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array}Module["intArrayFromString"]=intArrayFromString;function intArrayToString(array){var ret=[];for(var i=0;i<array.length;i++){var chr=array[i];if(chr>255){chr&=255}ret.push(String.fromCharCode(chr))}return ret.join("")}Module["intArrayToString"]=intArrayToString;function writeStringToMemory(string,buffer,dontAddNull){Runtime.warnOnce("writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!");var lastChar,end;if(dontAddNull){end=buffer+lengthBytesUTF8(string);lastChar=HEAP8[end]}stringToUTF8(string,buffer,Infinity);if(dontAddNull)HEAP8[end]=lastChar}Module["writeStringToMemory"]=writeStringToMemory;function writeArrayToMemory(array,buffer){HEAP8.set(array,buffer)}Module["writeArrayToMemory"]=writeArrayToMemory;function writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i<str.length;++i){HEAP8[buffer++>>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}Module["writeAsciiToMemory"]=writeAsciiToMemory;if(!Math["imul"]||Math["imul"](4294967295,5)!==-5)Math["imul"]=function imul(a,b){var ah=a>>>16;var al=a&65535;var bh=b>>>16;var bl=b&65535;return al*bl+(ah*bl+al*bh<<16)|0};Math.imul=Math["imul"];if(!Math["clz32"])Math["clz32"]=(function(x){x=x>>>0;for(var i=0;i<32;i++){if(x&1<<31-i)return i}return 32});Math.clz32=Math["clz32"];if(!Math["trunc"])Math["trunc"]=(function(x){return x<0?Math.ceil(x):Math.floor(x)});Math.trunc=Math["trunc"];var Math_abs=Math.abs;var Math_cos=Math.cos;var Math_sin=Math.sin;var Math_tan=Math.tan;var Math_acos=Math.acos;var Math_asin=Math.asin;var Math_atan=Math.atan;var Math_atan2=Math.atan2;var Math_exp=Math.exp;var Math_log=Math.log;var Math_sqrt=Math.sqrt;var Math_ceil=Math.ceil;var Math_floor=Math.floor;var Math_pow=Math.pow;var Math_imul=Math.imul;var Math_fround=Math.fround;var Math_round=Math.round;var Math_min=Math.min;var Math_clz32=Math.clz32;var Math_trunc=Math.trunc;var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}Module["addRunDependency"]=addRunDependency;function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["removeRunDependency"]=removeRunDependency;Module["preloadedImages"]={};Module["preloadedAudios"]={};var memoryInitializer=null;var ASM_CONSTS=[];STATIC_BASE=Runtime.GLOBAL_BASE;STATICTOP=STATIC_BASE+361488112;__ATINIT__.push();memoryInitializer="kernels_asmjs.js.mem";var tempDoublePtr=STATICTOP;STATICTOP+=16;function ___assert_fail(condition,filename,line,func){ABORT=true;throw"Assertion failed: "+Pointer_stringify(condition)+", at: "+[filename?Pointer_stringify(filename):"unknown filename",line,func?Pointer_stringify(func):"unknown function"]+" at "+stackTrace()}function ___setErrNo(value){if(Module["___errno_location"])HEAP32[Module["___errno_location"]()>>2]=value;return value}Module["_sbrk"]=_sbrk;function ___cxa_allocate_exception(size){return _malloc(size)}function __ZSt18uncaught_exceptionv(){return!!__ZSt18uncaught_exceptionv.uncaught_exception}var EXCEPTIONS={last:0,caught:[],infos:{},deAdjust:(function(adjusted){if(!adjusted||EXCEPTIONS.infos[adjusted])return adjusted;for(var ptr in EXCEPTIONS.infos){var info=EXCEPTIONS.infos[ptr];if(info.adjusted===adjusted){return ptr}}return adjusted}),addRef:(function(ptr){if(!ptr)return;var info=EXCEPTIONS.infos[ptr];info.refcount++}),decRef:(function(ptr){if(!ptr)return;var info=EXCEPTIONS.infos[ptr];assert(info.refcount>0);info.refcount--;if(info.refcount===0&&!info.rethrown){if(info.destructor){Module["dynCall_vi"](info.destructor,ptr)}delete EXCEPTIONS.infos[ptr];___cxa_free_exception(ptr)}}),clearRef:(function(ptr){if(!ptr)return;var info=EXCEPTIONS.infos[ptr];info.refcount=0})};function ___resumeException(ptr){if(!EXCEPTIONS.last){EXCEPTIONS.last=ptr}throw ptr+" - Exception catching is disabled, this exception cannot be caught. Compile with -s DISABLE_EXCEPTION_CATCHING=0 or DISABLE_EXCEPTION_CATCHING=2 to catch."}function ___cxa_find_matching_catch(){var thrown=EXCEPTIONS.last;if(!thrown){return(Runtime.setTempRet0(0),0)|0}var info=EXCEPTIONS.infos[thrown];var throwntype=info.type;if(!throwntype){return(Runtime.setTempRet0(0),thrown)|0}var typeArray=Array.prototype.slice.call(arguments);var pointer=Module["___cxa_is_pointer_type"](throwntype);if(!___cxa_find_matching_catch.buffer)___cxa_find_matching_catch.buffer=_malloc(4);HEAP32[___cxa_find_matching_catch.buffer>>2]=thrown;thrown=___cxa_find_matching_catch.buffer;for(var i=0;i<typeArray.length;i++){if(typeArray[i]&&Module["___cxa_can_catch"](typeArray[i],throwntype,thrown)){thrown=HEAP32[thrown>>2];info.adjusted=thrown;return(Runtime.setTempRet0(typeArray[i]),thrown)|0}}thrown=HEAP32[thrown>>2];return(Runtime.setTempRet0(throwntype),thrown)|0}function ___cxa_throw(ptr,type,destructor){EXCEPTIONS.infos[ptr]={ptr:ptr,adjusted:ptr,type:type,destructor:destructor,refcount:0,caught:false,rethrown:false};EXCEPTIONS.last=ptr;if(!("uncaught_exception"in __ZSt18uncaught_exceptionv)){__ZSt18uncaught_exceptionv.uncaught_exception=1}else{__ZSt18uncaught_exceptionv.uncaught_exception++}throw ptr+" - Exception catching is disabled, this exception cannot be caught. Compile with -s DISABLE_EXCEPTION_CATCHING=0 or DISABLE_EXCEPTION_CATCHING=2 to catch."}Module["_memset"]=_memset;function ___gxx_personality_v0(){}function ___lock(){}function _emscripten_memcpy_big(dest,src,num){HEAPU8.set(HEAPU8.subarray(src,src+num),dest);return dest}Module["_memcpy"]=_memcpy;var SYSCALLS={varargs:0,get:(function(varargs){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret}),getStr:(function(){var ret=Pointer_stringify(SYSCALLS.get());return ret}),get64:(function(){var low=SYSCALLS.get(),high=SYSCALLS.get();if(low>=0)assert(high===0);else assert(high===-1);return low}),getZero:(function(){assert(SYSCALLS.get()===0)})};function ___syscall140(which,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(),offset_high=SYSCALLS.get(),offset_low=SYSCALLS.get(),result=SYSCALLS.get(),whence=SYSCALLS.get();var offset=offset_low;FS.llseek(stream,offset,whence);HEAP32[result>>2]=stream.position;if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___syscall146(which,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.get(),iov=SYSCALLS.get(),iovcnt=SYSCALLS.get();var ret=0;if(!___syscall146.buffer){___syscall146.buffers=[null,[],[]];___syscall146.printChar=(function(stream,curr){var buffer=___syscall146.buffers[stream];assert(buffer);if(curr===0||curr===10){(stream===1?Module["print"]:Module["printErr"])(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}})}for(var i=0;i<iovcnt;i++){var ptr=HEAP32[iov+i*8>>2];var len=HEAP32[iov+(i*8+4)>>2];for(var j=0;j<len;j++){___syscall146.printChar(stream,HEAPU8[ptr+j])}ret+=len}return ret}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___syscall54(which,varargs){SYSCALLS.varargs=varargs;try{return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___unlock(){}function ___syscall6(which,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD();FS.close(stream);return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}__ATEXIT__.push((function(){var fflush=Module["_fflush"];if(fflush)fflush(0);var printChar=___syscall146.printChar;if(!printChar)return;var buffers=___syscall146.buffers;if(buffers[1].length)printChar(1,10);if(buffers[2].length)printChar(2,10)}));DYNAMICTOP_PTR=allocate(1,"i32",ALLOC_STATIC);STACK_BASE=STACKTOP=Runtime.alignMemory(STATICTOP);STACK_MAX=STACK_BASE+TOTAL_STACK;DYNAMIC_BASE=Runtime.alignMemory(STACK_MAX);HEAP32[DYNAMICTOP_PTR>>2]=DYNAMIC_BASE;staticSealed=true;function invoke_iiii(index,a1,a2,a3){try{return Module["dynCall_iiii"](index,a1,a2,a3)}catch(e){if(typeof e!=="number"&&e!=="longjmp")throw e;Module["setThrew"](1,0)}}function invoke_viiiii(index,a1,a2,a3,a4,a5){try{Module["dynCall_viiiii"](index,a1,a2,a3,a4,a5)}catch(e){if(typeof e!=="number"&&e!=="longjmp")throw e;Module["setThrew"](1,0)}}function invoke_vi(index,a1){try{Module["dynCall_vi"](index,a1)}catch(e){if(typeof e!=="number"&&e!=="longjmp")throw e;Module["setThrew"](1,0)}}function invoke_ii(index,a1){try{return Module["dynCall_ii"](index,a1)}catch(e){if(typeof e!=="number"&&e!=="longjmp")throw e;Module["setThrew"](1,0)}}function invoke_viiiiii(index,a1,a2,a3,a4,a5,a6){try{Module["dynCall_viiiiii"](index,a1,a2,a3,a4,a5,a6)}catch(e){if(typeof e!=="number"&&e!=="longjmp")throw e;Module["setThrew"](1,0)}}function invoke_viiii(index,a1,a2,a3,a4){try{Module["dynCall_viiii"](index,a1,a2,a3,a4)}catch(e){if(typeof e!=="number"&&e!=="longjmp")throw e;Module["setThrew"](1,0)}}Module.asmGlobalArg={"Math":Math,"Int8Array":Int8Array,"Int16Array":Int16Array,"Int32Array":Int32Array,"Uint8Array":Uint8Array,"Uint16Array":Uint16Array,"Uint32Array":Uint32Array,"Float32Array":Float32Array,"Float64Array":Float64Array,"NaN":NaN,"Infinity":Infinity};Module.asmLibraryArg={"abort":abort,"assert":assert,"enlargeMemory":enlargeMemory,"getTotalMemory":getTotalMemory,"abortOnCannotGrowMemory":abortOnCannotGrowMemory,"invoke_iiii":invoke_iiii,"invoke_viiiii":invoke_viiiii,"invoke_vi":invoke_vi,"invoke_ii":invoke_ii,"invoke_viiiiii":invoke_viiiiii,"invoke_viiii":invoke_viiii,"___cxa_throw":___cxa_throw,"___lock":___lock,"___syscall6":___syscall6,"___setErrNo":___setErrNo,"___syscall140":___syscall140,"___gxx_personality_v0":___gxx_personality_v0,"___cxa_allocate_exception":___cxa_allocate_exception,"_emscripten_memcpy_big":_emscripten_memcpy_big,"___syscall54":___syscall54,"___unlock":___unlock,"___resumeException":___resumeException,"__ZSt18uncaught_exceptionv":__ZSt18uncaught_exceptionv,"___assert_fail":___assert_fail,"___syscall146":___syscall146,"___cxa_find_matching_catch":___cxa_find_matching_catch,"DYNAMICTOP_PTR":DYNAMICTOP_PTR,"tempDoublePtr":tempDoublePtr,"ABORT":ABORT,"STACKTOP":STACKTOP,"STACK_MAX":STACK_MAX};// EMSCRIPTEN_START_ASM
var asm=(function(global,env,buffer) {
"use asm";var a=new global.Int8Array(buffer);var b=new global.Int16Array(buffer);var c=new global.Int32Array(buffer);var d=new global.Uint8Array(buffer);var e=new global.Uint16Array(buffer);var f=new global.Uint32Array(buffer);var g=new global.Float32Array(buffer);var h=new global.Float64Array(buffer);var i=env.DYNAMICTOP_PTR|0;var j=env.tempDoublePtr|0;var k=env.ABORT|0;var l=env.STACKTOP|0;var m=env.STACK_MAX|0;var n=0;var o=0;var p=0;var q=0;var r=global.NaN,s=global.Infinity;var t=0,u=0,v=0,w=0,x=0.0;var y=0;var z=global.Math.floor;var A=global.Math.abs;var B=global.Math.sqrt;var C=global.Math.pow;var D=global.Math.cos;var E=global.Math.sin;var F=global.Math.tan;var G=global.Math.acos;var H=global.Math.asin;var I=global.Math.atan;var J=global.Math.atan2;var K=global.Math.exp;var L=global.Math.log;var M=global.Math.ceil;var N=global.Math.imul;var O=global.Math.min;var P=global.Math.max;var Q=global.Math.clz32;var R=env.abort;var S=env.assert;var T=env.enlargeMemory;var U=env.getTotalMemory;var V=env.abortOnCannotGrowMemory;var W=env.invoke_iiii;var X=env.invoke_viiiii;var Y=env.invoke_vi;var Z=env.invoke_ii;var _=env.invoke_viiiiii;var $=env.invoke_viiii;var aa=env.___cxa_throw;var ba=env.___lock;var ca=env.___syscall6;var da=env.___setErrNo;var ea=env.___syscall140;var fa=env.___gxx_personality_v0;var ga=env.___cxa_allocate_exception;var ha=env._emscripten_memcpy_big;var ia=env.___syscall54;var ja=env.___unlock;var ka=env.___resumeException;var la=env.__ZSt18uncaught_exceptionv;var ma=env.___assert_fail;var na=env.___syscall146;var oa=env.___cxa_find_matching_catch;var pa=0.0;
// EMSCRIPTEN_START_FUNCS
function wa(a){a=a|0;var b=0;b=l;l=l+a|0;l=l+15&-16;return b|0}function xa(){return l|0}function ya(a){a=a|0;l=a}function za(a,b){a=a|0;b=b|0;l=a;m=b}function Aa(a,b){a=a|0;b=b|0;if(!n){n=a;o=b}}function Ba(a){a=a|0;y=a}function Ca(){return y|0}function Da(){return}function Ea(){return 11760}function Fa(a){a=a|0;var b=0;b=c[90371620]|0;if(b|0){Ta(b);c[90371620]=0}a=Sa(a<<2)|0;c[90371620]=a;return a|0}function Ga(){return c[90371620]|0}function Ha(a,b,d){a=a|0;b=b|0;d=d|0;c[(c[8840+(a<<2)>>2]|0)+(b<<2)>>2]=d;return}function Ia(a){a=a|0;var b=0,d=0,e=0,f=0,h=0,i=0,j=0,k=0,m=0,n=0,o=0,p=0,q=0;q=l;l=l+112|0;p=q+48|0;i=q+32|0;j=q;d=11760+(c[a>>2]<<2)|0;e=11760+(c[a+4>>2]<<2)|0;o=11760+(c[a+8>>2]<<2)|0;b=c[a+12>>2]|0;h=c[a+20>>2]|0;if(!((d|0)==0|(h|b|0)>-1))ma(10232,10402,175,10470);k=c[a+16>>2]|0;if(!((e|0)==0|(k|h|0)>-1))ma(10232,10402,175,10470);c[i>>2]=o;n=i+4|0;c[n>>2]=b;m=i+8|0;c[m>>2]=k;f=(k|b|0)>-1;if(!((o|0)==0|f))ma(10232,10402,175,10470);c[j>>2]=d;c[j+4>>2]=b;c[j+8>>2]=h;c[j+16>>2]=e;c[j+20>>2]=h;c[j+24>>2]=k;a=d;d=j+16|0;if(!((h|0)>0&(b+k+h|0)<20)){if(!f)ma(11002,11151,74,11226);b=N(b,k)|0;if((b|0)>0)Mb(o|0,0,b<<2|0)|0;g[p>>2]=1.0;La(i,j,d,p);l=q;return}f=d;j=c[f>>2]|0;f=c[f+4>>2]|0;c[p>>2]=a;c[p+4>>2]=b;c[p+8>>2]=h;i=p+16|0;c[i>>2]=j;c[i+4>>2]=f;c[p+24>>2]=k;c[p+32>>2]=a;c[p+40>>2]=h;c[p+44>>2]=j;c[p+52>>2]=k;c[p+56>>2]=h;if((b|0)>0){a=k;e=0;do{if((a|0)>0){d=N(e,k)|0;b=0;do{g[o+(b+d<<2)>>2]=+Ma(p,e,b);b=b+1|0;a=c[m>>2]|0}while((b|0)<(a|0));b=c[n>>2]|0}e=e+1|0}while((e|0)<(b|0))}l=q;return}function Ja(a){a=a|0;var b=0.0,d=0,e=0,f=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0;v=11760+(c[a>>2]<<2)|0;w=11760+(c[a+4>>2]<<2)|0;o=c[a+12>>2]|0;p=c[a+16>>2]|0;q=c[a+20>>2]|0;r=c[a+24>>2]|0;s=c[a+28>>2]|0;t=c[a+32>>2]|0;u=c[a+36>>2]|0;i=c[a+40>>2]|0;j=c[a+44>>2]|0;k=c[a+48>>2]|0;l=c[a+52>>2]|0;m=c[a+56>>2]|0;n=c[a+60>>2]|0;h=N(N(N(N(N(o,c[a+8>>2]|0)|0,r)|0,s)|0,t)|0,u)|0;if((h|0)>0)f=0;else return;do{d=(f|0)/(o|0)|0;a=(d|0)/(u|0)|0;x=(a|0)/(t|0)|0;e=(x|0)/(s|0)|0;a=(N((e|0)%(r|0)|0,k)|0)-m+(N((a|0)%(t|0)|0,i)|0)|0;d=(N((x|0)%(s|0)|0,l)|0)-n+(N((d|0)%(u|0)|0,j)|0)|0;if((a|0)>=0?(d|0)<(q|0)&((d|0)>-1&(a|0)<(p|0)):0)b=+g[v+((N((N((N((e|0)/(r|0)|0,p)|0)+a|0,q)|0)+d|0,o)|0)+((f|0)%(o|0)|0)<<2)>>2];else b=0.0;g[w+(f<<2)>>2]=b;f=f+1|0}while((f|0)!=(h|0));return}function Ka(){var a=0,b=0,d=0,e=0,f=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0.0,o=0,p=0,q=0;Ia(88);d=11760+(c[28]<<2)|0;e=11760+(c[30]<<2)|0;f=11760+(c[29]<<2)|0;a=c[32]|0;b=c[33]|0;i=N(N(a,c[31]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[34]<<2)|0;e=11760+(c[36]<<2)|0;f=11760+(c[35]<<2)|0;a=c[38]|0;b=c[39]|0;i=N(N(a,c[37]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[40]<<2)|0;e=11760+(c[42]<<2)|0;f=11760+(c[41]<<2)|0;a=c[44]|0;b=c[45]|0;i=N(N(a,c[43]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[46]<<2)|0;a=c[48]|0;f=c[90371620]|0;d=(c[50]|0?11760:f)+(c[49]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}b=11760+(c[55]<<2)|0;d=11760+(c[56]<<2)|0;a=c[57]|0;if((a|0)>0){e=0;do{c[d+(e<<2)>>2]=c[b+(e<<2)>>2];e=e+1|0}while((e|0)!=(a|0))}i=11760+(c[58]<<2)|0;h=c[60]|0;f=(c[62]|0?11760:f)+(c[61]<<2)|0;a:do if((h|0)>0){m=c[59]<<24;a=m>>24;if((m|0)>0)d=0;else{a=0;while(1){c[i+(a<<2)>>2]=c[f>>2];a=a+1|0;if((a|0)==(h|0))break a}}do{b=0;e=0;do{l=c[268+(b<<2)>>2]|0;m=N(l,e)|0;e=(((d|0)/(c[252+(b<<2)>>2]|0)|0|0)%(l|0)|0)+m|0;b=b+1|0}while((b|0)<(a|0));c[i+(d<<2)>>2]=c[f+(e<<2)>>2];d=d+1|0}while((d|0)!=(h|0))}while(0);Ja(284);Ia(348);d=11760+(c[93]<<2)|0;e=11760+(c[95]<<2)|0;f=11760+(c[94]<<2)|0;a=c[97]|0;b=c[98]|0;i=N(N(a,c[96]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[99]<<2)|0;e=11760+(c[101]<<2)|0;f=11760+(c[100]<<2)|0;a=c[103]|0;b=c[104]|0;i=N(N(a,c[102]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[105]<<2)|0;e=11760+(c[107]<<2)|0;f=11760+(c[106]<<2)|0;a=c[109]|0;b=c[110]|0;i=N(N(a,c[108]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[111]<<2)|0;a=c[113]|0;d=(c[115]|0?11760:c[90371620]|0)+(c[114]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(496);Ia(560);d=11760+(c[146]<<2)|0;e=11760+(c[148]<<2)|0;f=11760+(c[147]<<2)|0;a=c[150]|0;b=c[151]|0;i=N(N(a,c[149]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[152]<<2)|0;e=11760+(c[154]<<2)|0;f=11760+(c[153]<<2)|0;a=c[156]|0;b=c[157]|0;i=N(N(a,c[155]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[158]<<2)|0;e=11760+(c[160]<<2)|0;f=11760+(c[159]<<2)|0;a=c[162]|0;b=c[163]|0;i=N(N(a,c[161]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[164]<<2)|0;a=c[166]|0;d=c[90371620]|0;e=(c[169]|0?11760:d)+(c[167]<<2)|0;d=(c[170]|0?11760:d)+(c[168]<<2)|0;if((a|0)>0){f=0;do{g[b+(f<<2)>>2]=+g[e+(f<<2)>>2]+ +g[d+(f<<2)>>2];f=f+1|0}while((f|0)!=(a|0))}Ja(748);Ia(812);d=11760+(c[209]<<2)|0;e=11760+(c[211]<<2)|0;f=11760+(c[210]<<2)|0;a=c[213]|0;b=c[214]|0;i=N(N(a,c[212]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[215]<<2)|0;e=11760+(c[217]<<2)|0;f=11760+(c[216]<<2)|0;a=c[219]|0;b=c[220]|0;i=N(N(a,c[218]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[221]<<2)|0;e=11760+(c[223]<<2)|0;f=11760+(c[222]<<2)|0;a=c[225]|0;b=c[226]|0;i=N(N(a,c[224]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[227]<<2)|0;a=c[229]|0;d=(c[231]|0?11760:c[90371620]|0)+(c[230]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(960);Ia(1024);d=11760+(c[262]<<2)|0;e=11760+(c[264]<<2)|0;f=11760+(c[263]<<2)|0;a=c[266]|0;b=c[267]|0;i=N(N(a,c[265]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[268]<<2)|0;e=11760+(c[270]<<2)|0;f=11760+(c[269]<<2)|0;a=c[272]|0;b=c[273]|0;i=N(N(a,c[271]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[274]<<2)|0;e=11760+(c[276]<<2)|0;f=11760+(c[275]<<2)|0;a=c[278]|0;b=c[279]|0;i=N(N(a,c[277]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[280]<<2)|0;a=c[282]|0;d=c[90371620]|0;e=(c[285]|0?11760:d)+(c[283]<<2)|0;d=(c[286]|0?11760:d)+(c[284]<<2)|0;if((a|0)>0){f=0;do{g[b+(f<<2)>>2]=+g[e+(f<<2)>>2]+ +g[d+(f<<2)>>2];f=f+1|0}while((f|0)!=(a|0))}Ja(1212);Ia(1276);d=11760+(c[325]<<2)|0;e=11760+(c[327]<<2)|0;f=11760+(c[326]<<2)|0;a=c[329]|0;b=c[330]|0;i=N(N(a,c[328]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[331]<<2)|0;e=11760+(c[333]<<2)|0;f=11760+(c[332]<<2)|0;a=c[335]|0;b=c[336]|0;i=N(N(a,c[334]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[337]<<2)|0;e=11760+(c[339]<<2)|0;f=11760+(c[338]<<2)|0;a=c[341]|0;b=c[342]|0;i=N(N(a,c[340]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[343]<<2)|0;a=c[345]|0;d=(c[347]|0?11760:c[90371620]|0)+(c[346]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(1424);Ia(1488);d=11760+(c[378]<<2)|0;e=11760+(c[380]<<2)|0;f=11760+(c[379]<<2)|0;a=c[382]|0;b=c[383]|0;i=N(N(a,c[381]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[384]<<2)|0;e=11760+(c[386]<<2)|0;f=11760+(c[385]<<2)|0;a=c[388]|0;b=c[389]|0;i=N(N(a,c[387]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[390]<<2)|0;e=11760+(c[392]<<2)|0;f=11760+(c[391]<<2)|0;a=c[394]|0;b=c[395]|0;i=N(N(a,c[393]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[396]<<2)|0;a=c[398]|0;d=c[90371620]|0;e=(c[401]|0?11760:d)+(c[399]<<2)|0;d=(c[402]|0?11760:d)+(c[400]<<2)|0;if((a|0)>0){f=0;do{g[b+(f<<2)>>2]=+g[e+(f<<2)>>2]+ +g[d+(f<<2)>>2];f=f+1|0}while((f|0)!=(a|0))}Ja(1676);Ia(1740);d=11760+(c[441]<<2)|0;e=11760+(c[443]<<2)|0;f=11760+(c[442]<<2)|0;a=c[445]|0;b=c[446]|0;i=N(N(a,c[444]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[447]<<2)|0;e=11760+(c[449]<<2)|0;f=11760+(c[448]<<2)|0;a=c[451]|0;b=c[452]|0;i=N(N(a,c[450]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[453]<<2)|0;e=11760+(c[455]<<2)|0;f=11760+(c[454]<<2)|0;a=c[457]|0;b=c[458]|0;i=N(N(a,c[456]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[459]<<2)|0;a=c[461]|0;d=(c[463]|0?11760:c[90371620]|0)+(c[462]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(1888);Ia(1952);d=11760+(c[494]<<2)|0;e=11760+(c[496]<<2)|0;f=11760+(c[495]<<2)|0;a=c[498]|0;b=c[499]|0;i=N(N(a,c[497]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[500]<<2)|0;e=11760+(c[502]<<2)|0;f=11760+(c[501]<<2)|0;a=c[504]|0;b=c[505]|0;i=N(N(a,c[503]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[506]<<2)|0;e=11760+(c[508]<<2)|0;f=11760+(c[507]<<2)|0;a=c[510]|0;b=c[511]|0;i=N(N(a,c[509]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[512]<<2)|0;a=c[514]|0;d=c[90371620]|0;e=(c[517]|0?11760:d)+(c[515]<<2)|0;d=(c[518]|0?11760:d)+(c[516]<<2)|0;if((a|0)>0){f=0;do{g[b+(f<<2)>>2]=+g[e+(f<<2)>>2]+ +g[d+(f<<2)>>2];f=f+1|0}while((f|0)!=(a|0))}Ja(2140);Ia(2204);d=11760+(c[557]<<2)|0;e=11760+(c[559]<<2)|0;f=11760+(c[558]<<2)|0;a=c[561]|0;b=c[562]|0;i=N(N(a,c[560]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[563]<<2)|0;e=11760+(c[565]<<2)|0;f=11760+(c[564]<<2)|0;a=c[567]|0;b=c[568]|0;i=N(N(a,c[566]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[569]<<2)|0;e=11760+(c[571]<<2)|0;f=11760+(c[570]<<2)|0;a=c[573]|0;b=c[574]|0;i=N(N(a,c[572]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[575]<<2)|0;a=c[577]|0;d=(c[579]|0?11760:c[90371620]|0)+(c[578]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(2352);Ia(2416);d=11760+(c[610]<<2)|0;e=11760+(c[612]<<2)|0;f=11760+(c[611]<<2)|0;a=c[614]|0;b=c[615]|0;i=N(N(a,c[613]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[616]<<2)|0;e=11760+(c[618]<<2)|0;f=11760+(c[617]<<2)|0;a=c[620]|0;b=c[621]|0;i=N(N(a,c[619]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[622]<<2)|0;e=11760+(c[624]<<2)|0;f=11760+(c[623]<<2)|0;a=c[626]|0;b=c[627]|0;i=N(N(a,c[625]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[628]<<2)|0;a=c[630]|0;d=c[90371620]|0;e=(c[633]|0?11760:d)+(c[631]<<2)|0;d=(c[634]|0?11760:d)+(c[632]<<2)|0;if((a|0)>0){f=0;do{g[b+(f<<2)>>2]=+g[e+(f<<2)>>2]+ +g[d+(f<<2)>>2];f=f+1|0}while((f|0)!=(a|0))}Ja(2604);Ia(2668);d=11760+(c[673]<<2)|0;e=11760+(c[675]<<2)|0;f=11760+(c[674]<<2)|0;a=c[677]|0;b=c[678]|0;i=N(N(a,c[676]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[679]<<2)|0;e=11760+(c[681]<<2)|0;f=11760+(c[680]<<2)|0;a=c[683]|0;b=c[684]|0;i=N(N(a,c[682]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[685]<<2)|0;e=11760+(c[687]<<2)|0;f=11760+(c[686]<<2)|0;a=c[689]|0;b=c[690]|0;i=N(N(a,c[688]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[691]<<2)|0;a=c[693]|0;d=(c[695]|0?11760:c[90371620]|0)+(c[694]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(2816);Ia(2880);d=11760+(c[726]<<2)|0;e=11760+(c[728]<<2)|0;f=11760+(c[727]<<2)|0;a=c[730]|0;b=c[731]|0;i=N(N(a,c[729]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[732]<<2)|0;e=11760+(c[734]<<2)|0;f=11760+(c[733]<<2)|0;a=c[736]|0;b=c[737]|0;i=N(N(a,c[735]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[738]<<2)|0;e=11760+(c[740]<<2)|0;f=11760+(c[739]<<2)|0;a=c[742]|0;b=c[743]|0;i=N(N(a,c[741]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[744]<<2)|0;a=c[746]|0;d=c[90371620]|0;e=(c[749]|0?11760:d)+(c[747]<<2)|0;d=(c[750]|0?11760:d)+(c[748]<<2)|0;if((a|0)>0){f=0;do{g[b+(f<<2)>>2]=+g[e+(f<<2)>>2]+ +g[d+(f<<2)>>2];f=f+1|0}while((f|0)!=(a|0))}Ja(3068);Ia(3132);d=11760+(c[789]<<2)|0;e=11760+(c[791]<<2)|0;f=11760+(c[790]<<2)|0;a=c[793]|0;b=c[794]|0;i=N(N(a,c[792]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[795]<<2)|0;e=11760+(c[797]<<2)|0;f=11760+(c[796]<<2)|0;a=c[799]|0;b=c[800]|0;i=N(N(a,c[798]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[801]<<2)|0;e=11760+(c[803]<<2)|0;f=11760+(c[802]<<2)|0;a=c[805]|0;b=c[806]|0;i=N(N(a,c[804]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[807]<<2)|0;a=c[809]|0;d=(c[811]|0?11760:c[90371620]|0)+(c[810]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(3280);Ia(3344);d=11760+(c[842]<<2)|0;e=11760+(c[844]<<2)|0;f=11760+(c[843]<<2)|0;a=c[846]|0;b=c[847]|0;i=N(N(a,c[845]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[848]<<2)|0;e=11760+(c[850]<<2)|0;f=11760+(c[849]<<2)|0;a=c[852]|0;b=c[853]|0;i=N(N(a,c[851]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[854]<<2)|0;e=11760+(c[856]<<2)|0;f=11760+(c[855]<<2)|0;a=c[858]|0;b=c[859]|0;i=N(N(a,c[857]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[860]<<2)|0;a=c[862]|0;d=c[90371620]|0;e=(c[865]|0?11760:d)+(c[863]<<2)|0;d=(c[866]|0?11760:d)+(c[864]<<2)|0;if((a|0)>0){f=0;do{g[b+(f<<2)>>2]=+g[e+(f<<2)>>2]+ +g[d+(f<<2)>>2];f=f+1|0}while((f|0)!=(a|0))}Ja(3532);Ia(3596);d=11760+(c[905]<<2)|0;e=11760+(c[907]<<2)|0;f=11760+(c[906]<<2)|0;a=c[909]|0;b=c[910]|0;i=N(N(a,c[908]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[911]<<2)|0;e=11760+(c[913]<<2)|0;f=11760+(c[912]<<2)|0;a=c[915]|0;b=c[916]|0;i=N(N(a,c[914]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[917]<<2)|0;e=11760+(c[919]<<2)|0;f=11760+(c[918]<<2)|0;a=c[921]|0;b=c[922]|0;i=N(N(a,c[920]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[923]<<2)|0;a=c[925]|0;d=(c[927]|0?11760:c[90371620]|0)+(c[926]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(3744);Ia(3808);d=11760+(c[958]<<2)|0;e=11760+(c[960]<<2)|0;f=11760+(c[959]<<2)|0;a=c[962]|0;b=c[963]|0;i=N(N(a,c[961]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[964]<<2)|0;e=11760+(c[966]<<2)|0;f=11760+(c[965]<<2)|0;a=c[968]|0;b=c[969]|0;i=N(N(a,c[967]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[970]<<2)|0;e=11760+(c[972]<<2)|0;f=11760+(c[971]<<2)|0;a=c[974]|0;b=c[975]|0;i=N(N(a,c[973]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[976]<<2)|0;a=c[978]|0;d=c[90371620]|0;e=(c[981]|0?11760:d)+(c[979]<<2)|0;d=(c[982]|0?11760:d)+(c[980]<<2)|0;if((a|0)>0){f=0;do{g[b+(f<<2)>>2]=+g[e+(f<<2)>>2]+ +g[d+(f<<2)>>2];f=f+1|0}while((f|0)!=(a|0))}Ja(3996);Ia(4060);d=11760+(c[1021]<<2)|0;e=11760+(c[1023]<<2)|0;f=11760+(c[1022]<<2)|0;a=c[1025]|0;b=c[1026]|0;i=N(N(a,c[1024]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1027]<<2)|0;e=11760+(c[1029]<<2)|0;f=11760+(c[1028]<<2)|0;a=c[1031]|0;b=c[1032]|0;i=N(N(a,c[1030]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1033]<<2)|0;e=11760+(c[1035]<<2)|0;f=11760+(c[1034]<<2)|0;a=c[1037]|0;b=c[1038]|0;i=N(N(a,c[1036]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1039]<<2)|0;a=c[1041]|0;d=(c[1043]|0?11760:c[90371620]|0)+(c[1042]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(4208);Ia(4272);d=11760+(c[1074]<<2)|0;e=11760+(c[1076]<<2)|0;f=11760+(c[1075]<<2)|0;a=c[1078]|0;b=c[1079]|0;i=N(N(a,c[1077]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1080]<<2)|0;e=11760+(c[1082]<<2)|0;f=11760+(c[1081]<<2)|0;a=c[1084]|0;b=c[1085]|0;i=N(N(a,c[1083]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1086]<<2)|0;e=11760+(c[1088]<<2)|0;f=11760+(c[1087]<<2)|0;a=c[1090]|0;b=c[1091]|0;i=N(N(a,c[1089]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1092]<<2)|0;a=c[1094]|0;d=c[90371620]|0;e=(c[1097]|0?11760:d)+(c[1095]<<2)|0;d=(c[1098]|0?11760:d)+(c[1096]<<2)|0;if((a|0)>0){f=0;do{g[b+(f<<2)>>2]=+g[e+(f<<2)>>2]+ +g[d+(f<<2)>>2];f=f+1|0}while((f|0)!=(a|0))}Ja(4460);Ia(4524);d=11760+(c[1137]<<2)|0;e=11760+(c[1139]<<2)|0;f=11760+(c[1138]<<2)|0;a=c[1141]|0;b=c[1142]|0;i=N(N(a,c[1140]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1143]<<2)|0;e=11760+(c[1145]<<2)|0;f=11760+(c[1144]<<2)|0;a=c[1147]|0;b=c[1148]|0;i=N(N(a,c[1146]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1149]<<2)|0;e=11760+(c[1151]<<2)|0;f=11760+(c[1150]<<2)|0;a=c[1153]|0;b=c[1154]|0;i=N(N(a,c[1152]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1155]<<2)|0;a=c[1157]|0;d=(c[1159]|0?11760:c[90371620]|0)+(c[1158]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(4672);Ia(4736);d=11760+(c[1190]<<2)|0;e=11760+(c[1192]<<2)|0;f=11760+(c[1191]<<2)|0;a=c[1194]|0;b=c[1195]|0;i=N(N(a,c[1193]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1196]<<2)|0;e=11760+(c[1198]<<2)|0;f=11760+(c[1197]<<2)|0;a=c[1200]|0;b=c[1201]|0;i=N(N(a,c[1199]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1202]<<2)|0;e=11760+(c[1204]<<2)|0;f=11760+(c[1203]<<2)|0;a=c[1206]|0;b=c[1207]|0;i=N(N(a,c[1205]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1208]<<2)|0;a=c[1210]|0;d=c[90371620]|0;e=(c[1213]|0?11760:d)+(c[1211]<<2)|0;d=(c[1214]|0?11760:d)+(c[1212]<<2)|0;if((a|0)>0){f=0;do{g[b+(f<<2)>>2]=+g[e+(f<<2)>>2]+ +g[d+(f<<2)>>2];f=f+1|0}while((f|0)!=(a|0))}Ja(4924);Ia(4988);d=11760+(c[1253]<<2)|0;e=11760+(c[1255]<<2)|0;f=11760+(c[1254]<<2)|0;a=c[1257]|0;b=c[1258]|0;i=N(N(a,c[1256]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1259]<<2)|0;e=11760+(c[1261]<<2)|0;f=11760+(c[1260]<<2)|0;a=c[1263]|0;b=c[1264]|0;i=N(N(a,c[1262]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1265]<<2)|0;e=11760+(c[1267]<<2)|0;f=11760+(c[1266]<<2)|0;a=c[1269]|0;b=c[1270]|0;i=N(N(a,c[1268]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1271]<<2)|0;a=c[1273]|0;d=(c[1275]|0?11760:c[90371620]|0)+(c[1274]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(5136);Ia(5200);d=11760+(c[1306]<<2)|0;e=11760+(c[1308]<<2)|0;f=11760+(c[1307]<<2)|0;a=c[1310]|0;b=c[1311]|0;i=N(N(a,c[1309]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1312]<<2)|0;e=11760+(c[1314]<<2)|0;f=11760+(c[1313]<<2)|0;a=c[1316]|0;b=c[1317]|0;i=N(N(a,c[1315]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1318]<<2)|0;e=11760+(c[1320]<<2)|0;f=11760+(c[1319]<<2)|0;a=c[1322]|0;b=c[1323]|0;i=N(N(a,c[1321]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1324]<<2)|0;a=c[1326]|0;d=c[90371620]|0;e=(c[1329]|0?11760:d)+(c[1327]<<2)|0;d=(c[1330]|0?11760:d)+(c[1328]<<2)|0;if((a|0)>0){f=0;do{g[b+(f<<2)>>2]=+g[e+(f<<2)>>2]+ +g[d+(f<<2)>>2];f=f+1|0}while((f|0)!=(a|0))}Ja(5388);Ia(5452);d=11760+(c[1369]<<2)|0;e=11760+(c[1371]<<2)|0;f=11760+(c[1370]<<2)|0;a=c[1373]|0;b=c[1374]|0;i=N(N(a,c[1372]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1375]<<2)|0;e=11760+(c[1377]<<2)|0;f=11760+(c[1376]<<2)|0;a=c[1379]|0;b=c[1380]|0;i=N(N(a,c[1378]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1381]<<2)|0;e=11760+(c[1383]<<2)|0;f=11760+(c[1382]<<2)|0;a=c[1385]|0;b=c[1386]|0;i=N(N(a,c[1384]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1387]<<2)|0;a=c[1389]|0;d=(c[1391]|0?11760:c[90371620]|0)+(c[1390]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(5600);Ia(5664);d=11760+(c[1422]<<2)|0;e=11760+(c[1424]<<2)|0;f=11760+(c[1423]<<2)|0;a=c[1426]|0;b=c[1427]|0;i=N(N(a,c[1425]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1428]<<2)|0;e=11760+(c[1430]<<2)|0;f=11760+(c[1429]<<2)|0;a=c[1432]|0;b=c[1433]|0;i=N(N(a,c[1431]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1434]<<2)|0;e=11760+(c[1436]<<2)|0;f=11760+(c[1435]<<2)|0;a=c[1438]|0;b=c[1439]|0;i=N(N(a,c[1437]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1440]<<2)|0;a=c[1442]|0;d=c[90371620]|0;e=(c[1445]|0?11760:d)+(c[1443]<<2)|0;d=(c[1446]|0?11760:d)+(c[1444]<<2)|0;if((a|0)>0){f=0;do{g[b+(f<<2)>>2]=+g[e+(f<<2)>>2]+ +g[d+(f<<2)>>2];f=f+1|0}while((f|0)!=(a|0))}Ja(5852);Ia(5916);d=11760+(c[1485]<<2)|0;e=11760+(c[1487]<<2)|0;f=11760+(c[1486]<<2)|0;a=c[1489]|0;b=c[1490]|0;i=N(N(a,c[1488]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1491]<<2)|0;e=11760+(c[1493]<<2)|0;f=11760+(c[1492]<<2)|0;a=c[1495]|0;b=c[1496]|0;i=N(N(a,c[1494]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1497]<<2)|0;e=11760+(c[1499]<<2)|0;f=11760+(c[1498]<<2)|0;a=c[1501]|0;b=c[1502]|0;i=N(N(a,c[1500]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1503]<<2)|0;a=c[1505]|0;d=(c[1507]|0?11760:c[90371620]|0)+(c[1506]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(6064);Ia(6128);d=11760+(c[1538]<<2)|0;e=11760+(c[1540]<<2)|0;f=11760+(c[1539]<<2)|0;a=c[1542]|0;b=c[1543]|0;i=N(N(a,c[1541]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1544]<<2)|0;e=11760+(c[1546]<<2)|0;f=11760+(c[1545]<<2)|0;a=c[1548]|0;b=c[1549]|0;i=N(N(a,c[1547]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1550]<<2)|0;e=11760+(c[1552]<<2)|0;f=11760+(c[1551]<<2)|0;a=c[1554]|0;b=c[1555]|0;i=N(N(a,c[1553]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1556]<<2)|0;a=c[1558]|0;d=c[90371620]|0;e=(c[1561]|0?11760:d)+(c[1559]<<2)|0;d=(c[1562]|0?11760:d)+(c[1560]<<2)|0;if((a|0)>0){f=0;do{g[b+(f<<2)>>2]=+g[e+(f<<2)>>2]+ +g[d+(f<<2)>>2];f=f+1|0}while((f|0)!=(a|0))}Ja(6316);Ia(6380);d=11760+(c[1601]<<2)|0;e=11760+(c[1603]<<2)|0;f=11760+(c[1602]<<2)|0;a=c[1605]|0;b=c[1606]|0;i=N(N(a,c[1604]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1607]<<2)|0;e=11760+(c[1609]<<2)|0;f=11760+(c[1608]<<2)|0;a=c[1611]|0;b=c[1612]|0;i=N(N(a,c[1610]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1613]<<2)|0;e=11760+(c[1615]<<2)|0;f=11760+(c[1614]<<2)|0;a=c[1617]|0;b=c[1618]|0;i=N(N(a,c[1616]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1619]<<2)|0;a=c[1621]|0;d=(c[1623]|0?11760:c[90371620]|0)+(c[1622]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(6528);Ia(6592);d=11760+(c[1654]<<2)|0;e=11760+(c[1656]<<2)|0;f=11760+(c[1655]<<2)|0;a=c[1658]|0;b=c[1659]|0;i=N(N(a,c[1657]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1660]<<2)|0;e=11760+(c[1662]<<2)|0;f=11760+(c[1661]<<2)|0;a=c[1664]|0;b=c[1665]|0;i=N(N(a,c[1663]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1666]<<2)|0;e=11760+(c[1668]<<2)|0;f=11760+(c[1667]<<2)|0;a=c[1670]|0;b=c[1671]|0;i=N(N(a,c[1669]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1672]<<2)|0;a=c[1674]|0;d=c[90371620]|0;e=(c[1677]|0?11760:d)+(c[1675]<<2)|0;d=(c[1678]|0?11760:d)+(c[1676]<<2)|0;if((a|0)>0){f=0;do{g[b+(f<<2)>>2]=+g[e+(f<<2)>>2]+ +g[d+(f<<2)>>2];f=f+1|0}while((f|0)!=(a|0))}Ja(6780);Ia(6844);d=11760+(c[1717]<<2)|0;e=11760+(c[1719]<<2)|0;f=11760+(c[1718]<<2)|0;a=c[1721]|0;b=c[1722]|0;i=N(N(a,c[1720]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1723]<<2)|0;e=11760+(c[1725]<<2)|0;f=11760+(c[1724]<<2)|0;a=c[1727]|0;b=c[1728]|0;i=N(N(a,c[1726]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1729]<<2)|0;e=11760+(c[1731]<<2)|0;f=11760+(c[1730]<<2)|0;a=c[1733]|0;b=c[1734]|0;i=N(N(a,c[1732]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1735]<<2)|0;a=c[1737]|0;d=(c[1739]|0?11760:c[90371620]|0)+(c[1738]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(6992);Ia(7056);d=11760+(c[1770]<<2)|0;e=11760+(c[1772]<<2)|0;f=11760+(c[1771]<<2)|0;a=c[1774]|0;b=c[1775]|0;i=N(N(a,c[1773]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1776]<<2)|0;e=11760+(c[1778]<<2)|0;f=11760+(c[1777]<<2)|0;a=c[1780]|0;b=c[1781]|0;i=N(N(a,c[1779]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1782]<<2)|0;e=11760+(c[1784]<<2)|0;f=11760+(c[1783]<<2)|0;a=c[1786]|0;b=c[1787]|0;i=N(N(a,c[1785]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1788]<<2)|0;a=c[1790]|0;d=c[90371620]|0;e=(c[1793]|0?11760:d)+(c[1791]<<2)|0;d=(c[1794]|0?11760:d)+(c[1792]<<2)|0;if((a|0)>0){f=0;do{g[b+(f<<2)>>2]=+g[e+(f<<2)>>2]+ +g[d+(f<<2)>>2];f=f+1|0}while((f|0)!=(a|0))}Ja(7244);Ia(7308);d=11760+(c[1833]<<2)|0;e=11760+(c[1835]<<2)|0;f=11760+(c[1834]<<2)|0;a=c[1837]|0;b=c[1838]|0;i=N(N(a,c[1836]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1839]<<2)|0;e=11760+(c[1841]<<2)|0;f=11760+(c[1840]<<2)|0;a=c[1843]|0;b=c[1844]|0;i=N(N(a,c[1842]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1845]<<2)|0;e=11760+(c[1847]<<2)|0;f=11760+(c[1846]<<2)|0;a=c[1849]|0;b=c[1850]|0;i=N(N(a,c[1848]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1851]<<2)|0;a=c[1853]|0;d=(c[1855]|0?11760:c[90371620]|0)+(c[1854]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(7456);Ia(7520);d=11760+(c[1886]<<2)|0;e=11760+(c[1888]<<2)|0;f=11760+(c[1887]<<2)|0;a=c[1890]|0;b=c[1891]|0;i=N(N(a,c[1889]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1892]<<2)|0;e=11760+(c[1894]<<2)|0;f=11760+(c[1893]<<2)|0;a=c[1896]|0;b=c[1897]|0;i=N(N(a,c[1895]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1898]<<2)|0;e=11760+(c[1900]<<2)|0;f=11760+(c[1899]<<2)|0;a=c[1902]|0;b=c[1903]|0;i=N(N(a,c[1901]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1904]<<2)|0;a=c[1906]|0;d=c[90371620]|0;e=(c[1909]|0?11760:d)+(c[1907]<<2)|0;d=(c[1910]|0?11760:d)+(c[1908]<<2)|0;if((a|0)>0){f=0;do{g[b+(f<<2)>>2]=+g[e+(f<<2)>>2]+ +g[d+(f<<2)>>2];f=f+1|0}while((f|0)!=(a|0))}Ja(7708);Ia(7772);d=11760+(c[1949]<<2)|0;e=11760+(c[1951]<<2)|0;f=11760+(c[1950]<<2)|0;a=c[1953]|0;b=c[1954]|0;i=N(N(a,c[1952]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1955]<<2)|0;e=11760+(c[1957]<<2)|0;f=11760+(c[1956]<<2)|0;a=c[1959]|0;b=c[1960]|0;i=N(N(a,c[1958]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[1961]<<2)|0;e=11760+(c[1963]<<2)|0;f=11760+(c[1962]<<2)|0;a=c[1965]|0;b=c[1966]|0;i=N(N(a,c[1964]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[1967]<<2)|0;a=c[1969]|0;d=(c[1971]|0?11760:c[90371620]|0)+(c[1970]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(7920);Ia(7984);d=11760+(c[2002]<<2)|0;e=11760+(c[2004]<<2)|0;f=11760+(c[2003]<<2)|0;a=c[2006]|0;b=c[2007]|0;i=N(N(a,c[2005]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}j=11760+(c[2008]<<2)|0;k=11760+(c[2009]<<2)|0;a=c[2010]|0;b=c[2012]|0;d=c[2013]|0;e=c[2014]|0;f=c[2015]|0;h=c[2016]|0;i=c[2017]|0;m=N(N(N(d,c[2011]|0)|0,f)|0,i)|0;if((m|0)>0){l=0;do{q=(l|0)/(d|0)|0;o=(q|0)%(i|0)|0;q=(q|0)/(i|0)|0;p=(q|0)%(f|0)|0;c[k+(l<<2)>>2]=c[j+((N((N(((p|0)/(a|0)|0)+(N((q|0)/(f|0)|0,e)|0)|0,h)|0)+((o|0)/(a|0)|0)|0,b)|0)+((l|0)%(d|0)|0)+(N((N((p|0)%(a|0)|0,a)|0)+((o|0)%(a|0)|0)|0,d)|0)<<2)>>2];l=l+1|0}while((l|0)!=(m|0))}d=11760+(c[2018]<<2)|0;e=11760+(c[2020]<<2)|0;f=11760+(c[2019]<<2)|0;a=c[2022]|0;b=c[2023]|0;i=N(N(a,c[2021]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[2024]<<2)|0;e=11760+(c[2026]<<2)|0;f=11760+(c[2025]<<2)|0;a=c[2028]|0;b=c[2029]|0;i=N(N(a,c[2027]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[2030]<<2)|0;a=c[2032]|0;d=(c[2034]|0?11760:c[90371620]|0)+(c[2033]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(8172);Ia(8236);d=11760+(c[2065]<<2)|0;e=11760+(c[2067]<<2)|0;f=11760+(c[2066]<<2)|0;a=c[2069]|0;b=c[2070]|0;i=N(N(a,c[2068]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}j=11760+(c[2071]<<2)|0;k=11760+(c[2072]<<2)|0;a=c[2073]|0;b=c[2075]|0;d=c[2076]|0;e=c[2077]|0;f=c[2078]|0;h=c[2079]|0;i=c[2080]|0;m=N(N(N(d,c[2074]|0)|0,f)|0,i)|0;if((m|0)>0){l=0;do{o=(l|0)/(d|0)|0;q=(o|0)%(i|0)|0;o=(o|0)/(i|0)|0;p=(o|0)%(f|0)|0;c[k+(l<<2)>>2]=c[j+((N((N(((p|0)/(a|0)|0)+(N((o|0)/(f|0)|0,e)|0)|0,h)|0)+((q|0)/(a|0)|0)|0,b)|0)+((l|0)%(d|0)|0)+(N((N((p|0)%(a|0)|0,a)|0)+((q|0)%(a|0)|0)|0,d)|0)<<2)>>2];l=l+1|0}while((l|0)!=(m|0))}d=11760+(c[2081]<<2)|0;e=11760+(c[2083]<<2)|0;f=11760+(c[2082]<<2)|0;a=c[2085]|0;b=c[2086]|0;i=N(N(a,c[2084]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[2087]<<2)|0;e=11760+(c[2089]<<2)|0;f=11760+(c[2088]<<2)|0;a=c[2091]|0;b=c[2092]|0;i=N(N(a,c[2090]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[2093]<<2)|0;a=c[2095]|0;d=(c[2097]|0?11760:c[90371620]|0)+(c[2096]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(8424);Ia(8488);d=11760+(c[2128]<<2)|0;e=11760+(c[2130]<<2)|0;f=11760+(c[2129]<<2)|0;a=c[2132]|0;b=c[2133]|0;i=N(N(a,c[2131]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}j=11760+(c[2134]<<2)|0;k=11760+(c[2135]<<2)|0;a=c[2136]|0;b=c[2138]|0;d=c[2139]|0;e=c[2140]|0;f=c[2141]|0;h=c[2142]|0;i=c[2143]|0;m=N(N(N(d,c[2137]|0)|0,f)|0,i)|0;if((m|0)>0){l=0;do{o=(l|0)/(d|0)|0;q=(o|0)%(i|0)|0;o=(o|0)/(i|0)|0;p=(o|0)%(f|0)|0;c[k+(l<<2)>>2]=c[j+((N((N(((p|0)/(a|0)|0)+(N((o|0)/(f|0)|0,e)|0)|0,h)|0)+((q|0)/(a|0)|0)|0,b)|0)+((l|0)%(d|0)|0)+(N((N((p|0)%(a|0)|0,a)|0)+((q|0)%(a|0)|0)|0,d)|0)<<2)>>2];l=l+1|0}while((l|0)!=(m|0))}d=11760+(c[2144]<<2)|0;e=11760+(c[2146]<<2)|0;f=11760+(c[2145]<<2)|0;a=c[2148]|0;b=c[2149]|0;i=N(N(a,c[2147]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]*+g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}d=11760+(c[2150]<<2)|0;e=11760+(c[2152]<<2)|0;f=11760+(c[2151]<<2)|0;a=c[2154]|0;b=c[2155]|0;i=N(N(a,c[2153]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[2156]<<2)|0;a=c[2158]|0;d=(c[2160]|0?11760:c[90371620]|0)+(c[2159]<<2)|0;if((a|0)>0){e=0;do{n=+g[d+(e<<2)>>2];g[b+(e<<2)>>2]=n>0.0?n:0.0;e=e+1|0}while((e|0)!=(a|0))}Ja(8676);Ia(8740);d=11760+(c[2191]<<2)|0;e=11760+(c[2193]<<2)|0;f=11760+(c[2192]<<2)|0;a=c[2195]|0;b=c[2196]|0;i=N(N(a,c[2194]|0)|0,b)|0;if((i|0)>0){h=0;do{g[e+(h<<2)>>2]=+g[d+(h<<2)>>2]+ +g[f+((((h|0)/(b|0)|0|0)%(a|0)|0)<<2)>>2];h=h+1|0}while((h|0)!=(i|0))}b=11760+(c[2197]<<2)|0;a=c[2199]|0;d=(c[2201]|0?11760:c[90371620]|0)+(c[2200]<<2)|0;if((a|0)>0)e=0;else return;do{g[b+(e<<2)>>2]=+fb(+g[d+(e<<2)>>2]);e=e+1|0}while((e|0)!=(a|0));return}function La(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,h=0,i=0,j=0,k=0,m=0,n=0,o=0,p=0,q=0.0,r=0;p=l;l=l+32|0;o=p;f=c[a+4>>2]|0;j=b+4|0;if((f|0)!=(c[j>>2]|0))ma(11241,11294,460,11383);k=a+8|0;h=c[k>>2]|0;m=d+8|0;if((h|0)!=(c[m>>2]|0))ma(11241,11294,460,11383);n=b+8|0;i=c[n>>2]|0;if((h|0)==0|((f|0)==0|(i|0)==0)){l=p;return}q=+g[e>>2];r=o;c[r>>2]=0;c[r+4>>2]=0;r=o+8|0;c[r>>2]=h;e=o+12|0;c[e>>2]=f;f=o+16|0;c[f>>2]=i;Na(f,r,e,1);f=c[f>>2]|0;c[o+20>>2]=N(f,c[r>>2]|0)|0;c[o+24>>2]=N(c[e>>2]|0,f)|0;m=c[m>>2]|0;f=c[n>>2]|0;Oa(m,c[j>>2]|0,f,c[d>>2]|0,m,c[b>>2]|0,f,c[a>>2]|0,c[k>>2]|0,q,o,0);f=c[o>>2]|0;if(f|0)Ta(c[f+-4>>2]|0);f=c[o+4>>2]|0;if(f|0)Ta(c[f+-4>>2]|0);l=p;return}function Ma(a,b,d){a=a|0;b=b|0;d=d|0;var e=0.0,f=0,h=0,i=0;h=c[a+8>>2]|0;i=(c[a>>2]|0)+((N(h,b)|0)<<2)|0;if(!((h|0)>-1|(i|0)==0))ma(10232,10402,175,10470);if((b|0)<=-1)ma(10478,10645,122,10711);if((c[a+4>>2]|0)<=(b|0))ma(10478,10645,122,10711);f=(c[a+16>>2]|0)+(d<<2)|0;b=c[a+20>>2]|0;if(!((f|0)==0|(b|0)>-1))ma(10232,10402,175,10470);a=c[a+24>>2]|0;if(!((d|0)>-1&(a|0)>(d|0)))ma(10478,10645,122,10711);if((h|0)!=(b|0))ma(10717,10774,110,10848);if(!h){e=0.0;return +e}if((h|0)<=0)ma(10862,10930,413,10996);e=+g[i>>2]*+g[f>>2];if((h|0)==1)return +e;else b=1;do{e=e+ +g[i+(b<<2)>>2]*+g[f+((N(b,a)|0)<<2)>>2];b=b+1|0}while((b|0)<(h|0));return +e}function Na(b,d,e,f){b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0;if((a[11752]|0)==0?Hb(11752)|0:0){c[90371621]=16384;c[90371622]=524288;c[90371623]=524288}m=c[90371621]|0;n=c[90371622]|0;o=c[90371623]|0;if((f|0)>1){h=(m+-16|0)/20|0;h=(h|0)<320?h:320;g=c[b>>2]|0;if((h|0)<(g|0)){g=h-((h|0)%8|0)|0;c[b>>2]=g}i=((n-m|0)>>>0)/(g<<4>>>0)|0;g=c[e>>2]|0;j=f+-1|0;h=(j+g|0)/(f|0)|0;if((i|0)>(h|0)){m=h+3|0;m=m-((m|0)%4|0)|0;g=(m|0)<(g|0)?m:g}else g=i-((i|0)%4|0)|0;c[e>>2]=g;if((o|0)<=(n|0))return;i=((o-n|0)>>>0)/((N(f<<2,c[b>>2]|0)|0)>>>0)|0;h=c[d>>2]|0;g=(j+h|0)/(f|0)|0;if((i|0)>0&(i|0)<(g|0)){c[d>>2]=i;return}else{c[d>>2]=(g|0)<(h|0)?g:h;return}}g=c[d>>2]|0;h=c[e>>2]|0;k=(g|0)<(h|0)?h:g;l=c[b>>2]|0;if((((l|0)<(k|0)?k:l)|0)<48)return;k=m+-16|0;f=((k|0)/20|0)&-8;f=(f|0)>1?f:1;if((l|0)>(f|0)){g=(l|0)%(f|0)|0;if(!g)g=f;else g=f-(((f+-1-g|0)/((((l|0)/(f|0)|0)<<3)+8|0)|0)<<3)|0;c[b>>2]=g;b=c[d>>2]|0;i=g;j=c[e>>2]|0}else{b=g;i=l;j=h}g=k-(N(b<<2,i)|0)|0;k=(g|0)<(i<<4|0);k=((k?4718592:g)>>>0)/((k?f<<4:i<<2)>>>0)|0;g=1572864/(i<<3>>>0)|0;g=((k|0)<(g|0)?k:g)&-4;if((j|0)>(g|0)){h=(j|0)%(g|0)|0;if(h)g=g-(((g-h|0)/((((j|0)/(g|0)|0)<<2)+4|0)|0)<<2)|0;c[e>>2]=g;return}if((l|0)!=(i|0))return;g=N(l<<2,j)|0;if((g|0)<1025){g=m;h=b}else{h=(o|0)!=0&(g|0)<32769;g=h?n:1572864;h=h?((b|0)<576?b:576):b}g=(g>>>0)/((l*12|0)>>>0)|0;g=(h|0)<(g|0)?h:g;if(!g)return;h=(b|0)%(g|0)|0;if(h)g=g-((g-h|0)/(((b|0)/(g|0)|0)+1|0)|0)|0;c[d>>2]=g;return}function Oa(a,b,d,e,f,g,h,i,j,k,m,n){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;i=i|0;j=j|0;k=+k;m=m|0;n=n|0;var o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,O=0,P=0,Q=0;O=l;l=l+16|0;K=O+10|0;L=O+9|0;J=O+8|0;M=O;I=c[m+16>>2]|0;H=c[m+8>>2]|0;s=(H|0)<(a|0);H=s?H:a;r=c[m+12>>2]|0;G=(r|0)<(b|0)?r:b;n=N(H,I)|0;q=N(G,I)|0;if(n>>>0>1073741823){a=ga(4)|0;Jb(a);aa(a|0,72,6)}o=c[m>>2]|0;p=n<<2;if(!o)do if(p>>>0>=131073){n=Sa(p+16|0)|0;o=n+16&-16;if(!n){a=ga(4)|0;Jb(a);aa(a|0,72,6)}c[o+-4>>2]=n;if(!o){a=ga(4)|0;Jb(a);aa(a|0,72,6)}else{n=c[m>>2]|0;break}}else{o=l;l=l+((1*(p+15|0)|0)+15&-16)|0;n=0;o=o+15&-16}while(0);else n=o;F=(n|0)==0?o:0;E=p>>>0>131072;if(q>>>0>1073741823){a=ga(4)|0;Jb(a);aa(a|0,72,6)}m=m+4|0;p=c[m>>2]|0;q=q<<2;if(!p)do if(q>>>0>=131073){n=Sa(q+16|0)|0;p=n+16&-16;if(!n){a=ga(4)|0;Jb(a);aa(a|0,72,6)}c[p+-4>>2]=n;if(!p){a=ga(4)|0;Jb(a);aa(a|0,72,6)}else{n=c[m>>2]|0;break}}else{p=l;l=l+((1*(q+15|0)|0)+15&-16)|0;n=0;p=p+15&-16}while(0);else n=p;D=(n|0)==0?p:0;z=q>>>0>131072;if((a|0)>0){A=(d|0)>0;C=M+4|0;B=(b|0)>0;y=(I|0)==(d|0)&s&(r|0)>=(b|0)^1;t=M+4|0;u=M+4|0;q=0;do{r=q;q=q+H|0;w=((q|0)>(a|0)?a:q)-r|0;if(A){v=(r|0)==0|y;s=0;do{m=s;s=s+I|0;x=((s|0)>(d|0)?d:s)-m|0;c[M>>2]=e+((N(m,f)|0)+r<<2);c[C>>2]=f;Pa(K,o,M,x,w,0,0);if(B)if(v){n=0;do{Q=n;n=n+G|0;P=((n|0)>(b|0)?b:n)-Q|0;c[M>>2]=g+((N(Q,h)|0)+m<<2);c[t>>2]=h;Qa(L,p,M,x,P,0,0);c[M>>2]=i+((N(Q,j)|0)+r<<2);c[u>>2]=j;Ra(J,M,o,p,w,x,P,k,-1,-1,0,0)}while((n|0)<(b|0))}else{n=0;do{Q=n;n=n+G|0;c[M>>2]=i+((N(Q,j)|0)+r<<2);c[u>>2]=j;Ra(J,M,o,p,w,x,((n|0)>(b|0)?b:n)-Q|0,k,-1,-1,0,0)}while((n|0)<(b|0))}}while((s|0)<(d|0))}}while((q|0)<(a|0))}if(!((D|0)==0|z^1))Ta(c[D+-4>>2]|0);if((F|0)==0|E^1){l=O;return}Ta(c[F+-4>>2]|0);l=O;return}function Pa(a,b,d,e,f,g,h){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;var i=0,j=0;if(h|g|0)ma(11397,11488,1705,11581);if((f|0)<=0)return;j=c[d>>2]|0;h=c[d+4>>2]|0;if((e|0)>0){g=0;d=0}else return;while(1){a=g;i=0;while(1){c[b+(a<<2)>>2]=c[j+((N(h,i)|0)+d<<2)>>2];i=i+1|0;if((i|0)==(e|0))break;else a=a+1|0}d=d+1|0;if((d|0)==(f|0))break;else g=g+e|0}return}function Qa(a,b,d,e,f,g,h){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;var i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0;if(h|g|0)ma(11397,11488,1906,11581);i=((f|0)/4|0)<<2;if((f|0)>3?(q=c[d>>2]|0,r=c[d+4>>2]|0,(e|0)>0):0){h=e<<2;p=(i|0)>4?i:4;l=0;n=0;while(1){k=q+((N(r,n)|0)<<2)|0;j=q+((N(r,n|1)|0)<<2)|0;a=q+((N(r,n|2)|0)<<2)|0;g=q+((N(r,n|3)|0)<<2)|0;m=l;o=0;while(1){c[b+(m<<2)>>2]=c[k+(o<<2)>>2];c[b+((m|1)<<2)>>2]=c[j+(o<<2)>>2];c[b+((m|2)<<2)>>2]=c[a+(o<<2)>>2];c[b+((m|3)<<2)>>2]=c[g+(o<<2)>>2];o=o+1|0;if((o|0)==(e|0))break;else m=m+4|0}n=n+4|0;if((n|0)>=(i|0))break;else l=h+l|0}h=N(p,e)|0}else h=0;if((i|0)>=(f|0))return;l=c[d>>2]|0;k=c[d+4>>2]|0;if((e|0)<=0)return;while(1){g=l+((N(k,i)|0)<<2)|0;a=h;j=0;while(1){c[b+(a<<2)>>2]=c[g+(j<<2)>>2];j=j+1|0;if((j|0)==(e|0))break;else a=a+1|0}i=i+1|0;if((i|0)==(f|0))break;else h=h+e|0}return}function Ra(a,b,d,e,f,h,i,j,k,l,m,n){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;h=h|0;i=i|0;j=+j;k=k|0;l=l|0;m=m|0;n=n|0;var o=0.0,p=0,q=0,r=0.0,s=0.0,t=0,u=0,v=0.0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,O=0,P=0.0,Q=0.0,R=0.0,S=0.0,T=0.0,U=0.0,V=0.0,W=0.0;O=(k|0)==-1?h:k;M=(l|0)==-1?h:l;k=(i|0)/4|0;J=k<<2;D=h&-8;if((f|0)<=0)return;H=(i|0)>3;I=b+4|0;K=n<<2;F=(D|0)>0;G=(D|0)<(h|0);E=(J|0)<(i|0);A=(D+-1|0)>>>3;L=e+((A<<5)+K+32<<2)|0;C=M<<2;A=A<<3;B=e+(((N(M,k)|0)<<2)+n+A+8<<2)|0;z=0;A=d+(A+m+8<<2)|0;while(1){if(H){p=d+((N(z,O)|0)+m<<2)|0;x=L;y=0;while(1){k=c[b>>2]|0;q=c[I>>2]|0;w=k+((N(q,y)|0)+z<<2)|0;u=k+((N(q,y|1)|0)+z<<2)|0;t=k+((N(q,y|2)|0)+z<<2)|0;q=k+((N(q,y|3)|0)+z<<2)|0;k=e+((N(y,M)|0)+K<<2)|0;if(F){v=0.0;s=0.0;r=0.0;o=0.0;l=p;a=0;while(1){W=+g[l>>2];V=+g[l+4>>2];U=+g[l+8>>2];T=+g[l+12>>2];S=+g[l+16>>2];R=+g[l+20>>2];Q=+g[l+24>>2];P=+g[l+28>>2];v=v+W*+g[k>>2]+V*+g[k+16>>2]+U*+g[k+32>>2]+T*+g[k+48>>2]+S*+g[k+64>>2]+R*+g[k+80>>2]+Q*+g[k+96>>2]+P*+g[k+112>>2];s=s+W*+g[k+4>>2]+V*+g[k+20>>2]+U*+g[k+36>>2]+T*+g[k+52>>2]+S*+g[k+68>>2]+R*+g[k+84>>2]+Q*+g[k+100>>2]+P*+g[k+116>>2];r=r+W*+g[k+8>>2]+V*+g[k+24>>2]+U*+g[k+40>>2]+T*+g[k+56>>2]+S*+g[k+72>>2]+R*+g[k+88>>2]+Q*+g[k+104>>2]+P*+g[k+120>>2];o=o+W*+g[k+12>>2]+V*+g[k+28>>2]+U*+g[k+44>>2]+T*+g[k+60>>2]+S*+g[k+76>>2]+R*+g[k+92>>2]+Q*+g[k+108>>2]+P*+g[k+124>>2];a=a+8|0;if((a|0)>=(D|0)){a=A;k=x;break}else{l=l+32|0;k=k+128|0}}}else{v=0.0;s=0.0;r=0.0;o=0.0;a=p}if(G){l=D;while(1){W=+g[a>>2];v=v+W*+g[k>>2];s=s+W*+g[k+4>>2];r=r+W*+g[k+8>>2];o=o+W*+g[k+12>>2];l=l+1|0;if((l|0)==(h|0))break;else{a=a+4|0;k=k+16|0}}}W=s*j+ +g[u>>2];g[w>>2]=v*j+ +g[w>>2];g[u>>2]=W;W=o*j+ +g[q>>2];g[t>>2]=r*j+ +g[t>>2];g[q>>2]=W;y=y+4|0;if((y|0)>=(J|0))break;else x=x+(C<<2)|0}}a:do if(E){w=d+((N(z,O)|0)+m<<2)|0;if(F){t=B;u=J}else{q=J;while(1){p=(c[b>>2]|0)+((N(c[I>>2]|0,q)|0)+z<<2)|0;if(G){o=0.0;k=w;a=e+((N(q,M)|0)+n<<2)|0;l=D;while(1){o=o+ +g[k>>2]*+g[a>>2];l=l+1|0;if((l|0)==(h|0))break;else{k=k+4|0;a=a+4|0}}}else o=0.0;g[p>>2]=o*j+ +g[p>>2];q=q+1|0;if((q|0)==(i|0))break a}}while(1){k=c[b>>2]|0;a=(N(c[I>>2]|0,u)|0)+z|0;o=0.0;l=w;p=e+((N(u,M)|0)+n<<2)|0;q=0;while(1){o=o+ +g[l>>2]*+g[p>>2]+ +g[l+4>>2]*+g[p+4>>2]+ +g[l+8>>2]*+g[p+8>>2]+ +g[l+12>>2]*+g[p+12>>2]+ +g[l+16>>2]*+g[p+16>>2]+ +g[l+20>>2]*+g[p+20>>2]+ +g[l+24>>2]*+g[p+24>>2]+ +g[l+28>>2]*+g[p+28>>2];q=q+8|0;if((q|0)>=(D|0))break;else{l=l+32|0;p=p+32|0}}p=k+(a<<2)|0;if(G){k=A;a=t;l=D;while(1){o=o+ +g[k>>2]*+g[a>>2];l=l+1|0;if((l|0)==(h|0))break;else{k=k+4|0;a=a+4|0}}}g[p>>2]=o*j+ +g[p>>2];u=u+1|0;if((u|0)==(i|0))break;else t=t+(M<<2)|0}}while(0);z=z+1|0;if((z|0)==(f|0))break;else A=A+(O<<2)|0}return}function Sa(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0;x=l;l=l+16|0;o=x;do if(a>>>0<245){k=a>>>0<11?16:a+11&-8;a=k>>>3;n=c[90371624]|0;d=n>>>a;if(d&3|0){e=(d&1^1)+a|0;f=361486536+(e<<1<<2)|0;b=f+8|0;a=c[b>>2]|0;g=a+8|0;d=c[g>>2]|0;if((f|0)==(d|0))c[90371624]=n&~(1<<e);else{c[d+12>>2]=f;c[b>>2]=d}w=e<<3;c[a+4>>2]=w|3;w=a+w+4|0;c[w>>2]=c[w>>2]|1;w=g;l=x;return w|0}m=c[90371626]|0;if(k>>>0>m>>>0){if(d|0){h=2<<a;d=d<<a&(h|0-h);d=(d&0-d)+-1|0;h=d>>>12&16;d=d>>>h;a=d>>>5&8;d=d>>>a;f=d>>>2&4;d=d>>>f;b=d>>>1&2;d=d>>>b;e=d>>>1&1;e=(a|h|f|b|e)+(d>>>e)|0;d=361486536+(e<<1<<2)|0;b=d+8|0;f=c[b>>2]|0;h=f+8|0;a=c[h>>2]|0;if((d|0)==(a|0)){a=n&~(1<<e);c[90371624]=a}else{c[a+12>>2]=d;c[b>>2]=a;a=n}g=(e<<3)-k|0;c[f+4>>2]=k|3;f=f+k|0;c[f+4>>2]=g|1;c[f+g>>2]=g;if(m|0){e=c[90371629]|0;b=m>>>3;d=361486536+(b<<1<<2)|0;b=1<<b;if(!(a&b)){c[90371624]=a|b;b=d+8|0;a=d}else{a=d+8|0;b=a;a=c[a>>2]|0}c[b>>2]=e;c[a+12>>2]=e;c[e+8>>2]=a;c[e+12>>2]=d}c[90371626]=g;c[90371629]=f;w=h;l=x;return w|0}i=c[90371625]|0;if(i){d=(i&0-i)+-1|0;h=d>>>12&16;d=d>>>h;g=d>>>5&8;d=d>>>g;j=d>>>2&4;d=d>>>j;a=d>>>1&2;d=d>>>a;e=d>>>1&1;e=c[361486800+((g|h|j|a|e)+(d>>>e)<<2)>>2]|0;d=(c[e+4>>2]&-8)-k|0;a=c[e+16+(((c[e+16>>2]|0)==0&1)<<2)>>2]|0;if(!a){j=d;h=e}else{do{h=(c[a+4>>2]&-8)-k|0;j=h>>>0<d>>>0;d=j?h:d;e=j?a:e;a=c[a+16+(((c[a+16>>2]|0)==0&1)<<2)>>2]|0}while((a|0)!=0);j=d;h=e}g=h+k|0;if(h>>>0<g>>>0){f=c[h+24>>2]|0;b=c[h+12>>2]|0;do if((b|0)==(h|0)){a=h+20|0;b=c[a>>2]|0;if(!b){a=h+16|0;b=c[a>>2]|0;if(!b){d=0;break}}while(1){e=b+20|0;d=c[e>>2]|0;if(d|0){b=d;a=e;continue}e=b+16|0;d=c[e>>2]|0;if(!d)break;else{b=d;a=e}}c[a>>2]=0;d=b}else{d=c[h+8>>2]|0;c[d+12>>2]=b;c[b+8>>2]=d;d=b}while(0);do if(f|0){b=c[h+28>>2]|0;a=361486800+(b<<2)|0;if((h|0)==(c[a>>2]|0)){c[a>>2]=d;if(!d){c[90371625]=i&~(1<<b);break}}else{c[f+16+(((c[f+16>>2]|0)!=(h|0)&1)<<2)>>2]=d;if(!d)break}c[d+24>>2]=f;b=c[h+16>>2]|0;if(b|0){c[d+16>>2]=b;c[b+24>>2]=d}b=c[h+20>>2]|0;if(b|0){c[d+20>>2]=b;c[b+24>>2]=d}}while(0);if(j>>>0<16){w=j+k|0;c[h+4>>2]=w|3;w=h+w+4|0;c[w>>2]=c[w>>2]|1}else{c[h+4>>2]=k|3;c[g+4>>2]=j|1;c[g+j>>2]=j;if(m|0){e=c[90371629]|0;b=m>>>3;d=361486536+(b<<1<<2)|0;b=1<<b;if(!(n&b)){c[90371624]=n|b;b=d+8|0;a=d}else{a=d+8|0;b=a;a=c[a>>2]|0}c[b>>2]=e;c[a+12>>2]=e;c[e+8>>2]=a;c[e+12>>2]=d}c[90371626]=j;c[90371629]=g}w=h+8|0;l=x;return w|0}else n=k}else n=k}else n=k}else if(a>>>0<=4294967231){a=a+11|0;k=a&-8;e=c[90371625]|0;if(e){d=0-k|0;a=a>>>8;if(a)if(k>>>0>16777215)j=31;else{n=(a+1048320|0)>>>16&8;v=a<<n;m=(v+520192|0)>>>16&4;v=v<<m;j=(v+245760|0)>>>16&2;j=14-(m|n|j)+(v<<j>>>15)|0;j=k>>>(j+7|0)&1|j<<1}else j=0;a=c[361486800+(j<<2)>>2]|0;a:do if(!a){f=0;a=0;v=57}else{f=0;h=k<<((j|0)==31?0:25-(j>>>1)|0);i=a;a=0;while(1){g=(c[i+4>>2]&-8)-k|0;if(g>>>0<d>>>0)if(!g){d=0;f=i;a=i;v=61;break a}else{d=g;a=i}g=c[i+20>>2]|0;i=c[i+16+(h>>>31<<2)>>2]|0;f=(g|0)==0|(g|0)==(i|0)?f:g;g=(i|0)==0;if(g){v=57;break}else h=h<<((g^1)&1)}}while(0);if((v|0)==57){if((f|0)==0&(a|0)==0){a=2<<j;a=e&(a|0-a);if(!a){n=k;break}a=(a&0-a)+-1|0;j=a>>>12&16;a=a>>>j;i=a>>>5&8;a=a>>>i;m=a>>>2&4;a=a>>>m;n=a>>>1&2;a=a>>>n;f=a>>>1&1;f=c[361486800+((i|j|m|n|f)+(a>>>f)<<2)>>2]|0;a=0}if(!f){i=d;j=a}else v=61}if((v|0)==61)while(1){v=0;m=(c[f+4>>2]&-8)-k|0;n=m>>>0<d>>>0;d=n?m:d;a=n?f:a;f=c[f+16+(((c[f+16>>2]|0)==0&1)<<2)>>2]|0;if(!f){i=d;j=a;break}else v=61}if((j|0)!=0?i>>>0<((c[90371626]|0)-k|0)>>>0:0){h=j+k|0;if(j>>>0>=h>>>0){w=0;l=x;return w|0}g=c[j+24>>2]|0;b=c[j+12>>2]|0;do if((b|0)==(j|0)){a=j+20|0;b=c[a>>2]|0;if(!b){a=j+16|0;b=c[a>>2]|0;if(!b){b=0;break}}while(1){f=b+20|0;d=c[f>>2]|0;if(d|0){b=d;a=f;continue}f=b+16|0;d=c[f>>2]|0;if(!d)break;else{b=d;a=f}}c[a>>2]=0}else{w=c[j+8>>2]|0;c[w+12>>2]=b;c[b+8>>2]=w}while(0);do if(g){a=c[j+28>>2]|0;d=361486800+(a<<2)|0;if((j|0)==(c[d>>2]|0)){c[d>>2]=b;if(!b){e=e&~(1<<a);c[90371625]=e;break}}else{c[g+16+(((c[g+16>>2]|0)!=(j|0)&1)<<2)>>2]=b;if(!b)break}c[b+24>>2]=g;a=c[j+16>>2]|0;if(a|0){c[b+16>>2]=a;c[a+24>>2]=b}a=c[j+20>>2]|0;if(a){c[b+20>>2]=a;c[a+24>>2]=b}}while(0);do if(i>>>0>=16){c[j+4>>2]=k|3;c[h+4>>2]=i|1;c[h+i>>2]=i;b=i>>>3;if(i>>>0<256){d=361486536+(b<<1<<2)|0;a=c[90371624]|0;b=1<<b;if(!(a&b)){c[90371624]=a|b;b=d+8|0;a=d}else{a=d+8|0;b=a;a=c[a>>2]|0}c[b>>2]=h;c[a+12>>2]=h;c[h+8>>2]=a;c[h+12>>2]=d;break}b=i>>>8;if(b)if(i>>>0>16777215)b=31;else{v=(b+1048320|0)>>>16&8;w=b<<v;u=(w+520192|0)>>>16&4;w=w<<u;b=(w+245760|0)>>>16&2;b=14-(u|v|b)+(w<<b>>>15)|0;b=i>>>(b+7|0)&1|b<<1}else b=0;d=361486800+(b<<2)|0;c[h+28>>2]=b;a=h+16|0;c[a+4>>2]=0;c[a>>2]=0;a=1<<b;if(!(e&a)){c[90371625]=e|a;c[d>>2]=h;c[h+24>>2]=d;c[h+12>>2]=h;c[h+8>>2]=h;break}a=i<<((b|0)==31?0:25-(b>>>1)|0);d=c[d>>2]|0;while(1){if((c[d+4>>2]&-8|0)==(i|0)){v=97;break}e=d+16+(a>>>31<<2)|0;b=c[e>>2]|0;if(!b){v=96;break}else{a=a<<1;d=b}}if((v|0)==96){c[e>>2]=h;c[h+24>>2]=d;c[h+12>>2]=h;c[h+8>>2]=h;break}else if((v|0)==97){v=d+8|0;w=c[v>>2]|0;c[w+12>>2]=h;c[v>>2]=h;c[h+8>>2]=w;c[h+12>>2]=d;c[h+24>>2]=0;break}}else{w=i+k|0;c[j+4>>2]=w|3;w=j+w+4|0;c[w>>2]=c[w>>2]|1}while(0);w=j+8|0;l=x;return w|0}else n=k}else n=k}else n=-1;while(0);d=c[90371626]|0;if(d>>>0>=n>>>0){a=d-n|0;b=c[90371629]|0;if(a>>>0>15){w=b+n|0;c[90371629]=w;c[90371626]=a;c[w+4>>2]=a|1;c[w+a>>2]=a;c[b+4>>2]=n|3}else{c[90371626]=0;c[90371629]=0;c[b+4>>2]=d|3;w=b+d+4|0;c[w>>2]=c[w>>2]|1}w=b+8|0;l=x;return w|0}h=c[90371627]|0;if(h>>>0>n>>>0){u=h-n|0;c[90371627]=u;w=c[90371630]|0;v=w+n|0;c[90371630]=v;c[v+4>>2]=u|1;c[w+4>>2]=n|3;w=w+8|0;l=x;return w|0}if(!(c[90371742]|0)){c[90371744]=4096;c[90371743]=4096;c[90371745]=-1;c[90371746]=-1;c[90371747]=0;c[90371735]=0;a=o&-16^1431655768;c[o>>2]=a;c[90371742]=a;a=4096}else a=c[90371744]|0;i=n+48|0;j=n+47|0;g=a+j|0;e=0-a|0;k=g&e;if(k>>>0<=n>>>0){w=0;l=x;return w|0}a=c[90371734]|0;if(a|0?(m=c[90371732]|0,o=m+k|0,o>>>0<=m>>>0|o>>>0>a>>>0):0){w=0;l=x;return w|0}b:do if(!(c[90371735]&4)){d=c[90371630]|0;c:do if(d){f=361486944;while(1){a=c[f>>2]|0;if(a>>>0<=d>>>0?(r=f+4|0,(a+(c[r>>2]|0)|0)>>>0>d>>>0):0)break;a=c[f+8>>2]|0;if(!a){v=118;break c}else f=a}b=g-h&e;if(b>>>0<2147483647){a=Lb(b|0)|0;if((a|0)==((c[f>>2]|0)+(c[r>>2]|0)|0)){if((a|0)!=(-1|0)){h=a;g=b;v=135;break b}}else{e=a;v=126}}else b=0}else v=118;while(0);do if((v|0)==118){d=Lb(0)|0;if((d|0)!=(-1|0)?(b=d,p=c[90371743]|0,q=p+-1|0,b=((q&b|0)==0?0:(q+b&0-p)-b|0)+k|0,p=c[90371732]|0,q=b+p|0,b>>>0>n>>>0&b>>>0<2147483647):0){r=c[90371734]|0;if(r|0?q>>>0<=p>>>0|q>>>0>r>>>0:0){b=0;break}a=Lb(b|0)|0;if((a|0)==(d|0)){h=d;g=b;v=135;break b}else{e=a;v=126}}else b=0}while(0);do if((v|0)==126){d=0-b|0;if(!(i>>>0>b>>>0&(b>>>0<2147483647&(e|0)!=(-1|0))))if((e|0)==(-1|0)){b=0;break}else{h=e;g=b;v=135;break b}a=c[90371744]|0;a=j-b+a&0-a;if(a>>>0>=2147483647){h=e;g=b;v=135;break b}if((Lb(a|0)|0)==(-1|0)){Lb(d|0)|0;b=0;break}else{h=e;g=a+b|0;v=135;break b}}while(0);c[90371735]=c[90371735]|4;v=133}else{b=0;v=133}while(0);if(((v|0)==133?k>>>0<2147483647:0)?(s=Lb(k|0)|0,r=Lb(0)|0,u=r-s|0,t=u>>>0>(n+40|0)>>>0,!((s|0)==(-1|0)|t^1|s>>>0<r>>>0&((s|0)!=(-1|0)&(r|0)!=(-1|0))^1)):0){h=s;g=t?u:b;v=135}if((v|0)==135){b=(c[90371732]|0)+g|0;c[90371732]=b;if(b>>>0>(c[90371733]|0)>>>0)c[90371733]=b;j=c[90371630]|0;do if(j){f=361486944;while(1){b=c[f>>2]|0;e=f+4|0;a=c[e>>2]|0;if((h|0)==(b+a|0)){v=145;break}d=c[f+8>>2]|0;if(!d)break;else f=d}if(((v|0)==145?(c[f+12>>2]&8|0)==0:0)?j>>>0<h>>>0&j>>>0>=b>>>0:0){c[e>>2]=a+g;w=j+8|0;w=(w&7|0)==0?0:0-w&7;v=j+w|0;w=(c[90371627]|0)+(g-w)|0;c[90371630]=v;c[90371627]=w;c[v+4>>2]=w|1;c[v+w+4>>2]=40;c[90371631]=c[90371746];break}if(h>>>0<(c[90371628]|0)>>>0)c[90371628]=h;d=h+g|0;a=361486944;while(1){if((c[a>>2]|0)==(d|0)){v=153;break}b=c[a+8>>2]|0;if(!b)break;else a=b}if((v|0)==153?(c[a+12>>2]&8|0)==0:0){c[a>>2]=h;m=a+4|0;c[m>>2]=(c[m>>2]|0)+g;m=h+8|0;m=h+((m&7|0)==0?0:0-m&7)|0;b=d+8|0;b=d+((b&7|0)==0?0:0-b&7)|0;k=m+n|0;i=b-m-n|0;c[m+4>>2]=n|3;do if((b|0)!=(j|0)){if((b|0)==(c[90371629]|0)){w=(c[90371626]|0)+i|0;c[90371626]=w;c[90371629]=k;c[k+4>>2]=w|1;c[k+w>>2]=w;break}a=c[b+4>>2]|0;if((a&3|0)==1){h=a&-8;e=a>>>3;d:do if(a>>>0<256){a=c[b+8>>2]|0;d=c[b+12>>2]|0;if((d|0)==(a|0)){c[90371624]=c[90371624]&~(1<<e);break}else{c[a+12>>2]=d;c[d+8>>2]=a;break}}else{g=c[b+24>>2]|0;a=c[b+12>>2]|0;do if((a|0)==(b|0)){e=b+16|0;d=e+4|0;a=c[d>>2]|0;if(!a){a=c[e>>2]|0;if(!a){a=0;break}else f=e}else f=d;while(1){e=a+20|0;d=c[e>>2]|0;if(d|0){a=d;f=e;continue}e=a+16|0;d=c[e>>2]|0;if(!d)break;else{a=d;f=e}}c[f>>2]=0}else{w=c[b+8>>2]|0;c[w+12>>2]=a;c[a+8>>2]=w}while(0);if(!g)break;d=c[b+28>>2]|0;e=361486800+(d<<2)|0;do if((b|0)!=(c[e>>2]|0)){c[g+16+(((c[g+16>>2]|0)!=(b|0)&1)<<2)>>2]=a;if(!a)break d}else{c[e>>2]=a;if(a|0)break;c[90371625]=c[90371625]&~(1<<d);break d}while(0);c[a+24>>2]=g;e=b+16|0;d=c[e>>2]|0;if(d|0){c[a+16>>2]=d;c[d+24>>2]=a}d=c[e+4>>2]|0;if(!d)break;c[a+20>>2]=d;c[d+24>>2]=a}while(0);b=b+h|0;f=h+i|0}else f=i;b=b+4|0;c[b>>2]=c[b>>2]&-2;c[k+4>>2]=f|1;c[k+f>>2]=f;b=f>>>3;if(f>>>0<256){d=361486536+(b<<1<<2)|0;a=c[90371624]|0;b=1<<b;if(!(a&b)){c[90371624]=a|b;b=d+8|0;a=d}else{a=d+8|0;b=a;a=c[a>>2]|0}c[b>>2]=k;c[a+12>>2]=k;c[k+8>>2]=a;c[k+12>>2]=d;break}b=f>>>8;do if(!b)a=0;else{if(f>>>0>16777215){a=31;break}v=(b+1048320|0)>>>16&8;w=b<<v;u=(w+520192|0)>>>16&4;w=w<<u;a=(w+245760|0)>>>16&2;a=14-(u|v|a)+(w<<a>>>15)|0;a=f>>>(a+7|0)&1|a<<1}while(0);e=361486800+(a<<2)|0;c[k+28>>2]=a;b=k+16|0;c[b+4>>2]=0;c[b>>2]=0;b=c[90371625]|0;d=1<<a;if(!(b&d)){c[90371625]=b|d;c[e>>2]=k;c[k+24>>2]=e;c[k+12>>2]=k;c[k+8>>2]=k;break}a=f<<((a|0)==31?0:25-(a>>>1)|0);d=c[e>>2]|0;while(1){if((c[d+4>>2]&-8|0)==(f|0)){v=194;break}e=d+16+(a>>>31<<2)|0;b=c[e>>2]|0;if(!b){v=193;break}else{a=a<<1;d=b}}if((v|0)==193){c[e>>2]=k;c[k+24>>2]=d;c[k+12>>2]=k;c[k+8>>2]=k;break}else if((v|0)==194){v=d+8|0;w=c[v>>2]|0;c[w+12>>2]=k;c[v>>2]=k;c[k+8>>2]=w;c[k+12>>2]=d;c[k+24>>2]=0;break}}else{w=(c[90371627]|0)+i|0;c[90371627]=w;c[90371630]=k;c[k+4>>2]=w|1}while(0);w=m+8|0;l=x;return w|0}a=361486944;while(1){b=c[a>>2]|0;if(b>>>0<=j>>>0?(w=b+(c[a+4>>2]|0)|0,w>>>0>j>>>0):0)break;a=c[a+8>>2]|0}f=w+-47|0;a=f+8|0;a=f+((a&7|0)==0?0:0-a&7)|0;f=j+16|0;a=a>>>0<f>>>0?j:a;b=a+8|0;d=h+8|0;d=(d&7|0)==0?0:0-d&7;v=h+d|0;d=g+-40-d|0;c[90371630]=v;c[90371627]=d;c[v+4>>2]=d|1;c[v+d+4>>2]=40;c[90371631]=c[90371746];d=a+4|0;c[d>>2]=27;c[b>>2]=c[90371736];c[b+4>>2]=c[90371737];c[b+8>>2]=c[90371738];c[b+12>>2]=c[90371739];c[90371736]=h;c[90371737]=g;c[90371739]=0;c[90371738]=b;b=a+24|0;do{v=b;b=b+4|0;c[b>>2]=7}while((v+8|0)>>>0<w>>>0);if((a|0)!=(j|0)){g=a-j|0;c[d>>2]=c[d>>2]&-2;c[j+4>>2]=g|1;c[a>>2]=g;b=g>>>3;if(g>>>0<256){d=361486536+(b<<1<<2)|0;a=c[90371624]|0;b=1<<b;if(!(a&b)){c[90371624]=a|b;b=d+8|0;a=d}else{a=d+8|0;b=a;a=c[a>>2]|0}c[b>>2]=j;c[a+12>>2]=j;c[j+8>>2]=a;c[j+12>>2]=d;break}b=g>>>8;if(b)if(g>>>0>16777215)d=31;else{v=(b+1048320|0)>>>16&8;w=b<<v;u=(w+520192|0)>>>16&4;w=w<<u;d=(w+245760|0)>>>16&2;d=14-(u|v|d)+(w<<d>>>15)|0;d=g>>>(d+7|0)&1|d<<1}else d=0;e=361486800+(d<<2)|0;c[j+28>>2]=d;c[j+20>>2]=0;c[f>>2]=0;b=c[90371625]|0;a=1<<d;if(!(b&a)){c[90371625]=b|a;c[e>>2]=j;c[j+24>>2]=e;c[j+12>>2]=j;c[j+8>>2]=j;break}a=g<<((d|0)==31?0:25-(d>>>1)|0);d=c[e>>2]|0;while(1){if((c[d+4>>2]&-8|0)==(g|0)){v=216;break}e=d+16+(a>>>31<<2)|0;b=c[e>>2]|0;if(!b){v=215;break}else{a=a<<1;d=b}}if((v|0)==215){c[e>>2]=j;c[j+24>>2]=d;c[j+12>>2]=j;c[j+8>>2]=j;break}else if((v|0)==216){v=d+8|0;w=c[v>>2]|0;c[w+12>>2]=j;c[v>>2]=j;c[j+8>>2]=w;c[j+12>>2]=d;c[j+24>>2]=0;break}}}else{w=c[90371628]|0;if((w|0)==0|h>>>0<w>>>0)c[90371628]=h;c[90371736]=h;c[90371737]=g;c[90371739]=0;c[90371633]=c[90371742];c[90371632]=-1;b=0;do{w=361486536+(b<<1<<2)|0;c[w+12>>2]=w;c[w+8>>2]=w;b=b+1|0}while((b|0)!=32);w=h+8|0;w=(w&7|0)==0?0:0-w&7;v=h+w|0;w=g+-40-w|0;c[90371630]=v;c[90371627]=w;c[v+4>>2]=w|1;c[v+w+4>>2]=40;c[90371631]=c[90371746]}while(0);b=c[90371627]|0;if(b>>>0>n>>>0){u=b-n|0;c[90371627]=u;w=c[90371630]|0;v=w+n|0;c[90371630]=v;c[v+4>>2]=u|1;c[w+4>>2]=n|3;w=w+8|0;l=x;return w|0}}c[(Za()|0)>>2]=12;w=0;l=x;return w|0}function Ta(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0;if(!a)return;d=a+-8|0;e=c[90371628]|0;a=c[a+-4>>2]|0;b=a&-8;k=d+b|0;do if(!(a&1)){f=c[d>>2]|0;if(!(a&3))return;g=d+(0-f)|0;h=f+b|0;if(g>>>0<e>>>0)return;if((g|0)==(c[90371629]|0)){b=k+4|0;a=c[b>>2]|0;if((a&3|0)!=3){i=g;j=g;b=h;break}c[90371626]=h;c[b>>2]=a&-2;c[g+4>>2]=h|1;c[g+h>>2]=h;return}d=f>>>3;if(f>>>0<256){a=c[g+8>>2]|0;b=c[g+12>>2]|0;if((b|0)==(a|0)){c[90371624]=c[90371624]&~(1<<d);i=g;j=g;b=h;break}else{c[a+12>>2]=b;c[b+8>>2]=a;i=g;j=g;b=h;break}}f=c[g+24>>2]|0;a=c[g+12>>2]|0;do if((a|0)==(g|0)){d=g+16|0;b=d+4|0;a=c[b>>2]|0;if(!a){a=c[d>>2]|0;if(!a){d=0;break}else e=d}else e=b;while(1){d=a+20|0;b=c[d>>2]|0;if(b|0){a=b;e=d;continue}d=a+16|0;b=c[d>>2]|0;if(!b)break;else{a=b;e=d}}c[e>>2]=0;d=a}else{d=c[g+8>>2]|0;c[d+12>>2]=a;c[a+8>>2]=d;d=a}while(0);if(f){a=c[g+28>>2]|0;b=361486800+(a<<2)|0;if((g|0)==(c[b>>2]|0)){c[b>>2]=d;if(!d){c[90371625]=c[90371625]&~(1<<a);i=g;j=g;b=h;break}}else{c[f+16+(((c[f+16>>2]|0)!=(g|0)&1)<<2)>>2]=d;if(!d){i=g;j=g;b=h;break}}c[d+24>>2]=f;b=g+16|0;a=c[b>>2]|0;if(a|0){c[d+16>>2]=a;c[a+24>>2]=d}a=c[b+4>>2]|0;if(a){c[d+20>>2]=a;c[a+24>>2]=d;i=g;j=g;b=h}else{i=g;j=g;b=h}}else{i=g;j=g;b=h}}else{i=d;j=d}while(0);if(i>>>0>=k>>>0)return;a=k+4|0;e=c[a>>2]|0;if(!(e&1))return;if(!(e&2)){a=c[90371629]|0;if((k|0)==(c[90371630]|0)){k=(c[90371627]|0)+b|0;c[90371627]=k;c[90371630]=j;c[j+4>>2]=k|1;if((j|0)!=(a|0))return;c[90371629]=0;c[90371626]=0;return}if((k|0)==(a|0)){k=(c[90371626]|0)+b|0;c[90371626]=k;c[90371629]=i;c[j+4>>2]=k|1;c[i+k>>2]=k;return}f=(e&-8)+b|0;d=e>>>3;do if(e>>>0<256){b=c[k+8>>2]|0;a=c[k+12>>2]|0;if((a|0)==(b|0)){c[90371624]=c[90371624]&~(1<<d);break}else{c[b+12>>2]=a;c[a+8>>2]=b;break}}else{g=c[k+24>>2]|0;a=c[k+12>>2]|0;do if((a|0)==(k|0)){d=k+16|0;b=d+4|0;a=c[b>>2]|0;if(!a){a=c[d>>2]|0;if(!a){d=0;break}else e=d}else e=b;while(1){d=a+20|0;b=c[d>>2]|0;if(b|0){a=b;e=d;continue}d=a+16|0;b=c[d>>2]|0;if(!b)break;else{a=b;e=d}}c[e>>2]=0;d=a}else{d=c[k+8>>2]|0;c[d+12>>2]=a;c[a+8>>2]=d;d=a}while(0);if(g|0){a=c[k+28>>2]|0;b=361486800+(a<<2)|0;if((k|0)==(c[b>>2]|0)){c[b>>2]=d;if(!d){c[90371625]=c[90371625]&~(1<<a);break}}else{c[g+16+(((c[g+16>>2]|0)!=(k|0)&1)<<2)>>2]=d;if(!d)break}c[d+24>>2]=g;b=k+16|0;a=c[b>>2]|0;if(a|0){c[d+16>>2]=a;c[a+24>>2]=d}a=c[b+4>>2]|0;if(a|0){c[d+20>>2]=a;c[a+24>>2]=d}}}while(0);c[j+4>>2]=f|1;c[i+f>>2]=f;if((j|0)==(c[90371629]|0)){c[90371626]=f;return}}else{c[a>>2]=e&-2;c[j+4>>2]=b|1;c[i+b>>2]=b;f=b}a=f>>>3;if(f>>>0<256){d=361486536+(a<<1<<2)|0;b=c[90371624]|0;a=1<<a;if(!(b&a)){c[90371624]=b|a;a=d+8|0;b=d}else{b=d+8|0;a=b;b=c[b>>2]|0}c[a>>2]=j;c[b+12>>2]=j;c[j+8>>2]=b;c[j+12>>2]=d;return}a=f>>>8;if(a)if(f>>>0>16777215)b=31;else{i=(a+1048320|0)>>>16&8;k=a<<i;h=(k+520192|0)>>>16&4;k=k<<h;b=(k+245760|0)>>>16&2;b=14-(h|i|b)+(k<<b>>>15)|0;b=f>>>(b+7|0)&1|b<<1}else b=0;e=361486800+(b<<2)|0;c[j+28>>2]=b;c[j+20>>2]=0;c[j+16>>2]=0;a=c[90371625]|0;d=1<<b;do if(a&d){b=f<<((b|0)==31?0:25-(b>>>1)|0);d=c[e>>2]|0;while(1){if((c[d+4>>2]&-8|0)==(f|0)){a=73;break}e=d+16+(b>>>31<<2)|0;a=c[e>>2]|0;if(!a){a=72;break}else{b=b<<1;d=a}}if((a|0)==72){c[e>>2]=j;c[j+24>>2]=d;c[j+12>>2]=j;c[j+8>>2]=j;break}else if((a|0)==73){i=d+8|0;k=c[i>>2]|0;c[k+12>>2]=j;c[i>>2]=j;c[j+8>>2]=k;c[j+12>>2]=d;c[j+24>>2]=0;break}}else{c[90371625]=a|d;c[e>>2]=j;c[j+24>>2]=e;c[j+12>>2]=j;c[j+8>>2]=j}while(0);k=(c[90371632]|0)+-1|0;c[90371632]=k;if(!k)a=361486952;else return;while(1){a=c[a>>2]|0;if(!a)break;else a=a+8|0}c[90371632]=-1;return}function Ua(){return 361486992}function Va(a){a=a|0;var b=0,d=0;b=l;l=l+16|0;d=b;c[d>>2]=ab(c[a+60>>2]|0)|0;a=Ya(ca(6,d|0)|0)|0;l=b;return a|0}function Wa(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0,k=0,m=0,n=0,o=0,p=0;n=l;l=l+48|0;i=n+16|0;f=n;e=n+32|0;j=a+28|0;g=c[j>>2]|0;c[e>>2]=g;k=a+20|0;g=(c[k>>2]|0)-g|0;c[e+4>>2]=g;c[e+8>>2]=b;c[e+12>>2]=d;g=g+d|0;h=a+60|0;c[f>>2]=c[h>>2];c[f+4>>2]=e;c[f+8>>2]=2;b=Ya(na(146,f|0)|0)|0;a:do if((g|0)!=(b|0)){f=2;while(1){if((b|0)<0)break;g=g-b|0;p=c[e+4>>2]|0;o=b>>>0>p>>>0;e=o?e+8|0:e;f=(o<<31>>31)+f|0;p=b-(o?p:0)|0;c[e>>2]=(c[e>>2]|0)+p;o=e+4|0;c[o>>2]=(c[o>>2]|0)-p;c[i>>2]=c[h>>2];c[i+4>>2]=e;c[i+8>>2]=f;b=Ya(na(146,i|0)|0)|0;if((g|0)==(b|0)){m=3;break a}}c[a+16>>2]=0;c[j>>2]=0;c[k>>2]=0;c[a>>2]=c[a>>2]|32;if((f|0)==2)d=0;else d=d-(c[e+4>>2]|0)|0}else m=3;while(0);if((m|0)==3){p=c[a+44>>2]|0;c[a+16>>2]=p+(c[a+48>>2]|0);c[j>>2]=p;c[k>>2]=p}l=n;return d|0}function Xa(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0;f=l;l=l+32|0;g=f;e=f+20|0;c[g>>2]=c[a+60>>2];c[g+4>>2]=0;c[g+8>>2]=b;c[g+12>>2]=e;c[g+16>>2]=d;if((Ya(ea(140,g|0)|0)|0)<0){c[e>>2]=-1;a=-1}else a=c[e>>2]|0;l=f;return a|0}function Ya(a){a=a|0;if(a>>>0>4294963200){c[(Za()|0)>>2]=0-a;a=-1}return a|0}function Za(){return (_a()|0)+64|0}function _a(){return $a()|0}function $a(){return 9760}function ab(a){a=a|0;return a|0}function bb(b,d,e){b=b|0;d=d|0;e=e|0;var f=0,g=0;g=l;l=l+32|0;f=g;c[b+36>>2]=4;if((c[b>>2]&64|0)==0?(c[f>>2]=c[b+60>>2],c[f+4>>2]=21523,c[f+8>>2]=g+16,ia(54,f|0)|0):0)a[b+75>>0]=-1;f=Wa(b,d,e)|0;l=g;return f|0}function cb(a){a=+a;var b=0.0,d=0,e=0.0,f=0,h=0.0,i=0,k=0.0;d=(g[j>>2]=a,c[j>>2]|0);f=d&2147483647;d=d>>>31;do if(f>>>0>1100331075){if(f>>>0<=2139095040)if(!d)if(a>88.7216796875)a=a*1701411834604692317316873.0e14;else{b=.5;i=12}else a=-1.0}else{if(f>>>0<=1051816472)if(f>>>0<855638016)break;else{h=0.0;d=0;i=15;break}d=(d|0)!=0;if(f>>>0>=1065686418){b=d?-.5:.5;i=12;break}if(d){a=a+.6931381225585938;d=-1;b=-9.05800061445916e-06;i=13;break}else{a=a+-.6931381225585938;d=1;b=9.05800061445916e-06;i=13;break}}while(0);if((i|0)==12){d=~~(a*1.4426950216293335+b);b=+(d|0);a=a-b*.6931381225585938;b=b*9.05800061445916e-06;i=13}if((i|0)==13){e=a-b;h=a-e-b;a=e;i=15}a:do if((i|0)==15){e=a*.5;b=a*e;k=b*(b*1.5807170420885086e-03+-.03333321213722229)+1.0;e=3.0-e*k;e=b*((k-e)/(6.0-a*e));if(!d){a=a-(a*e-b);break}e=a*(e-h)-h-b;switch(d|0){case -1:{a=(a-e)*.5+-.5;break a}case 1:if(a<-.25){a=(e-(a+.5))*-2.0;break a}else{a=(a-e)*2.0+1.0;break a}default:{b=(c[j>>2]=(d<<23)+1065353216,+g[j>>2]);if(d>>>0>56){a=a-e+1.0;a=((d|0)==128?a*2.0*1701411834604692317316873.0e14:b*a)+-1.0;break a}else{i=(d|0)<23;k=(c[j>>2]=127-d<<23,+g[j>>2]);a=b*((i?1.0-k:1.0)+(a-(i?e:k+e)));break a}}}}while(0);return +a}function db(a){a=a|0;return 0}function eb(a){a=a|0;return}function fb(a){a=+a;var b=0,d=0;d=(g[j>>2]=a,c[j>>2]|0);b=d&2147483647;a=(c[j>>2]=b,+g[j>>2]);do if(b>>>0>1057791828)if(b>>>0>1092616192){a=0.0/a+1.0;break}else{a=1.0-2.0/(+cb(a*2.0)+2.0);break}else{if(b>>>0>1048757624){a=+cb(a*2.0);a=a/(a+2.0);break}if(b>>>0>8388607){a=+cb(a*-2.0);a=-a/(a+2.0)}}while(0);return +((d|0)<0?-a:a)}function gb(){ba(361487056);return 361487064}function hb(){ja(361487056);return}function ib(a){a=a|0;var b=0,d=0;do if(a){if((c[a+76>>2]|0)<=-1){b=jb(a)|0;break}d=(db(a)|0)==0;b=jb(a)|0;if(!d)eb(a)}else{if(!(c[2532]|0))b=0;else b=ib(c[2532]|0)|0;a=c[(gb()|0)>>2]|0;if(a)do{if((c[a+76>>2]|0)>-1)d=db(a)|0;else d=0;if((c[a+20>>2]|0)>>>0>(c[a+28>>2]|0)>>>0)b=jb(a)|0|b;if(d|0)eb(a);a=c[a+56>>2]|0}while((a|0)!=0);hb()}while(0);return b|0}function jb(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0;h=a+20|0;g=a+28|0;if((c[h>>2]|0)>>>0>(c[g>>2]|0)>>>0?(qa[c[a+36>>2]&7](a,0,0)|0,(c[h>>2]|0)==0):0)b=-1;else{f=a+4|0;b=c[f>>2]|0;e=a+8|0;d=c[e>>2]|0;if(b>>>0<d>>>0)qa[c[a+40>>2]&7](a,b-d|0,1)|0;c[a+16>>2]=0;c[g>>2]=0;c[h>>2]=0;c[e>>2]=0;c[f>>2]=0;b=0}return b|0}function kb(a){a=a|0;return}function lb(a){a=a|0;kb(a);Bb(a);return}function mb(a){a=a|0;return}function nb(a){a=a|0;return}function ob(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0;h=l;l=l+64|0;g=h;if(!(sb(a,b,0)|0))if((b|0)!=0?(f=wb(b,32,16,0)|0,(f|0)!=0):0){b=g+4|0;e=b+52|0;do{c[b>>2]=0;b=b+4|0}while((b|0)<(e|0));c[g>>2]=f;c[g+8>>2]=a;c[g+12>>2]=-1;c[g+48>>2]=1;va[c[(c[f>>2]|0)+28>>2]&3](f,g,c[d>>2]|0,1);if((c[g+24>>2]|0)==1){c[d>>2]=c[g+16>>2];b=1}else b=0}else b=0;else b=1;l=h;return b|0}function pb(a,b,d,e,f,g){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;if(sb(a,c[b+8>>2]|0,g)|0)vb(0,b,d,e,f);return}function qb(b,d,e,f,g){b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0;do if(!(sb(b,c[d+8>>2]|0,g)|0)){if(sb(b,c[d>>2]|0,g)|0){b=d+32|0;if((c[d+16>>2]|0)!=(e|0)?(h=d+20|0,(c[h>>2]|0)!=(e|0)):0){c[b>>2]=f;c[h>>2]=e;f=d+40|0;c[f>>2]=(c[f>>2]|0)+1;if((c[d+36>>2]|0)==1?(c[d+24>>2]|0)==2:0)a[d+54>>0]=1;c[d+44>>2]=4;break}if((f|0)==1)c[b>>2]=1}}else ub(0,d,e,f);while(0);return}function rb(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;if(sb(a,c[b+8>>2]|0,0)|0)tb(0,b,d,e);return}function sb(a,b,c){a=a|0;b=b|0;c=c|0;return (a|0)==(b|0)|0}function tb(b,d,e,f){b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0;g=d+16|0;b=c[g>>2]|0;h=d+36|0;i=d+24|0;do if(b){if((b|0)!=(e|0)){c[h>>2]=(c[h>>2]|0)+1;c[i>>2]=2;a[d+54>>0]=1;break}if((c[i>>2]|0)==2)c[i>>2]=f}else{c[g>>2]=e;c[i>>2]=f;c[h>>2]=1}while(0);return}function ub(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0;if((c[b+4>>2]|0)==(d|0)?(f=b+28|0,(c[f>>2]|0)!=1):0)c[f>>2]=e;return}function vb(b,d,e,f,g){b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0,i=0,j=0,k=0;a[d+53>>0]=1;do if((c[d+4>>2]|0)==(f|0)){a[d+52>>0]=1;h=d+16|0;b=c[h>>2]|0;k=d+54|0;j=d+48|0;i=d+24|0;f=d+36|0;if(!b){c[h>>2]=e;c[i>>2]=g;c[f>>2]=1;if(!((c[j>>2]|0)==1&(g|0)==1))break;a[k>>0]=1;break}if((b|0)!=(e|0)){c[f>>2]=(c[f>>2]|0)+1;a[k>>0]=1;break}f=c[i>>2]|0;if((f|0)==2){c[i>>2]=g;f=g}if((c[j>>2]|0)==1&(f|0)==1)a[k>>0]=1}while(0);return}function wb(d,e,f,g){d=d|0;e=e|0;f=f|0;g=g|0;var h=0,i=0,j=0,k=0,m=0,n=0,o=0,p=0,q=0;q=l;l=l+64|0;p=q;n=c[d>>2]|0;o=d+(c[n+-8>>2]|0)|0;n=c[n+-4>>2]|0;c[p>>2]=f;c[p+4>>2]=d;c[p+8>>2]=e;c[p+12>>2]=g;g=p+16|0;d=p+20|0;h=p+24|0;j=p+28|0;i=p+32|0;e=p+40|0;k=g;m=k+36|0;do{c[k>>2]=0;k=k+4|0}while((k|0)<(m|0));b[g+36>>1]=0;a[g+38>>0]=0;a:do if(sb(n,f,0)|0){c[p+48>>2]=1;ua[c[(c[n>>2]|0)+20>>2]&3](n,p,o,o,1,0);g=(c[h>>2]|0)==1?o:0}else{ra[c[(c[n>>2]|0)+24>>2]&3](n,p,o,1,0);switch(c[p+36>>2]|0){case 0:{g=(c[e>>2]|0)==1&(c[j>>2]|0)==1&(c[i>>2]|0)==1?c[d>>2]|0:0;break a}case 1:break;default:{g=0;break a}}if((c[h>>2]|0)!=1?!((c[e>>2]|0)==0&(c[j>>2]|0)==1&(c[i>>2]|0)==1):0){g=0;break}g=c[g>>2]|0}while(0);l=q;return g|0}function xb(a){a=a|0;kb(a);Bb(a);return}function yb(a,b,d,e,f,g){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;if(sb(a,c[b+8>>2]|0,g)|0)vb(0,b,d,e,f);else{a=c[a+8>>2]|0;ua[c[(c[a>>2]|0)+20>>2]&3](a,b,d,e,f,g)}return}function zb(b,d,e,f,g){b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0,i=0,j=0,k=0;do if(!(sb(b,c[d+8>>2]|0,g)|0)){h=b+8|0;if(!(sb(b,c[d>>2]|0,g)|0)){j=c[h>>2]|0;ra[c[(c[j>>2]|0)+24>>2]&3](j,d,e,f,g);break}b=d+32|0;if((c[d+16>>2]|0)!=(e|0)?(i=d+20|0,(c[i>>2]|0)!=(e|0)):0){c[b>>2]=f;f=d+44|0;if((c[f>>2]|0)==4)break;b=d+52|0;a[b>>0]=0;k=d+53|0;a[k>>0]=0;h=c[h>>2]|0;ua[c[(c[h>>2]|0)+20>>2]&3](h,d,e,e,1,g);if(a[k>>0]|0)if(!(a[b>>0]|0)){b=3;j=11}else b=3;else{b=4;j=11}if((j|0)==11){c[i>>2]=e;k=d+40|0;c[k>>2]=(c[k>>2]|0)+1;if((c[d+36>>2]|0)==1?(c[d+24>>2]|0)==2:0)a[d+54>>0]=1}c[f>>2]=b;break}if((f|0)==1)c[b>>2]=1}else ub(0,d,e,f);while(0);return}function Ab(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;if(sb(a,c[b+8>>2]|0,0)|0)tb(0,b,d,e);else{a=c[a+8>>2]|0;va[c[(c[a>>2]|0)+28>>2]&3](a,b,d,e)}return}function Bb(a){a=a|0;Ta(a);return}function Cb(a){a=a|0;return}function Db(a){a=a|0;return}function Eb(a){a=a|0;Db(a);Bb(a);return}function Fb(a){a=a|0;return 11722}function Gb(a){a=a|0;return}function Hb(b){b=b|0;if((a[b>>0]|0)==1)b=0;else{a[b>>0]=1;b=1}return b|0}function Ib(a){a=a|0;return}function Jb(a){a=a|0;c[a>>2]=10220;return}function Kb(){}function Lb(a){a=a|0;var b=0,d=0;d=a+15&-16|0;b=c[i>>2]|0;a=b+d|0;if((d|0)>0&(a|0)<(b|0)|(a|0)<0){V()|0;da(12);return -1}c[i>>2]=a;if((a|0)>(U()|0)?(T()|0)==0:0){c[i>>2]=b;da(12);return -1}return b|0}function Mb(b,d,e){b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0;h=b+e|0;d=d&255;if((e|0)>=67){while(b&3){a[b>>0]=d;b=b+1|0}f=h&-4|0;g=f-64|0;i=d|d<<8|d<<16|d<<24;while((b|0)<=(g|0)){c[b>>2]=i;c[b+4>>2]=i;c[b+8>>2]=i;c[b+12>>2]=i;c[b+16>>2]=i;c[b+20>>2]=i;c[b+24>>2]=i;c[b+28>>2]=i;c[b+32>>2]=i;c[b+36>>2]=i;c[b+40>>2]=i;c[b+44>>2]=i;c[b+48>>2]=i;c[b+52>>2]=i;c[b+56>>2]=i;c[b+60>>2]=i;b=b+64|0}while((b|0)<(f|0)){c[b>>2]=i;b=b+4|0}}while((b|0)<(h|0)){a[b>>0]=d;b=b+1|0}return h-e|0}function Nb(b,d,e){b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0;if((e|0)>=8192)return ha(b|0,d|0,e|0)|0;h=b|0;g=b+e|0;if((b&3)==(d&3)){while(b&3){if(!e)return h|0;a[b>>0]=a[d>>0]|0;b=b+1|0;d=d+1|0;e=e-1|0}e=g&-4|0;f=e-64|0;while((b|0)<=(f|0)){c[b>>2]=c[d>>2];c[b+4>>2]=c[d+4>>2];c[b+8>>2]=c[d+8>>2];c[b+12>>2]=c[d+12>>2];c[b+16>>2]=c[d+16>>2];c[b+20>>2]=c[d+20>>2];c[b+24>>2]=c[d+24>>2];c[b+28>>2]=c[d+28>>2];c[b+32>>2]=c[d+32>>2];c[b+36>>2]=c[d+36>>2];c[b+40>>2]=c[d+40>>2];c[b+44>>2]=c[d+44>>2];c[b+48>>2]=c[d+48>>2];c[b+52>>2]=c[d+52>>2];c[b+56>>2]=c[d+56>>2];c[b+60>>2]=c[d+60>>2];b=b+64|0;d=d+64|0}while((b|0)<(e|0)){c[b>>2]=c[d>>2];b=b+4|0;d=d+4|0}}else{e=g-4|0;while((b|0)<(e|0)){a[b>>0]=a[d>>0]|0;a[b+1>>0]=a[d+1>>0]|0;a[b+2>>0]=a[d+2>>0]|0;a[b+3>>0]=a[d+3>>0]|0;b=b+4|0;d=d+4|0}}while((b|0)<(g|0)){a[b>>0]=a[d>>0]|0;b=b+1|0;d=d+1|0}return h|0}function Ob(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;return qa[a&7](b|0,c|0,d|0)|0}function Pb(a,b,c,d,e,f){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;ra[a&3](b|0,c|0,d|0,e|0,f|0)}function Qb(a,b){a=a|0;b=b|0;sa[a&7](b|0)}function Rb(a,b){a=a|0;b=b|0;return ta[a&3](b|0)|0}function Sb(a,b,c,d,e,f,g){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;ua[a&3](b|0,c|0,d|0,e|0,f|0,g|0)}function Tb(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;va[a&3](b|0,c|0,d|0,e|0)}function Ub(a,b,c){a=a|0;b=b|0;c=c|0;R(0);return 0}function Vb(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;R(1)}function Wb(a){a=a|0;R(2)}function Xb(a){a=a|0;R(3);return 0}function Yb(a,b,c,d,e,f){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;R(4)}function Zb(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;R(5)}
// EMSCRIPTEN_END_FUNCS
var qa=[Ub,bb,Xa,ob,Wa,Ub,Ub,Ub];var ra=[Vb,qb,zb,Vb];var sa=[Wb,kb,lb,mb,nb,xb,Db,Eb];var ta=[Xb,Va,Fb,Xb];var ua=[Yb,pb,yb,Yb];var va=[Zb,rb,Ab,Zb];return{_init:Da,getTempRet0:Ca,_get_dynamic_buffer:Ga,setThrew:Aa,_get_static_buffer:Ea,_fflush:ib,___errno_location:Za,_memset:Mb,_sbrk:Lb,_memcpy:Nb,_allocate_dynamic_buffer:Fa,stackAlloc:wa,_run:Ka,setTempRet0:Ba,stackRestore:ya,stackSave:xa,_free:Ta,runPostSets:Kb,establishStackSpace:za,_emscripten_get_global_libc:Ua,_malloc:Sa,_set_placeholder_value:Ha,stackAlloc:wa,stackSave:xa,stackRestore:ya,establishStackSpace:za,setThrew:Aa,setTempRet0:Ba,getTempRet0:Ca,dynCall_iiii:Ob,dynCall_viiiii:Pb,dynCall_vi:Qb,dynCall_ii:Rb,dynCall_viiiiii:Sb,dynCall_viiii:Tb}})
// EMSCRIPTEN_END_ASM
(Module.asmGlobalArg,Module.asmLibraryArg,buffer);var _init=Module["_init"]=asm["_init"];var getTempRet0=Module["getTempRet0"]=asm["getTempRet0"];var _get_dynamic_buffer=Module["_get_dynamic_buffer"]=asm["_get_dynamic_buffer"];var setThrew=Module["setThrew"]=asm["setThrew"];var _get_static_buffer=Module["_get_static_buffer"]=asm["_get_static_buffer"];var _fflush=Module["_fflush"]=asm["_fflush"];var ___errno_location=Module["___errno_location"]=asm["___errno_location"];var _memset=Module["_memset"]=asm["_memset"];var _sbrk=Module["_sbrk"]=asm["_sbrk"];var _memcpy=Module["_memcpy"]=asm["_memcpy"];var _allocate_dynamic_buffer=Module["_allocate_dynamic_buffer"]=asm["_allocate_dynamic_buffer"];var stackAlloc=Module["stackAlloc"]=asm["stackAlloc"];var _run=Module["_run"]=asm["_run"];var setTempRet0=Module["setTempRet0"]=asm["setTempRet0"];var stackRestore=Module["stackRestore"]=asm["stackRestore"];var stackSave=Module["stackSave"]=asm["stackSave"];var _free=Module["_free"]=asm["_free"];var runPostSets=Module["runPostSets"]=asm["runPostSets"];var establishStackSpace=Module["establishStackSpace"]=asm["establishStackSpace"];var _emscripten_get_global_libc=Module["_emscripten_get_global_libc"]=asm["_emscripten_get_global_libc"];var _malloc=Module["_malloc"]=asm["_malloc"];var _set_placeholder_value=Module["_set_placeholder_value"]=asm["_set_placeholder_value"];var dynCall_iiii=Module["dynCall_iiii"]=asm["dynCall_iiii"];var dynCall_viiiii=Module["dynCall_viiiii"]=asm["dynCall_viiiii"];var dynCall_vi=Module["dynCall_vi"]=asm["dynCall_vi"];var dynCall_ii=Module["dynCall_ii"]=asm["dynCall_ii"];var dynCall_viiiiii=Module["dynCall_viiiiii"]=asm["dynCall_viiiiii"];var dynCall_viiii=Module["dynCall_viiii"]=asm["dynCall_viiii"];Runtime.stackAlloc=Module["stackAlloc"];Runtime.stackSave=Module["stackSave"];Runtime.stackRestore=Module["stackRestore"];Runtime.establishStackSpace=Module["establishStackSpace"];Runtime.setTempRet0=Module["setTempRet0"];Runtime.getTempRet0=Module["getTempRet0"];Module["asm"]=asm;if(memoryInitializer){if(typeof Module["locateFile"]==="function"){memoryInitializer=Module["locateFile"](memoryInitializer)}else if(Module["memoryInitializerPrefixURL"]){memoryInitializer=Module["memoryInitializerPrefixURL"]+memoryInitializer}if(ENVIRONMENT_IS_NODE||ENVIRONMENT_IS_SHELL){var data=Module["readBinary"](memoryInitializer);HEAPU8.set(data,Runtime.GLOBAL_BASE)}else{addRunDependency("memory initializer");var applyMemoryInitializer=(function(data){if(data.byteLength)data=new Uint8Array(data);HEAPU8.set(data,Runtime.GLOBAL_BASE);if(Module["memoryInitializerRequest"])delete Module["memoryInitializerRequest"].response;removeRunDependency("memory initializer")});function doBrowserLoad(){Module["readAsync"](memoryInitializer,applyMemoryInitializer,(function(){throw"could not load memory initializer "+memoryInitializer}))}if(Module["memoryInitializerRequest"]){function useRequest(){var request=Module["memoryInitializerRequest"];if(request.status!==200&&request.status!==0){console.warn("a problem seems to have happened with Module.memoryInitializerRequest, status: "+request.status+", retrying "+memoryInitializer);doBrowserLoad();return}applyMemoryInitializer(request.response)}if(Module["memoryInitializerRequest"].response){setTimeout(useRequest,0)}else{Module["memoryInitializerRequest"].addEventListener("load",useRequest)}}else{doBrowserLoad()}}}function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}ExitStatus.prototype=new Error;ExitStatus.prototype.constructor=ExitStatus;var initialStackTop;var preloadStartTime=null;var calledMain=false;dependenciesFulfilled=function runCaller(){if(!Module["calledRun"])run();if(!Module["calledRun"])dependenciesFulfilled=runCaller};Module["callMain"]=Module.callMain=function callMain(args){args=args||[];ensureInitRuntime();var argc=args.length+1;function pad(){for(var i=0;i<4-1;i++){argv.push(0)}}var argv=[allocate(intArrayFromString(Module["thisProgram"]),"i8",ALLOC_NORMAL)];pad();for(var i=0;i<argc-1;i=i+1){argv.push(allocate(intArrayFromString(args[i]),"i8",ALLOC_NORMAL));pad()}argv.push(0);argv=allocate(argv,"i32",ALLOC_NORMAL);try{var ret=Module["_main"](argc,argv,0);exit(ret,true)}catch(e){if(e instanceof ExitStatus){return}else if(e=="SimulateInfiniteLoop"){Module["noExitRuntime"]=true;return}else{var toLog=e;if(e&&typeof e==="object"&&e.stack){toLog=[e,e.stack]}Module.printErr("exception thrown: "+toLog);Module["quit"](1,e)}}finally{calledMain=true}};function run(args){args=args||Module["arguments"];if(preloadStartTime===null)preloadStartTime=Date.now();if(runDependencies>0){return}preRun();if(runDependencies>0)return;if(Module["calledRun"])return;function doRun(){if(Module["calledRun"])return;Module["calledRun"]=true;if(ABORT)return;ensureInitRuntime();preMain();if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();if(Module["_main"]&&shouldRunNow)Module["callMain"](args);postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout((function(){setTimeout((function(){Module["setStatus"]("")}),1);doRun()}),1)}else{doRun()}}Module["run"]=Module.run=run;function exit(status,implicit){if(implicit&&Module["noExitRuntime"]){return}if(Module["noExitRuntime"]){}else{ABORT=true;EXITSTATUS=status;STACKTOP=initialStackTop;exitRuntime();if(Module["onExit"])Module["onExit"](status)}if(ENVIRONMENT_IS_NODE){process["exit"](status)}Module["quit"](status,new ExitStatus(status))}Module["exit"]=Module.exit=exit;var abortDecorators=[];function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}if(what!==undefined){Module.print(what);Module.printErr(what);what=JSON.stringify(what)}else{what=""}ABORT=true;EXITSTATUS=1;var extra="\nIf this abort() is unexpected, build with -s ASSERTIONS=1 which can give more information.";var output="abort("+what+") at "+stackTrace()+extra;if(abortDecorators){abortDecorators.forEach((function(decorator){output=decorator(output,what)}))}throw output}Module["abort"]=Module.abort=abort;if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}var shouldRunNow=true;if(Module["noInitialRun"]){shouldRunNow=false}run()
|
require('babel-register')({
ignore: /node_modules\/(?!openzeppelin-solidity\/test\/helpers)/
});
require('babel-polyfill');
// -------------------------------------------------------------------
// Emulate mocha --grep option to run only matching tests
let mochaConf = {}; // Passed as module.exports.mocha
// -------------------------------------------------------------------
for (let i = 0; i < process.argv.length; i++) {
const arg = process.argv[i];
if (arg != '-g' && arg != "--grep" ) continue;
if (++i >= process.argv.length) {
console.error(arg + " option requires argument");
process.exit(1);
};
mochaConf.grep = new RegExp(process.argv[i]);
break;
}
// -------------------------------------------------------------------
module.exports = {
mocha: mochaConf,
networks: {
development: {
host: "localhost",
port: 9545,
network_id: "*" // Match any network id
},
rinkeby: { // testnet
host: "localhost",
port: 8547,
network_id: 4
},
},
solc: {
optimizer: {
enabled: true,
runs: 200
}
}
};
|
'use strict';
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
var forceQuit = false;
let mainWindow = null;
// 起動時に呼び出される
app.on('ready', function()
{
// ウィンドウを作成する
mainWindow = new BrowserWindow(
{
title: app.getName(),
'overlay-scrollbars':false,
"title-bar-style": "hidden-inset",
'always-on-top': true,
});
// ベースとなるHTMLファイル
mainWindow.loadURL('file://' + __dirname + '/index.html');
// フルスクリーンモードに設定する
mainWindow.setFullScreen(false);
//下記のコメントを解除すると、デベロッパツールが起動する
//mainWindow.webContents.openDevTools();
//ウィンドウの大きさを決めます
mainWindow.setSize(500, 650);
//ウィンドウのサイズを固定にします
mainWindow.setResizable(false);
// ウィンドウを閉じるときに呼び出される
mainWindow.on('close', function(e)
{
if (!forceQuit)
{
e.preventDefault();
app.quit();
}
});
});
app.on('window-all-closed', function()
{
// すべてのウィンドウが閉じられたときに、アプリも終了する
app.quit();
});
app.on('before-quit', function(e)
{
forceQuit = true;
});
app.on('will-quit', function()
{
mainWindow = null;
});
app.on('activate', function()
{
mainWindow.show();
});
|
import React from "react";
import style from "../friendList/FriendList.module.css";
import FriendListItem from "./FriendListItem";
const FriendList = ({ friends }) => {
return (
<div className={style.profile} >
<ul className={style.item} >
{friends.map((item, id) => (
<FriendListItem item={item} key={id}/>
))}
</ul>
</div>
);
};
export default FriendList;
|
// This file is generated automatically by `scripts/build/fp.js`. Please, don't change it.
import fn from "../../eachWeekOfInterval/index.js";
import convertToFP from "../_lib/convertToFP/index.js";
var eachWeekOfIntervalWithOptions = convertToFP(fn, 2);
export default eachWeekOfIntervalWithOptions;
|
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { useTranslation } from 'react-i18next';
import { v4 as uuid } from 'uuid';
import { useToast, SimpleGrid } from '@chakra-ui/react';
import { Formik, Form } from 'formik';
import { CreateTagSchema } from 'constants/formSchemas';
import StringField from 'components/FormFields/StringField';
import SelectField from 'components/FormFields/SelectField';
import SelectWithSearchField from 'components/FormFields/SelectWithSearchField';
import { useGetEntities } from 'hooks/Network/Entity';
import { useGetVenues } from 'hooks/Network/Venues';
import SpecialConfigurationManager from '../../../CustomFields/SpecialConfigurationManager';
const propTypes = {
isOpen: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
create: PropTypes.instanceOf(Object).isRequired,
refresh: PropTypes.func.isRequired,
formRef: PropTypes.instanceOf(Object).isRequired,
onConfigurationChange: PropTypes.func.isRequired,
configuration: PropTypes.instanceOf(Object),
deviceTypesList: PropTypes.arrayOf(PropTypes.string).isRequired,
entityId: PropTypes.string.isRequired,
deviceClass: PropTypes.string.isRequired,
subId: PropTypes.string.isRequired,
};
const defaultProps = {
configuration: null,
};
const CreateTagForm = ({
isOpen,
onClose,
create,
refresh,
formRef,
deviceTypesList,
entityId,
onConfigurationChange,
configuration,
deviceClass,
subId,
}) => {
const { t } = useTranslation();
const toast = useToast();
const [formKey, setFormKey] = useState(uuid());
const { data: entities } = useGetEntities({ t, toast });
const { data: venues } = useGetVenues({ t, toast });
const getEntityId = () => {
if (entityId === '') return '';
const splitEntity = entityId.split(':');
if (splitEntity[0] === 'entity') return `ent:${splitEntity[1]}`;
return `ven:${splitEntity[1]}`;
};
const createParameters = ({ serialNumber, name, description, note, deviceType, devClass, rrm, entity }) => ({
serialNumber,
name,
rrm,
deviceType,
devClass: deviceClass !== '' ? deviceClass : devClass,
description: description.length > 0 ? description : undefined,
notes: note.length > 0 ? [{ note }] : undefined,
entity: entity === '' || entity.split(':')[0] !== 'ent' ? '' : entity.split(':')[1],
venue: entity === '' || entity.split(':')[0] !== 'ven' ? '' : entity.split(':')[1],
subscriber: subId !== '' ? subId : '',
});
useEffect(() => {
setFormKey(uuid());
}, [isOpen]);
return (
<Formik
innerRef={formRef}
key={formKey}
initialValues={{
serialNumber: '',
name: '',
description: '',
deviceType: deviceTypesList[0],
rrm: 'inherit',
devClass: deviceClass !== '' ? deviceClass : 'any',
note: '',
entity: getEntityId(),
}}
validationSchema={CreateTagSchema(t)}
onSubmit={(formData, { setSubmitting, resetForm }) => {
const params = createParameters(formData);
if (configuration !== null) {
params.__newConfig = {
...configuration.data,
name: `device:${formData.serialNumber}`,
description: 'Created from the Edit Tag menu',
deviceTypes: [formData.deviceType],
};
}
create.mutateAsync(params, {
onSuccess: () => {
setSubmitting(false);
resetForm();
toast({
id: 'tag-creation-success',
title: t('common.success'),
description: t('crud.success_create_obj', {
obj: t('certificates.device'),
}),
status: 'success',
duration: 5000,
isClosable: true,
position: 'top-right',
});
refresh();
onClose();
},
onError: (e) => {
toast({
id: uuid(),
title: t('common.error'),
description: t('crud.error_create_obj', {
obj: t('certificates.device'),
e: e?.response?.data?.ErrorDescription,
}),
status: 'error',
duration: 5000,
isClosable: true,
position: 'top-right',
});
setSubmitting(false);
},
});
}}
>
<Form>
<SimpleGrid minChildWidth="300px" spacing="20px" mb={6}>
<StringField name="serialNumber" label={t('inventory.serial_number')} isRequired />
<StringField name="name" label={t('common.name')} isRequired />
<SelectField
name="deviceType"
label={t('inventory.device_type')}
options={deviceTypesList.map((deviceType) => ({
value: deviceType,
label: deviceType,
}))}
isRequired
/>
<SelectWithSearchField
name="entity"
label={t('inventory.parent')}
options={[
{ label: t('common.none'), value: '' },
{
label: t('entities.title'),
options:
entities?.map((ent) => ({
value: `ent:${ent.id}`,
label: `${ent.name}${ent.description ? `: ${ent.description}` : ''}`,
})) ?? [],
},
{
label: t('venues.title'),
options:
venues?.map((ven) => ({
value: `ven:${ven.id}`,
label: `${ven.name}${ven.description ? `: ${ven.description}` : ''}`,
})) ?? [],
},
]}
isHidden={entityId !== '' || subId !== '' || deviceClass === 'subscriber'}
/>
<SelectField
name="rrm"
label="RRM"
options={[
{ value: 'inherit', label: 'inherit' },
{ value: 'on', label: 'on' },
{ value: 'off', label: 'off' },
]}
isRequired
w={28}
/>
<SelectField
name="devClass"
label={t('inventory.dev_class')}
options={[
{ value: 'any', label: 'any' },
{ value: 'entity', label: 'entity' },
{ value: 'venue', label: 'venue' },
{ value: 'subscriber', label: 'subscriber' },
]}
isRequired
isHidden={deviceClass !== ''}
/>
<StringField name="description" label={t('common.description')} />
<StringField name="note" label={t('common.note')} />
</SimpleGrid>
<SpecialConfigurationManager editing onChange={onConfigurationChange} />
</Form>
</Formik>
);
};
CreateTagForm.propTypes = propTypes;
CreateTagForm.defaultProps = defaultProps;
export default CreateTagForm;
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
var OakStreaming = require("./oakstreaming");
var oakStreaming = new OakStreaming();
var theSharedArray = null;
var streamSource = false;
var theHtmlVideoTag = document.getElementById("myVideo");
console.log("This is the live demo");
Y({
db: {
name: 'memory'
},
connector: {
url: "http://gaudi.informatik.rwth-aachen.de:9914",
name: 'webrtc',
room: 'schduukfherkn32k3289h821'
},
share: {
myArray: 'Array'
}
}).then(function (y) {
theSharedArray = y.share.myArray;
theSharedArray.observe(function (event) {
console.log("The following event-type was thrown: " + event.type);
console.log("The event object has more information:");
console.log(event);
if (!streamSource) {
// returns the received Stream_Ticket object: theSharedArray.get(0)
// {xhr_hostname: "localhost", xhr_port: 8080,
// path_to_file_on_web_server: "/videos/grassland.mp4", SIZE_VIDEO_FILE: 374824780,
// webTorrent_trackers: []}
oakStreaming.receive_stream(theSharedArray.get(0), theHtmlVideoTag, function () {
console.log("receive_stream callback: All video data has been received");
});
}
});
});
window.handleFiles = function (files) {
streamSource = true;
// files[0] contains the file from the user
// addToSharedArray(content) transfers content to all other peers
// Maybe useful: webTorrent_trackers: [["wss://tracker.webtorrent.io"]] web_server_URL : "http://gaudi.informatik.rwth-aachen.de:9912"
oakStreaming.create_stream(files[0], { web_server_URL: "localhost:8080", webTorrent_trackers: ["ws://localhost:8085"] }, function (streamInformationObject) {
addToSharedArray(streamInformationObject);
});
};
function updateChart() {
document.getElementById("A").innerHTML = "File size in byte: " + oakStreaming.get_file_size();
document.getElementById("B").innerHTML = "Bytes downloaded from other peers: " + oakStreaming.get_number_of_bytes_downloaded_P2P();
document.getElementById("C").innerHTML = "Bytes uploaded to other peers: " + oakStreaming.get_number_of_bytes_uploaded_P2P();
document.getElementById("D").innerHTML = "Percentage of video file downloaded from P2P network: " + oakStreaming.get_percentage_downloaded_of_torrent();
document.getElementById("E").innerHTML = "Bytes downloaded from server: " + oakStreaming.get_number_of_bytes_downloaded_from_server();
setTimeout(updateChart, 50);
}
updateChart();
function addToSharedArray(streamInformationObject) {
if (theSharedArray !== null) {
theSharedArray.insert(0, [streamInformationObject]);
} else {
setTimeout(function () {
addToSharedArray(streamInformationObject);
}, 10);
}
}
},{"./oakstreaming":192}],2:[function(require,module,exports){
module.exports = function(haystack, needle, comparator, low, high) {
var mid, cmp;
if(low === undefined)
low = 0;
else {
low = low|0;
if(low < 0 || low >= haystack.length)
throw new RangeError("invalid lower bound");
}
if(high === undefined)
high = haystack.length - 1;
else {
high = high|0;
if(high < low || high >= haystack.length)
throw new RangeError("invalid upper bound");
}
while(low <= high) {
/* Note that "(low + high) >>> 1" may overflow, and results in a typecast
* to double (which gives the wrong results). */
mid = low + (high - low >> 1);
cmp = +comparator(haystack[mid], needle, mid, haystack);
/* Too low. */
if(cmp < 0.0)
low = mid + 1;
/* Too high. */
else if(cmp > 0.0)
high = mid - 1;
/* Key found. */
else
return mid;
}
/* Key not found. */
return ~low;
}
},{}],3:[function(require,module,exports){
(function (process){
module.exports = Client
var Buffer = require('safe-buffer').Buffer
var debug = require('debug')('bittorrent-tracker')
var EventEmitter = require('events').EventEmitter
var extend = require('xtend')
var inherits = require('inherits')
var once = require('once')
var parallel = require('run-parallel')
var Peer = require('simple-peer')
var uniq = require('uniq')
var url = require('url')
var common = require('./lib/common')
var HTTPTracker = require('./lib/client/http-tracker') // empty object in browser
var UDPTracker = require('./lib/client/udp-tracker') // empty object in browser
var WebSocketTracker = require('./lib/client/websocket-tracker')
inherits(Client, EventEmitter)
/**
* BitTorrent tracker client.
*
* Find torrent peers, to help a torrent client participate in a torrent swarm.
*
* @param {Object} opts options object
* @param {string|Buffer} opts.infoHash torrent info hash
* @param {string|Buffer} opts.peerId peer id
* @param {string|Array.<string>} opts.announce announce
* @param {number} opts.port torrent client listening port
* @param {function} opts.getAnnounceOpts callback to provide data to tracker
* @param {number} opts.rtcConfig RTCPeerConnection configuration object
* @param {number} opts.wrtc custom webrtc impl (useful in node.js)
*/
function Client (opts) {
var self = this
if (!(self instanceof Client)) return new Client(opts)
EventEmitter.call(self)
if (!opts) opts = {}
if (!opts.peerId) throw new Error('Option `peerId` is required')
if (!opts.infoHash) throw new Error('Option `infoHash` is required')
if (!opts.announce) throw new Error('Option `announce` is required')
if (!process.browser && !opts.port) throw new Error('Option `port` is required')
// required
self.peerId = typeof opts.peerId === 'string'
? opts.peerId
: opts.peerId.toString('hex')
self._peerIdBuffer = Buffer.from(self.peerId, 'hex')
self._peerIdBinary = self._peerIdBuffer.toString('binary')
self.infoHash = typeof opts.infoHash === 'string'
? opts.infoHash
: opts.infoHash.toString('hex')
self._infoHashBuffer = Buffer.from(self.infoHash, 'hex')
self._infoHashBinary = self._infoHashBuffer.toString('binary')
self._port = opts.port
self.destroyed = false
self._rtcConfig = opts.rtcConfig
self._getAnnounceOpts = opts.getAnnounceOpts
self._wrtc = opts.wrtc
// Support lazy 'wrtc' module initialization
// See: https://github.com/feross/webtorrent-hybrid/issues/46
if (typeof self._wrtc === 'function') self._wrtc = self._wrtc()
debug('new client %s', self.infoHash)
var webrtcSupport = self._wrtc !== false && (!!self._wrtc || Peer.WEBRTC_SUPPORT)
var announce = (typeof opts.announce === 'string')
? [ opts.announce ]
: opts.announce == null
? []
: opts.announce
announce = announce.map(function (announceUrl) {
announceUrl = announceUrl.toString()
if (announceUrl[announceUrl.length - 1] === '/') {
// remove trailing slash from trackers to catch duplicates
announceUrl = announceUrl.substring(0, announceUrl.length - 1)
}
return announceUrl
})
announce = uniq(announce)
self._trackers = announce
.map(function (announceUrl) {
var protocol = url.parse(announceUrl).protocol
if ((protocol === 'http:' || protocol === 'https:') &&
typeof HTTPTracker === 'function') {
return new HTTPTracker(self, announceUrl)
} else if (protocol === 'udp:' && typeof UDPTracker === 'function') {
return new UDPTracker(self, announceUrl)
} else if ((protocol === 'ws:' || protocol === 'wss:') && webrtcSupport) {
// Skip ws:// trackers on https:// sites because they throw SecurityError
if (protocol === 'ws:' && typeof window !== 'undefined' &&
window.location.protocol === 'https:') {
nextTickWarn(new Error('Unsupported tracker protocol: ' + announceUrl))
return null
}
return new WebSocketTracker(self, announceUrl)
} else {
nextTickWarn(new Error('Unsupported tracker protocol: ' + announceUrl))
return null
}
})
.filter(Boolean)
function nextTickWarn (err) {
process.nextTick(function () {
self.emit('warning', err)
})
}
}
/**
* Simple convenience function to scrape a tracker for an info hash without needing to
* create a Client, pass it a parsed torrent, etc. Support scraping a tracker for multiple
* torrents at the same time.
* @params {Object} opts
* @param {string|Array.<string>} opts.infoHash
* @param {string} opts.announce
* @param {function} cb
*/
Client.scrape = function (opts, cb) {
cb = once(cb)
if (!opts.infoHash) throw new Error('Option `infoHash` is required')
if (!opts.announce) throw new Error('Option `announce` is required')
var clientOpts = extend(opts, {
infoHash: Array.isArray(opts.infoHash) ? opts.infoHash[0] : opts.infoHash,
peerId: Buffer.from('01234567890123456789'), // dummy value
port: 6881 // dummy value
})
var client = new Client(clientOpts)
client.once('error', cb)
client.once('warning', cb)
var len = Array.isArray(opts.infoHash) ? opts.infoHash.length : 1
var results = {}
client.on('scrape', function (data) {
len -= 1
results[data.infoHash] = data
if (len === 0) {
client.destroy()
var keys = Object.keys(results)
if (keys.length === 1) {
cb(null, results[keys[0]])
} else {
cb(null, results)
}
}
})
opts.infoHash = Array.isArray(opts.infoHash)
? opts.infoHash.map(function (infoHash) {
return Buffer.from(infoHash, 'hex')
})
: Buffer.from(opts.infoHash, 'hex')
client.scrape({ infoHash: opts.infoHash })
return client
}
/**
* Send a `start` announce to the trackers.
* @param {Object} opts
* @param {number=} opts.uploaded
* @param {number=} opts.downloaded
* @param {number=} opts.left (if not set, calculated automatically)
*/
Client.prototype.start = function (opts) {
var self = this
debug('send `start`')
opts = self._defaultAnnounceOpts(opts)
opts.event = 'started'
self._announce(opts)
// start announcing on intervals
self._trackers.forEach(function (tracker) {
tracker.setInterval()
})
}
/**
* Send a `stop` announce to the trackers.
* @param {Object} opts
* @param {number=} opts.uploaded
* @param {number=} opts.downloaded
* @param {number=} opts.numwant
* @param {number=} opts.left (if not set, calculated automatically)
*/
Client.prototype.stop = function (opts) {
var self = this
debug('send `stop`')
opts = self._defaultAnnounceOpts(opts)
opts.event = 'stopped'
self._announce(opts)
}
/**
* Send a `complete` announce to the trackers.
* @param {Object} opts
* @param {number=} opts.uploaded
* @param {number=} opts.downloaded
* @param {number=} opts.numwant
* @param {number=} opts.left (if not set, calculated automatically)
*/
Client.prototype.complete = function (opts) {
var self = this
debug('send `complete`')
if (!opts) opts = {}
opts = self._defaultAnnounceOpts(opts)
opts.event = 'completed'
self._announce(opts)
}
/**
* Send a `update` announce to the trackers.
* @param {Object} opts
* @param {number=} opts.uploaded
* @param {number=} opts.downloaded
* @param {number=} opts.numwant
* @param {number=} opts.left (if not set, calculated automatically)
*/
Client.prototype.update = function (opts) {
var self = this
debug('send `update`')
opts = self._defaultAnnounceOpts(opts)
if (opts.event) delete opts.event
self._announce(opts)
}
Client.prototype._announce = function (opts) {
var self = this
self._trackers.forEach(function (tracker) {
// tracker should not modify `opts` object, it's passed to all trackers
tracker.announce(opts)
})
}
/**
* Send a scrape request to the trackers.
* @param {Object} opts
*/
Client.prototype.scrape = function (opts) {
var self = this
debug('send `scrape`')
if (!opts) opts = {}
self._trackers.forEach(function (tracker) {
// tracker should not modify `opts` object, it's passed to all trackers
tracker.scrape(opts)
})
}
Client.prototype.setInterval = function (intervalMs) {
var self = this
debug('setInterval %d', intervalMs)
self._trackers.forEach(function (tracker) {
tracker.setInterval(intervalMs)
})
}
Client.prototype.destroy = function (cb) {
var self = this
if (self.destroyed) return
self.destroyed = true
debug('destroy')
var tasks = self._trackers.map(function (tracker) {
return function (cb) {
tracker.destroy(cb)
}
})
parallel(tasks, cb)
self._trackers = []
self._getAnnounceOpts = null
}
Client.prototype._defaultAnnounceOpts = function (opts) {
var self = this
if (!opts) opts = {}
if (opts.numwant == null) opts.numwant = common.DEFAULT_ANNOUNCE_PEERS
if (opts.uploaded == null) opts.uploaded = 0
if (opts.downloaded == null) opts.downloaded = 0
if (self._getAnnounceOpts) opts = extend(opts, self._getAnnounceOpts())
return opts
}
}).call(this,require('_process'))
},{"./lib/client/http-tracker":20,"./lib/client/udp-tracker":20,"./lib/client/websocket-tracker":5,"./lib/common":6,"_process":29,"debug":7,"events":25,"inherits":63,"once":11,"run-parallel":13,"safe-buffer":14,"simple-peer":113,"uniq":16,"url":40,"xtend":17}],4:[function(require,module,exports){
module.exports = Tracker
var EventEmitter = require('events').EventEmitter
var inherits = require('inherits')
inherits(Tracker, EventEmitter)
function Tracker (client, announceUrl) {
var self = this
EventEmitter.call(self)
self.client = client
self.announceUrl = announceUrl
self.interval = null
self.destroyed = false
}
Tracker.prototype.setInterval = function (intervalMs) {
var self = this
if (intervalMs == null) intervalMs = self.DEFAULT_ANNOUNCE_INTERVAL
clearInterval(self.interval)
if (intervalMs) {
self.interval = setInterval(function () {
self.announce(self.client._defaultAnnounceOpts())
}, intervalMs)
if (self.interval.unref) self.interval.unref()
}
}
},{"events":25,"inherits":63}],5:[function(require,module,exports){
module.exports = WebSocketTracker
var debug = require('debug')('bittorrent-tracker:websocket-tracker')
var extend = require('xtend')
var inherits = require('inherits')
var Peer = require('simple-peer')
var randombytes = require('randombytes')
var Socket = require('simple-websocket')
var common = require('../common')
var Tracker = require('./tracker')
// Use a socket pool, so tracker clients share WebSocket objects for the same server.
// In practice, WebSockets are pretty slow to establish, so this gives a nice performance
// boost, and saves browser resources.
var socketPool = {}
var RECONNECT_MINIMUM = 15 * 1000
var RECONNECT_MAXIMUM = 30 * 60 * 1000
var RECONNECT_VARIANCE = 30 * 1000
var OFFER_TIMEOUT = 50 * 1000
inherits(WebSocketTracker, Tracker)
function WebSocketTracker (client, announceUrl, opts) {
var self = this
Tracker.call(self, client, announceUrl)
debug('new websocket tracker %s', announceUrl)
self.peers = {} // peers (offer id -> peer)
self.socket = null
self.reconnecting = false
self.retries = 0
self.reconnectTimer = null
self._openSocket()
}
WebSocketTracker.prototype.DEFAULT_ANNOUNCE_INTERVAL = 30 * 1000 // 30 seconds
WebSocketTracker.prototype.announce = function (opts) {
var self = this
if (self.destroyed || self.reconnecting) return
if (!self.socket.connected) {
self.socket.once('connect', function () {
self.announce(opts)
})
return
}
var params = extend(opts, {
action: 'announce',
info_hash: self.client._infoHashBinary,
peer_id: self.client._peerIdBinary
})
if (self._trackerId) params.trackerid = self._trackerId
if (opts.event === 'stopped') {
// Don't include offers with 'stopped' event
self._send(params)
} else {
// Limit the number of offers that are generated, since it can be slow
var numwant = Math.min(opts.numwant, 10)
self._generateOffers(numwant, function (offers) {
params.numwant = numwant
params.offers = offers
self._send(params)
})
}
}
WebSocketTracker.prototype.scrape = function (opts) {
var self = this
if (self.destroyed || self.reconnecting) return
if (!self.socket.connected) {
self.socket.once('connect', function () {
self.scrape(opts)
})
return
}
var infoHashes = (Array.isArray(opts.infoHash) && opts.infoHash.length > 0)
? opts.infoHash.map(function (infoHash) {
return infoHash.toString('binary')
})
: (opts.infoHash && opts.infoHash.toString('binary')) || self.client._infoHashBinary
var params = {
action: 'scrape',
info_hash: infoHashes
}
self._send(params)
}
WebSocketTracker.prototype.destroy = function (cb) {
var self = this
if (!cb) cb = noop
if (self.destroyed) return cb(null)
self.destroyed = true
clearInterval(self.interval)
clearTimeout(self.reconnectTimer)
if (self.socket) {
self.socket.removeListener('connect', self._onSocketConnectBound)
self.socket.removeListener('data', self._onSocketDataBound)
self.socket.removeListener('close', self._onSocketCloseBound)
self.socket.removeListener('error', self._onSocketErrorBound)
}
self._onSocketConnectBound = null
self._onSocketErrorBound = null
self._onSocketDataBound = null
self._onSocketCloseBound = null
// Destroy peers
for (var peerId in self.peers) {
var peer = self.peers[peerId]
clearTimeout(peer.trackerTimeout)
peer.destroy()
}
self.peers = null
if (socketPool[self.announceUrl]) {
socketPool[self.announceUrl].consumers -= 1
}
if (socketPool[self.announceUrl].consumers === 0) {
delete socketPool[self.announceUrl]
try {
self.socket.on('error', noop) // ignore all future errors
self.socket.destroy(cb)
} catch (err) {
cb(null)
}
} else {
cb(null)
}
self.socket = null
}
WebSocketTracker.prototype._openSocket = function () {
var self = this
self.destroyed = false
if (!self.peers) self.peers = {}
self._onSocketConnectBound = function () {
self._onSocketConnect()
}
self._onSocketErrorBound = function (err) {
self._onSocketError(err)
}
self._onSocketDataBound = function (data) {
self._onSocketData(data)
}
self._onSocketCloseBound = function () {
self._onSocketClose()
}
self.socket = socketPool[self.announceUrl]
if (self.socket) {
socketPool[self.announceUrl].consumers += 1
} else {
self.socket = socketPool[self.announceUrl] = new Socket(self.announceUrl)
self.socket.consumers = 1
self.socket.once('connect', self._onSocketConnectBound)
}
self.socket.on('data', self._onSocketDataBound)
self.socket.once('close', self._onSocketCloseBound)
self.socket.once('error', self._onSocketErrorBound)
}
WebSocketTracker.prototype._onSocketConnect = function () {
var self = this
if (self.destroyed) return
if (self.reconnecting) {
self.reconnecting = false
self.retries = 0
self.announce(self.client._defaultAnnounceOpts())
}
}
WebSocketTracker.prototype._onSocketData = function (data) {
var self = this
if (self.destroyed) return
try {
data = JSON.parse(data)
} catch (err) {
self.client.emit('warning', new Error('Invalid tracker response'))
return
}
if (data.action === 'announce') {
self._onAnnounceResponse(data)
} else if (data.action === 'scrape') {
self._onScrapeResponse(data)
} else {
self._onSocketError(new Error('invalid action in WS response: ' + data.action))
}
}
WebSocketTracker.prototype._onAnnounceResponse = function (data) {
var self = this
if (data.info_hash !== self.client._infoHashBinary) {
debug(
'ignoring websocket data from %s for %s (looking for %s: reused socket)',
self.announceUrl, common.binaryToHex(data.info_hash), self.client.infoHash
)
return
}
if (data.peer_id && data.peer_id === self.client._peerIdBinary) {
// ignore offers/answers from this client
return
}
debug(
'received %s from %s for %s',
JSON.stringify(data), self.announceUrl, self.client.infoHash
)
var failure = data['failure reason']
if (failure) return self.client.emit('warning', new Error(failure))
var warning = data['warning message']
if (warning) self.client.emit('warning', new Error(warning))
var interval = data.interval || data['min interval']
if (interval) self.setInterval(interval * 1000)
var trackerId = data['tracker id']
if (trackerId) {
// If absent, do not discard previous trackerId value
self._trackerId = trackerId
}
if (data.complete != null) {
self.client.emit('update', {
announce: self.announceUrl,
complete: data.complete,
incomplete: data.incomplete
})
}
var peer
if (data.offer && data.peer_id) {
debug('creating peer (from remote offer)')
peer = new Peer({
trickle: false,
config: self.client._rtcConfig,
wrtc: self.client._wrtc
})
peer.id = common.binaryToHex(data.peer_id)
peer.once('signal', function (answer) {
var params = {
action: 'announce',
info_hash: self.client._infoHashBinary,
peer_id: self.client._peerIdBinary,
to_peer_id: data.peer_id,
answer: answer,
offer_id: data.offer_id
}
if (self._trackerId) params.trackerid = self._trackerId
self._send(params)
})
peer.signal(data.offer)
self.client.emit('peer', peer)
}
if (data.answer && data.peer_id) {
var offerId = common.binaryToHex(data.offer_id)
peer = self.peers[offerId]
if (peer) {
peer.id = common.binaryToHex(data.peer_id)
peer.signal(data.answer)
self.client.emit('peer', peer)
clearTimeout(peer.trackerTimeout)
peer.trackerTimeout = null
delete self.peers[offerId]
} else {
debug('got unexpected answer: ' + JSON.stringify(data.answer))
}
}
}
WebSocketTracker.prototype._onScrapeResponse = function (data) {
var self = this
data = data.files || {}
var keys = Object.keys(data)
if (keys.length === 0) {
self.client.emit('warning', new Error('invalid scrape response'))
return
}
keys.forEach(function (infoHash) {
var response = data[infoHash]
// TODO: optionally handle data.flags.min_request_interval
// (separate from announce interval)
self.client.emit('scrape', {
announce: self.announceUrl,
infoHash: common.binaryToHex(infoHash),
complete: response.complete,
incomplete: response.incomplete,
downloaded: response.downloaded
})
})
}
WebSocketTracker.prototype._onSocketClose = function () {
var self = this
if (self.destroyed) return
self.destroy()
self._startReconnectTimer()
}
WebSocketTracker.prototype._onSocketError = function (err) {
var self = this
if (self.destroyed) return
self.destroy()
// errors will often happen if a tracker is offline, so don't treat it as fatal
self.client.emit('warning', err)
self._startReconnectTimer()
}
WebSocketTracker.prototype._startReconnectTimer = function () {
var self = this
var ms = Math.floor(Math.random() * RECONNECT_VARIANCE) + Math.min(Math.pow(2, self.retries) * RECONNECT_MINIMUM, RECONNECT_MAXIMUM)
self.reconnecting = true
clearTimeout(self.reconnectTimer)
self.reconnectTimer = setTimeout(function () {
self.retries++
self._openSocket()
}, ms)
if (self.reconnectTimer.unref) self.reconnectTimer.unref()
debug('reconnecting socket in %s ms', ms)
}
WebSocketTracker.prototype._send = function (params) {
var self = this
if (self.destroyed) return
var message = JSON.stringify(params)
debug('send %s', message)
self.socket.send(message)
}
WebSocketTracker.prototype._generateOffers = function (numwant, cb) {
var self = this
var offers = []
debug('generating %s offers', numwant)
for (var i = 0; i < numwant; ++i) {
generateOffer()
}
checkDone()
function generateOffer () {
var offerId = randombytes(20).toString('hex')
debug('creating peer (from _generateOffers)')
var peer = self.peers[offerId] = new Peer({
initiator: true,
trickle: false,
config: self.client._rtcConfig,
wrtc: self.client._wrtc
})
peer.once('signal', function (offer) {
offers.push({
offer: offer,
offer_id: common.hexToBinary(offerId)
})
checkDone()
})
peer.trackerTimeout = setTimeout(function () {
debug('tracker timeout: destroying peer')
peer.trackerTimeout = null
delete self.peers[offerId]
peer.destroy()
}, OFFER_TIMEOUT)
if (peer.trackerTimeout.unref) peer.trackerTimeout.unref()
}
function checkDone () {
if (offers.length === numwant) {
debug('generated %s offers', numwant)
cb(offers)
}
}
}
function noop () {}
},{"../common":6,"./tracker":4,"debug":7,"inherits":63,"randombytes":12,"simple-peer":113,"simple-websocket":15,"xtend":17}],6:[function(require,module,exports){
/**
* Functions/constants needed by both the client and server.
*/
var Buffer = require('safe-buffer').Buffer
var extend = require('xtend/mutable')
exports.DEFAULT_ANNOUNCE_PEERS = 50
exports.MAX_ANNOUNCE_PEERS = 82
exports.binaryToHex = function (str) {
if (typeof str !== 'string') {
str = String(str)
}
return Buffer.from(str, 'binary').toString('hex')
}
exports.hexToBinary = function (str) {
if (typeof str !== 'string') {
str = String(str)
}
return Buffer.from(str, 'hex').toString('binary')
}
var config = require('./common-node')
extend(exports, config)
},{"./common-node":20,"safe-buffer":14,"xtend/mutable":18}],7:[function(require,module,exports){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// is webkit? http://stackoverflow.com/a/16459606/376773
return ('WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
return JSON.stringify(v);
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return args;
var c = 'color: ' + this.color;
args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
return args;
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage(){
try {
return window.localStorage;
} catch (e) {}
}
},{"./debug":8}],8:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
*/
exports.formatters = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function debug(namespace) {
// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
// define the `enabled` version
function enabled() {
var self = enabled;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();
var args = Array.prototype.slice.call(arguments);
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %o
args = ['%o'].concat(args);
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
if ('function' === typeof exports.formatArgs) {
args = exports.formatArgs.apply(self, args);
}
var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;
var fn = exports.enabled(namespace) ? enabled : disabled;
fn.namespace = namespace;
return fn;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"ms":9}],9:[function(require,module,exports){
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} options
* @return {String|Number}
* @api public
*/
module.exports = function(val, options){
options = options || {};
if ('string' == typeof val) return parse(val);
return options.long
? long(val)
: short(val);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = '' + str;
if (str.length > 10000) return;
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
if (!match) return;
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function short(ms) {
if (ms >= d) return Math.round(ms / d) + 'd';
if (ms >= h) return Math.round(ms / h) + 'h';
if (ms >= m) return Math.round(ms / m) + 'm';
if (ms >= s) return Math.round(ms / s) + 's';
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function long(ms) {
return plural(ms, d, 'day')
|| plural(ms, h, 'hour')
|| plural(ms, m, 'minute')
|| plural(ms, s, 'second')
|| ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) return;
if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
return Math.ceil(ms / n) + ' ' + name + 's';
}
},{}],10:[function(require,module,exports){
// Returns a wrapper function that returns a wrapped callback
// The wrapper function should do some stuff, and return a
// presumably different callback function.
// This makes sure that own properties are retained, so that
// decorations and such are not lost along the way.
module.exports = wrappy
function wrappy (fn, cb) {
if (fn && cb) return wrappy(fn)(cb)
if (typeof fn !== 'function')
throw new TypeError('need wrapper function')
Object.keys(fn).forEach(function (k) {
wrapper[k] = fn[k]
})
return wrapper
function wrapper() {
var args = new Array(arguments.length)
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i]
}
var ret = fn.apply(this, args)
var cb = args[args.length-1]
if (typeof ret === 'function' && ret !== cb) {
Object.keys(cb).forEach(function (k) {
ret[k] = cb[k]
})
}
return ret
}
}
},{}],11:[function(require,module,exports){
var wrappy = require('wrappy')
module.exports = wrappy(once)
module.exports.strict = wrappy(onceStrict)
once.proto = once(function () {
Object.defineProperty(Function.prototype, 'once', {
value: function () {
return once(this)
},
configurable: true
})
Object.defineProperty(Function.prototype, 'onceStrict', {
value: function () {
return onceStrict(this)
},
configurable: true
})
})
function once (fn) {
var f = function () {
if (f.called) return f.value
f.called = true
return f.value = fn.apply(this, arguments)
}
f.called = false
return f
}
function onceStrict (fn) {
var f = function () {
if (f.called)
throw new Error(f.onceError)
f.called = true
return f.value = fn.apply(this, arguments)
}
var name = fn.name || 'Function wrapped with `once`'
f.onceError = name + " shouldn't be called more than once"
f.called = false
return f
}
},{"wrappy":10}],12:[function(require,module,exports){
(function (process,global,Buffer){
'use strict'
function oldBrowser () {
throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
}
var crypto = global.crypto || global.msCrypto
if (crypto && crypto.getRandomValues) {
module.exports = randomBytes
} else {
module.exports = oldBrowser
}
function randomBytes (size, cb) {
// phantomjs needs to throw
if (size > 65536) throw new Error('requested too many random bytes')
// in case browserify isn't using the Uint8Array version
var rawBytes = new global.Uint8Array(size)
// This will not work in older browsers.
// See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
if (size > 0) { // getRandomValues fails on IE if size == 0
crypto.getRandomValues(rawBytes)
}
// phantomjs doesn't like a buffer being passed here
var bytes = new Buffer(rawBytes.buffer)
if (typeof cb === 'function') {
return process.nextTick(function () {
cb(null, bytes)
})
}
return bytes
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
},{"_process":29,"buffer":21}],13:[function(require,module,exports){
(function (process){
module.exports = function (tasks, cb) {
var results, pending, keys
var isSync = true
if (Array.isArray(tasks)) {
results = []
pending = tasks.length
} else {
keys = Object.keys(tasks)
results = {}
pending = keys.length
}
function done (err) {
function end () {
if (cb) cb(err, results)
cb = null
}
if (isSync) process.nextTick(end)
else end()
}
function each (i, err, result) {
results[i] = result
if (--pending === 0 || err) {
done(err)
}
}
if (!pending) {
// empty
done(null)
} else if (keys) {
// object
keys.forEach(function (key) {
tasks[key](function (err, result) { each(key, err, result) })
})
} else {
// array
tasks.forEach(function (task, i) {
task(function (err, result) { each(i, err, result) })
})
}
isSync = false
}
}).call(this,require('_process'))
},{"_process":29}],14:[function(require,module,exports){
module.exports = require('buffer')
},{"buffer":21}],15:[function(require,module,exports){
(function (process,Buffer){
/* global WebSocket */
module.exports = Socket
var debug = require('debug')('simple-websocket')
var inherits = require('inherits')
var stream = require('readable-stream')
var ws = require('ws') // websockets in node - will be empty object in browser
var _WebSocket = typeof WebSocket !== 'undefined' ? WebSocket : ws
inherits(Socket, stream.Duplex)
/**
* WebSocket. Same API as node core `net.Socket`. Duplex stream.
* @param {string} url websocket server url
* @param {Object} opts options to stream.Duplex
*/
function Socket (url, opts) {
var self = this
if (!(self instanceof Socket)) return new Socket(url, opts)
if (!opts) opts = {}
debug('new websocket: %s %o', url, opts)
opts.allowHalfOpen = false
if (opts.highWaterMark == null) opts.highWaterMark = 1024 * 1024
stream.Duplex.call(self, opts)
self.url = url
self.connected = false
self.destroyed = false
self._maxBufferedAmount = opts.highWaterMark
self._chunk = null
self._cb = null
self._interval = null
try {
if (typeof WebSocket === 'undefined') {
// `ws` package accepts options
self._ws = new _WebSocket(self.url, opts)
} else {
self._ws = new _WebSocket(self.url)
}
} catch (err) {
process.nextTick(function () {
self._onError(err)
})
return
}
self._ws.binaryType = 'arraybuffer'
self._ws.onopen = function () {
self._onOpen()
}
self._ws.onmessage = function (event) {
self._onMessage(event)
}
self._ws.onclose = function () {
self._onClose()
}
self._ws.onerror = function () {
self._onError(new Error('connection error to ' + self.url))
}
self.on('finish', function () {
if (self.connected) {
// When stream is finished writing, close socket connection. Half open connections
// are currently not supported.
// Wait a bit before destroying so the socket flushes.
// TODO: is there a more reliable way to accomplish this?
setTimeout(function () {
self._destroy()
}, 100)
} else {
// If socket is not connected when stream is finished writing, wait until data is
// flushed to network at "connect" event.
// TODO: is there a more reliable way to accomplish this?
self.once('connect', function () {
setTimeout(function () {
self._destroy()
}, 100)
})
}
})
}
Socket.WEBSOCKET_SUPPORT = !!_WebSocket
/**
* Send text/binary data to the WebSocket server.
* @param {TypedArrayView|ArrayBuffer|Buffer|string|Blob|Object} chunk
*/
Socket.prototype.send = function (chunk) {
var self = this
var len = chunk.length || chunk.byteLength || chunk.size
self._ws.send(chunk)
debug('write: %d bytes', len)
}
Socket.prototype.destroy = function (onclose) {
var self = this
self._destroy(null, onclose)
}
Socket.prototype._destroy = function (err, onclose) {
var self = this
if (self.destroyed) return
if (onclose) self.once('close', onclose)
debug('destroy (error: %s)', err && err.message)
this.readable = this.writable = false
if (!self._readableState.ended) self.push(null)
if (!self._writableState.finished) self.end()
self.connected = false
self.destroyed = true
clearInterval(self._interval)
self._interval = null
self._chunk = null
self._cb = null
if (self._ws) {
var ws = self._ws
var onClose = function () {
ws.onclose = null
self.emit('close')
}
if (ws.readyState === _WebSocket.CLOSED) {
onClose()
} else {
try {
ws.onclose = onClose
ws.close()
} catch (err) {
onClose()
}
}
ws.onopen = null
ws.onmessage = null
ws.onerror = null
}
self._ws = null
if (err) self.emit('error', err)
}
Socket.prototype._read = function () {}
Socket.prototype._write = function (chunk, encoding, cb) {
var self = this
if (self.destroyed) return cb(new Error('cannot write after socket is destroyed'))
if (self.connected) {
try {
self.send(chunk)
} catch (err) {
return self._onError(err)
}
if (typeof ws !== 'function' && self._ws.bufferedAmount > self._maxBufferedAmount) {
debug('start backpressure: bufferedAmount %d', self._ws.bufferedAmount)
self._cb = cb
} else {
cb(null)
}
} else {
debug('write before connect')
self._chunk = chunk
self._cb = cb
}
}
Socket.prototype._onMessage = function (event) {
var self = this
if (self.destroyed) return
var data = event.data
debug('read: %d bytes', data.byteLength || data.length)
if (data instanceof ArrayBuffer) data = new Buffer(data)
self.push(data)
}
Socket.prototype._onOpen = function () {
var self = this
if (self.connected || self.destroyed) return
self.connected = true
if (self._chunk) {
try {
self.send(self._chunk)
} catch (err) {
return self._onError(err)
}
self._chunk = null
debug('sent chunk from "write before connect"')
var cb = self._cb
self._cb = null
cb(null)
}
// No backpressure in node. The `ws` module has a buggy `bufferedAmount` property.
// See: https://github.com/websockets/ws/issues/492
if (typeof ws !== 'function') {
self._interval = setInterval(function () {
if (!self._cb || !self._ws || self._ws.bufferedAmount > self._maxBufferedAmount) {
return
}
debug('ending backpressure: bufferedAmount %d', self._ws.bufferedAmount)
var cb = self._cb
self._cb = null
cb(null)
}, 150)
if (self._interval.unref) self._interval.unref()
}
debug('connect')
self.emit('connect')
}
Socket.prototype._onClose = function () {
var self = this
if (self.destroyed) return
debug('on close')
self._destroy()
}
Socket.prototype._onError = function (err) {
var self = this
if (self.destroyed) return
debug('error: %s', err.message || err)
self._destroy(err)
}
}).call(this,require('_process'),require("buffer").Buffer)
},{"_process":29,"buffer":21,"debug":7,"inherits":63,"readable-stream":112,"ws":20}],16:[function(require,module,exports){
"use strict"
function unique_pred(list, compare) {
var ptr = 1
, len = list.length
, a=list[0], b=list[0]
for(var i=1; i<len; ++i) {
b = a
a = list[i]
if(compare(a, b)) {
if(i === ptr) {
ptr++
continue
}
list[ptr++] = a
}
}
list.length = ptr
return list
}
function unique_eq(list) {
var ptr = 1
, len = list.length
, a=list[0], b = list[0]
for(var i=1; i<len; ++i, b=a) {
b = a
a = list[i]
if(a !== b) {
if(i === ptr) {
ptr++
continue
}
list[ptr++] = a
}
}
list.length = ptr
return list
}
function unique(list, compare, sorted) {
if(list.length === 0) {
return list
}
if(compare) {
if(!sorted) {
list.sort(compare)
}
return unique_pred(list, compare)
}
if(!sorted) {
list.sort()
}
return unique_eq(list)
}
module.exports = unique
},{}],17:[function(require,module,exports){
module.exports = extend
var hasOwnProperty = Object.prototype.hasOwnProperty;
function extend() {
var target = {}
for (var i = 0; i < arguments.length; i++) {
var source = arguments[i]
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
target[key] = source[key]
}
}
}
return target
}
},{}],18:[function(require,module,exports){
module.exports = extend
var hasOwnProperty = Object.prototype.hasOwnProperty;
function extend(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i]
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
target[key] = source[key]
}
}
}
return target
}
},{}],19:[function(require,module,exports){
},{}],20:[function(require,module,exports){
arguments[4][19][0].apply(exports,arguments)
},{"dup":19}],21:[function(require,module,exports){
(function (global){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
var isArray = require('isarray')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport()
/*
* Export kMaxLength after typed array support is determined.
*/
exports.kMaxLength = kMaxLength()
function typedArraySupport () {
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
}
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
function createBuffer (that, length) {
if (kMaxLength() < length) {
throw new RangeError('Invalid typed array length')
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array(length)
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
if (that === null) {
that = new Buffer(length)
}
that.length = length
}
return that
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
return new Buffer(arg, encodingOrOffset, length)
}
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(this, arg)
}
return from(this, arg, encodingOrOffset, length)
}
Buffer.poolSize = 8192 // not used by this implementation
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
arr.__proto__ = Buffer.prototype
return arr
}
function from (that, value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
return fromArrayBuffer(that, value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(that, value, encodingOrOffset)
}
return fromObject(that, value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(null, value, encodingOrOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true
})
}
}
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (that, size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(that, size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(that, size).fill(fill, encoding)
: createBuffer(that, size).fill(fill)
}
return createBuffer(that, size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(null, size, fill, encoding)
}
function allocUnsafe (that, size) {
assertSize(size)
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < size; ++i) {
that[i] = 0
}
}
return that
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(null, size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(null, size)
}
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
that = createBuffer(that, length)
var actual = that.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
that = that.slice(0, actual)
}
return that
}
function fromArrayLike (that, array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
that = createBuffer(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function fromArrayBuffer (that, array, byteOffset, length) {
array.byteLength // this throws if `array` is not a valid ArrayBuffer
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
if (byteOffset === undefined && length === undefined) {
array = new Uint8Array(array)
} else if (length === undefined) {
array = new Uint8Array(array, byteOffset)
} else {
array = new Uint8Array(array, byteOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = array
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
that = fromArrayLike(that, array)
}
return that
}
function fromObject (that, obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
that = createBuffer(that, len)
if (that.length === 0) {
return that
}
obj.copy(that, 0, 0, len)
return that
}
if (obj) {
if ((typeof ArrayBuffer !== 'undefined' &&
obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
if (typeof obj.length !== 'number' || isnan(obj.length)) {
return createBuffer(that, 0)
}
return fromArrayLike(that, obj)
}
if (obj.type === 'Buffer' && isArray(obj.data)) {
return fromArrayLike(that, obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < kMaxLength()` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
(ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length | 0
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (isNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (Buffer.TYPED_ARRAY_SUPPORT &&
typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0
if (isFinite(length)) {
length = length | 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = this.subarray(start, end)
newBuf.__proto__ = Buffer.prototype
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; ++i) {
newBuf[i] = this[i + start]
}
}
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = (value & 0xff)
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if (code < 256) {
val = code
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: utf8ToBytes(new Buffer(val, encoding).toString())
var len = bytes.length
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
function isnan (val) {
return val !== val // eslint-disable-line no-self-compare
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"base64-js":22,"ieee754":23,"isarray":24}],22:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function placeHoldersCount (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
}
function byteLength (b64) {
// base64 is 4/3 + up to two characters of the original data
return b64.length * 3 / 4 - placeHoldersCount(b64)
}
function toByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
var len = b64.length
placeHolders = placeHoldersCount(b64)
arr = new Arr(len * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len
var L = 0
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
arr[L++] = (tmp >> 16) & 0xFF
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
if (placeHolders === 2) {
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[L++] = tmp & 0xFF
} else if (placeHolders === 1) {
tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var output = ''
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
output += lookup[tmp >> 2]
output += lookup[(tmp << 4) & 0x3F]
output += '=='
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
output += lookup[tmp >> 10]
output += lookup[(tmp >> 4) & 0x3F]
output += lookup[(tmp << 2) & 0x3F]
output += '='
}
parts.push(output)
return parts.join('')
}
},{}],23:[function(require,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],24:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],25:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],26:[function(require,module,exports){
var http = require('http');
var https = module.exports;
for (var key in http) {
if (http.hasOwnProperty(key)) https[key] = http[key];
};
https.request = function (params, cb) {
if (!params) params = {};
params.scheme = 'https';
params.protocol = 'https:';
return http.request.call(this, params, cb);
}
},{"http":34}],27:[function(require,module,exports){
/*!
* Determine if an object is a Buffer
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
// The _isBuffer check is for Safari 5-7 support, because it's missing
// Object.prototype.constructor. Remove this eventually
module.exports = function (obj) {
return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
}
function isBuffer (obj) {
return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}
// For Node v0.10 support. Remove this eventually.
function isSlowBuffer (obj) {
return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
}
},{}],28:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
return splitPathRe.exec(filename).slice(1);
};
// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function(p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function(path) {
var result = splitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
exports.basename = function(path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function(path) {
return splitPath(path)[3];
};
function filter (xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
? function (str, start, len) { return str.substr(start, len) }
: function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
}
;
}).call(this,require('_process'))
},{"_process":29}],29:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],30:[function(require,module,exports){
(function (global){
/*! https://mths.be/punycode v1.4.1 by @mathias */
;(function(root) {
/** Detect free variables */
var freeExports = typeof exports == 'object' && exports &&
!exports.nodeType && exports;
var freeModule = typeof module == 'object' && module &&
!module.nodeType && module;
var freeGlobal = typeof global == 'object' && global;
if (
freeGlobal.global === freeGlobal ||
freeGlobal.window === freeGlobal ||
freeGlobal.self === freeGlobal
) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
var result = [];
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
var parts = string.split('@');
var result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
string = string.replace(regexSeparators, '\x2E');
var labels = string.split('.');
var encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
function toASCII(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.4.1',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
typeof define == 'function' &&
typeof define.amd == 'object' &&
define.amd
) {
define('punycode', function() {
return punycode;
});
} else if (freeExports && freeModule) {
if (module.exports == freeExports) {
// in Node.js, io.js, or RingoJS v0.8.0+
freeModule.exports = punycode;
} else {
// in Narwhal or RingoJS v0.7.0-
for (key in punycode) {
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
}
}
} else {
// in Rhino or a web browser
root.punycode = punycode;
}
}(this));
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],31:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = function(qs, sep, eq, options) {
sep = sep || '&';
eq = eq || '=';
var obj = {};
if (typeof qs !== 'string' || qs.length === 0) {
return obj;
}
var regexp = /\+/g;
qs = qs.split(sep);
var maxKeys = 1000;
if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys;
}
var len = qs.length;
// maxKeys <= 0 means that we should not limit keys count
if (maxKeys > 0 && len > maxKeys) {
len = maxKeys;
}
for (var i = 0; i < len; ++i) {
var x = qs[i].replace(regexp, '%20'),
idx = x.indexOf(eq),
kstr, vstr, k, v;
if (idx >= 0) {
kstr = x.substr(0, idx);
vstr = x.substr(idx + 1);
} else {
kstr = x;
vstr = '';
}
k = decodeURIComponent(kstr);
v = decodeURIComponent(vstr);
if (!hasOwnProperty(obj, k)) {
obj[k] = v;
} else if (isArray(obj[k])) {
obj[k].push(v);
} else {
obj[k] = [obj[k], v];
}
}
return obj;
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
},{}],32:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
},{}],33:[function(require,module,exports){
'use strict';
exports.decode = exports.parse = require('./decode');
exports.encode = exports.stringify = require('./encode');
},{"./decode":31,"./encode":32}],34:[function(require,module,exports){
(function (global){
var ClientRequest = require('./lib/request')
var extend = require('xtend')
var statusCodes = require('builtin-status-codes')
var url = require('url')
var http = exports
http.request = function (opts, cb) {
if (typeof opts === 'string')
opts = url.parse(opts)
else
opts = extend(opts)
// Normally, the page is loaded from http or https, so not specifying a protocol
// will result in a (valid) protocol-relative url. However, this won't work if
// the protocol is something else, like 'file:'
var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
var protocol = opts.protocol || defaultProtocol
var host = opts.hostname || opts.host
var port = opts.port
var path = opts.path || '/'
// Necessary for IPv6 addresses
if (host && host.indexOf(':') !== -1)
host = '[' + host + ']'
// This may be a relative url. The browser should always be able to interpret it correctly.
opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
opts.method = (opts.method || 'GET').toUpperCase()
opts.headers = opts.headers || {}
// Also valid opts.auth, opts.mode
var req = new ClientRequest(opts)
if (cb)
req.on('response', cb)
return req
}
http.get = function get (opts, cb) {
var req = http.request(opts, cb)
req.end()
return req
}
http.Agent = function () {}
http.Agent.defaultMaxSockets = 4
http.STATUS_CODES = statusCodes
http.METHODS = [
'CHECKOUT',
'CONNECT',
'COPY',
'DELETE',
'GET',
'HEAD',
'LOCK',
'M-SEARCH',
'MERGE',
'MKACTIVITY',
'MKCOL',
'MOVE',
'NOTIFY',
'OPTIONS',
'PATCH',
'POST',
'PROPFIND',
'PROPPATCH',
'PURGE',
'PUT',
'REPORT',
'SEARCH',
'SUBSCRIBE',
'TRACE',
'UNLOCK',
'UNSUBSCRIBE'
]
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./lib/request":36,"builtin-status-codes":38,"url":40,"xtend":42}],35:[function(require,module,exports){
(function (global){
exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream)
exports.blobConstructor = false
try {
new Blob([new ArrayBuffer(1)])
exports.blobConstructor = true
} catch (e) {}
var xhr = new global.XMLHttpRequest()
// If location.host is empty, e.g. if this page/worker was loaded
// from a Blob, then use example.com to avoid an error
xhr.open('GET', global.location.host ? '/' : 'https://example.com')
function checkTypeSupport (type) {
try {
xhr.responseType = type
return xhr.responseType === type
} catch (e) {}
return false
}
// For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'.
// Safari 7.1 appears to have fixed this bug.
var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined'
var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice)
exports.arraybuffer = haveArrayBuffer && checkTypeSupport('arraybuffer')
// These next two tests unavoidably show warnings in Chrome. Since fetch will always
// be used if it's available, just return false for these to avoid the warnings.
exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream')
exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer &&
checkTypeSupport('moz-chunked-arraybuffer')
exports.overrideMimeType = isFunction(xhr.overrideMimeType)
exports.vbArray = isFunction(global.VBArray)
function isFunction (value) {
return typeof value === 'function'
}
xhr = null // Help gc
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],36:[function(require,module,exports){
(function (process,global,Buffer){
var capability = require('./capability')
var inherits = require('inherits')
var response = require('./response')
var stream = require('readable-stream')
var toArrayBuffer = require('to-arraybuffer')
var IncomingMessage = response.IncomingMessage
var rStates = response.readyStates
function decideMode (preferBinary, useFetch) {
if (capability.fetch && useFetch) {
return 'fetch'
} else if (capability.mozchunkedarraybuffer) {
return 'moz-chunked-arraybuffer'
} else if (capability.msstream) {
return 'ms-stream'
} else if (capability.arraybuffer && preferBinary) {
return 'arraybuffer'
} else if (capability.vbArray && preferBinary) {
return 'text:vbarray'
} else {
return 'text'
}
}
var ClientRequest = module.exports = function (opts) {
var self = this
stream.Writable.call(self)
self._opts = opts
self._body = []
self._headers = {}
if (opts.auth)
self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64'))
Object.keys(opts.headers).forEach(function (name) {
self.setHeader(name, opts.headers[name])
})
var preferBinary
var useFetch = true
if (opts.mode === 'disable-fetch') {
// If the use of XHR should be preferred and includes preserving the 'content-type' header
useFetch = false
preferBinary = true
} else if (opts.mode === 'prefer-streaming') {
// If streaming is a high priority but binary compatibility and
// the accuracy of the 'content-type' header aren't
preferBinary = false
} else if (opts.mode === 'allow-wrong-content-type') {
// If streaming is more important than preserving the 'content-type' header
preferBinary = !capability.overrideMimeType
} else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
// Use binary if text streaming may corrupt data or the content-type header, or for speed
preferBinary = true
} else {
throw new Error('Invalid value for opts.mode')
}
self._mode = decideMode(preferBinary, useFetch)
self.on('finish', function () {
self._onFinish()
})
}
inherits(ClientRequest, stream.Writable)
ClientRequest.prototype.setHeader = function (name, value) {
var self = this
var lowerName = name.toLowerCase()
// This check is not necessary, but it prevents warnings from browsers about setting unsafe
// headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
// http-browserify did it, so I will too.
if (unsafeHeaders.indexOf(lowerName) !== -1)
return
self._headers[lowerName] = {
name: name,
value: value
}
}
ClientRequest.prototype.getHeader = function (name) {
var self = this
return self._headers[name.toLowerCase()].value
}
ClientRequest.prototype.removeHeader = function (name) {
var self = this
delete self._headers[name.toLowerCase()]
}
ClientRequest.prototype._onFinish = function () {
var self = this
if (self._destroyed)
return
var opts = self._opts
var headersObj = self._headers
var body
if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH') {
if (capability.blobConstructor) {
body = new global.Blob(self._body.map(function (buffer) {
return toArrayBuffer(buffer)
}), {
type: (headersObj['content-type'] || {}).value || ''
})
} else {
// get utf8 string
body = Buffer.concat(self._body).toString()
}
}
if (self._mode === 'fetch') {
var headers = Object.keys(headersObj).map(function (name) {
return [headersObj[name].name, headersObj[name].value]
})
global.fetch(self._opts.url, {
method: self._opts.method,
headers: headers,
body: body,
mode: 'cors',
credentials: opts.withCredentials ? 'include' : 'same-origin'
}).then(function (response) {
self._fetchResponse = response
self._connect()
}, function (reason) {
self.emit('error', reason)
})
} else {
var xhr = self._xhr = new global.XMLHttpRequest()
try {
xhr.open(self._opts.method, self._opts.url, true)
} catch (err) {
process.nextTick(function () {
self.emit('error', err)
})
return
}
// Can't set responseType on really old browsers
if ('responseType' in xhr)
xhr.responseType = self._mode.split(':')[0]
if ('withCredentials' in xhr)
xhr.withCredentials = !!opts.withCredentials
if (self._mode === 'text' && 'overrideMimeType' in xhr)
xhr.overrideMimeType('text/plain; charset=x-user-defined')
Object.keys(headersObj).forEach(function (name) {
xhr.setRequestHeader(headersObj[name].name, headersObj[name].value)
})
self._response = null
xhr.onreadystatechange = function () {
switch (xhr.readyState) {
case rStates.LOADING:
case rStates.DONE:
self._onXHRProgress()
break
}
}
// Necessary for streaming in Firefox, since xhr.response is ONLY defined
// in onprogress, not in onreadystatechange with xhr.readyState = 3
if (self._mode === 'moz-chunked-arraybuffer') {
xhr.onprogress = function () {
self._onXHRProgress()
}
}
xhr.onerror = function () {
if (self._destroyed)
return
self.emit('error', new Error('XHR error'))
}
try {
xhr.send(body)
} catch (err) {
process.nextTick(function () {
self.emit('error', err)
})
return
}
}
}
/**
* Checks if xhr.status is readable and non-zero, indicating no error.
* Even though the spec says it should be available in readyState 3,
* accessing it throws an exception in IE8
*/
function statusValid (xhr) {
try {
var status = xhr.status
return (status !== null && status !== 0)
} catch (e) {
return false
}
}
ClientRequest.prototype._onXHRProgress = function () {
var self = this
if (!statusValid(self._xhr) || self._destroyed)
return
if (!self._response)
self._connect()
self._response._onXHRProgress()
}
ClientRequest.prototype._connect = function () {
var self = this
if (self._destroyed)
return
self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode)
self.emit('response', self._response)
}
ClientRequest.prototype._write = function (chunk, encoding, cb) {
var self = this
self._body.push(chunk)
cb()
}
ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
var self = this
self._destroyed = true
if (self._response)
self._response._destroyed = true
if (self._xhr)
self._xhr.abort()
// Currently, there isn't a way to truly abort a fetch.
// If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27
}
ClientRequest.prototype.end = function (data, encoding, cb) {
var self = this
if (typeof data === 'function') {
cb = data
data = undefined
}
stream.Writable.prototype.end.call(self, data, encoding, cb)
}
ClientRequest.prototype.flushHeaders = function () {}
ClientRequest.prototype.setTimeout = function () {}
ClientRequest.prototype.setNoDelay = function () {}
ClientRequest.prototype.setSocketKeepAlive = function () {}
// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
var unsafeHeaders = [
'accept-charset',
'accept-encoding',
'access-control-request-headers',
'access-control-request-method',
'connection',
'content-length',
'cookie',
'cookie2',
'date',
'dnt',
'expect',
'host',
'keep-alive',
'origin',
'referer',
'te',
'trailer',
'transfer-encoding',
'upgrade',
'user-agent',
'via'
]
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
},{"./capability":35,"./response":37,"_process":29,"buffer":21,"inherits":63,"readable-stream":112,"to-arraybuffer":39}],37:[function(require,module,exports){
(function (process,global,Buffer){
var capability = require('./capability')
var inherits = require('inherits')
var stream = require('readable-stream')
var rStates = exports.readyStates = {
UNSENT: 0,
OPENED: 1,
HEADERS_RECEIVED: 2,
LOADING: 3,
DONE: 4
}
var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode) {
var self = this
stream.Readable.call(self)
self._mode = mode
self.headers = {}
self.rawHeaders = []
self.trailers = {}
self.rawTrailers = []
// Fake the 'close' event, but only once 'end' fires
self.on('end', function () {
// The nextTick is necessary to prevent the 'request' module from causing an infinite loop
process.nextTick(function () {
self.emit('close')
})
})
if (mode === 'fetch') {
self._fetchResponse = response
self.url = response.url
self.statusCode = response.status
self.statusMessage = response.statusText
// backwards compatible version of for (<item> of <iterable>):
// for (var <item>,_i,_it = <iterable>[Symbol.iterator](); <item> = (_i = _it.next()).value,!_i.done;)
for (var header, _i, _it = response.headers[Symbol.iterator](); header = (_i = _it.next()).value, !_i.done;) {
self.headers[header[0].toLowerCase()] = header[1]
self.rawHeaders.push(header[0], header[1])
}
// TODO: this doesn't respect backpressure. Once WritableStream is available, this can be fixed
var reader = response.body.getReader()
function read () {
reader.read().then(function (result) {
if (self._destroyed)
return
if (result.done) {
self.push(null)
return
}
self.push(new Buffer(result.value))
read()
})
}
read()
} else {
self._xhr = xhr
self._pos = 0
self.url = xhr.responseURL
self.statusCode = xhr.status
self.statusMessage = xhr.statusText
var headers = xhr.getAllResponseHeaders().split(/\r?\n/)
headers.forEach(function (header) {
var matches = header.match(/^([^:]+):\s*(.*)/)
if (matches) {
var key = matches[1].toLowerCase()
if (key === 'set-cookie') {
if (self.headers[key] === undefined) {
self.headers[key] = []
}
self.headers[key].push(matches[2])
} else if (self.headers[key] !== undefined) {
self.headers[key] += ', ' + matches[2]
} else {
self.headers[key] = matches[2]
}
self.rawHeaders.push(matches[1], matches[2])
}
})
self._charset = 'x-user-defined'
if (!capability.overrideMimeType) {
var mimeType = self.rawHeaders['mime-type']
if (mimeType) {
var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/)
if (charsetMatch) {
self._charset = charsetMatch[1].toLowerCase()
}
}
if (!self._charset)
self._charset = 'utf-8' // best guess
}
}
}
inherits(IncomingMessage, stream.Readable)
IncomingMessage.prototype._read = function () {}
IncomingMessage.prototype._onXHRProgress = function () {
var self = this
var xhr = self._xhr
var response = null
switch (self._mode) {
case 'text:vbarray': // For IE9
if (xhr.readyState !== rStates.DONE)
break
try {
// This fails in IE8
response = new global.VBArray(xhr.responseBody).toArray()
} catch (e) {}
if (response !== null) {
self.push(new Buffer(response))
break
}
// Falls through in IE8
case 'text':
try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4
response = xhr.responseText
} catch (e) {
self._mode = 'text:vbarray'
break
}
if (response.length > self._pos) {
var newData = response.substr(self._pos)
if (self._charset === 'x-user-defined') {
var buffer = new Buffer(newData.length)
for (var i = 0; i < newData.length; i++)
buffer[i] = newData.charCodeAt(i) & 0xff
self.push(buffer)
} else {
self.push(newData, self._charset)
}
self._pos = response.length
}
break
case 'arraybuffer':
if (xhr.readyState !== rStates.DONE || !xhr.response)
break
response = xhr.response
self.push(new Buffer(new Uint8Array(response)))
break
case 'moz-chunked-arraybuffer': // take whole
response = xhr.response
if (xhr.readyState !== rStates.LOADING || !response)
break
self.push(new Buffer(new Uint8Array(response)))
break
case 'ms-stream':
response = xhr.response
if (xhr.readyState !== rStates.LOADING)
break
var reader = new global.MSStreamReader()
reader.onprogress = function () {
if (reader.result.byteLength > self._pos) {
self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos))))
self._pos = reader.result.byteLength
}
}
reader.onload = function () {
self.push(null)
}
// reader.onerror = ??? // TODO: this
reader.readAsArrayBuffer(response)
break
}
// The ms-stream case handles end separately in reader.onload()
if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
self.push(null)
}
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
},{"./capability":35,"_process":29,"buffer":21,"inherits":63,"readable-stream":112}],38:[function(require,module,exports){
module.exports = {
"100": "Continue",
"101": "Switching Protocols",
"102": "Processing",
"200": "OK",
"201": "Created",
"202": "Accepted",
"203": "Non-Authoritative Information",
"204": "No Content",
"205": "Reset Content",
"206": "Partial Content",
"207": "Multi-Status",
"208": "Already Reported",
"226": "IM Used",
"300": "Multiple Choices",
"301": "Moved Permanently",
"302": "Found",
"303": "See Other",
"304": "Not Modified",
"305": "Use Proxy",
"307": "Temporary Redirect",
"308": "Permanent Redirect",
"400": "Bad Request",
"401": "Unauthorized",
"402": "Payment Required",
"403": "Forbidden",
"404": "Not Found",
"405": "Method Not Allowed",
"406": "Not Acceptable",
"407": "Proxy Authentication Required",
"408": "Request Timeout",
"409": "Conflict",
"410": "Gone",
"411": "Length Required",
"412": "Precondition Failed",
"413": "Payload Too Large",
"414": "URI Too Long",
"415": "Unsupported Media Type",
"416": "Range Not Satisfiable",
"417": "Expectation Failed",
"418": "I'm a teapot",
"421": "Misdirected Request",
"422": "Unprocessable Entity",
"423": "Locked",
"424": "Failed Dependency",
"425": "Unordered Collection",
"426": "Upgrade Required",
"428": "Precondition Required",
"429": "Too Many Requests",
"431": "Request Header Fields Too Large",
"500": "Internal Server Error",
"501": "Not Implemented",
"502": "Bad Gateway",
"503": "Service Unavailable",
"504": "Gateway Timeout",
"505": "HTTP Version Not Supported",
"506": "Variant Also Negotiates",
"507": "Insufficient Storage",
"508": "Loop Detected",
"509": "Bandwidth Limit Exceeded",
"510": "Not Extended",
"511": "Network Authentication Required"
}
},{}],39:[function(require,module,exports){
var Buffer = require('buffer').Buffer
module.exports = function (buf) {
// If the buffer is backed by a Uint8Array, a faster version will work
if (buf instanceof Uint8Array) {
// If the buffer isn't a subarray, return the underlying ArrayBuffer
if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
return buf.buffer
} else if (typeof buf.buffer.slice === 'function') {
// Otherwise we need to get a proper copy
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
}
}
if (Buffer.isBuffer(buf)) {
// This is the slow version that will work with any Buffer
// implementation (even in old browsers)
var arrayCopy = new Uint8Array(buf.length)
var len = buf.length
for (var i = 0; i < len; i++) {
arrayCopy[i] = buf[i]
}
return arrayCopy.buffer
} else {
throw new Error('Argument must be a Buffer')
}
}
},{"buffer":21}],40:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var punycode = require('punycode');
var util = require('./util');
exports.parse = urlParse;
exports.resolve = urlResolve;
exports.resolveObject = urlResolveObject;
exports.format = urlFormat;
exports.Url = Url;
function Url() {
this.protocol = null;
this.slashes = null;
this.auth = null;
this.host = null;
this.port = null;
this.hostname = null;
this.hash = null;
this.search = null;
this.query = null;
this.pathname = null;
this.path = null;
this.href = null;
}
// Reference: RFC 3986, RFC 1808, RFC 2396
// define these here so at least they only have to be
// compiled once on the first module load.
var protocolPattern = /^([a-z0-9.+-]+:)/i,
portPattern = /:[0-9]*$/,
// Special case for a simple path URL
simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
// RFC 2396: characters reserved for delimiting URLs.
// We actually just auto-escape these.
delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
// RFC 2396: characters not allowed for various reasons.
unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
// Allowed by RFCs, but cause of XSS attacks. Always escape these.
autoEscape = ['\''].concat(unwise),
// Characters that are never ever allowed in a hostname.
// Note that any invalid chars are also handled, but these
// are the ones that are *expected* to be seen, so we fast-path
// them.
nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
hostEndingChars = ['/', '?', '#'],
hostnameMaxLen = 255,
hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
// protocols that can allow "unsafe" and "unwise" chars.
unsafeProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that never have a hostname.
hostlessProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that always contain a // bit.
slashedProtocol = {
'http': true,
'https': true,
'ftp': true,
'gopher': true,
'file': true,
'http:': true,
'https:': true,
'ftp:': true,
'gopher:': true,
'file:': true
},
querystring = require('querystring');
function urlParse(url, parseQueryString, slashesDenoteHost) {
if (url && util.isObject(url) && url instanceof Url) return url;
var u = new Url;
u.parse(url, parseQueryString, slashesDenoteHost);
return u;
}
Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
if (!util.isString(url)) {
throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
}
// Copy chrome, IE, opera backslash-handling behavior.
// Back slashes before the query string get converted to forward slashes
// See: https://code.google.com/p/chromium/issues/detail?id=25916
var queryIndex = url.indexOf('?'),
splitter =
(queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
uSplit = url.split(splitter),
slashRegex = /\\/g;
uSplit[0] = uSplit[0].replace(slashRegex, '/');
url = uSplit.join(splitter);
var rest = url;
// trim before proceeding.
// This is to support parse stuff like " http://foo.com \n"
rest = rest.trim();
if (!slashesDenoteHost && url.split('#').length === 1) {
// Try fast path regexp
var simplePath = simplePathPattern.exec(rest);
if (simplePath) {
this.path = rest;
this.href = rest;
this.pathname = simplePath[1];
if (simplePath[2]) {
this.search = simplePath[2];
if (parseQueryString) {
this.query = querystring.parse(this.search.substr(1));
} else {
this.query = this.search.substr(1);
}
} else if (parseQueryString) {
this.search = '';
this.query = {};
}
return this;
}
}
var proto = protocolPattern.exec(rest);
if (proto) {
proto = proto[0];
var lowerProto = proto.toLowerCase();
this.protocol = lowerProto;
rest = rest.substr(proto.length);
}
// figure out if it's got a host
// user@server is *always* interpreted as a hostname, and url
// resolution will treat //foo/bar as host=foo,path=bar because that's
// how the browser resolves relative URLs.
if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
var slashes = rest.substr(0, 2) === '//';
if (slashes && !(proto && hostlessProtocol[proto])) {
rest = rest.substr(2);
this.slashes = true;
}
}
if (!hostlessProtocol[proto] &&
(slashes || (proto && !slashedProtocol[proto]))) {
// there's a hostname.
// the first instance of /, ?, ;, or # ends the host.
//
// If there is an @ in the hostname, then non-host chars *are* allowed
// to the left of the last @ sign, unless some host-ending character
// comes *before* the @-sign.
// URLs are obnoxious.
//
// ex:
// http://a@b@c/ => user:a@b host:c
// http://a@b?@c => user:a host:c path:/?@c
// v0.12 TODO(isaacs): This is not quite how Chrome does things.
// Review our test case against browsers more comprehensively.
// find the first instance of any hostEndingChars
var hostEnd = -1;
for (var i = 0; i < hostEndingChars.length; i++) {
var hec = rest.indexOf(hostEndingChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
hostEnd = hec;
}
// at this point, either we have an explicit point where the
// auth portion cannot go past, or the last @ char is the decider.
var auth, atSign;
if (hostEnd === -1) {
// atSign can be anywhere.
atSign = rest.lastIndexOf('@');
} else {
// atSign must be in auth portion.
// http://a@b/c@d => host:b auth:a path:/c@d
atSign = rest.lastIndexOf('@', hostEnd);
}
// Now we have a portion which is definitely the auth.
// Pull that off.
if (atSign !== -1) {
auth = rest.slice(0, atSign);
rest = rest.slice(atSign + 1);
this.auth = decodeURIComponent(auth);
}
// the host is the remaining to the left of the first non-host char
hostEnd = -1;
for (var i = 0; i < nonHostChars.length; i++) {
var hec = rest.indexOf(nonHostChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
hostEnd = hec;
}
// if we still have not hit it, then the entire thing is a host.
if (hostEnd === -1)
hostEnd = rest.length;
this.host = rest.slice(0, hostEnd);
rest = rest.slice(hostEnd);
// pull out port.
this.parseHost();
// we've indicated that there is a hostname,
// so even if it's empty, it has to be present.
this.hostname = this.hostname || '';
// if hostname begins with [ and ends with ]
// assume that it's an IPv6 address.
var ipv6Hostname = this.hostname[0] === '[' &&
this.hostname[this.hostname.length - 1] === ']';
// validate a little.
if (!ipv6Hostname) {
var hostparts = this.hostname.split(/\./);
for (var i = 0, l = hostparts.length; i < l; i++) {
var part = hostparts[i];
if (!part) continue;
if (!part.match(hostnamePartPattern)) {
var newpart = '';
for (var j = 0, k = part.length; j < k; j++) {
if (part.charCodeAt(j) > 127) {
// we replace non-ASCII char with a temporary placeholder
// we need this to make sure size of hostname is not
// broken by replacing non-ASCII by nothing
newpart += 'x';
} else {
newpart += part[j];
}
}
// we test again with ASCII char only
if (!newpart.match(hostnamePartPattern)) {
var validParts = hostparts.slice(0, i);
var notHost = hostparts.slice(i + 1);
var bit = part.match(hostnamePartStart);
if (bit) {
validParts.push(bit[1]);
notHost.unshift(bit[2]);
}
if (notHost.length) {
rest = '/' + notHost.join('.') + rest;
}
this.hostname = validParts.join('.');
break;
}
}
}
}
if (this.hostname.length > hostnameMaxLen) {
this.hostname = '';
} else {
// hostnames are always lower case.
this.hostname = this.hostname.toLowerCase();
}
if (!ipv6Hostname) {
// IDNA Support: Returns a punycoded representation of "domain".
// It only converts parts of the domain name that
// have non-ASCII characters, i.e. it doesn't matter if
// you call it with a domain that already is ASCII-only.
this.hostname = punycode.toASCII(this.hostname);
}
var p = this.port ? ':' + this.port : '';
var h = this.hostname || '';
this.host = h + p;
this.href += this.host;
// strip [ and ] from the hostname
// the host field still retains them, though
if (ipv6Hostname) {
this.hostname = this.hostname.substr(1, this.hostname.length - 2);
if (rest[0] !== '/') {
rest = '/' + rest;
}
}
}
// now rest is set to the post-host stuff.
// chop off any delim chars.
if (!unsafeProtocol[lowerProto]) {
// First, make 100% sure that any "autoEscape" chars get
// escaped, even if encodeURIComponent doesn't think they
// need to be.
for (var i = 0, l = autoEscape.length; i < l; i++) {
var ae = autoEscape[i];
if (rest.indexOf(ae) === -1)
continue;
var esc = encodeURIComponent(ae);
if (esc === ae) {
esc = escape(ae);
}
rest = rest.split(ae).join(esc);
}
}
// chop off from the tail first.
var hash = rest.indexOf('#');
if (hash !== -1) {
// got a fragment string.
this.hash = rest.substr(hash);
rest = rest.slice(0, hash);
}
var qm = rest.indexOf('?');
if (qm !== -1) {
this.search = rest.substr(qm);
this.query = rest.substr(qm + 1);
if (parseQueryString) {
this.query = querystring.parse(this.query);
}
rest = rest.slice(0, qm);
} else if (parseQueryString) {
// no query string, but parseQueryString still requested
this.search = '';
this.query = {};
}
if (rest) this.pathname = rest;
if (slashedProtocol[lowerProto] &&
this.hostname && !this.pathname) {
this.pathname = '/';
}
//to support http.request
if (this.pathname || this.search) {
var p = this.pathname || '';
var s = this.search || '';
this.path = p + s;
}
// finally, reconstruct the href based on what has been validated.
this.href = this.format();
return this;
};
// format a parsed object into a url string
function urlFormat(obj) {
// ensure it's an object, and not a string url.
// If it's an obj, this is a no-op.
// this way, you can call url_format() on strings
// to clean up potentially wonky urls.
if (util.isString(obj)) obj = urlParse(obj);
if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
return obj.format();
}
Url.prototype.format = function() {
var auth = this.auth || '';
if (auth) {
auth = encodeURIComponent(auth);
auth = auth.replace(/%3A/i, ':');
auth += '@';
}
var protocol = this.protocol || '',
pathname = this.pathname || '',
hash = this.hash || '',
host = false,
query = '';
if (this.host) {
host = auth + this.host;
} else if (this.hostname) {
host = auth + (this.hostname.indexOf(':') === -1 ?
this.hostname :
'[' + this.hostname + ']');
if (this.port) {
host += ':' + this.port;
}
}
if (this.query &&
util.isObject(this.query) &&
Object.keys(this.query).length) {
query = querystring.stringify(this.query);
}
var search = this.search || (query && ('?' + query)) || '';
if (protocol && protocol.substr(-1) !== ':') protocol += ':';
// only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
// unless they had them to begin with.
if (this.slashes ||
(!protocol || slashedProtocol[protocol]) && host !== false) {
host = '//' + (host || '');
if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
} else if (!host) {
host = '';
}
if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
if (search && search.charAt(0) !== '?') search = '?' + search;
pathname = pathname.replace(/[?#]/g, function(match) {
return encodeURIComponent(match);
});
search = search.replace('#', '%23');
return protocol + host + pathname + search + hash;
};
function urlResolve(source, relative) {
return urlParse(source, false, true).resolve(relative);
}
Url.prototype.resolve = function(relative) {
return this.resolveObject(urlParse(relative, false, true)).format();
};
function urlResolveObject(source, relative) {
if (!source) return relative;
return urlParse(source, false, true).resolveObject(relative);
}
Url.prototype.resolveObject = function(relative) {
if (util.isString(relative)) {
var rel = new Url();
rel.parse(relative, false, true);
relative = rel;
}
var result = new Url();
var tkeys = Object.keys(this);
for (var tk = 0; tk < tkeys.length; tk++) {
var tkey = tkeys[tk];
result[tkey] = this[tkey];
}
// hash is always overridden, no matter what.
// even href="" will remove it.
result.hash = relative.hash;
// if the relative url is empty, then there's nothing left to do here.
if (relative.href === '') {
result.href = result.format();
return result;
}
// hrefs like //foo/bar always cut to the protocol.
if (relative.slashes && !relative.protocol) {
// take everything except the protocol from relative
var rkeys = Object.keys(relative);
for (var rk = 0; rk < rkeys.length; rk++) {
var rkey = rkeys[rk];
if (rkey !== 'protocol')
result[rkey] = relative[rkey];
}
//urlParse appends trailing / to urls like http://www.example.com
if (slashedProtocol[result.protocol] &&
result.hostname && !result.pathname) {
result.path = result.pathname = '/';
}
result.href = result.format();
return result;
}
if (relative.protocol && relative.protocol !== result.protocol) {
// if it's a known url protocol, then changing
// the protocol does weird things
// first, if it's not file:, then we MUST have a host,
// and if there was a path
// to begin with, then we MUST have a path.
// if it is file:, then the host is dropped,
// because that's known to be hostless.
// anything else is assumed to be absolute.
if (!slashedProtocol[relative.protocol]) {
var keys = Object.keys(relative);
for (var v = 0; v < keys.length; v++) {
var k = keys[v];
result[k] = relative[k];
}
result.href = result.format();
return result;
}
result.protocol = relative.protocol;
if (!relative.host && !hostlessProtocol[relative.protocol]) {
var relPath = (relative.pathname || '').split('/');
while (relPath.length && !(relative.host = relPath.shift()));
if (!relative.host) relative.host = '';
if (!relative.hostname) relative.hostname = '';
if (relPath[0] !== '') relPath.unshift('');
if (relPath.length < 2) relPath.unshift('');
result.pathname = relPath.join('/');
} else {
result.pathname = relative.pathname;
}
result.search = relative.search;
result.query = relative.query;
result.host = relative.host || '';
result.auth = relative.auth;
result.hostname = relative.hostname || relative.host;
result.port = relative.port;
// to support http.request
if (result.pathname || result.search) {
var p = result.pathname || '';
var s = result.search || '';
result.path = p + s;
}
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
}
var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
isRelAbs = (
relative.host ||
relative.pathname && relative.pathname.charAt(0) === '/'
),
mustEndAbs = (isRelAbs || isSourceAbs ||
(result.host && relative.pathname)),
removeAllDots = mustEndAbs,
srcPath = result.pathname && result.pathname.split('/') || [],
relPath = relative.pathname && relative.pathname.split('/') || [],
psychotic = result.protocol && !slashedProtocol[result.protocol];
// if the url is a non-slashed url, then relative
// links like ../.. should be able
// to crawl up to the hostname, as well. This is strange.
// result.protocol has already been set by now.
// Later on, put the first path part into the host field.
if (psychotic) {
result.hostname = '';
result.port = null;
if (result.host) {
if (srcPath[0] === '') srcPath[0] = result.host;
else srcPath.unshift(result.host);
}
result.host = '';
if (relative.protocol) {
relative.hostname = null;
relative.port = null;
if (relative.host) {
if (relPath[0] === '') relPath[0] = relative.host;
else relPath.unshift(relative.host);
}
relative.host = null;
}
mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
}
if (isRelAbs) {
// it's absolute.
result.host = (relative.host || relative.host === '') ?
relative.host : result.host;
result.hostname = (relative.hostname || relative.hostname === '') ?
relative.hostname : result.hostname;
result.search = relative.search;
result.query = relative.query;
srcPath = relPath;
// fall through to the dot-handling below.
} else if (relPath.length) {
// it's relative
// throw away the existing file, and take the new path instead.
if (!srcPath) srcPath = [];
srcPath.pop();
srcPath = srcPath.concat(relPath);
result.search = relative.search;
result.query = relative.query;
} else if (!util.isNullOrUndefined(relative.search)) {
// just pull out the search.
// like href='?foo'.
// Put this after the other two cases because it simplifies the booleans
if (psychotic) {
result.hostname = result.host = srcPath.shift();
//occationaly the auth can get stuck only in host
//this especially happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ?
result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
result.search = relative.search;
result.query = relative.query;
//to support http.request
if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.href = result.format();
return result;
}
if (!srcPath.length) {
// no path at all. easy.
// we've already handled the other stuff above.
result.pathname = null;
//to support http.request
if (result.search) {
result.path = '/' + result.search;
} else {
result.path = null;
}
result.href = result.format();
return result;
}
// if a url ENDs in . or .., then it must get a trailing slash.
// however, if it ends in anything else non-slashy,
// then it must NOT get a trailing slash.
var last = srcPath.slice(-1)[0];
var hasTrailingSlash = (
(result.host || relative.host || srcPath.length > 1) &&
(last === '.' || last === '..') || last === '');
// strip single dots, resolve double dots to parent dir
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = srcPath.length; i >= 0; i--) {
last = srcPath[i];
if (last === '.') {
srcPath.splice(i, 1);
} else if (last === '..') {
srcPath.splice(i, 1);
up++;
} else if (up) {
srcPath.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (!mustEndAbs && !removeAllDots) {
for (; up--; up) {
srcPath.unshift('..');
}
}
if (mustEndAbs && srcPath[0] !== '' &&
(!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
srcPath.unshift('');
}
if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
srcPath.push('');
}
var isAbsolute = srcPath[0] === '' ||
(srcPath[0] && srcPath[0].charAt(0) === '/');
// put the host back
if (psychotic) {
result.hostname = result.host = isAbsolute ? '' :
srcPath.length ? srcPath.shift() : '';
//occationaly the auth can get stuck only in host
//this especially happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ?
result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
mustEndAbs = mustEndAbs || (result.host && srcPath.length);
if (mustEndAbs && !isAbsolute) {
srcPath.unshift('');
}
if (!srcPath.length) {
result.pathname = null;
result.path = null;
} else {
result.pathname = srcPath.join('/');
}
//to support request.http
if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.auth = relative.auth || result.auth;
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
};
Url.prototype.parseHost = function() {
var host = this.host;
var port = portPattern.exec(host);
if (port) {
port = port[0];
if (port !== ':') {
this.port = port.substr(1);
}
host = host.substr(0, host.length - port.length);
}
if (host) this.hostname = host;
};
},{"./util":41,"punycode":30,"querystring":33}],41:[function(require,module,exports){
'use strict';
module.exports = {
isString: function(arg) {
return typeof(arg) === 'string';
},
isObject: function(arg) {
return typeof(arg) === 'object' && arg !== null;
},
isNull: function(arg) {
return arg === null;
},
isNullOrUndefined: function(arg) {
return arg == null;
}
};
},{}],42:[function(require,module,exports){
arguments[4][17][0].apply(exports,arguments)
},{"dup":17}],43:[function(require,module,exports){
(function (process,global,Buffer){
module.exports = createTorrent
module.exports.parseInput = parseInput
module.exports.announceList = [
[ 'udp://tracker.openbittorrent.com:80' ],
[ 'udp://tracker.internetwarriors.net:1337' ],
[ 'udp://tracker.leechers-paradise.org:6969' ],
[ 'udp://tracker.coppersurfer.tk:6969' ],
[ 'udp://exodus.desync.com:6969' ],
[ 'wss://tracker.btorrent.xyz' ],
[ 'wss://tracker.openwebtorrent.com' ],
[ 'wss://tracker.fastcast.nz' ]
]
var bencode = require('bencode')
var BlockStream = require('block-stream2')
var calcPieceLength = require('piece-length')
var corePath = require('path')
var extend = require('xtend')
var FileReadStream = require('filestream/read')
var flatten = require('flatten')
var fs = require('fs')
var isFile = require('is-file')
var junk = require('junk')
var MultiStream = require('multistream')
var once = require('once')
var parallel = require('run-parallel')
var sha1 = require('simple-sha1')
var stream = require('readable-stream')
/**
* Create a torrent.
* @param {string|File|FileList|Buffer|Stream|Array.<string|File|Buffer|Stream>} input
* @param {Object} opts
* @param {string=} opts.name
* @param {Date=} opts.creationDate
* @param {string=} opts.comment
* @param {string=} opts.createdBy
* @param {boolean|number=} opts.private
* @param {number=} opts.pieceLength
* @param {Array.<Array.<string>>=} opts.announceList
* @param {Array.<string>=} opts.urlList
* @param {function} cb
* @return {Buffer} buffer of .torrent file data
*/
function createTorrent (input, opts, cb) {
if (typeof opts === 'function') return createTorrent(input, null, opts)
opts = opts ? extend(opts) : {}
_parseInput(input, opts, function (err, files, singleFileTorrent) {
if (err) return cb(err)
opts.singleFileTorrent = singleFileTorrent
onFiles(files, opts, cb)
})
}
function parseInput (input, opts, cb) {
if (typeof opts === 'function') return parseInput(input, null, opts)
opts = opts ? extend(opts) : {}
_parseInput(input, opts, cb)
}
/**
* Parse input file and return file information.
*/
function _parseInput (input, opts, cb) {
if (Array.isArray(input) && input.length === 0) throw new Error('invalid input type')
if (isFileList(input)) input = Array.prototype.slice.call(input)
if (!Array.isArray(input)) input = [ input ]
// In Electron, use the true file path
input = input.map(function (item) {
if (isBlob(item) && typeof item.path === 'string' && typeof fs.stat === 'function') return item.path
return item
})
// If there's just one file, allow the name to be set by `opts.name`
if (input.length === 1 && typeof input[0] !== 'string' && !input[0].name) input[0].name = opts.name
var commonPrefix = null
input.forEach(function (item, i) {
if (typeof item === 'string') {
return
}
var path = item.fullPath || item.name
if (!path) {
path = 'Unknown File ' + (i + 1)
item.unknownName = true
}
item.path = path.split('/')
// Remove initial slash
if (!item.path[0]) {
item.path.shift()
}
if (item.path.length < 2) { // No real prefix
commonPrefix = null
} else if (i === 0 && input.length > 1) { // The first file has a prefix
commonPrefix = item.path[0]
} else if (item.path[0] !== commonPrefix) { // The prefix doesn't match
commonPrefix = null
}
})
// remove junk files
input = input.filter(function (item) {
if (typeof item === 'string') {
return true
}
var filename = item.path[item.path.length - 1]
return notHidden(filename) && junk.not(filename)
})
if (commonPrefix) {
input.forEach(function (item) {
var pathless = (Buffer.isBuffer(item) || isReadable(item)) && !item.path
if (typeof item === 'string' || pathless) return
item.path.shift()
})
}
if (!opts.name && commonPrefix) {
opts.name = commonPrefix
}
if (!opts.name) {
// use first user-set file name
input.some(function (item) {
if (typeof item === 'string') {
opts.name = corePath.basename(item)
return true
} else if (!item.unknownName) {
opts.name = item.path[item.path.length - 1]
return true
}
})
}
if (!opts.name) {
opts.name = 'Unnamed Torrent ' + Date.now()
}
var numPaths = input.reduce(function (sum, item) {
return sum + Number(typeof item === 'string')
}, 0)
var isSingleFileTorrent = (input.length === 1)
if (input.length === 1 && typeof input[0] === 'string') {
if (typeof fs.stat !== 'function') {
throw new Error('filesystem paths do not work in the browser')
}
// If there's a single path, verify it's a file before deciding this is a single
// file torrent
isFile(input[0], function (err, pathIsFile) {
if (err) return cb(err)
isSingleFileTorrent = pathIsFile
processInput()
})
} else {
process.nextTick(function () {
processInput()
})
}
function processInput () {
parallel(input.map(function (item) {
return function (cb) {
var file = {}
if (isBlob(item)) {
file.getStream = getBlobStream(item)
file.length = item.size
} else if (Buffer.isBuffer(item)) {
file.getStream = getBufferStream(item)
file.length = item.length
} else if (isReadable(item)) {
file.getStream = getStreamStream(item, file)
file.length = 0
} else if (typeof item === 'string') {
if (typeof fs.stat !== 'function') {
throw new Error('filesystem paths do not work in the browser')
}
var keepRoot = numPaths > 1 || isSingleFileTorrent
getFiles(item, keepRoot, cb)
return // early return!
} else {
throw new Error('invalid input type')
}
file.path = item.path
cb(null, file)
}
}), function (err, files) {
if (err) return cb(err)
files = flatten(files)
cb(null, files, isSingleFileTorrent)
})
}
}
function getFiles (path, keepRoot, cb) {
traversePath(path, getFileInfo, function (err, files) {
if (err) return cb(err)
if (Array.isArray(files)) files = flatten(files)
else files = [ files ]
path = corePath.normalize(path)
if (keepRoot) {
path = path.slice(0, path.lastIndexOf(corePath.sep) + 1)
}
if (path[path.length - 1] !== corePath.sep) path += corePath.sep
files.forEach(function (file) {
file.getStream = getFilePathStream(file.path)
file.path = file.path.replace(path, '').split(corePath.sep)
})
cb(null, files)
})
}
function getFileInfo (path, cb) {
cb = once(cb)
fs.stat(path, function (err, stat) {
if (err) return cb(err)
var info = {
length: stat.size,
path: path
}
cb(null, info)
})
}
function traversePath (path, fn, cb) {
fs.readdir(path, function (err, entries) {
if (err && err.code === 'ENOTDIR') {
// this is a file
fn(path, cb)
} else if (err) {
// real error
cb(err)
} else {
// this is a folder
parallel(entries.filter(notHidden).filter(junk.not).map(function (entry) {
return function (cb) {
traversePath(corePath.join(path, entry), fn, cb)
}
}), cb)
}
})
}
function notHidden (file) {
return file[0] !== '.'
}
function getPieceList (files, pieceLength, cb) {
cb = once(cb)
var pieces = []
var length = 0
var streams = files.map(function (file) {
return file.getStream
})
var remainingHashes = 0
var pieceNum = 0
var ended = false
var multistream = new MultiStream(streams)
var blockstream = new BlockStream(pieceLength, { zeroPadding: false })
multistream.on('error', onError)
multistream
.pipe(blockstream)
.on('data', onData)
.on('end', onEnd)
.on('error', onError)
function onData (chunk) {
length += chunk.length
var i = pieceNum
sha1(chunk, function (hash) {
pieces[i] = hash
remainingHashes -= 1
maybeDone()
})
remainingHashes += 1
pieceNum += 1
}
function onEnd () {
ended = true
maybeDone()
}
function onError (err) {
cleanup()
cb(err)
}
function cleanup () {
multistream.removeListener('error', onError)
blockstream.removeListener('data', onData)
blockstream.removeListener('end', onEnd)
blockstream.removeListener('error', onError)
}
function maybeDone () {
if (ended && remainingHashes === 0) {
cleanup()
cb(null, new Buffer(pieces.join(''), 'hex'), length)
}
}
}
function onFiles (files, opts, cb) {
var announceList = opts.announceList
if (!announceList) {
if (typeof opts.announce === 'string') announceList = [ [ opts.announce ] ]
else if (Array.isArray(opts.announce)) {
announceList = opts.announce.map(function (u) { return [ u ] })
}
}
if (!announceList) announceList = []
if (global.WEBTORRENT_ANNOUNCE) {
if (typeof global.WEBTORRENT_ANNOUNCE === 'string') {
announceList.push([ [ global.WEBTORRENT_ANNOUNCE ] ])
} else if (Array.isArray(global.WEBTORRENT_ANNOUNCE)) {
announceList = announceList.concat(global.WEBTORRENT_ANNOUNCE.map(function (u) {
return [ u ]
}))
}
}
// When no trackers specified, use some reasonable defaults
if (opts.announce === undefined && opts.announceList === undefined) {
announceList = announceList.concat(module.exports.announceList)
}
if (typeof opts.urlList === 'string') opts.urlList = [ opts.urlList ]
var torrent = {
info: {
name: opts.name
},
'creation date': Math.ceil((Number(opts.creationDate) || Date.now()) / 1000),
encoding: 'UTF-8'
}
if (announceList.length !== 0) {
torrent.announce = announceList[0][0]
torrent['announce-list'] = announceList
}
if (opts.comment !== undefined) torrent.comment = opts.comment
if (opts.createdBy !== undefined) torrent['created by'] = opts.createdBy
if (opts.private !== undefined) torrent.info.private = Number(opts.private)
// "ssl-cert" key is for SSL torrents, see:
// - http://blog.libtorrent.org/2012/01/bittorrent-over-ssl/
// - http://www.libtorrent.org/manual-ref.html#ssl-torrents
// - http://www.libtorrent.org/reference-Create_Torrents.html
if (opts.sslCert !== undefined) torrent.info['ssl-cert'] = opts.sslCert
if (opts.urlList !== undefined) torrent['url-list'] = opts.urlList
var pieceLength = opts.pieceLength || calcPieceLength(files.reduce(sumLength, 0))
torrent.info['piece length'] = pieceLength
getPieceList(files, pieceLength, function (err, pieces, torrentLength) {
if (err) return cb(err)
torrent.info.pieces = pieces
files.forEach(function (file) {
delete file.getStream
})
if (opts.singleFileTorrent) {
torrent.info.length = torrentLength
} else {
torrent.info.files = files
}
cb(null, bencode.encode(torrent))
})
}
/**
* Accumulator to sum file lengths
* @param {number} sum
* @param {Object} file
* @return {number}
*/
function sumLength (sum, file) {
return sum + file.length
}
/**
* Check if `obj` is a W3C `Blob` object (which `File` inherits from)
* @param {*} obj
* @return {boolean}
*/
function isBlob (obj) {
return typeof Blob !== 'undefined' && obj instanceof Blob
}
/**
* Check if `obj` is a W3C `FileList` object
* @param {*} obj
* @return {boolean}
*/
function isFileList (obj) {
return typeof FileList !== 'undefined' && obj instanceof FileList
}
/**
* Check if `obj` is a node Readable stream
* @param {*} obj
* @return {boolean}
*/
function isReadable (obj) {
return typeof obj === 'object' && obj != null && typeof obj.pipe === 'function'
}
/**
* Convert a `File` to a lazy readable stream.
* @param {File|Blob} file
* @return {function}
*/
function getBlobStream (file) {
return function () {
return new FileReadStream(file)
}
}
/**
* Convert a `Buffer` to a lazy readable stream.
* @param {Buffer} buffer
* @return {function}
*/
function getBufferStream (buffer) {
return function () {
var s = new stream.PassThrough()
s.end(buffer)
return s
}
}
/**
* Convert a file path to a lazy readable stream.
* @param {string} path
* @return {function}
*/
function getFilePathStream (path) {
return function () {
return fs.createReadStream(path)
}
}
/**
* Convert a readable stream to a lazy readable stream. Adds instrumentation to track
* the number of bytes in the stream and set `file.length`.
*
* @param {Stream} stream
* @param {Object} file
* @return {function}
*/
function getStreamStream (readable, file) {
return function () {
var counter = new stream.Transform()
counter._transform = function (buf, enc, done) {
file.length += buf.length
this.push(buf)
done()
}
readable.pipe(counter)
return counter
}
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
},{"_process":29,"bencode":46,"block-stream2":47,"buffer":21,"filestream/read":51,"flatten":52,"fs":19,"is-file":53,"junk":54,"multistream":74,"once":56,"path":28,"piece-length":57,"readable-stream":112,"run-parallel":59,"simple-sha1":60,"xtend":62}],44:[function(require,module,exports){
(function (Buffer){
/**
* Decodes bencoded data.
*
* @param {Buffer} data
* @param {Number} start (optional)
* @param {Number} end (optional)
* @param {String} encoding (optional)
* @return {Object|Array|Buffer|String|Number}
*/
function decode (data, start, end, encoding) {
if (typeof start !== 'number' && encoding == null) {
encoding = start
start = undefined
}
if (typeof end !== 'number' && encoding == null) {
encoding = end
end = undefined
}
decode.position = 0
decode.encoding = encoding || null
decode.data = !(Buffer.isBuffer(data))
? new Buffer(data)
: data.slice(start, end)
decode.bytes = decode.data.length
return decode.next()
}
decode.bytes = 0
decode.position = 0
decode.data = null
decode.encoding = null
decode.next = function () {
switch (decode.data[decode.position]) {
case 0x64:
return decode.dictionary()
case 0x6C:
return decode.list()
case 0x69:
return decode.integer()
default:
return decode.buffer()
}
}
decode.find = function (chr) {
var i = decode.position
var c = decode.data.length
var d = decode.data
while (i < c) {
if (d[i] === chr) return i
i++
}
throw new Error(
'Invalid data: Missing delimiter "' +
String.fromCharCode(chr) + '" [0x' +
chr.toString(16) + ']'
)
}
decode.dictionary = function () {
decode.position++
var dict = {}
while (decode.data[decode.position] !== 0x65) {
dict[decode.buffer()] = decode.next()
}
decode.position++
return dict
}
decode.list = function () {
decode.position++
var lst = []
while (decode.data[decode.position] !== 0x65) {
lst.push(decode.next())
}
decode.position++
return lst
}
decode.integer = function () {
var end = decode.find(0x65)
var number = decode.data.toString('ascii', decode.position + 1, end)
decode.position += end + 1 - decode.position
return parseInt(number, 10)
}
decode.buffer = function () {
var sep = decode.find(0x3A)
var length = parseInt(decode.data.toString('ascii', decode.position, sep), 10)
var end = ++sep + length
decode.position = end
return decode.encoding
? decode.data.toString(decode.encoding, sep, end)
: decode.data.slice(sep, end)
}
module.exports = decode
}).call(this,require("buffer").Buffer)
},{"buffer":21}],45:[function(require,module,exports){
(function (Buffer){
/**
* Encodes data in bencode.
*
* @param {Buffer|Array|String|Object|Number|Boolean} data
* @return {Buffer}
*/
function encode (data, buffer, offset) {
var buffers = []
var result = null
encode._encode(buffers, data)
result = Buffer.concat(buffers)
encode.bytes = result.length
if (Buffer.isBuffer(buffer)) {
result.copy(buffer, offset)
return buffer
}
return result
}
encode.bytes = -1
encode._floatConversionDetected = false
encode._encode = function (buffers, data) {
if (Buffer.isBuffer(data)) {
buffers.push(new Buffer(data.length + ':'))
buffers.push(data)
return
}
switch (typeof data) {
case 'string':
encode.buffer(buffers, data)
break
case 'number':
encode.number(buffers, data)
break
case 'object':
data.constructor === Array
? encode.list(buffers, data)
: encode.dict(buffers, data)
break
case 'boolean':
encode.number(buffers, data ? 1 : 0)
break
}
}
var buffE = new Buffer('e')
var buffD = new Buffer('d')
var buffL = new Buffer('l')
encode.buffer = function (buffers, data) {
buffers.push(new Buffer(Buffer.byteLength(data) + ':' + data))
}
encode.number = function (buffers, data) {
var maxLo = 0x80000000
var hi = (data / maxLo) << 0
var lo = (data % maxLo) << 0
var val = hi * maxLo + lo
buffers.push(new Buffer('i' + val + 'e'))
if (val !== data && !encode._floatConversionDetected) {
encode._floatConversionDetected = true
console.warn(
'WARNING: Possible data corruption detected with value "' + data + '":',
'Bencoding only defines support for integers, value was converted to "' + val + '"'
)
console.trace()
}
}
encode.dict = function (buffers, data) {
buffers.push(buffD)
var j = 0
var k
// fix for issue #13 - sorted dicts
var keys = Object.keys(data).sort()
var kl = keys.length
for (; j < kl; j++) {
k = keys[j]
encode.buffer(buffers, k)
encode._encode(buffers, data[k])
}
buffers.push(buffE)
}
encode.list = function (buffers, data) {
var i = 0
var c = data.length
buffers.push(buffL)
for (; i < c; i++) {
encode._encode(buffers, data[i])
}
buffers.push(buffE)
}
module.exports = encode
}).call(this,require("buffer").Buffer)
},{"buffer":21}],46:[function(require,module,exports){
var bencode = module.exports
bencode.encode = require('./encode')
bencode.decode = require('./decode')
/**
* Determines the amount of bytes
* needed to encode the given value
* @param {Object|Array|Buffer|String|Number|Boolean} value
* @return {Number} byteCount
*/
bencode.byteLength = bencode.encodingLength = function (value) {
return bencode.encode(value).length
}
},{"./decode":44,"./encode":45}],47:[function(require,module,exports){
(function (Buffer){
var inherits = require('inherits');
var Transform = require('readable-stream').Transform;
var defined = require('defined');
module.exports = Block;
inherits(Block, Transform);
function Block (size, opts) {
if (!(this instanceof Block)) return new Block(size, opts);
Transform.call(this);
if (!opts) opts = {};
if (typeof size === 'object') {
opts = size;
size = opts.size;
}
this.size = size || 512;
if (opts.nopad) this._zeroPadding = false;
else this._zeroPadding = defined(opts.zeroPadding, true);
this._buffered = [];
this._bufferedBytes = 0;
}
Block.prototype._transform = function (buf, enc, next) {
this._bufferedBytes += buf.length;
this._buffered.push(buf);
while (this._bufferedBytes >= this.size) {
var b = Buffer.concat(this._buffered);
this._bufferedBytes -= this.size;
this.push(b.slice(0, this.size));
this._buffered = [ b.slice(this.size, b.length) ];
}
next();
};
Block.prototype._flush = function () {
if (this._bufferedBytes && this._zeroPadding) {
var zeroes = new Buffer(this.size - this._bufferedBytes);
zeroes.fill(0);
this._buffered.push(zeroes);
this.push(Buffer.concat(this._buffered));
this._buffered = null;
}
else if (this._bufferedBytes) {
this.push(Buffer.concat(this._buffered));
this._buffered = null;
}
this.push(null);
};
}).call(this,require("buffer").Buffer)
},{"buffer":21,"defined":48,"inherits":63,"readable-stream":112}],48:[function(require,module,exports){
module.exports = function () {
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] !== undefined) return arguments[i];
}
};
},{}],49:[function(require,module,exports){
(function (Buffer){
/**
* Convert a typed array to a Buffer without a copy
*
* Author: Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* License: MIT
*
* `npm install typedarray-to-buffer`
*/
var isTypedArray = require('is-typedarray').strict
module.exports = function typedarrayToBuffer (arr) {
if (isTypedArray(arr)) {
// To avoid a copy, use the typed array's underlying ArrayBuffer to back new Buffer
var buf = new Buffer(arr.buffer)
if (arr.byteLength !== arr.buffer.byteLength) {
// Respect the "view", i.e. byteOffset and byteLength, without doing a copy
buf = buf.slice(arr.byteOffset, arr.byteOffset + arr.byteLength)
}
return buf
} else {
// Pass through all other types to the `Buffer` constructor
return new Buffer(arr)
}
}
}).call(this,require("buffer").Buffer)
},{"buffer":21,"is-typedarray":50}],50:[function(require,module,exports){
module.exports = isTypedArray
isTypedArray.strict = isStrictTypedArray
isTypedArray.loose = isLooseTypedArray
var toString = Object.prototype.toString
var names = {
'[object Int8Array]': true
, '[object Int16Array]': true
, '[object Int32Array]': true
, '[object Uint8Array]': true
, '[object Uint8ClampedArray]': true
, '[object Uint16Array]': true
, '[object Uint32Array]': true
, '[object Float32Array]': true
, '[object Float64Array]': true
}
function isTypedArray(arr) {
return (
isStrictTypedArray(arr)
|| isLooseTypedArray(arr)
)
}
function isStrictTypedArray(arr) {
return (
arr instanceof Int8Array
|| arr instanceof Int16Array
|| arr instanceof Int32Array
|| arr instanceof Uint8Array
|| arr instanceof Uint8ClampedArray
|| arr instanceof Uint16Array
|| arr instanceof Uint32Array
|| arr instanceof Float32Array
|| arr instanceof Float64Array
)
}
function isLooseTypedArray(arr) {
return names[toString.call(arr)]
}
},{}],51:[function(require,module,exports){
var Readable = require('readable-stream').Readable;
var inherits = require('inherits');
var reExtension = /^.*\.(\w+)$/;
var toBuffer = require('typedarray-to-buffer');
function FileReadStream(file, opts) {
var readStream = this;
if (! (this instanceof FileReadStream)) {
return new FileReadStream(file, opts);
}
opts = opts || {};
// inherit readable
Readable.call(this, opts);
// save the read offset
this._offset = 0;
this._ready = false;
this._file = file;
this._size = file.size;
this._chunkSize = opts.chunkSize || Math.max(this._size / 1000, 200 * 1024);
// create the reader
this.reader = new FileReader();
// generate the header blocks that we will send as part of the initial payload
this._generateHeaderBlocks(file, opts, function(err, blocks) {
// if we encountered an error, emit it
if (err) {
return readStream.emit('error', err);
}
// push the header blocks out to the stream
if (Array.isArray(blocks)) {
blocks.forEach(function (block) {
readStream.push(block);
});
}
readStream._ready = true;
readStream.emit('_ready');
});
}
inherits(FileReadStream, Readable);
module.exports = FileReadStream;
FileReadStream.prototype._generateHeaderBlocks = function(file, opts, callback) {
callback(null, []);
};
FileReadStream.prototype._read = function() {
if (!this._ready) {
this.once('_ready', this._read.bind(this));
return;
}
var readStream = this;
var reader = this.reader;
var startOffset = this._offset;
var endOffset = this._offset + this._chunkSize;
if (endOffset > this._size) endOffset = this._size;
if (startOffset === this._size) {
this.destroy();
this.push(null);
return;
}
reader.onload = function() {
// update the stream offset
readStream._offset = endOffset;
// get the data chunk
readStream.push(toBuffer(reader.result));
}
reader.onerror = function() {
readStream.emit('error', reader.error);
}
reader.readAsArrayBuffer(this._file.slice(startOffset, endOffset));
};
FileReadStream.prototype.destroy = function() {
this._file = null;
if (this.reader) {
this.reader.onload = null;
this.reader.onerror = null;
try { this.reader.abort(); } catch (e) {};
}
this.reader = null;
}
},{"inherits":63,"readable-stream":112,"typedarray-to-buffer":49}],52:[function(require,module,exports){
module.exports = function flatten(list, depth) {
depth = (typeof depth == 'number') ? depth : Infinity;
if (!depth) {
if (Array.isArray(list)) {
return list.map(function(i) { return i; });
}
return list;
}
return _flatten(list, 1);
function _flatten(list, d) {
return list.reduce(function (acc, item) {
if (Array.isArray(item) && d < depth) {
return acc.concat(_flatten(item, d + 1));
}
else {
return acc.concat(item);
}
}, []);
}
};
},{}],53:[function(require,module,exports){
'use strict';
var fs = require('fs');
module.exports = function isFile(path, cb){
if(!cb)return isFileSync(path);
fs.stat(path, function(err, stats){
if(err)return cb(err);
return cb(null, stats.isFile());
});
};
module.exports.sync = isFileSync;
function isFileSync(path){
return fs.existsSync(path) && fs.statSync(path).isFile();
}
},{"fs":19}],54:[function(require,module,exports){
'use strict';
// // All
// /^npm-debug\.log$/, // npm error log
// /^\..*\.swp$/, // vim state
// // macOS
// /^\.DS_Store$/, // stores custom folder attributes
// /^\.AppleDouble$/, // stores additional file resources
// /^\.LSOverride$/, // contains the absolute path to the app to be used
// /^Icon\r$/, // custom Finder icon: http://superuser.com/questions/298785/icon-file-on-os-x-desktop
// /^\._.*/, // thumbnail
// /^\.Spotlight-V100$/, // file that might appear on external disk
// /\.Trashes/, // file that might appear on external disk
// /^__MACOSX$/, // resource fork
// // Linux
// /~$/, // backup file
// // Windows
// /^Thumbs\.db$/, // image file cache
// /^ehthumbs\.db$/, // folder config file
// /^Desktop\.ini$/ // stores custom folder attributes
exports.re = /^npm-debug\.log$|^\..*\.swp$|^\.DS_Store$|^\.AppleDouble$|^\.LSOverride$|^Icon\r$|^\._.*|^\.Spotlight-V100$|\.Trashes|^__MACOSX$|~$|^Thumbs\.db$|^ehthumbs\.db$|^Desktop\.ini$/;
exports.is = function (filename) {
return exports.re.test(filename);
};
exports.not = exports.isnt = function (filename) {
return !exports.is(filename);
};
},{}],55:[function(require,module,exports){
arguments[4][10][0].apply(exports,arguments)
},{"dup":10}],56:[function(require,module,exports){
arguments[4][11][0].apply(exports,arguments)
},{"dup":11,"wrappy":55}],57:[function(require,module,exports){
var closest = require('closest-to')
// Create a range from 16kb–4mb
var sizes = []
for (var i = 14; i <= 22; i++) {
sizes.push(Math.pow(2, i))
}
module.exports = function(size) {
return closest(
size / Math.pow(2, 10), sizes
)
}
},{"closest-to":58}],58:[function(require,module,exports){
module.exports = function(target, numbers) {
var closest = Infinity
var difference = 0
var winner = null
numbers.sort(function(a, b) {
return a - b
})
for (var i = 0, l = numbers.length; i < l; i++) {
difference = Math.abs(target - numbers[i])
if (difference >= closest) {
break
}
closest = difference
winner = numbers[i]
}
return winner
}
},{}],59:[function(require,module,exports){
(function (process){
module.exports = function (tasks, cb) {
var results, pending, keys
var isSync = true
if (Array.isArray(tasks)) {
results = []
pending = tasks.length
} else {
keys = Object.keys(tasks)
results = {}
pending = keys.length
}
function done (err) {
function end () {
if (cb) cb(err, results)
cb = null
}
if (isSync) process.nextTick(end)
else end()
}
function each (i, err, result) {
results[i] = result
if (--pending === 0 || err) {
done(err)
}
}
if (!pending) {
// empty
done(null)
} else if (keys) {
// object
keys.forEach(function (key) {
tasks[key](function (err, result) { each(key, err, result) })
})
} else {
// array
tasks.forEach(function (task, i) {
task(function (err, result) { each(i, err, result) })
})
}
isSync = false
}
}).call(this,require('_process'))
},{"_process":29}],60:[function(require,module,exports){
var Rusha = require('rusha')
var rusha = new Rusha
var crypto = window.crypto || window.msCrypto || {}
var subtle = crypto.subtle || crypto.webkitSubtle
function sha1sync (buf) {
return rusha.digest(buf)
}
// Browsers throw if they lack support for an algorithm.
// Promise will be rejected on non-secure origins. (http://goo.gl/lq4gCo)
try {
subtle.digest({ name: 'sha-1' }, new Uint8Array).catch(function () {
subtle = false
})
} catch (err) { subtle = false }
function sha1 (buf, cb) {
if (!subtle) {
// Use Rusha
setTimeout(cb, 0, sha1sync(buf))
return
}
if (typeof buf === 'string') {
buf = uint8array(buf)
}
subtle.digest({ name: 'sha-1' }, buf)
.then(function succeed (result) {
cb(hex(new Uint8Array(result)))
},
function fail (error) {
cb(sha1sync(buf))
})
}
function uint8array (s) {
var l = s.length
var array = new Uint8Array(l)
for (var i = 0; i < l; i++) {
array[i] = s.charCodeAt(i)
}
return array
}
function hex (buf) {
var l = buf.length
var chars = []
for (var i = 0; i < l; i++) {
var bite = buf[i]
chars.push((bite >>> 4).toString(16))
chars.push((bite & 0x0f).toString(16))
}
return chars.join('')
}
module.exports = sha1
module.exports.sync = sha1sync
},{"rusha":61}],61:[function(require,module,exports){
(function (global){
(function () {
var /*
* Rusha, a JavaScript implementation of the Secure Hash Algorithm, SHA-1,
* as defined in FIPS PUB 180-1, tuned for high performance with large inputs.
* (http://github.com/srijs/rusha)
*
* Inspired by Paul Johnstons implementation (http://pajhome.org.uk/crypt/md5).
*
* Copyright (c) 2013 Sam Rijs (http://awesam.de).
* Released under the terms of the MIT license as follows:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
util = {
getDataType: function (data) {
if (typeof data === 'string') {
return 'string';
}
if (data instanceof Array) {
return 'array';
}
if (typeof global !== 'undefined' && global.Buffer && global.Buffer.isBuffer(data)) {
return 'buffer';
}
if (data instanceof ArrayBuffer) {
return 'arraybuffer';
}
if (data.buffer instanceof ArrayBuffer) {
return 'view';
}
if (data instanceof Blob) {
return 'blob';
}
throw new Error('Unsupported data type.');
}
};
function Rusha(chunkSize) {
'use strict';
var // Private object structure.
self$2 = { fill: 0 };
var // Calculate the length of buffer that the sha1 routine uses
// including the padding.
padlen = function (len) {
for (len += 9; len % 64 > 0; len += 1);
return len;
};
var padZeroes = function (bin, len) {
for (var i$2 = len >> 2; i$2 < bin.length; i$2++)
bin[i$2] = 0;
};
var padData = function (bin, chunkLen, msgLen) {
bin[chunkLen >> 2] |= 128 << 24 - (chunkLen % 4 << 3);
// To support msgLen >= 2 GiB, use a float division when computing the
// high 32-bits of the big-endian message length in bits.
bin[((chunkLen >> 2) + 2 & ~15) + 14] = msgLen / (1 << 29) | 0;
bin[((chunkLen >> 2) + 2 & ~15) + 15] = msgLen << 3;
};
var // Convert a binary string and write it to the heap.
// A binary string is expected to only contain char codes < 256.
convStr = function (H8, H32, start, len, off) {
var str = this, i$2, om = off % 4, lm = len % 4, j = len - lm;
if (j > 0) {
switch (om) {
case 0:
H8[off + 3 | 0] = str.charCodeAt(start);
case 1:
H8[off + 2 | 0] = str.charCodeAt(start + 1);
case 2:
H8[off + 1 | 0] = str.charCodeAt(start + 2);
case 3:
H8[off | 0] = str.charCodeAt(start + 3);
}
}
for (i$2 = om; i$2 < j; i$2 = i$2 + 4 | 0) {
H32[off + i$2 >> 2] = str.charCodeAt(start + i$2) << 24 | str.charCodeAt(start + i$2 + 1) << 16 | str.charCodeAt(start + i$2 + 2) << 8 | str.charCodeAt(start + i$2 + 3);
}
switch (lm) {
case 3:
H8[off + j + 1 | 0] = str.charCodeAt(start + j + 2);
case 2:
H8[off + j + 2 | 0] = str.charCodeAt(start + j + 1);
case 1:
H8[off + j + 3 | 0] = str.charCodeAt(start + j);
}
};
var // Convert a buffer or array and write it to the heap.
// The buffer or array is expected to only contain elements < 256.
convBuf = function (H8, H32, start, len, off) {
var buf = this, i$2, om = off % 4, lm = len % 4, j = len - lm;
if (j > 0) {
switch (om) {
case 0:
H8[off + 3 | 0] = buf[start];
case 1:
H8[off + 2 | 0] = buf[start + 1];
case 2:
H8[off + 1 | 0] = buf[start + 2];
case 3:
H8[off | 0] = buf[start + 3];
}
}
for (i$2 = 4 - om; i$2 < j; i$2 = i$2 += 4 | 0) {
H32[off + i$2 >> 2] = buf[start + i$2] << 24 | buf[start + i$2 + 1] << 16 | buf[start + i$2 + 2] << 8 | buf[start + i$2 + 3];
}
switch (lm) {
case 3:
H8[off + j + 1 | 0] = buf[start + j + 2];
case 2:
H8[off + j + 2 | 0] = buf[start + j + 1];
case 1:
H8[off + j + 3 | 0] = buf[start + j];
}
};
var convBlob = function (H8, H32, start, len, off) {
var blob = this, i$2, om = off % 4, lm = len % 4, j = len - lm;
var buf = new Uint8Array(reader.readAsArrayBuffer(blob.slice(start, start + len)));
if (j > 0) {
switch (om) {
case 0:
H8[off + 3 | 0] = buf[0];
case 1:
H8[off + 2 | 0] = buf[1];
case 2:
H8[off + 1 | 0] = buf[2];
case 3:
H8[off | 0] = buf[3];
}
}
for (i$2 = 4 - om; i$2 < j; i$2 = i$2 += 4 | 0) {
H32[off + i$2 >> 2] = buf[i$2] << 24 | buf[i$2 + 1] << 16 | buf[i$2 + 2] << 8 | buf[i$2 + 3];
}
switch (lm) {
case 3:
H8[off + j + 1 | 0] = buf[j + 2];
case 2:
H8[off + j + 2 | 0] = buf[j + 1];
case 1:
H8[off + j + 3 | 0] = buf[j];
}
};
var convFn = function (data) {
switch (util.getDataType(data)) {
case 'string':
return convStr.bind(data);
case 'array':
return convBuf.bind(data);
case 'buffer':
return convBuf.bind(data);
case 'arraybuffer':
return convBuf.bind(new Uint8Array(data));
case 'view':
return convBuf.bind(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
case 'blob':
return convBlob.bind(data);
}
};
var slice = function (data, offset) {
switch (util.getDataType(data)) {
case 'string':
return data.slice(offset);
case 'array':
return data.slice(offset);
case 'buffer':
return data.slice(offset);
case 'arraybuffer':
return data.slice(offset);
case 'view':
return data.buffer.slice(offset);
}
};
var // Precompute 00 - ff strings
precomputedHex = new Array(256);
for (var i = 0; i < 256; i++) {
precomputedHex[i] = (i < 16 ? '0' : '') + i.toString(16);
}
var // Convert an ArrayBuffer into its hexadecimal string representation.
hex = function (arrayBuffer) {
var binarray = new Uint8Array(arrayBuffer);
var res = new Array(arrayBuffer.byteLength);
for (var i$2 = 0; i$2 < res.length; i$2++) {
res[i$2] = precomputedHex[binarray[i$2]];
}
return res.join('');
};
var ceilHeapSize = function (v) {
// The asm.js spec says:
// The heap object's byteLength must be either
// 2^n for n in [12, 24) or 2^24 * n for n ≥ 1.
// Also, byteLengths smaller than 2^16 are deprecated.
var p;
if (// If v is smaller than 2^16, the smallest possible solution
// is 2^16.
v <= 65536)
return 65536;
if (// If v < 2^24, we round up to 2^n,
// otherwise we round up to 2^24 * n.
v < 16777216) {
for (p = 1; p < v; p = p << 1);
} else {
for (p = 16777216; p < v; p += 16777216);
}
return p;
};
var // Initialize the internal data structures to a new capacity.
init = function (size) {
if (size % 64 > 0) {
throw new Error('Chunk size must be a multiple of 128 bit');
}
self$2.maxChunkLen = size;
self$2.padMaxChunkLen = padlen(size);
// The size of the heap is the sum of:
// 1. The padded input message size
// 2. The extended space the algorithm needs (320 byte)
// 3. The 160 bit state the algoritm uses
self$2.heap = new ArrayBuffer(ceilHeapSize(self$2.padMaxChunkLen + 320 + 20));
self$2.h32 = new Int32Array(self$2.heap);
self$2.h8 = new Int8Array(self$2.heap);
self$2.core = new Rusha._core({
Int32Array: Int32Array,
DataView: DataView
}, {}, self$2.heap);
self$2.buffer = null;
};
// Iinitializethe datastructures according
// to a chunk siyze.
init(chunkSize || 64 * 1024);
var initState = function (heap, padMsgLen) {
var io = new Int32Array(heap, padMsgLen + 320, 5);
io[0] = 1732584193;
io[1] = -271733879;
io[2] = -1732584194;
io[3] = 271733878;
io[4] = -1009589776;
};
var padChunk = function (chunkLen, msgLen) {
var padChunkLen = padlen(chunkLen);
var view = new Int32Array(self$2.heap, 0, padChunkLen >> 2);
padZeroes(view, chunkLen);
padData(view, chunkLen, msgLen);
return padChunkLen;
};
var // Write data to the heap.
write = function (data, chunkOffset, chunkLen) {
convFn(data)(self$2.h8, self$2.h32, chunkOffset, chunkLen, 0);
};
var // Initialize and call the RushaCore,
// assuming an input buffer of length len * 4.
coreCall = function (data, chunkOffset, chunkLen, msgLen, finalize) {
var padChunkLen = chunkLen;
if (finalize) {
padChunkLen = padChunk(chunkLen, msgLen);
}
write(data, chunkOffset, chunkLen);
self$2.core.hash(padChunkLen, self$2.padMaxChunkLen);
};
var getRawDigest = function (heap, padMaxChunkLen) {
var io = new Int32Array(heap, padMaxChunkLen + 320, 5);
var out = new Int32Array(5);
var arr = new DataView(out.buffer);
arr.setInt32(0, io[0], false);
arr.setInt32(4, io[1], false);
arr.setInt32(8, io[2], false);
arr.setInt32(12, io[3], false);
arr.setInt32(16, io[4], false);
return out;
};
var // Calculate the hash digest as an array of 5 32bit integers.
rawDigest = this.rawDigest = function (str) {
var msgLen = str.byteLength || str.length || str.size || 0;
initState(self$2.heap, self$2.padMaxChunkLen);
var chunkOffset = 0, chunkLen = self$2.maxChunkLen, last;
for (chunkOffset = 0; msgLen > chunkOffset + chunkLen; chunkOffset += chunkLen) {
coreCall(str, chunkOffset, chunkLen, msgLen, false);
}
coreCall(str, chunkOffset, msgLen - chunkOffset, msgLen, true);
return getRawDigest(self$2.heap, self$2.padMaxChunkLen);
};
// The digest and digestFrom* interface returns the hash digest
// as a hex string.
this.digest = this.digestFromString = this.digestFromBuffer = this.digestFromArrayBuffer = function (str) {
return hex(rawDigest(str).buffer);
};
}
;
// The low-level RushCore module provides the heart of Rusha,
// a high-speed sha1 implementation working on an Int32Array heap.
// At first glance, the implementation seems complicated, however
// with the SHA1 spec at hand, it is obvious this almost a textbook
// implementation that has a few functions hand-inlined and a few loops
// hand-unrolled.
Rusha._core = function RushaCore(stdlib, foreign, heap) {
'use asm';
var H = new stdlib.Int32Array(heap);
function hash(k, x) {
// k in bytes
k = k | 0;
x = x | 0;
var i = 0, j = 0, y0 = 0, z0 = 0, y1 = 0, z1 = 0, y2 = 0, z2 = 0, y3 = 0, z3 = 0, y4 = 0, z4 = 0, t0 = 0, t1 = 0;
y0 = H[x + 320 >> 2] | 0;
y1 = H[x + 324 >> 2] | 0;
y2 = H[x + 328 >> 2] | 0;
y3 = H[x + 332 >> 2] | 0;
y4 = H[x + 336 >> 2] | 0;
for (i = 0; (i | 0) < (k | 0); i = i + 64 | 0) {
z0 = y0;
z1 = y1;
z2 = y2;
z3 = y3;
z4 = y4;
for (j = 0; (j | 0) < 64; j = j + 4 | 0) {
t1 = H[i + j >> 2] | 0;
t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | ~y1 & y3) | 0) + ((t1 + y4 | 0) + 1518500249 | 0) | 0;
y4 = y3;
y3 = y2;
y2 = y1 << 30 | y1 >>> 2;
y1 = y0;
y0 = t0;
H[k + j >> 2] = t1;
}
for (j = k + 64 | 0; (j | 0) < (k + 80 | 0); j = j + 4 | 0) {
t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31;
t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | ~y1 & y3) | 0) + ((t1 + y4 | 0) + 1518500249 | 0) | 0;
y4 = y3;
y3 = y2;
y2 = y1 << 30 | y1 >>> 2;
y1 = y0;
y0 = t0;
H[j >> 2] = t1;
}
for (j = k + 80 | 0; (j | 0) < (k + 160 | 0); j = j + 4 | 0) {
t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31;
t0 = ((y0 << 5 | y0 >>> 27) + (y1 ^ y2 ^ y3) | 0) + ((t1 + y4 | 0) + 1859775393 | 0) | 0;
y4 = y3;
y3 = y2;
y2 = y1 << 30 | y1 >>> 2;
y1 = y0;
y0 = t0;
H[j >> 2] = t1;
}
for (j = k + 160 | 0; (j | 0) < (k + 240 | 0); j = j + 4 | 0) {
t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31;
t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | y1 & y3 | y2 & y3) | 0) + ((t1 + y4 | 0) - 1894007588 | 0) | 0;
y4 = y3;
y3 = y2;
y2 = y1 << 30 | y1 >>> 2;
y1 = y0;
y0 = t0;
H[j >> 2] = t1;
}
for (j = k + 240 | 0; (j | 0) < (k + 320 | 0); j = j + 4 | 0) {
t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31;
t0 = ((y0 << 5 | y0 >>> 27) + (y1 ^ y2 ^ y3) | 0) + ((t1 + y4 | 0) - 899497514 | 0) | 0;
y4 = y3;
y3 = y2;
y2 = y1 << 30 | y1 >>> 2;
y1 = y0;
y0 = t0;
H[j >> 2] = t1;
}
y0 = y0 + z0 | 0;
y1 = y1 + z1 | 0;
y2 = y2 + z2 | 0;
y3 = y3 + z3 | 0;
y4 = y4 + z4 | 0;
}
H[x + 320 >> 2] = y0;
H[x + 324 >> 2] = y1;
H[x + 328 >> 2] = y2;
H[x + 332 >> 2] = y3;
H[x + 336 >> 2] = y4;
}
return { hash: hash };
};
if (// If we'e running in Node.JS, export a module.
typeof module !== 'undefined') {
module.exports = Rusha;
} else if (// If we're running in a DOM context, export
// the Rusha object to toplevel.
typeof window !== 'undefined') {
window.Rusha = Rusha;
}
if (// If we're running in a webworker, accept
// messages containing a jobid and a buffer
// or blob object, and return the hash result.
typeof FileReaderSync !== 'undefined') {
var reader = new FileReaderSync(), hasher = new Rusha(4 * 1024 * 1024);
self.onmessage = function onMessage(event) {
var hash, data = event.data.data;
try {
hash = hasher.digest(data);
self.postMessage({
id: event.data.id,
hash: hash
});
} catch (e) {
self.postMessage({
id: event.data.id,
error: e.name
});
}
};
}
}());
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],62:[function(require,module,exports){
arguments[4][17][0].apply(exports,arguments)
},{"dup":17}],63:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],64:[function(require,module,exports){
module.exports = MediaElementWrapper
var inherits = require('inherits')
var stream = require('readable-stream')
var toArrayBuffer = require('to-arraybuffer')
var MediaSource = typeof window !== 'undefined' && window.MediaSource
var DEFAULT_BUFFER_DURATION = 60 // seconds
function MediaElementWrapper (elem, opts) {
var self = this
if (!(self instanceof MediaElementWrapper)) return new MediaElementWrapper(elem, opts)
if (!MediaSource) throw new Error('web browser lacks MediaSource support')
if (!opts) opts = {}
self._bufferDuration = opts.bufferDuration || DEFAULT_BUFFER_DURATION
self._elem = elem
self._mediaSource = new MediaSource()
self._streams = []
self.detailedError = null
self._errorHandler = function () {
self._elem.removeEventListener('error', self._errorHandler)
var streams = self._streams.slice()
streams.forEach(function (stream) {
stream.destroy(self._elem.error)
})
}
self._elem.addEventListener('error', self._errorHandler)
self._elem.src = window.URL.createObjectURL(self._mediaSource)
}
/*
* `obj` can be a previous value returned by this function
* or a string
*/
MediaElementWrapper.prototype.createWriteStream = function (obj) {
var self = this
return new MediaSourceStream(self, obj)
}
/*
* Use to trigger an error on the underlying media element
*/
MediaElementWrapper.prototype.error = function (err) {
var self = this
// be careful not to overwrite any existing detailedError values
if (!self.detailedError) {
self.detailedError = err
}
try {
self._mediaSource.endOfStream('decode')
} catch (err) {}
}
inherits(MediaSourceStream, stream.Writable)
function MediaSourceStream (wrapper, obj) {
var self = this
stream.Writable.call(self)
self._wrapper = wrapper
self._elem = wrapper._elem
self._mediaSource = wrapper._mediaSource
self._allStreams = wrapper._streams
self._allStreams.push(self)
self._bufferDuration = wrapper._bufferDuration
self._sourceBuffer = null
self._openHandler = function () {
self._onSourceOpen()
}
self._flowHandler = function () {
self._flow()
}
if (typeof obj === 'string') {
self._type = obj
// Need to create a new sourceBuffer
if (self._mediaSource.readyState === 'open') {
self._createSourceBuffer()
} else {
self._mediaSource.addEventListener('sourceopen', self._openHandler)
}
} else if (obj._sourceBuffer === null) {
obj.destroy()
self._type = obj._type // The old stream was created but hasn't finished initializing
self._mediaSource.addEventListener('sourceopen', self._openHandler)
} else if (obj._sourceBuffer) {
obj.destroy()
self._type = obj._type
self._sourceBuffer = obj._sourceBuffer // Copy over the old sourceBuffer
self._sourceBuffer.addEventListener('updateend', self._flowHandler)
} else {
throw new Error('The argument to MediaElementWrapper.createWriteStream must be a string or a previous stream returned from that function')
}
self._elem.addEventListener('timeupdate', self._flowHandler)
self.on('error', function (err) {
self._wrapper.error(err)
})
self.on('finish', function () {
if (self.destroyed) return
self._finished = true
if (self._allStreams.every(function (other) { return other._finished })) {
try {
self._mediaSource.endOfStream()
} catch (err) {}
}
})
}
MediaSourceStream.prototype._onSourceOpen = function () {
var self = this
if (self.destroyed) return
self._mediaSource.removeEventListener('sourceopen', self._openHandler)
self._createSourceBuffer()
}
MediaSourceStream.prototype.destroy = function (err) {
var self = this
if (self.destroyed) return
self.destroyed = true
// Remove from allStreams
self._allStreams.splice(self._allStreams.indexOf(self), 1)
self._mediaSource.removeEventListener('sourceopen', self._openHandler)
self._elem.removeEventListener('timeupdate', self._flowHandler)
if (self._sourceBuffer) {
self._sourceBuffer.removeEventListener('updateend', self._flowHandler)
if (self._mediaSource.readyState === 'open') {
self._sourceBuffer.abort()
}
}
if (err) self.emit('error', err)
self.emit('close')
}
MediaSourceStream.prototype._createSourceBuffer = function () {
var self = this
if (self.destroyed) return
if (MediaSource.isTypeSupported(self._type)) {
self._sourceBuffer = self._mediaSource.addSourceBuffer(self._type)
self._sourceBuffer.addEventListener('updateend', self._flowHandler)
if (self._cb) {
var cb = self._cb
self._cb = null
cb()
}
} else {
self.destroy(new Error('The provided type is not supported'))
}
}
MediaSourceStream.prototype._write = function (chunk, encoding, cb) {
var self = this
if (self.destroyed) return
if (!self._sourceBuffer) {
self._cb = function (err) {
if (err) return cb(err)
self._write(chunk, encoding, cb)
}
return
}
if (self._sourceBuffer.updating) {
return cb(new Error('Cannot append buffer while source buffer updating'))
}
try {
self._sourceBuffer.appendBuffer(toArrayBuffer(chunk))
} catch (err) {
// appendBuffer can throw for a number of reasons, most notably when the data
// being appended is invalid or if appendBuffer is called after another error
// already occurred on the media element. In Chrome, there may be useful debugging
// info in chrome://media-internals
self.destroy(err)
return
}
self._cb = cb
}
MediaSourceStream.prototype._flow = function () {
var self = this
if (self.destroyed || !self._sourceBuffer || self._sourceBuffer.updating) {
return
}
if (self._mediaSource.readyState === 'open') {
// check buffer size
if (self._getBufferDuration() > self._bufferDuration) {
return
}
}
if (self._cb) {
var cb = self._cb
self._cb = null
cb()
}
}
// TODO: if zero actually works in all browsers, remove the logic associated with this below
var EPSILON = 0
MediaSourceStream.prototype._getBufferDuration = function () {
var self = this
var buffered = self._sourceBuffer.buffered
var currentTime = self._elem.currentTime
var bufferEnd = -1 // end of the buffer
// This is a little over complex because some browsers seem to separate the
// buffered region into multiple sections with slight gaps.
for (var i = 0; i < buffered.length; i++) {
var start = buffered.start(i)
var end = buffered.end(i) + EPSILON
if (start > currentTime) {
// Reached past the joined buffer
break
} else if (bufferEnd >= 0 || currentTime <= end) {
// Found the start/continuation of the joined buffer
bufferEnd = end
}
}
var bufferedTime = bufferEnd - currentTime
if (bufferedTime < 0) {
bufferedTime = 0
}
return bufferedTime
}
},{"inherits":63,"readable-stream":112,"to-arraybuffer":65}],65:[function(require,module,exports){
arguments[4][39][0].apply(exports,arguments)
},{"buffer":21,"dup":39}],66:[function(require,module,exports){
(function (Buffer){
// This is an intentionally recursive require. I don't like it either.
var Box = require('./index')
var Descriptor = require('./descriptor')
var TIME_OFFSET = 2082844800000
/*
TODO:
test these
add new box versions
*/
// These have 'version' and 'flags' fields in the headers
exports.fullBoxes = {}
var fullBoxes = [
'mvhd',
'tkhd',
'mdhd',
'vmhd',
'smhd',
'stsd',
'esds',
'stsz',
'stco',
'stss',
'stts',
'ctts',
'stsc',
'dref',
'elst',
'hdlr',
'mehd',
'trex',
'mfhd',
'tfhd',
'tfdt',
'trun'
]
fullBoxes.forEach(function (type) {
exports.fullBoxes[type] = true
})
exports.ftyp = {}
exports.ftyp.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(exports.ftyp.encodingLength(box))
var brands = box.compatibleBrands || []
buf.write(box.brand, 0, 4, 'ascii')
buf.writeUInt32BE(box.brandVersion, 4)
for (var i = 0; i < brands.length; i++) buf.write(brands[i], 8 + (i * 4), 4, 'ascii')
exports.ftyp.encode.bytes = 8 + brands.length * 4
return buf
}
exports.ftyp.decode = function (buf, offset) {
buf = buf.slice(offset)
var brand = buf.toString('ascii', 0, 4)
var version = buf.readUInt32BE(4)
var compatibleBrands = []
for (var i = 8; i < buf.length; i += 4) compatibleBrands.push(buf.toString('ascii', i, i + 4))
return {
brand: brand,
brandVersion: version,
compatibleBrands: compatibleBrands
}
}
exports.ftyp.encodingLength = function (box) {
return 8 + (box.compatibleBrands || []).length * 4
}
exports.mvhd = {}
exports.mvhd.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(96)
writeDate(box.ctime || new Date(), buf, 0)
writeDate(box.mtime || new Date(), buf, 4)
buf.writeUInt32BE(box.timeScale || 0, 8)
buf.writeUInt32BE(box.duration || 0, 12)
writeFixed32(box.preferredRate || 0, buf, 16)
writeFixed16(box.preferredVolume || 0, buf, 20)
writeReserved(buf, 22, 32)
writeMatrix(box.matrix, buf, 32)
buf.writeUInt32BE(box.previewTime || 0, 68)
buf.writeUInt32BE(box.previewDuration || 0, 72)
buf.writeUInt32BE(box.posterTime || 0, 76)
buf.writeUInt32BE(box.selectionTime || 0, 80)
buf.writeUInt32BE(box.selectionDuration || 0, 84)
buf.writeUInt32BE(box.currentTime || 0, 88)
buf.writeUInt32BE(box.nextTrackId || 0, 92)
exports.mvhd.encode.bytes = 96
return buf
}
exports.mvhd.decode = function (buf, offset) {
buf = buf.slice(offset)
return {
ctime: readDate(buf, 0),
mtime: readDate(buf, 4),
timeScale: buf.readUInt32BE(8),
duration: buf.readUInt32BE(12),
preferredRate: readFixed32(buf, 16),
preferredVolume: readFixed16(buf, 20),
matrix: readMatrix(buf.slice(32, 68)),
previewTime: buf.readUInt32BE(68),
previewDuration: buf.readUInt32BE(72),
posterTime: buf.readUInt32BE(76),
selectionTime: buf.readUInt32BE(80),
selectionDuration: buf.readUInt32BE(84),
currentTime: buf.readUInt32BE(88),
nextTrackId: buf.readUInt32BE(92)
}
}
exports.mvhd.encodingLength = function (box) {
return 96
}
exports.tkhd = {}
exports.tkhd.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(80)
writeDate(box.ctime || new Date(), buf, 0)
writeDate(box.mtime || new Date(), buf, 4)
buf.writeUInt32BE(box.trackId || 0, 8)
writeReserved(buf, 12, 16)
buf.writeUInt32BE(box.duration || 0, 16)
writeReserved(buf, 20, 28)
buf.writeUInt16BE(box.layer || 0, 28)
buf.writeUInt16BE(box.alternateGroup || 0, 30)
buf.writeUInt16BE(box.volume || 0, 32)
writeMatrix(box.matrix, buf, 36)
buf.writeUInt32BE(box.trackWidth || 0, 72)
buf.writeUInt32BE(box.trackHeight || 0, 76)
exports.tkhd.encode.bytes = 80
return buf
}
exports.tkhd.decode = function (buf, offset) {
buf = buf.slice(offset)
return {
ctime: readDate(buf, 0),
mtime: readDate(buf, 4),
trackId: buf.readUInt32BE(8),
duration: buf.readUInt32BE(16),
layer: buf.readUInt16BE(28),
alternateGroup: buf.readUInt16BE(30),
volume: buf.readUInt16BE(32),
matrix: readMatrix(buf.slice(36, 72)),
trackWidth: buf.readUInt32BE(72),
trackHeight: buf.readUInt32BE(76)
}
}
exports.tkhd.encodingLength = function (box) {
return 80
}
exports.mdhd = {}
exports.mdhd.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(20)
writeDate(box.ctime || new Date(), buf, 0)
writeDate(box.mtime || new Date(), buf, 4)
buf.writeUInt32BE(box.timeScale || 0, 8)
buf.writeUInt32BE(box.duration || 0, 12)
buf.writeUInt16BE(box.language || 0, 16)
buf.writeUInt16BE(box.quality || 0, 18)
exports.mdhd.encode.bytes = 20
return buf
}
exports.mdhd.decode = function (buf, offset) {
buf = buf.slice(offset)
return {
ctime: readDate(buf, 0),
mtime: readDate(buf, 4),
timeScale: buf.readUInt32BE(8),
duration: buf.readUInt32BE(12),
language: buf.readUInt16BE(16),
quality: buf.readUInt16BE(18)
}
}
exports.mdhd.encodingLength = function (box) {
return 20
}
exports.vmhd = {}
exports.vmhd.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(8)
buf.writeUInt16BE(box.graphicsMode || 0, 0)
var opcolor = box.opcolor || [0, 0, 0]
buf.writeUInt16BE(opcolor[0], 2)
buf.writeUInt16BE(opcolor[1], 4)
buf.writeUInt16BE(opcolor[2], 6)
exports.vmhd.encode.bytes = 8
return buf
}
exports.vmhd.decode = function (buf, offset) {
buf = buf.slice(offset)
return {
graphicsMode: buf.readUInt16BE(0),
opcolor: [buf.readUInt16BE(2), buf.readUInt16BE(4), buf.readUInt16BE(6)]
}
}
exports.vmhd.encodingLength = function (box) {
return 8
}
exports.smhd = {}
exports.smhd.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(4)
buf.writeUInt16BE(box.balance || 0, 0)
writeReserved(buf, 2, 4)
exports.smhd.encode.bytes = 4
return buf
}
exports.smhd.decode = function (buf, offset) {
buf = buf.slice(offset)
return {
balance: buf.readUInt16BE(0)
}
}
exports.smhd.encodingLength = function (box) {
return 4
}
exports.stsd = {}
exports.stsd.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(exports.stsd.encodingLength(box))
var entries = box.entries || []
buf.writeUInt32BE(entries.length, 0)
var ptr = 4
for (var i = 0; i < entries.length; i++) {
var entry = entries[i]
Box.encode(entry, buf, ptr)
ptr += Box.encode.bytes
}
exports.stsd.encode.bytes = ptr
return buf
}
exports.stsd.decode = function (buf, offset, end) {
buf = buf.slice(offset)
var num = buf.readUInt32BE(0)
var entries = new Array(num)
var ptr = 4
for (var i = 0; i < num; i++) {
var entry = Box.decode(buf, ptr, end)
entries[i] = entry
ptr += entry.length
}
return {
entries: entries
}
}
exports.stsd.encodingLength = function (box) {
var totalSize = 4
if (!box.entries) return totalSize
for (var i = 0; i < box.entries.length; i++) {
totalSize += Box.encodingLength(box.entries[i])
}
return totalSize
}
exports.avc1 = exports.VisualSampleEntry = {}
exports.VisualSampleEntry.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(exports.VisualSampleEntry.encodingLength(box))
writeReserved(buf, 0, 6)
buf.writeUInt16BE(box.dataReferenceIndex || 0, 6)
writeReserved(buf, 8, 24)
buf.writeUInt16BE(box.width || 0, 24)
buf.writeUInt16BE(box.height || 0, 26)
buf.writeUInt32BE(box.hResolution || 0x480000, 28)
buf.writeUInt32BE(box.vResolution || 0x480000, 32)
writeReserved(buf, 36, 40)
buf.writeUInt16BE(box.frameCount || 1, 40)
var compressorName = box.compressorName || ''
var nameLen = Math.min(compressorName.length, 31)
buf.writeUInt8(nameLen, 42)
buf.write(compressorName, 43, nameLen, 'utf8')
buf.writeUInt16BE(box.depth || 0x18, 74)
buf.writeInt16BE(-1, 76)
var ptr = 78
var children = box.children || []
children.forEach(function (child) {
Box.encode(child, buf, ptr)
ptr += Box.encode.bytes
})
exports.VisualSampleEntry.encode.bytes = ptr
}
exports.VisualSampleEntry.decode = function (buf, offset, end) {
buf = buf.slice(offset)
var length = end - offset
var nameLen = Math.min(buf.readUInt8(42), 31)
var box = {
dataReferenceIndex: buf.readUInt16BE(6),
width: buf.readUInt16BE(24),
height: buf.readUInt16BE(26),
hResolution: buf.readUInt32BE(28),
vResolution: buf.readUInt32BE(32),
frameCount: buf.readUInt16BE(40),
compressorName: buf.toString('utf8', 43, 43 + nameLen),
depth: buf.readUInt16BE(74),
children: []
}
var ptr = 78
while (length - ptr >= 8) {
var child = Box.decode(buf, ptr, length)
box.children.push(child)
box[child.type] = child
ptr += child.length
}
return box
}
exports.VisualSampleEntry.encodingLength = function (box) {
var len = 78
var children = box.children || []
children.forEach(function (child) {
len += Box.encodingLength(child)
})
return len
}
exports.avcC = {}
exports.avcC.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : Buffer(box.buffer.length)
box.buffer.copy(buf)
exports.avcC.encode.bytes = box.buffer.length
}
exports.avcC.decode = function (buf, offset, end) {
buf = buf.slice(offset, end)
return {
mimeCodec: buf.toString('hex', 1, 4),
buffer: new Buffer(buf)
}
}
exports.avcC.encodingLength = function (box) {
return box.buffer.length
}
exports.mp4a = exports.AudioSampleEntry = {}
exports.AudioSampleEntry.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(exports.AudioSampleEntry.encodingLength(box))
writeReserved(buf, 0, 6)
buf.writeUInt16BE(box.dataReferenceIndex || 0, 6)
writeReserved(buf, 8, 16)
buf.writeUInt16BE(box.channelCount || 2, 16)
buf.writeUInt16BE(box.sampleSize || 16, 18)
writeReserved(buf, 20, 24)
buf.writeUInt32BE(box.sampleRate || 0, 24)
var ptr = 28
var children = box.children || []
children.forEach(function (child) {
Box.encode(child, buf, ptr)
ptr += Box.encode.bytes
})
exports.AudioSampleEntry.encode.bytes = ptr
}
exports.AudioSampleEntry.decode = function (buf, offset, end) {
buf = buf.slice(offset, end)
var length = end - offset
var box = {
dataReferenceIndex: buf.readUInt16BE(6),
channelCount: buf.readUInt16BE(16),
sampleSize: buf.readUInt16BE(18),
sampleRate: buf.readUInt32BE(24),
children: []
}
var ptr = 28
while (length - ptr >= 8) {
var child = Box.decode(buf, ptr, length)
box.children.push(child)
box[child.type] = child
ptr += child.length
}
return box
}
exports.AudioSampleEntry.encodingLength = function (box) {
var len = 28
var children = box.children || []
children.forEach(function (child) {
len += Box.encodingLength(child)
})
return len
}
exports.esds = {}
exports.esds.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : Buffer(box.buffer.length)
box.buffer.copy(buf, 0)
exports.esds.encode.bytes = box.buffer.length
}
exports.esds.decode = function (buf, offset, end) {
buf = buf.slice(offset, end)
var desc = Descriptor.Descriptor.decode(buf, 0, buf.length)
var esd = (desc.tagName === 'ESDescriptor') ? desc : {}
var dcd = esd.DecoderConfigDescriptor || {}
var oti = dcd.oti || 0
var dsi = dcd.DecoderSpecificInfo
var audioConfig = dsi ? (dsi.buffer.readUInt8(0) & 0xf8) >> 3 : 0
var mimeCodec = null
if (oti) {
mimeCodec = oti.toString(16)
if (audioConfig) {
mimeCodec += '.' + audioConfig
}
}
return {
mimeCodec: mimeCodec,
buffer: new Buffer(buf.slice(0))
}
}
exports.esds.encodingLength = function (box) {
return box.buffer.length
}
// TODO: integrate the two versions in a saner way
exports.stsz = {}
exports.stsz.encode = function (box, buf, offset) {
var entries = box.entries || []
buf = buf ? buf.slice(offset) : Buffer(exports.stsz.encodingLength(box))
buf.writeUInt32BE(0, 0)
buf.writeUInt32BE(entries.length, 4)
for (var i = 0; i < entries.length; i++) {
buf.writeUInt32BE(entries[i], i * 4 + 8)
}
exports.stsz.encode.bytes = 8 + entries.length * 4
return buf
}
exports.stsz.decode = function (buf, offset) {
buf = buf.slice(offset)
var size = buf.readUInt32BE(0)
var num = buf.readUInt32BE(4)
var entries = new Array(num)
for (var i = 0; i < num; i++) {
if (size === 0) {
entries[i] = buf.readUInt32BE(i * 4 + 8)
} else {
entries[i] = size
}
}
return {
entries: entries
}
}
exports.stsz.encodingLength = function (box) {
return 8 + box.entries.length * 4
}
exports.stss =
exports.stco = {}
exports.stco.encode = function (box, buf, offset) {
var entries = box.entries || []
buf = buf ? buf.slice(offset) : new Buffer(exports.stco.encodingLength(box))
buf.writeUInt32BE(entries.length, 0)
for (var i = 0; i < entries.length; i++) {
buf.writeUInt32BE(entries[i], i * 4 + 4)
}
exports.stco.encode.bytes = 4 + entries.length * 4
return buf
}
exports.stco.decode = function (buf, offset) {
buf = buf.slice(offset)
var num = buf.readUInt32BE(0)
var entries = new Array(num)
for (var i = 0; i < num; i++) {
entries[i] = buf.readUInt32BE(i * 4 + 4)
}
return {
entries: entries
}
}
exports.stco.encodingLength = function (box) {
return 4 + box.entries.length * 4
}
exports.stts = {}
exports.stts.encode = function (box, buf, offset) {
var entries = box.entries || []
buf = buf ? buf.slice(offset) : new Buffer(exports.stts.encodingLength(box))
buf.writeUInt32BE(entries.length, 0)
for (var i = 0; i < entries.length; i++) {
var ptr = i * 8 + 4
buf.writeUInt32BE(entries[i].count || 0, ptr)
buf.writeUInt32BE(entries[i].duration || 0, ptr + 4)
}
exports.stts.encode.bytes = 4 + box.entries.length * 8
return buf
}
exports.stts.decode = function (buf, offset) {
buf = buf.slice(offset)
var num = buf.readUInt32BE(0)
var entries = new Array(num)
for (var i = 0; i < num; i++) {
var ptr = i * 8 + 4
entries[i] = {
count: buf.readUInt32BE(ptr),
duration: buf.readUInt32BE(ptr + 4)
}
}
return {
entries: entries
}
}
exports.stts.encodingLength = function (box) {
return 4 + box.entries.length * 8
}
exports.ctts = {}
exports.ctts.encode = function (box, buf, offset) {
var entries = box.entries || []
buf = buf ? buf.slice(offset) : new Buffer(exports.ctts.encodingLength(box))
buf.writeUInt32BE(entries.length, 0)
for (var i = 0; i < entries.length; i++) {
var ptr = i * 8 + 4
buf.writeUInt32BE(entries[i].count || 0, ptr)
buf.writeUInt32BE(entries[i].compositionOffset || 0, ptr + 4)
}
exports.ctts.encode.bytes = 4 + entries.length * 8
return buf
}
exports.ctts.decode = function (buf, offset) {
buf = buf.slice(offset)
var num = buf.readUInt32BE(0)
var entries = new Array(num)
for (var i = 0; i < num; i++) {
var ptr = i * 8 + 4
entries[i] = {
count: buf.readUInt32BE(ptr),
compositionOffset: buf.readInt32BE(ptr + 4)
}
}
return {
entries: entries
}
}
exports.ctts.encodingLength = function (box) {
return 4 + box.entries.length * 8
}
exports.stsc = {}
exports.stsc.encode = function (box, buf, offset) {
var entries = box.entries || []
buf = buf ? buf.slice(offset) : new Buffer(exports.stsc.encodingLength(box))
buf.writeUInt32BE(entries.length, 0)
for (var i = 0; i < entries.length; i++) {
var ptr = i * 12 + 4
buf.writeUInt32BE(entries[i].firstChunk || 0, ptr)
buf.writeUInt32BE(entries[i].samplesPerChunk || 0, ptr + 4)
buf.writeUInt32BE(entries[i].sampleDescriptionId || 0, ptr + 8)
}
exports.stsc.encode.bytes = 4 + entries.length * 12
return buf
}
exports.stsc.decode = function (buf, offset) {
buf = buf.slice(offset)
var num = buf.readUInt32BE(0)
var entries = new Array(num)
for (var i = 0; i < num; i++) {
var ptr = i * 12 + 4
entries[i] = {
firstChunk: buf.readUInt32BE(ptr),
samplesPerChunk: buf.readUInt32BE(ptr + 4),
sampleDescriptionId: buf.readUInt32BE(ptr + 8)
}
}
return {
entries: entries
}
}
exports.stsc.encodingLength = function (box) {
return 4 + box.entries.length * 12
}
exports.dref = {}
exports.dref.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(exports.dref.encodingLength(box))
var entries = box.entries || []
buf.writeUInt32BE(entries.length, 0)
var ptr = 4
for (var i = 0; i < entries.length; i++) {
var entry = entries[i]
var size = (entry.buf ? entry.buf.length : 0) + 4 + 4
buf.writeUInt32BE(size, ptr)
ptr += 4
buf.write(entry.type, ptr, 4, 'ascii')
ptr += 4
if (entry.buf) {
entry.buf.copy(buf, ptr)
ptr += entry.buf.length
}
}
exports.dref.encode.bytes = ptr
return buf
}
exports.dref.decode = function (buf, offset) {
buf = buf.slice(offset)
var num = buf.readUInt32BE(0)
var entries = new Array(num)
var ptr = 4
for (var i = 0; i < num; i++) {
var size = buf.readUInt32BE(ptr)
var type = buf.toString('ascii', ptr + 4, ptr + 8)
var tmp = buf.slice(ptr + 8, ptr + size)
ptr += size
entries[i] = {
type: type,
buf: tmp
}
}
return {
entries: entries
}
}
exports.dref.encodingLength = function (box) {
var totalSize = 4
if (!box.entries) return totalSize
for (var i = 0; i < box.entries.length; i++) {
var buf = box.entries[i].buf
totalSize += (buf ? buf.length : 0) + 4 + 4
}
return totalSize
}
exports.elst = {}
exports.elst.encode = function (box, buf, offset) {
var entries = box.entries || []
buf = buf ? buf.slice(offset) : new Buffer(exports.elst.encodingLength(box))
buf.writeUInt32BE(entries.length, 0)
for (var i = 0; i < entries.length; i++) {
var ptr = i * 12 + 4
buf.writeUInt32BE(entries[i].trackDuration || 0, ptr)
buf.writeUInt32BE(entries[i].mediaTime || 0, ptr + 4)
writeFixed32(entries[i].mediaRate || 0, buf, ptr + 8)
}
exports.elst.encode.bytes = 4 + entries.length * 12
return buf
}
exports.elst.decode = function (buf, offset) {
buf = buf.slice(offset)
var num = buf.readUInt32BE(0)
var entries = new Array(num)
for (var i = 0; i < num; i++) {
var ptr = i * 12 + 4
entries[i] = {
trackDuration: buf.readUInt32BE(ptr),
mediaTime: buf.readInt32BE(ptr + 4),
mediaRate: readFixed32(buf, ptr + 8)
}
}
return {
entries: entries
}
}
exports.elst.encodingLength = function (box) {
return 4 + box.entries.length * 12
}
exports.hdlr = {}
exports.hdlr.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(exports.hdlr.encodingLength(box))
var len = 21 + (box.name || '').length
buf.fill(0, 0, len)
buf.write(box.handlerType || '', 4, 4, 'ascii')
writeString(box.name || '', buf, 20)
exports.hdlr.encode.bytes = len
return buf
}
exports.hdlr.decode = function (buf, offset, end) {
buf = buf.slice(offset)
return {
handlerType: buf.toString('ascii', 4, 8),
name: readString(buf, 20, end)
}
}
exports.hdlr.encodingLength = function (box) {
return 21 + (box.name || '').length
}
exports.mehd = {}
exports.mehd.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(4)
buf.writeUInt32BE(box.fragmentDuration || 0, 0)
exports.mehd.encode.bytes = 4
return buf
}
exports.mehd.decode = function (buf, offset) {
buf = buf.slice(offset)
return {
fragmentDuration: buf.readUInt32BE(0)
}
}
exports.mehd.encodingLength = function (box) {
return 4
}
exports.trex = {}
exports.trex.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(20)
buf.writeUInt32BE(box.trackId || 0, 0)
buf.writeUInt32BE(box.defaultSampleDescriptionIndex || 0, 4)
buf.writeUInt32BE(box.defaultSampleDuration || 0, 8)
buf.writeUInt32BE(box.defaultSampleSize || 0, 12)
buf.writeUInt32BE(box.defaultSampleFlags || 0, 16)
exports.trex.encode.bytes = 20
return buf
}
exports.trex.decode = function (buf, offset) {
buf = buf.slice(offset)
return {
trackId: buf.readUInt32BE(0),
defaultSampleDescriptionIndex: buf.readUInt32BE(4),
defaultSampleDuration: buf.readUInt32BE(8),
defaultSampleSize: buf.readUInt32BE(12),
defaultSampleFlags: buf.readUInt32BE(16)
}
}
exports.trex.encodingLength = function (box) {
return 20
}
exports.mfhd = {}
exports.mfhd.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(4)
buf.writeUInt32BE(box.sequenceNumber || 0, 0)
exports.mfhd.encode.bytes = 4
return buf
}
exports.mfhd.decode = function (buf, offset) {
return {
sequenceNumber: buf.readUint32BE(0)
}
}
exports.mfhd.encodingLength = function (box) {
return 4
}
exports.tfhd = {}
exports.tfhd.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(4)
buf.writeUInt32BE(box.trackId, 0)
exports.tfhd.encode.bytes = 4
return buf
}
exports.tfhd.decode = function (buf, offset) {
// TODO: this
}
exports.tfhd.encodingLength = function (box) {
// TODO: this is wrong!
return 4
}
exports.tfdt = {}
exports.tfdt.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(4)
buf.writeUInt32BE(box.baseMediaDecodeTime || 0, 0)
exports.tfdt.encode.bytes = 4
return buf
}
exports.tfdt.decode = function (buf, offset) {
// TODO: this
}
exports.tfdt.encodingLength = function (box) {
return 4
}
exports.trun = {}
exports.trun.encode = function (box, buf, offset) {
buf = buf ? buf.slice(offset) : new Buffer(8 + box.entries.length * 16)
// TODO: this is wrong
buf.writeUInt32BE(box.entries.length, 0)
buf.writeInt32BE(box.dataOffset, 4)
var ptr = 8
for (var i = 0; i < box.entries.length; i++) {
var entry = box.entries[i]
buf.writeUInt32BE(entry.sampleDuration, ptr)
ptr += 4
buf.writeUInt32BE(entry.sampleSize, ptr)
ptr += 4
buf.writeUInt32BE(entry.sampleFlags, ptr)
ptr += 4
buf.writeUInt32BE(entry.sampleCompositionTimeOffset, ptr)
ptr += 4
}
exports.trun.encode.bytes = ptr
}
exports.trun.decode = function (buf, offset) {
// TODO: this
}
exports.trun.encodingLength = function (box) {
// TODO: this is wrong
return 8 + box.entries.length * 16
}
exports.mdat = {}
exports.mdat.encode = function (box, buf, offset) {
if (box.buffer) {
box.buffer.copy(buf, offset)
exports.mdat.encode.bytes = box.buffer.length
} else {
exports.mdat.encode.bytes = exports.mdat.encodingLength(box)
}
}
exports.mdat.decode = function (buf, start, end) {
return {
buffer: new Buffer(buf.slice(start, end))
}
}
exports.mdat.encodingLength = function (box) {
return box.buffer ? box.buffer.length : box.contentLength
}
function writeReserved (buf, offset, end) {
for (var i = offset; i < end; i++) buf[i] = 0
}
function writeDate (date, buf, offset) {
buf.writeUInt32BE(Math.floor((date.getTime() + TIME_OFFSET) / 1000), offset)
}
// TODO: think something is wrong here
function writeFixed32 (num, buf, offset) {
buf.writeUInt16BE(Math.floor(num) % (256 * 256), offset)
buf.writeUInt16BE(Math.floor(num * 256 * 256) % (256 * 256), offset + 2)
}
function writeFixed16 (num, buf, offset) {
buf[offset] = Math.floor(num) % 256
buf[offset + 1] = Math.floor(num * 256) % 256
}
function writeMatrix (list, buf, offset) {
if (!list) list = [0, 0, 0, 0, 0, 0, 0, 0, 0]
for (var i = 0; i < list.length; i++) {
writeFixed32(list[i], buf, offset + i * 4)
}
}
function writeString (str, buf, offset) {
var strBuffer = new Buffer(str, 'utf8')
strBuffer.copy(buf, offset)
buf[offset + strBuffer.length] = 0
}
function readMatrix (buf) {
var list = new Array(buf.length / 4)
for (var i = 0; i < list.length; i++) list[i] = readFixed32(buf, i * 4)
return list
}
function readDate (buf, offset) {
return new Date(buf.readUInt32BE(offset) * 1000 - TIME_OFFSET)
}
function readFixed32 (buf, offset) {
return buf.readUInt16BE(offset) + buf.readUInt16BE(offset + 2) / (256 * 256)
}
function readFixed16 (buf, offset) {
return buf[offset] + buf[offset + 1] / 256
}
function readString (buf, offset, length) {
var i
for (i = 0; i < length; i++) {
if (buf[offset + i] === 0) {
break
}
}
return buf.toString('utf8', offset, offset + i)
}
}).call(this,require("buffer").Buffer)
},{"./descriptor":67,"./index":68,"buffer":21}],67:[function(require,module,exports){
(function (Buffer){
var tagToName = {
0x03: 'ESDescriptor',
0x04: 'DecoderConfigDescriptor',
0x05: 'DecoderSpecificInfo',
0x06: 'SLConfigDescriptor'
}
exports.Descriptor = {}
exports.Descriptor.decode = function (buf, start, end) {
var tag = buf.readUInt8(start)
var ptr = start + 1
var lenByte
var len = 0
do {
lenByte = buf.readUInt8(ptr++)
len = (len << 7) | (lenByte & 0x7f)
} while (lenByte & 0x80)
var obj
var tagName = tagToName[tag] // May be undefined; that's ok
if (exports[tagName]) {
obj = exports[tagName].decode(buf, ptr, end)
} else {
obj = {
buffer: new Buffer(buf.slice(ptr, ptr + len))
}
}
obj.tag = tag
obj.tagName = tagName
obj.length = (ptr - start) + len
obj.contentsLen = len
return obj
}
exports.DescriptorArray = {}
exports.DescriptorArray.decode = function (buf, start, end) {
var ptr = start
var obj = {}
while (ptr + 2 <= end) {
var descriptor = exports.Descriptor.decode(buf, ptr, end)
ptr += descriptor.length
var tagName = tagToName[descriptor.tag] || ('Descriptor' + descriptor.tag)
obj[tagName] = descriptor
}
return obj
}
exports.ESDescriptor = {}
exports.ESDescriptor.decode = function (buf, start, end) {
var flags = buf.readUInt8(start + 2)
var ptr = start + 3
if (flags & 0x80) {
ptr += 2
}
if (flags & 0x40) {
var len = buf.readUInt8(ptr)
ptr += len + 1
}
if (flags & 0x20) {
ptr += 2
}
return exports.DescriptorArray.decode(buf, ptr, end)
}
exports.DecoderConfigDescriptor = {}
exports.DecoderConfigDescriptor.decode = function (buf, start, end) {
var oti = buf.readUInt8(start)
var obj = exports.DescriptorArray.decode(buf, start + 13, end)
obj.oti = oti
return obj
}
}).call(this,require("buffer").Buffer)
},{"buffer":21}],68:[function(require,module,exports){
(function (Buffer){
// var assert = require('assert')
var uint64be = require('uint64be')
var boxes = require('./boxes')
var UINT32_MAX = 4294967295
var Box = exports
/*
* Lists the proper order for boxes inside containers.
* Five-character names ending in 's' indicate arrays instead of single elements.
*/
var containers = exports.containers = {
'moov': ['mvhd', 'meta', 'traks', 'mvex'],
'trak': ['tkhd', 'tref', 'trgr', 'edts', 'meta', 'mdia', 'udta'],
'edts': ['elst'],
'mdia': ['mdhd', 'hdlr', 'elng', 'minf'],
'minf': ['vmhd', 'smhd', 'hmhd', 'sthd', 'nmhd', 'dinf', 'stbl'],
'dinf': ['dref'],
'stbl': ['stsd', 'stts', 'ctts', 'cslg', 'stsc', 'stsz', 'stz2', 'stco', 'co64', 'stss', 'stsh', 'padb', 'stdp', 'sdtp', 'sbgps', 'sgpds', 'subss', 'saizs', 'saios'],
'mvex': ['mehd', 'trexs', 'leva'],
'moof': ['mfhd', 'meta', 'trafs'],
'traf': ['tfhd', 'trun', 'sbgps', 'sgpds', 'subss', 'saizs', 'saios', 'tfdt', 'meta']
}
Box.encode = function (obj, buffer, offset) {
Box.encodingLength(obj) // sets every level appropriately
offset = offset || 0
buffer = buffer || new Buffer(obj.length)
return Box._encode(obj, buffer, offset)
}
Box._encode = function (obj, buffer, offset) {
var type = obj.type
var len = obj.length
if (len > UINT32_MAX) {
len = 1
}
buffer.writeUInt32BE(len, offset)
buffer.write(obj.type, offset + 4, 4, 'ascii')
var ptr = offset + 8
if (len === 1) {
uint64be.encode(obj.length, buffer, ptr)
ptr += 8
}
if (boxes.fullBoxes[type]) {
buffer.writeUInt32BE(obj.flags || 0, ptr)
buffer.writeUInt8(obj.version || 0, ptr)
ptr += 4
}
if (containers[type]) {
var contents = containers[type]
contents.forEach(function (childType) {
if (childType.length === 5) {
var entry = obj[childType] || []
childType = childType.substr(0, 4)
entry.forEach(function (child) {
Box._encode(child, buffer, ptr)
ptr += Box.encode.bytes
})
} else if (obj[childType]) {
Box._encode(obj[childType], buffer, ptr)
ptr += Box.encode.bytes
}
})
if (obj.otherBoxes) {
obj.otherBoxes.forEach(function (child) {
Box._encode(child, buffer, ptr)
ptr += Box.encode.bytes
})
}
} else if (boxes[type]) {
var encode = boxes[type].encode
encode(obj, buffer, ptr)
ptr += encode.bytes
} else if (obj.buffer) {
var buf = obj.buffer
buf.copy(buffer, ptr)
ptr += obj.buffer.length
} else {
throw new Error('Either `type` must be set to a known type (not\'' + type + '\') or `buffer` must be set')
}
Box.encode.bytes = ptr - offset
// assert.equal(ptr - offset, obj.length, 'Error encoding \'' + type + '\': wrote ' + ptr - offset + ' bytes, expecting ' + obj.length)
return buffer
}
/*
* Returns an object with `type` and `size` fields,
* or if there isn't enough data, returns the total
* number of bytes needed to read the headers
*/
Box.readHeaders = function (buffer, start, end) {
start = start || 0
end = end || buffer.length
if (end - start < 8) {
return 8
}
var len = buffer.readUInt32BE(start)
var type = buffer.toString('ascii', start + 4, start + 8)
var ptr = start + 8
if (len === 1) {
if (end - start < 16) {
return 16
}
len = uint64be.decode(buffer, ptr)
ptr += 8
}
var version
var flags
if (boxes.fullBoxes[type]) {
version = buffer.readUInt8(ptr)
flags = buffer.readUInt32BE(ptr) & 0xffffff
ptr += 4
}
return {
length: len,
headersLen: ptr - start,
contentLen: len - (ptr - start),
type: type,
version: version,
flags: flags
}
}
Box.decode = function (buffer, start, end) {
start = start || 0
end = end || buffer.length
var headers = Box.readHeaders(buffer, start, end)
if (!headers || headers.length > end - start) {
throw new Error('Data too short')
}
return Box.decodeWithoutHeaders(headers, buffer, start + headers.headersLen, start + headers.length)
}
Box.decodeWithoutHeaders = function (headers, buffer, start, end) {
start = start || 0
end = end || buffer.length
var type = headers.type
var obj = {}
if (containers[type]) {
obj.otherBoxes = []
var contents = containers[type]
var ptr = start
while (end - ptr >= 8) {
var child = Box.decode(buffer, ptr, end)
ptr += child.length
if (contents.indexOf(child.type) >= 0) {
obj[child.type] = child
} else if (contents.indexOf(child.type + 's') >= 0) {
var childType = child.type + 's'
var entry = obj[childType] = obj[childType] || []
entry.push(child)
} else {
obj.otherBoxes.push(child)
}
}
} else if (boxes[type]) {
var decode = boxes[type].decode
obj = decode(buffer, start, end)
} else {
obj.buffer = new Buffer(buffer.slice(start, end))
}
obj.length = headers.length
obj.contentLen = headers.contentLen
obj.type = headers.type
obj.version = headers.version
obj.flags = headers.flags
return obj
}
Box.encodingLength = function (obj) {
var type = obj.type
var len = 8
if (boxes.fullBoxes[type]) {
len += 4
}
if (containers[type]) {
var contents = containers[type]
contents.forEach(function (childType) {
if (childType.length === 5) {
var entry = obj[childType] || []
childType = childType.substr(0, 4)
entry.forEach(function (child) {
child.type = childType
len += Box.encodingLength(child)
})
} else if (obj[childType]) {
var child = obj[childType]
child.type = childType
len += Box.encodingLength(child)
}
})
if (obj.otherBoxes) {
obj.otherBoxes.forEach(function (child) {
len += Box.encodingLength(child)
})
}
} else if (boxes[type]) {
len += boxes[type].encodingLength(obj)
} else if (obj.buffer) {
len += obj.buffer.length
} else {
throw new Error('Either `type` must be set to a known type (not\'' + type + '\') or `buffer` must be set')
}
if (len > UINT32_MAX) {
len += 8
}
obj.length = len
return len
}
}).call(this,require("buffer").Buffer)
},{"./boxes":66,"buffer":21,"uint64be":69}],69:[function(require,module,exports){
(function (Buffer){
var UINT_32_MAX = 0xffffffff
exports.encodingLength = function () {
return 8
}
exports.encode = function (num, buf, offset) {
if (!buf) buf = new Buffer(8)
if (!offset) offset = 0
var top = Math.floor(num / UINT_32_MAX)
var rem = num - top * UINT_32_MAX
buf.writeUInt32BE(top, offset)
buf.writeUInt32BE(rem, offset + 4)
return buf
}
exports.decode = function (buf, offset) {
if (!offset) offset = 0
if (!buf) buf = new Buffer(4)
if (!offset) offset = 0
var top = buf.readUInt32BE(offset)
var rem = buf.readUInt32BE(offset + 4)
return top * UINT_32_MAX + rem
}
exports.encode.bytes = 8
exports.decode.bytes = 8
}).call(this,require("buffer").Buffer)
},{"buffer":21}],70:[function(require,module,exports){
(function (Buffer){
var stream = require('readable-stream')
var inherits = require('inherits')
var nextEvent = require('next-event')
var Box = require('mp4-box-encoding')
var EMPTY = new Buffer(0)
module.exports = Decoder
function Decoder () {
if (!(this instanceof Decoder)) return new Decoder()
stream.Writable.call(this)
this.destroyed = false
this._pending = 0
this._missing = 0
this._buf = null
this._str = null
this._cb = null
this._ondrain = null
this._writeBuffer = null
this._writeCb = null
this._ondrain = null
this._kick()
}
inherits(Decoder, stream.Writable)
Decoder.prototype.destroy = function (err) {
if (this.destroyed) return
this.destroyed = true
if (err) this.emit('error', err)
this.emit('close')
}
Decoder.prototype._write = function (data, enc, next) {
if (this.destroyed) return
var drained = !this._str || !this._str._writableState.needDrain
while (data.length && !this.destroyed) {
if (!this._missing) {
this._writeBuffer = data
this._writeCb = next
return
}
var consumed = data.length < this._missing ? data.length : this._missing
if (this._buf) data.copy(this._buf, this._buf.length - this._missing)
else if (this._str) drained = this._str.write(consumed === data.length ? data : data.slice(0, consumed))
this._missing -= consumed
if (!this._missing) {
var buf = this._buf
var cb = this._cb
var stream = this._str
this._buf = this._cb = this._str = this._ondrain = null
drained = true
if (stream) stream.end()
if (cb) cb(buf)
}
data = consumed === data.length ? EMPTY : data.slice(consumed)
}
if (this._pending && !this._missing) {
this._writeBuffer = data
this._writeCb = next
return
}
if (drained) next()
else this._ondrain(next)
}
Decoder.prototype._buffer = function (size, cb) {
this._missing = size
this._buf = new Buffer(size)
this._cb = cb
}
Decoder.prototype._stream = function (size, cb) {
var self = this
this._missing = size
this._str = new MediaData(this)
this._ondrain = nextEvent(this._str, 'drain')
this._pending++
this._str.on('end', function () {
self._pending--
self._kick()
})
this._cb = cb
return this._str
}
Decoder.prototype._readBox = function () {
var self = this
bufferHeaders(8)
function bufferHeaders (len, buf) {
self._buffer(len, function (additionalBuf) {
if (buf) {
buf = Buffer.concat(buf, additionalBuf)
} else {
buf = additionalBuf
}
var headers = Box.readHeaders(buf)
if (typeof headers === 'number') {
bufferHeaders(headers - buf.length, buf)
} else {
self._pending++
self._headers = headers
self.emit('box', headers)
}
})
}
}
Decoder.prototype.stream = function () {
var self = this
if (!self._headers) throw new Error('this function can only be called once after \'box\' is emitted')
var headers = self._headers
self._headers = null
return self._stream(headers.contentLen, null)
}
Decoder.prototype.decode = function (cb) {
var self = this
if (!self._headers) throw new Error('this function can only be called once after \'box\' is emitted')
var headers = self._headers
self._headers = null
self._buffer(headers.contentLen, function (buf) {
var box = Box.decodeWithoutHeaders(headers, buf)
cb(box)
self._pending--
self._kick()
})
}
Decoder.prototype.ignore = function () {
var self = this
if (!self._headers) throw new Error('this function can only be called once after \'box\' is emitted')
var headers = self._headers
self._headers = null
this._missing = headers.contentLen
this._cb = function () {
self._pending--
self._kick()
}
}
Decoder.prototype._kick = function () {
if (this._pending) return
if (!this._buf && !this._str) this._readBox()
if (this._writeBuffer) {
var next = this._writeCb
var buffer = this._writeBuffer
this._writeBuffer = null
this._writeCb = null
this._write(buffer, null, next)
}
}
function MediaData (parent) {
this._parent = parent
this.destroyed = false
stream.PassThrough.call(this)
}
inherits(MediaData, stream.PassThrough)
MediaData.prototype.destroy = function (err) {
if (this.destroyed) return
this.destroyed = true
this._parent.destroy(err)
if (err) this.emit('error', err)
this.emit('close')
}
}).call(this,require("buffer").Buffer)
},{"buffer":21,"inherits":63,"mp4-box-encoding":68,"next-event":73,"readable-stream":112}],71:[function(require,module,exports){
(function (process,Buffer){
var stream = require('readable-stream')
var inherits = require('inherits')
var Box = require('mp4-box-encoding')
module.exports = Encoder
function noop () {}
function Encoder () {
if (!(this instanceof Encoder)) return new Encoder()
stream.Readable.call(this)
this.destroyed = false
this._reading = false
this._stream = null
this._drain = null
this._want = false
this._onreadable = onreadable
this._onend = onend
var self = this
function onreadable () {
if (!self._want) return
self._want = false
self._read()
}
function onend () {
self._stream = null
}
}
inherits(Encoder, stream.Readable)
Encoder.prototype.mediaData =
Encoder.prototype.mdat = function (size, cb) {
var stream = new MediaData(this)
this.box({type: 'mdat', contentLength: size, encodeBufferLen: 8, stream: stream}, cb)
return stream
}
Encoder.prototype.box = function (box, cb) {
if (!cb) cb = noop
if (this.destroyed) return cb(new Error('Encoder is destroyed'))
var buf
if (box.encodeBufferLen) {
buf = new Buffer(box.encodeBufferLen)
}
if (box.stream) {
box.buffer = null
buf = Box.encode(box, buf)
this.push(buf)
this._stream = box.stream
this._stream.on('readable', this._onreadable)
this._stream.on('end', this._onend)
this._stream.on('end', cb)
this._forward()
} else {
buf = Box.encode(box, buf)
var drained = this.push(buf)
if (drained) return process.nextTick(cb)
this._drain = cb
}
}
Encoder.prototype.destroy = function (err) {
if (this.destroyed) return
this.destroyed = true
if (this._stream && this._stream.destroy) this._stream.destroy()
this._stream = null
if (this._drain) {
var cb = this._drain
this._drain = null
cb(err)
}
if (err) this.emit('error', err)
this.emit('close')
}
Encoder.prototype.finalize = function () {
this.push(null)
}
Encoder.prototype._forward = function () {
if (!this._stream) return
while (!this.destroyed) {
var buf = this._stream.read()
if (!buf) {
this._want = !!this._stream
return
}
if (!this.push(buf)) return
}
}
Encoder.prototype._read = function () {
if (this._reading || this.destroyed) return
this._reading = true
if (this._stream) this._forward()
if (this._drain) {
var drain = this._drain
this._drain = null
drain()
}
this._reading = false
}
function MediaData (parent) {
this._parent = parent
this.destroyed = false
stream.PassThrough.call(this)
}
inherits(MediaData, stream.PassThrough)
MediaData.prototype.destroy = function (err) {
if (this.destroyed) return
this.destroyed = true
this._parent.destroy(err)
if (err) this.emit('error', err)
this.emit('close')
}
}).call(this,require('_process'),require("buffer").Buffer)
},{"_process":29,"buffer":21,"inherits":63,"mp4-box-encoding":68,"readable-stream":112}],72:[function(require,module,exports){
exports.decode = require('./decode')
exports.encode = require('./encode')
},{"./decode":70,"./encode":71}],73:[function(require,module,exports){
module.exports = nextEvent
function nextEvent (emitter, name) {
var next = null
emitter.on(name, function (data) {
if (!next) return
var fn = next
next = null
fn(data)
})
return function (once) {
next = once
}
}
},{}],74:[function(require,module,exports){
module.exports = MultiStream
var inherits = require('inherits')
var stream = require('readable-stream')
inherits(MultiStream, stream.Readable)
function MultiStream (streams, opts) {
var self = this
if (!(self instanceof MultiStream)) return new MultiStream(streams, opts)
stream.Readable.call(self, opts)
self.destroyed = false
self._drained = false
self._forwarding = false
self._current = null
if (typeof streams === 'function') {
self._queue = streams
} else {
self._queue = streams.map(toStreams2)
self._queue.forEach(function (stream) {
if (typeof stream !== 'function') self._attachErrorListener(stream)
})
}
self._next()
}
MultiStream.obj = function (streams) {
return new MultiStream(streams, { objectMode: true, highWaterMark: 16 })
}
MultiStream.prototype._read = function () {
this._drained = true
this._forward()
}
MultiStream.prototype._forward = function () {
if (this._forwarding || !this._drained || !this._current) return
this._forwarding = true
var chunk
while ((chunk = this._current.read()) !== null) {
this._drained = this.push(chunk)
}
this._forwarding = false
}
MultiStream.prototype.destroy = function (err) {
if (this.destroyed) return
this.destroyed = true
if (this._current && this._current.destroy) this._current.destroy()
if (typeof this._queue !== 'function') {
this._queue.forEach(function (stream) {
if (stream.destroy) stream.destroy()
})
}
if (err) this.emit('error', err)
this.emit('close')
}
MultiStream.prototype._next = function () {
var self = this
self._current = null
if (typeof self._queue === 'function') {
self._queue(function (err, stream) {
if (err) return self.destroy(err)
stream = toStreams2(stream)
self._attachErrorListener(stream)
self._gotNextStream(stream)
})
} else {
var stream = self._queue.shift()
if (typeof stream === 'function') {
stream = toStreams2(stream())
self._attachErrorListener(stream)
}
self._gotNextStream(stream)
}
}
MultiStream.prototype._gotNextStream = function (stream) {
var self = this
if (!stream) {
self.push(null)
self.destroy()
return
}
self._current = stream
self._forward()
stream.on('readable', onReadable)
stream.once('end', onEnd)
stream.once('close', onClose)
function onReadable () {
self._forward()
}
function onClose () {
if (!stream._readableState.ended) {
self.destroy()
}
}
function onEnd () {
self._current = null
stream.removeListener('readable', onReadable)
stream.removeListener('end', onEnd)
stream.removeListener('close', onClose)
self._next()
}
}
MultiStream.prototype._attachErrorListener = function (stream) {
var self = this
if (!stream) return
stream.once('error', onError)
function onError (err) {
stream.removeListener('error', onError)
self.destroy(err)
}
}
function toStreams2 (s) {
if (!s || typeof s === 'function' || s._readableState) return s
var wrap = new stream.Readable().wrap(s)
if (s.destroy) {
wrap.destroy = s.destroy.bind(s)
}
return wrap
}
},{"inherits":63,"readable-stream":112}],75:[function(require,module,exports){
(function (process,Buffer){
/* global Blob */
module.exports = parseTorrent
module.exports.remote = parseTorrentRemote
var blobToBuffer = require('blob-to-buffer')
var fs = require('fs') // browser exclude
var get = require('simple-get')
var magnet = require('magnet-uri')
var parseTorrentFile = require('parse-torrent-file')
module.exports.toMagnetURI = magnet.encode
module.exports.toTorrentFile = parseTorrentFile.encode
/**
* Parse a torrent identifier (magnet uri, .torrent file, info hash)
* @param {string|Buffer|Object} torrentId
* @return {Object}
*/
function parseTorrent (torrentId) {
if (typeof torrentId === 'string' && /^(stream-)?magnet:/.test(torrentId)) {
// magnet uri (string)
return magnet(torrentId)
} else if (typeof torrentId === 'string' && (/^[a-f0-9]{40}$/i.test(torrentId) || /^[a-z2-7]{32}$/i.test(torrentId))) {
// info hash (hex/base-32 string)
return magnet('magnet:?xt=urn:btih:' + torrentId)
} else if (Buffer.isBuffer(torrentId) && torrentId.length === 20) {
// info hash (buffer)
return magnet('magnet:?xt=urn:btih:' + torrentId.toString('hex'))
} else if (Buffer.isBuffer(torrentId)) {
// .torrent file (buffer)
return parseTorrentFile(torrentId) // might throw
} else if (torrentId && torrentId.infoHash) {
// parsed torrent (from `parse-torrent`, `parse-torrent-file`, or `magnet-uri`)
if (!torrentId.announce) torrentId.announce = []
if (typeof torrentId.announce === 'string') {
torrentId.announce = [ torrentId.announce ]
}
if (!torrentId.urlList) torrentId.urlList = []
return torrentId
} else {
throw new Error('Invalid torrent identifier')
}
}
function parseTorrentRemote (torrentId, cb) {
var parsedTorrent
if (typeof cb !== 'function') throw new Error('second argument must be a Function')
try {
parsedTorrent = parseTorrent(torrentId)
} catch (err) {
// If torrent fails to parse, it could be a Blob, http/https URL or
// filesystem path, so don't consider it an error yet.
}
if (parsedTorrent && parsedTorrent.infoHash) {
process.nextTick(function () {
cb(null, parsedTorrent)
})
} else if (isBlob(torrentId)) {
blobToBuffer(torrentId, function (err, torrentBuf) {
if (err) return cb(new Error('Error converting Blob: ' + err.message))
parseOrThrow(torrentBuf)
})
} else if (typeof get === 'function' && /^https?:/.test(torrentId)) {
// http, or https url to torrent file
get.concat({
url: torrentId,
headers: { 'user-agent': 'WebTorrent (http://webtorrent.io)' }
}, function (err, res, torrentBuf) {
if (err) return cb(new Error('Error downloading torrent: ' + err.message))
parseOrThrow(torrentBuf)
})
} else if (typeof fs.readFile === 'function' && typeof torrentId === 'string') {
// assume it's a filesystem path
fs.readFile(torrentId, function (err, torrentBuf) {
if (err) return cb(new Error('Invalid torrent identifier'))
parseOrThrow(torrentBuf)
})
} else {
process.nextTick(function () {
cb(new Error('Invalid torrent identifier'))
})
}
function parseOrThrow (torrentBuf) {
try {
parsedTorrent = parseTorrent(torrentBuf)
} catch (err) {
return cb(err)
}
if (parsedTorrent && parsedTorrent.infoHash) cb(null, parsedTorrent)
else cb(new Error('Invalid torrent identifier'))
}
}
/**
* Check if `obj` is a W3C `Blob` or `File` object
* @param {*} obj
* @return {boolean}
*/
function isBlob (obj) {
return typeof Blob !== 'undefined' && obj instanceof Blob
}
// Workaround Browserify v13 bug
// https://github.com/substack/node-browserify/issues/1483
;(function () { Buffer(0) })()
}).call(this,require('_process'),require("buffer").Buffer)
},{"_process":29,"blob-to-buffer":76,"buffer":21,"fs":19,"magnet-uri":77,"parse-torrent-file":82,"simple-get":89}],76:[function(require,module,exports){
(function (Buffer){
/* global Blob, FileReader */
module.exports = function blobToBuffer (blob, cb) {
if (typeof Blob === 'undefined' || !(blob instanceof Blob)) {
throw new Error('first argument must be a Blob')
}
if (typeof cb !== 'function') {
throw new Error('second argument must be a function')
}
var reader = new FileReader()
function onLoadEnd (e) {
reader.removeEventListener('loadend', onLoadEnd, false)
if (e.error) cb(e.error)
else cb(null, new Buffer(reader.result))
}
reader.addEventListener('loadend', onLoadEnd, false)
reader.readAsArrayBuffer(blob)
}
}).call(this,require("buffer").Buffer)
},{"buffer":21}],77:[function(require,module,exports){
(function (Buffer){
module.exports = magnetURIDecode
module.exports.decode = magnetURIDecode
module.exports.encode = magnetURIEncode
var base32 = require('thirty-two')
var extend = require('xtend')
var uniq = require('uniq')
/**
* Parse a magnet URI and return an object of keys/values
*
* @param {string} uri
* @return {Object} parsed uri
*/
function magnetURIDecode (uri) {
var result = {}
// Support 'magnet:' and 'stream-magnet:' uris
var data = uri.split('magnet:?')[1]
var params = (data && data.length >= 0)
? data.split('&')
: []
params.forEach(function (param) {
var keyval = param.split('=')
// This keyval is invalid, skip it
if (keyval.length !== 2) return
var key = keyval[0]
var val = keyval[1]
// Clean up torrent name
if (key === 'dn') val = decodeURIComponent(val).replace(/\+/g, ' ')
// Address tracker (tr), exact source (xs), and acceptable source (as) are encoded
// URIs, so decode them
if (key === 'tr' || key === 'xs' || key === 'as' || key === 'ws') {
val = decodeURIComponent(val)
}
// Return keywords as an array
if (key === 'kt') val = decodeURIComponent(val).split('+')
// If there are repeated parameters, return an array of values
if (result[key]) {
if (Array.isArray(result[key])) {
result[key].push(val)
} else {
var old = result[key]
result[key] = [old, val]
}
} else {
result[key] = val
}
})
// Convenience properties for parity with `parse-torrent-file` module
var m
if (result.xt) {
var xts = Array.isArray(result.xt) ? result.xt : [ result.xt ]
xts.forEach(function (xt) {
if ((m = xt.match(/^urn:btih:(.{40})/))) {
result.infoHash = m[1].toLowerCase()
} else if ((m = xt.match(/^urn:btih:(.{32})/))) {
var decodedStr = base32.decode(m[1])
result.infoHash = new Buffer(decodedStr, 'binary').toString('hex')
}
})
}
if (result.infoHash) result.infoHashBuffer = new Buffer(result.infoHash, 'hex')
if (result.dn) result.name = result.dn
if (result.kt) result.keywords = result.kt
if (typeof result.tr === 'string') result.announce = [ result.tr ]
else if (Array.isArray(result.tr)) result.announce = result.tr
else result.announce = []
result.urlList = []
if (typeof result.as === 'string' || Array.isArray(result.as)) {
result.urlList = result.urlList.concat(result.as)
}
if (typeof result.ws === 'string' || Array.isArray(result.ws)) {
result.urlList = result.urlList.concat(result.ws)
}
uniq(result.announce)
uniq(result.urlList)
return result
}
function magnetURIEncode (obj) {
obj = extend(obj) // clone obj, so we can mutate it
// support using convenience names, in addition to spec names
// (example: `infoHash` for `xt`, `name` for `dn`)
if (obj.infoHashBuffer) obj.xt = 'urn:btih:' + obj.infoHashBuffer.toString('hex')
if (obj.infoHash) obj.xt = 'urn:btih:' + obj.infoHash
if (obj.name) obj.dn = obj.name
if (obj.keywords) obj.kt = obj.keywords
if (obj.announce) obj.tr = obj.announce
if (obj.urlList) {
obj.ws = obj.urlList
delete obj.as
}
var result = 'magnet:?'
Object.keys(obj)
.filter(function (key) {
return key.length === 2
})
.forEach(function (key, i) {
var values = Array.isArray(obj[key]) ? obj[key] : [ obj[key] ]
values.forEach(function (val, j) {
if ((i > 0 || j > 0) && (key !== 'kt' || j === 0)) result += '&'
if (key === 'dn') val = encodeURIComponent(val).replace(/%20/g, '+')
if (key === 'tr' || key === 'xs' || key === 'as' || key === 'ws') {
val = encodeURIComponent(val)
}
if (key === 'kt') val = encodeURIComponent(val)
if (key === 'kt' && j > 0) result += '+' + val
else result += key + '=' + val
})
})
return result
}
}).call(this,require("buffer").Buffer)
},{"buffer":21,"thirty-two":78,"uniq":80,"xtend":81}],78:[function(require,module,exports){
/*
Copyright (c) 2011, Chris Umbel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
var base32 = require('./thirty-two');
exports.encode = base32.encode;
exports.decode = base32.decode;
},{"./thirty-two":79}],79:[function(require,module,exports){
(function (Buffer){
/*
Copyright (c) 2011, Chris Umbel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
'use strict';
var charTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
var byteTable = [
0xff, 0xff, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
0x17, 0x18, 0x19, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
0x17, 0x18, 0x19, 0xff, 0xff, 0xff, 0xff, 0xff
];
function quintetCount(buff) {
var quintets = Math.floor(buff.length / 5);
return buff.length % 5 === 0 ? quintets: quintets + 1;
}
exports.encode = function(plain) {
if(!Buffer.isBuffer(plain)){
plain = new Buffer(plain);
}
var i = 0;
var j = 0;
var shiftIndex = 0;
var digit = 0;
var encoded = new Buffer(quintetCount(plain) * 8);
/* byte by byte isn't as pretty as quintet by quintet but tests a bit
faster. will have to revisit. */
while(i < plain.length) {
var current = plain[i];
if(shiftIndex > 3) {
digit = current & (0xff >> shiftIndex);
shiftIndex = (shiftIndex + 5) % 8;
digit = (digit << shiftIndex) | ((i + 1 < plain.length) ?
plain[i + 1] : 0) >> (8 - shiftIndex);
i++;
} else {
digit = (current >> (8 - (shiftIndex + 5))) & 0x1f;
shiftIndex = (shiftIndex + 5) % 8;
if(shiftIndex === 0) i++;
}
encoded[j] = charTable.charCodeAt(digit);
j++;
}
for(i = j; i < encoded.length; i++) {
encoded[i] = 0x3d; //'='.charCodeAt(0)
}
return encoded;
};
exports.decode = function(encoded) {
var shiftIndex = 0;
var plainDigit = 0;
var plainChar;
var plainPos = 0;
if(!Buffer.isBuffer(encoded)){
encoded = new Buffer(encoded);
}
var decoded = new Buffer(Math.ceil(encoded.length * 5 / 8));
/* byte by byte isn't as pretty as octet by octet but tests a bit
faster. will have to revisit. */
for(var i = 0; i < encoded.length; i++) {
if(encoded[i] === 0x3d){ //'='
break;
}
var encodedByte = encoded[i] - 0x30;
if(encodedByte < byteTable.length) {
plainDigit = byteTable[encodedByte];
if(shiftIndex <= 3) {
shiftIndex = (shiftIndex + 5) % 8;
if(shiftIndex === 0) {
plainChar |= plainDigit;
decoded[plainPos] = plainChar;
plainPos++;
plainChar = 0;
} else {
plainChar |= 0xff & (plainDigit << (8 - shiftIndex));
}
} else {
shiftIndex = (shiftIndex + 5) % 8;
plainChar |= 0xff & (plainDigit >>> shiftIndex);
decoded[plainPos] = plainChar;
plainPos++;
plainChar = 0xff & (plainDigit << (8 - shiftIndex));
}
} else {
throw new Error('Invalid input - it is not base32 encoded string');
}
}
return decoded.slice(0, plainPos);
};
}).call(this,require("buffer").Buffer)
},{"buffer":21}],80:[function(require,module,exports){
arguments[4][16][0].apply(exports,arguments)
},{"dup":16}],81:[function(require,module,exports){
arguments[4][17][0].apply(exports,arguments)
},{"dup":17}],82:[function(require,module,exports){
(function (Buffer){
module.exports = decodeTorrentFile
module.exports.decode = decodeTorrentFile
module.exports.encode = encodeTorrentFile
var bencode = require('bencode')
var path = require('path')
var sha1 = require('simple-sha1')
var uniq = require('uniq')
/**
* Parse a torrent. Throws an exception if the torrent is missing required fields.
* @param {Buffer|Object} torrent
* @return {Object} parsed torrent
*/
function decodeTorrentFile (torrent) {
if (Buffer.isBuffer(torrent)) {
torrent = bencode.decode(torrent)
}
// sanity check
ensure(torrent.info, 'info')
ensure(torrent.info['name.utf-8'] || torrent.info.name, 'info.name')
ensure(torrent.info['piece length'], 'info[\'piece length\']')
ensure(torrent.info.pieces, 'info.pieces')
if (torrent.info.files) {
torrent.info.files.forEach(function (file) {
ensure(typeof file.length === 'number', 'info.files[0].length')
ensure(file['path.utf-8'] || file.path, 'info.files[0].path')
})
} else {
ensure(typeof torrent.info.length === 'number', 'info.length')
}
var result = {}
result.info = torrent.info
result.infoBuffer = bencode.encode(torrent.info)
result.infoHash = sha1.sync(result.infoBuffer)
result.infoHashBuffer = new Buffer(result.infoHash, 'hex')
result.name = (torrent.info['name.utf-8'] || torrent.info.name).toString()
if (torrent.info.private !== undefined) result.private = !!torrent.info.private
if (torrent['creation date']) result.created = new Date(torrent['creation date'] * 1000)
if (torrent['created by']) result.createdBy = torrent['created by'].toString()
if (Buffer.isBuffer(torrent.comment)) result.comment = torrent.comment.toString()
// announce and announce-list will be missing if metadata fetched via ut_metadata
result.announce = []
if (torrent['announce-list'] && torrent['announce-list'].length) {
torrent['announce-list'].forEach(function (urls) {
urls.forEach(function (url) {
result.announce.push(url.toString())
})
})
} else if (torrent.announce) {
result.announce.push(torrent.announce.toString())
}
// handle url-list (BEP19 / web seeding)
if (Buffer.isBuffer(torrent['url-list'])) {
// some clients set url-list to empty string
torrent['url-list'] = torrent['url-list'].length > 0
? [ torrent['url-list'] ]
: []
}
result.urlList = (torrent['url-list'] || []).map(function (url) {
return url.toString()
})
uniq(result.announce)
uniq(result.urlList)
var files = torrent.info.files || [ torrent.info ]
result.files = files.map(function (file, i) {
var parts = [].concat(result.name, file['path.utf-8'] || file.path || []).map(function (p) {
return p.toString()
})
return {
path: path.join.apply(null, [path.sep].concat(parts)).slice(1),
name: parts[parts.length - 1],
length: file.length,
offset: files.slice(0, i).reduce(sumLength, 0)
}
})
result.length = files.reduce(sumLength, 0)
var lastFile = result.files[result.files.length - 1]
result.pieceLength = torrent.info['piece length']
result.lastPieceLength = ((lastFile.offset + lastFile.length) % result.pieceLength) || result.pieceLength
result.pieces = splitPieces(torrent.info.pieces)
return result
}
/**
* Convert a parsed torrent object back into a .torrent file buffer.
* @param {Object} parsed parsed torrent
* @return {Buffer}
*/
function encodeTorrentFile (parsed) {
var torrent = {
info: parsed.info
}
torrent['announce-list'] = (parsed.announce || []).map(function (url) {
if (!torrent.announce) torrent.announce = url
url = new Buffer(url, 'utf8')
return [ url ]
})
torrent['url-list'] = parsed.urlList || []
if (parsed.created) {
torrent['creation date'] = (parsed.created.getTime() / 1000) | 0
}
if (parsed.createdBy) {
torrent['created by'] = parsed.createdBy
}
if (parsed.comment) {
torrent.comment = parsed.comment
}
return bencode.encode(torrent)
}
function sumLength (sum, file) {
return sum + file.length
}
function splitPieces (buf) {
var pieces = []
for (var i = 0; i < buf.length; i += 20) {
pieces.push(buf.slice(i, i + 20).toString('hex'))
}
return pieces
}
function ensure (bool, fieldName) {
if (!bool) throw new Error('Torrent is missing required field: ' + fieldName)
}
}).call(this,require("buffer").Buffer)
},{"bencode":85,"buffer":21,"path":28,"simple-sha1":86,"uniq":88}],83:[function(require,module,exports){
(function (Buffer){
/**
* Decodes bencoded data.
*
* @param {Buffer} data
* @param {Number} start (optional)
* @param {Number} end (optional)
* @param {String} encoding (optional)
* @return {Object|Array|Buffer|String|Number}
*/
function decode (data, start, end, encoding) {
if (typeof start !== 'number' && encoding == null) {
encoding = start
start = undefined
}
if (typeof end !== 'number' && encoding == null) {
encoding = end
end = undefined
}
decode.position = 0
decode.encoding = encoding || null
decode.data = !(Buffer.isBuffer(data))
? new Buffer(data)
: data.slice(start, end)
decode.bytes = decode.data.length
return decode.next()
}
decode.bytes = 0
decode.position = 0
decode.data = null
decode.encoding = null
decode.next = function () {
switch (decode.data[decode.position]) {
case 0x64:
return decode.dictionary()
case 0x6C:
return decode.list()
case 0x69:
return decode.integer()
default:
return decode.buffer()
}
}
decode.find = function (chr) {
var i = decode.position
var c = decode.data.length
var d = decode.data
while (i < c) {
if (d[i] === chr) return i
i++
}
throw new Error(
'Invalid data: Missing delimiter "' +
String.fromCharCode(chr) + '" [0x' +
chr.toString(16) + ']'
)
}
decode.dictionary = function () {
decode.position++
var dict = {}
while (decode.data[decode.position] !== 0x65) {
dict[decode.buffer()] = decode.next()
}
decode.position++
return dict
}
decode.list = function () {
decode.position++
var lst = []
while (decode.data[decode.position] !== 0x65) {
lst.push(decode.next())
}
decode.position++
return lst
}
decode.integer = function () {
var end = decode.find(0x65)
var number = decode.data.toString('ascii', decode.position + 1, end)
decode.position += end + 1 - decode.position
return parseInt(number, 10)
}
decode.buffer = function () {
var sep = decode.find(0x3A)
var length = parseInt(decode.data.toString('ascii', decode.position, sep), 10)
var end = ++sep + length
decode.position = end
return decode.encoding
? decode.data.toString(decode.encoding, sep, end)
: decode.data.slice(sep, end)
}
module.exports = decode
}).call(this,require("buffer").Buffer)
},{"buffer":21}],84:[function(require,module,exports){
(function (Buffer){
/**
* Encodes data in bencode.
*
* @param {Buffer|Array|String|Object|Number|Boolean} data
* @return {Buffer}
*/
function encode (data, buffer, offset) {
var buffers = []
var result = null
encode._encode(buffers, data)
result = Buffer.concat(buffers)
encode.bytes = result.length
if (Buffer.isBuffer(buffer)) {
result.copy(buffer, offset)
return buffer
}
return result
}
encode.bytes = -1
encode._floatConversionDetected = false
encode._encode = function (buffers, data) {
if (Buffer.isBuffer(data)) {
buffers.push(new Buffer(data.length + ':'))
buffers.push(data)
return
}
switch (typeof data) {
case 'string':
encode.buffer(buffers, data)
break
case 'number':
encode.number(buffers, data)
break
case 'object':
data.constructor === Array
? encode.list(buffers, data)
: encode.dict(buffers, data)
break
case 'boolean':
encode.number(buffers, data ? 1 : 0)
break
}
}
var buffE = new Buffer('e')
var buffD = new Buffer('d')
var buffL = new Buffer('l')
encode.buffer = function (buffers, data) {
buffers.push(new Buffer(Buffer.byteLength(data) + ':' + data))
}
encode.number = function (buffers, data) {
var maxLo = 0x80000000
var hi = (data / maxLo) << 0
var lo = (data % maxLo) << 0
var val = hi * maxLo + lo
buffers.push(new Buffer('i' + val + 'e'))
if (val !== data && !encode._floatConversionDetected) {
encode._floatConversionDetected = true
console.warn(
'WARNING: Possible data corruption detected with value "' + data + '":',
'Bencoding only defines support for integers, value was converted to "' + val + '"'
)
console.trace()
}
}
encode.dict = function (buffers, data) {
buffers.push(buffD)
var j = 0
var k
// fix for issue #13 - sorted dicts
var keys = Object.keys(data).sort()
var kl = keys.length
for (; j < kl; j++) {
k = keys[j]
encode.buffer(buffers, k)
encode._encode(buffers, data[k])
}
buffers.push(buffE)
}
encode.list = function (buffers, data) {
var i = 0
var c = data.length
buffers.push(buffL)
for (; i < c; i++) {
encode._encode(buffers, data[i])
}
buffers.push(buffE)
}
module.exports = encode
}).call(this,require("buffer").Buffer)
},{"buffer":21}],85:[function(require,module,exports){
arguments[4][46][0].apply(exports,arguments)
},{"./decode":83,"./encode":84,"dup":46}],86:[function(require,module,exports){
arguments[4][60][0].apply(exports,arguments)
},{"dup":60,"rusha":87}],87:[function(require,module,exports){
(function (global){
(function () {
var /*
* Rusha, a JavaScript implementation of the Secure Hash Algorithm, SHA-1,
* as defined in FIPS PUB 180-1, tuned for high performance with large inputs.
* (http://github.com/srijs/rusha)
*
* Inspired by Paul Johnstons implementation (http://pajhome.org.uk/crypt/md5).
*
* Copyright (c) 2013 Sam Rijs (http://awesam.de).
* Released under the terms of the MIT license as follows:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
util = {
getDataType: function (data) {
if (typeof data === 'string') {
return 'string';
}
if (data instanceof Array) {
return 'array';
}
if (typeof global !== 'undefined' && global.Buffer && global.Buffer.isBuffer(data)) {
return 'buffer';
}
if (data instanceof ArrayBuffer) {
return 'arraybuffer';
}
if (data.buffer instanceof ArrayBuffer) {
return 'view';
}
if (data instanceof Blob) {
return 'blob';
}
throw new Error('Unsupported data type.');
}
};
function Rusha(chunkSize) {
'use strict';
var // Private object structure.
self$2 = { fill: 0 };
var // Calculate the length of buffer that the sha1 routine uses
// including the padding.
padlen = function (len) {
for (len += 9; len % 64 > 0; len += 1);
return len;
};
var padZeroes = function (bin, len) {
for (var i$2 = len >> 2; i$2 < bin.length; i$2++)
bin[i$2] = 0;
};
var padData = function (bin, chunkLen, msgLen) {
bin[chunkLen >> 2] |= 128 << 24 - (chunkLen % 4 << 3);
// To support msgLen >= 2 GiB, use a float division when computing the
// high 32-bits of the big-endian message length in bits.
bin[((chunkLen >> 2) + 2 & ~15) + 14] = msgLen / (1 << 29) | 0;
bin[((chunkLen >> 2) + 2 & ~15) + 15] = msgLen << 3;
};
var // Convert a binary string and write it to the heap.
// A binary string is expected to only contain char codes < 256.
convStr = function (H8, H32, start, len, off) {
var str = this, i$2, om = off % 4, lm = len % 4, j = len - lm;
if (j > 0) {
switch (om) {
case 0:
H8[off + 3 | 0] = str.charCodeAt(start);
case 1:
H8[off + 2 | 0] = str.charCodeAt(start + 1);
case 2:
H8[off + 1 | 0] = str.charCodeAt(start + 2);
case 3:
H8[off | 0] = str.charCodeAt(start + 3);
}
}
for (i$2 = om; i$2 < j; i$2 = i$2 + 4 | 0) {
H32[off + i$2 >> 2] = str.charCodeAt(start + i$2) << 24 | str.charCodeAt(start + i$2 + 1) << 16 | str.charCodeAt(start + i$2 + 2) << 8 | str.charCodeAt(start + i$2 + 3);
}
switch (lm) {
case 3:
H8[off + j + 1 | 0] = str.charCodeAt(start + j + 2);
case 2:
H8[off + j + 2 | 0] = str.charCodeAt(start + j + 1);
case 1:
H8[off + j + 3 | 0] = str.charCodeAt(start + j);
}
};
var // Convert a buffer or array and write it to the heap.
// The buffer or array is expected to only contain elements < 256.
convBuf = function (H8, H32, start, len, off) {
var buf = this, i$2, om = off % 4, lm = len % 4, j = len - lm;
if (j > 0) {
switch (om) {
case 0:
H8[off + 3 | 0] = buf[start];
case 1:
H8[off + 2 | 0] = buf[start + 1];
case 2:
H8[off + 1 | 0] = buf[start + 2];
case 3:
H8[off | 0] = buf[start + 3];
}
}
for (i$2 = 4 - om; i$2 < j; i$2 = i$2 += 4 | 0) {
H32[off + i$2 >> 2] = buf[start + i$2] << 24 | buf[start + i$2 + 1] << 16 | buf[start + i$2 + 2] << 8 | buf[start + i$2 + 3];
}
switch (lm) {
case 3:
H8[off + j + 1 | 0] = buf[start + j + 2];
case 2:
H8[off + j + 2 | 0] = buf[start + j + 1];
case 1:
H8[off + j + 3 | 0] = buf[start + j];
}
};
var convBlob = function (H8, H32, start, len, off) {
var blob = this, i$2, om = off % 4, lm = len % 4, j = len - lm;
var buf = new Uint8Array(reader.readAsArrayBuffer(blob.slice(start, start + len)));
if (j > 0) {
switch (om) {
case 0:
H8[off + 3 | 0] = buf[0];
case 1:
H8[off + 2 | 0] = buf[1];
case 2:
H8[off + 1 | 0] = buf[2];
case 3:
H8[off | 0] = buf[3];
}
}
for (i$2 = 4 - om; i$2 < j; i$2 = i$2 += 4 | 0) {
H32[off + i$2 >> 2] = buf[i$2] << 24 | buf[i$2 + 1] << 16 | buf[i$2 + 2] << 8 | buf[i$2 + 3];
}
switch (lm) {
case 3:
H8[off + j + 1 | 0] = buf[j + 2];
case 2:
H8[off + j + 2 | 0] = buf[j + 1];
case 1:
H8[off + j + 3 | 0] = buf[j];
}
};
var convFn = function (data) {
switch (util.getDataType(data)) {
case 'string':
return convStr.bind(data);
case 'array':
return convBuf.bind(data);
case 'buffer':
return convBuf.bind(data);
case 'arraybuffer':
return convBuf.bind(new Uint8Array(data));
case 'view':
return convBuf.bind(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
case 'blob':
return convBlob.bind(data);
}
};
var slice = function (data, offset) {
switch (util.getDataType(data)) {
case 'string':
return data.slice(offset);
case 'array':
return data.slice(offset);
case 'buffer':
return data.slice(offset);
case 'arraybuffer':
return data.slice(offset);
case 'view':
return data.buffer.slice(offset);
}
};
var // Precompute 00 - ff strings
precomputedHex = new Array(256);
for (var i = 0; i < 256; i++) {
precomputedHex[i] = (i < 16 ? '0' : '') + i.toString(16);
}
var // Convert an ArrayBuffer into its hexadecimal string representation.
hex = function (arrayBuffer) {
var binarray = new Uint8Array(arrayBuffer);
var res = new Array(arrayBuffer.byteLength);
for (var i$2 = 0; i$2 < res.length; i$2++) {
res[i$2] = precomputedHex[binarray[i$2]];
}
return res.join('');
};
var ceilHeapSize = function (v) {
// The asm.js spec says:
// The heap object's byteLength must be either
// 2^n for n in [12, 24) or 2^24 * n for n ≥ 1.
// Also, byteLengths smaller than 2^16 are deprecated.
var p;
if (// If v is smaller than 2^16, the smallest possible solution
// is 2^16.
v <= 65536)
return 65536;
if (// If v < 2^24, we round up to 2^n,
// otherwise we round up to 2^24 * n.
v < 16777216) {
for (p = 1; p < v; p = p << 1);
} else {
for (p = 16777216; p < v; p += 16777216);
}
return p;
};
var // Initialize the internal data structures to a new capacity.
init = function (size) {
if (size % 64 > 0) {
throw new Error('Chunk size must be a multiple of 128 bit');
}
self$2.maxChunkLen = size;
self$2.padMaxChunkLen = padlen(size);
// The size of the heap is the sum of:
// 1. The padded input message size
// 2. The extended space the algorithm needs (320 byte)
// 3. The 160 bit state the algoritm uses
self$2.heap = new ArrayBuffer(ceilHeapSize(self$2.padMaxChunkLen + 320 + 20));
self$2.h32 = new Int32Array(self$2.heap);
self$2.h8 = new Int8Array(self$2.heap);
self$2.core = new Rusha._core({
Int32Array: Int32Array,
DataView: DataView
}, {}, self$2.heap);
self$2.buffer = null;
};
// Iinitializethe datastructures according
// to a chunk siyze.
init(chunkSize || 64 * 1024);
var initState = function (heap, padMsgLen) {
var io = new Int32Array(heap, padMsgLen + 320, 5);
io[0] = 1732584193;
io[1] = -271733879;
io[2] = -1732584194;
io[3] = 271733878;
io[4] = -1009589776;
};
var padChunk = function (chunkLen, msgLen) {
var padChunkLen = padlen(chunkLen);
var view = new Int32Array(self$2.heap, 0, padChunkLen >> 2);
padZeroes(view, chunkLen);
padData(view, chunkLen, msgLen);
return padChunkLen;
};
var // Write data to the heap.
write = function (data, chunkOffset, chunkLen) {
convFn(data)(self$2.h8, self$2.h32, chunkOffset, chunkLen, 0);
};
var // Initialize and call the RushaCore,
// assuming an input buffer of length len * 4.
coreCall = function (data, chunkOffset, chunkLen, msgLen, finalize) {
var padChunkLen = chunkLen;
if (finalize) {
padChunkLen = padChunk(chunkLen, msgLen);
}
write(data, chunkOffset, chunkLen);
self$2.core.hash(padChunkLen, self$2.padMaxChunkLen);
};
var getRawDigest = function (heap, padMaxChunkLen) {
var io = new Int32Array(heap, padMaxChunkLen + 320, 5);
var out = new Int32Array(5);
var arr = new DataView(out.buffer);
arr.setInt32(0, io[0], false);
arr.setInt32(4, io[1], false);
arr.setInt32(8, io[2], false);
arr.setInt32(12, io[3], false);
arr.setInt32(16, io[4], false);
return out;
};
var // Calculate the hash digest as an array of 5 32bit integers.
rawDigest = this.rawDigest = function (str) {
var msgLen = str.byteLength || str.length || str.size || 0;
initState(self$2.heap, self$2.padMaxChunkLen);
var chunkOffset = 0, chunkLen = self$2.maxChunkLen, last;
for (chunkOffset = 0; msgLen > chunkOffset + chunkLen; chunkOffset += chunkLen) {
coreCall(str, chunkOffset, chunkLen, msgLen, false);
}
coreCall(str, chunkOffset, msgLen - chunkOffset, msgLen, true);
return getRawDigest(self$2.heap, self$2.padMaxChunkLen);
};
// The digest and digestFrom* interface returns the hash digest
// as a hex string.
this.digest = this.digestFromString = this.digestFromBuffer = this.digestFromArrayBuffer = function (str) {
return hex(rawDigest(str).buffer);
};
}
;
// The low-level RushCore module provides the heart of Rusha,
// a high-speed sha1 implementation working on an Int32Array heap.
// At first glance, the implementation seems complicated, however
// with the SHA1 spec at hand, it is obvious this almost a textbook
// implementation that has a few functions hand-inlined and a few loops
// hand-unrolled.
Rusha._core = function RushaCore(stdlib, foreign, heap) {
'use asm';
var H = new stdlib.Int32Array(heap);
function hash(k, x) {
// k in bytes
k = k | 0;
x = x | 0;
var i = 0, j = 0, y0 = 0, z0 = 0, y1 = 0, z1 = 0, y2 = 0, z2 = 0, y3 = 0, z3 = 0, y4 = 0, z4 = 0, t0 = 0, t1 = 0;
y0 = H[x + 320 >> 2] | 0;
y1 = H[x + 324 >> 2] | 0;
y2 = H[x + 328 >> 2] | 0;
y3 = H[x + 332 >> 2] | 0;
y4 = H[x + 336 >> 2] | 0;
for (i = 0; (i | 0) < (k | 0); i = i + 64 | 0) {
z0 = y0;
z1 = y1;
z2 = y2;
z3 = y3;
z4 = y4;
for (j = 0; (j | 0) < 64; j = j + 4 | 0) {
t1 = H[i + j >> 2] | 0;
t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | ~y1 & y3) | 0) + ((t1 + y4 | 0) + 1518500249 | 0) | 0;
y4 = y3;
y3 = y2;
y2 = y1 << 30 | y1 >>> 2;
y1 = y0;
y0 = t0;
H[k + j >> 2] = t1;
}
for (j = k + 64 | 0; (j | 0) < (k + 80 | 0); j = j + 4 | 0) {
t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31;
t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | ~y1 & y3) | 0) + ((t1 + y4 | 0) + 1518500249 | 0) | 0;
y4 = y3;
y3 = y2;
y2 = y1 << 30 | y1 >>> 2;
y1 = y0;
y0 = t0;
H[j >> 2] = t1;
}
for (j = k + 80 | 0; (j | 0) < (k + 160 | 0); j = j + 4 | 0) {
t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31;
t0 = ((y0 << 5 | y0 >>> 27) + (y1 ^ y2 ^ y3) | 0) + ((t1 + y4 | 0) + 1859775393 | 0) | 0;
y4 = y3;
y3 = y2;
y2 = y1 << 30 | y1 >>> 2;
y1 = y0;
y0 = t0;
H[j >> 2] = t1;
}
for (j = k + 160 | 0; (j | 0) < (k + 240 | 0); j = j + 4 | 0) {
t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31;
t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | y1 & y3 | y2 & y3) | 0) + ((t1 + y4 | 0) - 1894007588 | 0) | 0;
y4 = y3;
y3 = y2;
y2 = y1 << 30 | y1 >>> 2;
y1 = y0;
y0 = t0;
H[j >> 2] = t1;
}
for (j = k + 240 | 0; (j | 0) < (k + 320 | 0); j = j + 4 | 0) {
t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31;
t0 = ((y0 << 5 | y0 >>> 27) + (y1 ^ y2 ^ y3) | 0) + ((t1 + y4 | 0) - 899497514 | 0) | 0;
y4 = y3;
y3 = y2;
y2 = y1 << 30 | y1 >>> 2;
y1 = y0;
y0 = t0;
H[j >> 2] = t1;
}
y0 = y0 + z0 | 0;
y1 = y1 + z1 | 0;
y2 = y2 + z2 | 0;
y3 = y3 + z3 | 0;
y4 = y4 + z4 | 0;
}
H[x + 320 >> 2] = y0;
H[x + 324 >> 2] = y1;
H[x + 328 >> 2] = y2;
H[x + 332 >> 2] = y3;
H[x + 336 >> 2] = y4;
}
return { hash: hash };
};
if (// If we'e running in Node.JS, export a module.
typeof module !== 'undefined') {
module.exports = Rusha;
} else if (// If we're running in a DOM context, export
// the Rusha object to toplevel.
typeof window !== 'undefined') {
window.Rusha = Rusha;
}
if (// If we're running in a webworker, accept
// messages containing a jobid and a buffer
// or blob object, and return the hash result.
typeof FileReaderSync !== 'undefined') {
var reader = new FileReaderSync(), hasher = new Rusha(4 * 1024 * 1024);
self.onmessage = function onMessage(event) {
var hash, data = event.data.data;
try {
hash = hasher.digest(data);
self.postMessage({
id: event.data.id,
hash: hash
});
} catch (e) {
self.postMessage({
id: event.data.id,
error: e.name
});
}
};
}
}());
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],88:[function(require,module,exports){
arguments[4][16][0].apply(exports,arguments)
},{"dup":16}],89:[function(require,module,exports){
(function (Buffer){
module.exports = simpleGet
var concat = require('simple-concat')
var http = require('http')
var https = require('https')
var once = require('once')
var querystring = require('querystring')
var unzipResponse = require('unzip-response') // excluded from browser build
var url = require('url')
function simpleGet (opts, cb) {
opts = typeof opts === 'string' ? {url: opts} : Object.assign({}, opts)
cb = once(cb)
if (opts.url) parseOptsUrl(opts)
if (opts.headers == null) opts.headers = {}
if (opts.maxRedirects == null) opts.maxRedirects = 10
var body
if (opts.form) body = typeof opts.form === 'string' ? opts.form : querystring.stringify(opts.form)
if (opts.body) body = opts.json ? JSON.stringify(opts.body) : opts.body
if (opts.json) opts.headers.accept = 'application/json'
if (opts.json && body) opts.headers['content-type'] = 'application/json'
if (opts.form) opts.headers['content-type'] = 'application/x-www-form-urlencoded'
if (body) opts.headers['content-length'] = Buffer.byteLength(body)
delete opts.body; delete opts.form
if (body && !opts.method) opts.method = 'POST'
if (opts.method) opts.method = opts.method.toUpperCase()
// Request gzip/deflate
var customAcceptEncoding = Object.keys(opts.headers).some(function (h) {
return h.toLowerCase() === 'accept-encoding'
})
if (!customAcceptEncoding) opts.headers['accept-encoding'] = 'gzip, deflate'
// Support http/https urls
var protocol = opts.protocol === 'https:' ? https : http
var req = protocol.request(opts, function (res) {
// Follow 3xx redirects
if (res.statusCode >= 300 && res.statusCode < 400 && 'location' in res.headers) {
opts.url = res.headers.location
parseOptsUrl(opts)
res.resume() // Discard response
opts.maxRedirects -= 1
if (opts.maxRedirects > 0) simpleGet(opts, cb)
else cb(new Error('too many redirects'))
return
}
var tryUnzip = typeof unzipResponse === 'function' && opts.method !== 'HEAD'
cb(null, tryUnzip ? unzipResponse(res) : res)
})
req.on('error', cb)
req.end(body)
return req
}
simpleGet.concat = function (opts, cb) {
return simpleGet(opts, function (err, res) {
if (err) return cb(err)
concat(res, function (err, data) {
if (err) return cb(err)
if (opts.json) {
try {
data = JSON.parse(data.toString())
} catch (err) {
return cb(err, res, data)
}
}
cb(null, res, data)
})
})
}
;['get', 'post', 'put', 'patch', 'head', 'delete'].forEach(function (method) {
simpleGet[method] = function (opts, cb) {
if (typeof opts === 'string') opts = {url: opts}
opts.method = method.toUpperCase()
return simpleGet(opts, cb)
}
})
function parseOptsUrl (opts) {
var loc = url.parse(opts.url)
if (loc.hostname) opts.hostname = loc.hostname
if (loc.port) opts.port = loc.port
if (loc.protocol) opts.protocol = loc.protocol
if (loc.auth) opts.auth = loc.auth
opts.path = loc.path
delete opts.url
}
}).call(this,require("buffer").Buffer)
},{"buffer":21,"http":34,"https":26,"once":91,"querystring":33,"simple-concat":92,"unzip-response":20,"url":40}],90:[function(require,module,exports){
arguments[4][10][0].apply(exports,arguments)
},{"dup":10}],91:[function(require,module,exports){
arguments[4][11][0].apply(exports,arguments)
},{"dup":11,"wrappy":90}],92:[function(require,module,exports){
(function (Buffer){
module.exports = function (stream, cb) {
var chunks = []
stream.on('data', function (chunk) {
chunks.push(chunk)
})
stream.once('end', function () {
if (cb) cb(null, Buffer.concat(chunks))
cb = null
})
stream.once('error', function (err) {
if (cb) cb(err)
cb = null
})
}
}).call(this,require("buffer").Buffer)
},{"buffer":21}],93:[function(require,module,exports){
var once = require('once')
var eos = require('end-of-stream')
var fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes
var noop = function () {}
var isFn = function (fn) {
return typeof fn === 'function'
}
var isFS = function (stream) {
return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close)
}
var isRequest = function (stream) {
return stream.setHeader && isFn(stream.abort)
}
var destroyer = function (stream, reading, writing, callback) {
callback = once(callback)
var closed = false
stream.on('close', function () {
closed = true
})
eos(stream, {readable: reading, writable: writing}, function (err) {
if (err) return callback(err)
closed = true
callback()
})
var destroyed = false
return function (err) {
if (closed) return
if (destroyed) return
destroyed = true
if (isFS(stream)) return stream.close() // use close for fs streams to avoid fd leaks
if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want
if (isFn(stream.destroy)) return stream.destroy()
callback(err || new Error('stream was destroyed'))
}
}
var call = function (fn) {
fn()
}
var pipe = function (from, to) {
return from.pipe(to)
}
var pump = function () {
var streams = Array.prototype.slice.call(arguments)
var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop
if (Array.isArray(streams[0])) streams = streams[0]
if (streams.length < 2) throw new Error('pump requires two streams per minimum')
var error
var destroys = streams.map(function (stream, i) {
var reading = i < streams.length - 1
var writing = i > 0
return destroyer(stream, reading, writing, function (err) {
if (!error) error = err
if (err) destroys.forEach(call)
if (reading) return
destroys.forEach(call)
callback(error)
})
})
return streams.reduce(pipe)
}
module.exports = pump
},{"end-of-stream":94,"fs":19,"once":98}],94:[function(require,module,exports){
var once = require('once');
var noop = function() {};
var isRequest = function(stream) {
return stream.setHeader && typeof stream.abort === 'function';
};
var isChildProcess = function(stream) {
return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
};
var eos = function(stream, opts, callback) {
if (typeof opts === 'function') return eos(stream, null, opts);
if (!opts) opts = {};
callback = once(callback || noop);
var ws = stream._writableState;
var rs = stream._readableState;
var readable = opts.readable || (opts.readable !== false && stream.readable);
var writable = opts.writable || (opts.writable !== false && stream.writable);
var onlegacyfinish = function() {
if (!stream.writable) onfinish();
};
var onfinish = function() {
writable = false;
if (!readable) callback();
};
var onend = function() {
readable = false;
if (!writable) callback();
};
var onexit = function(exitCode) {
callback(exitCode ? new Error('exited with error code: ' + exitCode) : null);
};
var onclose = function() {
if (readable && !(rs && rs.ended)) return callback(new Error('premature close'));
if (writable && !(ws && ws.ended)) return callback(new Error('premature close'));
};
var onrequest = function() {
stream.req.on('finish', onfinish);
};
if (isRequest(stream)) {
stream.on('complete', onfinish);
stream.on('abort', onclose);
if (stream.req) onrequest();
else stream.on('request', onrequest);
} else if (writable && !ws) { // legacy streams
stream.on('end', onlegacyfinish);
stream.on('close', onlegacyfinish);
}
if (isChildProcess(stream)) stream.on('exit', onexit);
stream.on('end', onend);
stream.on('finish', onfinish);
if (opts.error !== false) stream.on('error', callback);
stream.on('close', onclose);
return function() {
stream.removeListener('complete', onfinish);
stream.removeListener('abort', onclose);
stream.removeListener('request', onrequest);
if (stream.req) stream.req.removeListener('finish', onfinish);
stream.removeListener('end', onlegacyfinish);
stream.removeListener('close', onlegacyfinish);
stream.removeListener('finish', onfinish);
stream.removeListener('exit', onexit);
stream.removeListener('end', onend);
stream.removeListener('error', callback);
stream.removeListener('close', onclose);
};
};
module.exports = eos;
},{"once":96}],95:[function(require,module,exports){
arguments[4][10][0].apply(exports,arguments)
},{"dup":10}],96:[function(require,module,exports){
var wrappy = require('wrappy')
module.exports = wrappy(once)
once.proto = once(function () {
Object.defineProperty(Function.prototype, 'once', {
value: function () {
return once(this)
},
configurable: true
})
})
function once (fn) {
var f = function () {
if (f.called) return f.value
f.called = true
return f.value = fn.apply(this, arguments)
}
f.called = false
return f
}
},{"wrappy":95}],97:[function(require,module,exports){
arguments[4][10][0].apply(exports,arguments)
},{"dup":10}],98:[function(require,module,exports){
arguments[4][11][0].apply(exports,arguments)
},{"dup":11,"wrappy":97}],99:[function(require,module,exports){
/*
Instance of writable stream.
call .get(length) or .discard(length) to get a stream (relative to the last end)
emits 'stalled' once everything is written
*/
var inherits = require('inherits')
var stream = require('readable-stream')
module.exports = RangeSliceStream
inherits(RangeSliceStream, stream.Writable)
function RangeSliceStream (offset) {
var self = this
if (!(self instanceof RangeSliceStream)) return new RangeSliceStream(offset)
stream.Writable.call(self)
self.destroyed = false
self._queue = []
self._position = offset || 0
self._cb = null
self._buffer = null
self._out = null
}
RangeSliceStream.prototype._write = function (chunk, encoding, cb) {
var self = this
var drained = true
while (true) {
if (self.destroyed) {
return
}
// Wait for more queue entries
if (self._queue.length === 0) {
self._buffer = chunk
self._cb = cb
return
}
self._buffer = null
var currRange = self._queue[0]
// Relative to the start of chunk, what data do we need?
var writeStart = Math.max(currRange.start - self._position, 0)
var writeEnd = currRange.end - self._position
// Check if we need to throw it all away
if (writeStart >= chunk.length) {
self._position += chunk.length
return cb(null)
}
// Check if we need to use it all
var toWrite
if (writeEnd > chunk.length) {
self._position += chunk.length
if (writeStart === 0) {
toWrite = chunk
} else {
toWrite = chunk.slice(writeStart)
}
drained = currRange.stream.write(toWrite) && drained
break
}
self._position += writeEnd
if (writeStart === 0 && writeEnd === chunk.length) {
toWrite = chunk
} else {
toWrite = chunk.slice(writeStart, writeEnd)
}
drained = currRange.stream.write(toWrite) && drained
if (currRange.last) {
currRange.stream.end()
}
chunk = chunk.slice(writeEnd)
self._queue.shift()
}
if (drained) {
cb(null)
} else {
currRange.stream.once('drain', cb.bind(null, null))
}
}
RangeSliceStream.prototype.slice = function (ranges) {
var self = this
if (self.destroyed) return null
if (!(ranges instanceof Array)) {
ranges = [ranges]
}
var str = new stream.PassThrough()
ranges.forEach(function (range, i) {
self._queue.push({
start: range.start,
end: range.end,
stream: str,
last: i === (ranges.length - 1)
})
})
if (self._buffer) {
self._write(self._buffer, null, self._cb)
}
return str
}
RangeSliceStream.prototype.destroy = function (err) {
var self = this
if (self.destroyed) return
self.destroyed = true
if (err) self.emit('error', err)
}
},{"inherits":63,"readable-stream":112}],100:[function(require,module,exports){
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
'use strict';
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}return keys;
};
/*</replacement>*/
module.exports = Duplex;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false) this.readable = false;
if (options && options.writable === false) this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
this.once('end', onend);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
processNextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
function forEach(xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
},{"./_stream_readable":102,"./_stream_writable":104,"core-util-is":107,"inherits":63,"process-nextick-args":109}],101:[function(require,module,exports){
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
'use strict';
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough)) return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function (chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":103,"core-util-is":107,"inherits":63}],102:[function(require,module,exports){
(function (process){
'use strict';
module.exports = Readable;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
Readable.ReadableState = ReadableState;
/*<replacement>*/
var EE = require('events').EventEmitter;
var EElistenerCount = function (emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
/*<replacement>*/
var Stream;
(function () {
try {
Stream = require('st' + 'ream');
} catch (_) {} finally {
if (!Stream) Stream = require('events').EventEmitter;
}
})();
/*</replacement>*/
var Buffer = require('buffer').Buffer;
/*<replacement>*/
var bufferShim = require('buffer-shims');
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var debugUtil = require('util');
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
var BufferList = require('./internal/streams/BufferList');
var StringDecoder;
util.inherits(Readable, Stream);
function prependListener(emitter, event, fn) {
if (typeof emitter.prependListener === 'function') {
return emitter.prependListener(event, fn);
} else {
// This is a hack to make sure that our error handler is attached before any
// userland ones. NEVER DO THIS. This is here only because this code needs
// to continue to work with older versions of Node.js that do not include
// the prependListener() method. The goal is to eventually remove this hack.
if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}
}
var Duplex;
function ReadableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = ~ ~this.highWaterMark;
// A linked list is used to store data chunks instead of an array because the
// linked list can remove elements from the beginning faster than
// array.shift()
this.buffer = new BufferList();
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
this.resumeScheduled = false;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// when piping, we only care about 'readable' events that happen
// after read()ing all the bytes and not getting any pushback.
this.ranOut = false;
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
var Duplex;
function Readable(options) {
Duplex = Duplex || require('./_stream_duplex');
if (!(this instanceof Readable)) return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
if (options && typeof options.read === 'function') this._read = options.read;
Stream.call(this);
}
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
var state = this._readableState;
if (!state.objectMode && typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = bufferShim.from(chunk, encoding);
encoding = '';
}
}
return readableAddChunk(this, state, chunk, encoding, false);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
var state = this._readableState;
return readableAddChunk(this, state, chunk, '', true);
};
Readable.prototype.isPaused = function () {
return this._readableState.flowing === false;
};
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
var er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (chunk === null) {
state.reading = false;
onEofChunk(stream, state);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (state.ended && !addToFront) {
var e = new Error('stream.push() after EOF');
stream.emit('error', e);
} else if (state.endEmitted && addToFront) {
var _e = new Error('stream.unshift() after end event');
stream.emit('error', _e);
} else {
var skipAdd;
if (state.decoder && !addToFront && !encoding) {
chunk = state.decoder.write(chunk);
skipAdd = !state.objectMode && chunk.length === 0;
}
if (!addToFront) state.reading = false;
// Don't add to the buffer if we've decoded to an empty string chunk and
// we're not in object mode
if (!skipAdd) {
// if we want the data now, just emit it.
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
if (state.needReadable) emitReadable(stream);
}
}
maybeReadMore(stream, state);
}
} else if (!addToFront) {
state.reading = false;
}
return needMoreData(state);
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}
// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2 to prevent increasing hwm excessively in
// tiny amounts
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
n++;
}
return n;
}
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
if (n <= 0 || state.length === 0 && state.ended) return 0;
if (state.objectMode) return 1;
if (n !== n) {
// Only flow one buffer at a time
if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
}
// If we're asking for more than the current hwm, then raise the hwm.
if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
if (n <= state.length) return n;
// Don't have enough
if (!state.ended) {
state.needReadable = true;
return 0;
}
return state.length;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
debug('read', n);
n = parseInt(n, 10);
var state = this._readableState;
var nOrig = n;
if (n !== 0) state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0) endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
} else if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0) state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (!state.reading) n = howMuchToRead(nOrig, state);
}
var ret;
if (n > 0) ret = fromList(n, state);else ret = null;
if (ret === null) {
state.needReadable = true;
n = 0;
} else {
state.length -= n;
}
if (state.length === 0) {
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (!state.ended) state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended) endReadable(this);
}
if (ret !== null) this.emit('data', ret);
return ret;
};
function chunkInvalid(state, chunk) {
var er = null;
if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
function onEofChunk(stream, state) {
if (state.ended) return;
if (state.decoder) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
processNextTick(maybeReadMore_, stream, state);
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;else len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
this.emit('error', new Error('not implemented'));
};
Readable.prototype.pipe = function (dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
var endFn = doEnd ? onend : cleanup;
if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable) {
debug('onunpipe');
if (readable === src) {
cleanup();
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
var cleanedUp = false;
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', cleanup);
src.removeListener('data', ondata);
cleanedUp = true;
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
}
// If the user pushes more data while we're writing to dest then we'll end up
// in ondata again. However, we only want to increase awaitDrain once because
// dest will only emit one 'drain' event for the multiple writes.
// => Introduce a guard on increasing awaitDrain.
var increasedAwaitDrain = false;
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
increasedAwaitDrain = false;
var ret = dest.write(chunk);
if (false === ret && !increasedAwaitDrain) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
// => Check whether `dest` is still a piping destination.
if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
debug('false write response, pause', src._readableState.awaitDrain);
src._readableState.awaitDrain++;
increasedAwaitDrain = true;
}
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
}
// Make sure our error handler is attached before userland ones.
prependListener(dest, 'error', onerror);
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function () {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain) state.awaitDrain--;
if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function (dest) {
var state = this._readableState;
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0) return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes) return this;
if (!dest) dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest) dest.emit('unpipe', this);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var _i = 0; _i < len; _i++) {
dests[_i].emit('unpipe', this);
}return this;
}
// try to find the right one.
var i = indexOf(state.pipes, dest);
if (i === -1) return this;
state.pipes.splice(i, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1) state.pipes = state.pipes[0];
dest.emit('unpipe', this);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
if (ev === 'data') {
// Start flowing on next tick if stream isn't explicitly paused
if (this._readableState.flowing !== false) this.resume();
} else if (ev === 'readable') {
var state = this._readableState;
if (!state.endEmitted && !state.readableListening) {
state.readableListening = state.needReadable = true;
state.emittedReadable = false;
if (!state.reading) {
processNextTick(nReadingNextTick, this);
} else if (state.length) {
emitReadable(this, state);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
function nReadingNextTick(self) {
debug('readable nexttick read 0');
self.read(0);
}
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
processNextTick(resume_, stream, state);
}
}
function resume_(stream, state) {
if (!state.reading) {
debug('resume read 0');
stream.read(0);
}
state.resumeScheduled = false;
state.awaitDrain = 0;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading) stream.read(0);
}
Readable.prototype.pause = function () {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
while (state.flowing && stream.read() !== null) {}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
var state = this._readableState;
var paused = false;
var self = this;
stream.on('end', function () {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) self.push(chunk);
}
self.push(null);
});
stream.on('data', function (chunk) {
debug('wrapped data');
if (state.decoder) chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
var ret = self.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function (method) {
return function () {
return stream[method].apply(stream, arguments);
};
}(i);
}
}
// proxy certain important events.
var events = ['error', 'close', 'destroy', 'pause', 'resume'];
forEach(events, function (ev) {
stream.on(ev, self.emit.bind(self, ev));
});
// when we try to consume some more bytes, simply unpause the
// underlying stream.
self._read = function (n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return self;
};
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
// nothing buffered
if (state.length === 0) return null;
var ret;
if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the list
if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
state.buffer.clear();
} else {
// read part of list
ret = fromListPartial(n, state.buffer, state.decoder);
}
return ret;
}
// Extracts only enough buffered data to satisfy the amount requested.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromListPartial(n, list, hasStrings) {
var ret;
if (n < list.head.data.length) {
// slice is the same for buffers and strings
ret = list.head.data.slice(0, n);
list.head.data = list.head.data.slice(n);
} else if (n === list.head.data.length) {
// first chunk is a perfect match
ret = list.shift();
} else {
// result spans more than one buffer
ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
}
return ret;
}
// Copies a specified amount of characters from the list of buffered data
// chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBufferString(n, list) {
var p = list.head;
var c = 1;
var ret = p.data;
n -= ret.length;
while (p = p.next) {
var str = p.data;
var nb = n > str.length ? str.length : n;
if (nb === str.length) ret += str;else ret += str.slice(0, n);
n -= nb;
if (n === 0) {
if (nb === str.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = str.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
// Copies a specified amount of bytes from the list of buffered data chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBuffer(n, list) {
var ret = bufferShim.allocUnsafe(n);
var p = list.head;
var c = 1;
p.data.copy(ret);
n -= p.data.length;
while (p = p.next) {
var buf = p.data;
var nb = n > buf.length ? buf.length : n;
buf.copy(ret, ret.length - n, 0, nb);
n -= nb;
if (n === 0) {
if (nb === buf.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = buf.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
processNextTick(endReadableNT, state, stream);
}
}
function endReadableNT(state, stream) {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
}
function forEach(xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
function indexOf(xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
}).call(this,require('_process'))
},{"./_stream_duplex":100,"./internal/streams/BufferList":105,"_process":29,"buffer":21,"buffer-shims":106,"core-util-is":107,"events":25,"inherits":63,"isarray":108,"process-nextick-args":109,"string_decoder/":110,"util":20}],103:[function(require,module,exports){
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
'use strict';
module.exports = Transform;
var Duplex = require('./_stream_duplex');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(Transform, Duplex);
function TransformState(stream) {
this.afterTransform = function (er, data) {
return afterTransform(stream, er, data);
};
this.needTransform = false;
this.transforming = false;
this.writecb = null;
this.writechunk = null;
this.writeencoding = null;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
ts.writechunk = null;
ts.writecb = null;
if (data !== null && data !== undefined) stream.push(data);
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
Duplex.call(this, options);
this._transformState = new TransformState(this);
// when the writable side finishes, then flush out anything remaining.
var stream = this;
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
if (typeof options.flush === 'function') this._flush = options.flush;
}
this.once('prefinish', function () {
if (typeof this._flush === 'function') this._flush(function (er) {
done(stream, er);
});else done(stream);
});
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
throw new Error('Not implemented');
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
function done(stream, er) {
if (er) return stream.emit('error', er);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
var ws = stream._writableState;
var ts = stream._transformState;
if (ws.length) throw new Error('Calling transform done when ws.length != 0');
if (ts.transforming) throw new Error('Calling transform done when still transforming');
return stream.push(null);
}
},{"./_stream_duplex":100,"core-util-is":107,"inherits":63}],104:[function(require,module,exports){
(function (process){
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
'use strict';
module.exports = Writable;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var internalUtil = {
deprecate: require('util-deprecate')
};
/*</replacement>*/
/*<replacement>*/
var Stream;
(function () {
try {
Stream = require('st' + 'ream');
} catch (_) {} finally {
if (!Stream) Stream = require('events').EventEmitter;
}
})();
/*</replacement>*/
var Buffer = require('buffer').Buffer;
/*<replacement>*/
var bufferShim = require('buffer-shims');
/*</replacement>*/
util.inherits(Writable, Stream);
function nop() {}
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
this.next = null;
}
var Duplex;
function WritableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = ~ ~this.highWaterMark;
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function (er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.bufferedRequest = null;
this.lastBufferedRequest = null;
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
// count buffered requests
this.bufferedRequestCount = 0;
// allocate the first CorkedRequest, there is always
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function writableStateGetBuffer() {
var current = this.bufferedRequest;
var out = [];
while (current) {
out.push(current);
current = current.next;
}
return out;
};
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function () {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
});
} catch (_) {}
})();
var Duplex;
function Writable(options) {
Duplex = Duplex || require('./_stream_duplex');
// Writable ctor is applied to Duplexes, though they're not
// instanceof Writable, they're instanceof Readable.
if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options);
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
if (options) {
if (typeof options.write === 'function') this._write = options.write;
if (typeof options.writev === 'function') this._writev = options.writev;
}
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
this.emit('error', new Error('Cannot pipe, not readable'));
};
function writeAfterEnd(stream, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
processNextTick(cb, er);
}
// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
var valid = true;
var er = false;
// Always throw error if a null is written
// if we are not in object mode then throw
// if it is not a buffer, string, or undefined.
if (chunk === null) {
er = new TypeError('May not write null values to stream');
} else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
if (er) {
stream.emit('error', er);
processNextTick(cb, er);
valid = false;
}
return valid;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
if (typeof cb !== 'function') cb = nop;
if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function () {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function () {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
this._writableState.defaultEncoding = encoding;
return this;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = bufferShim.from(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
if (Buffer.isBuffer(chunk)) encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
if (sync) processNextTick(cb, er);else cb(er);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(state);
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
if (sync) {
/*<replacement>*/
asyncWrite(afterWrite, stream, state, finished, cb);
/*</replacement>*/
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
var count = 0;
while (entry) {
buffer[count] = entry;
entry = entry.next;
count += 1;
}
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
// as the hot path ends with doWrite
state.pendingcb++;
state.lastBufferedRequest = null;
if (holder.next) {
state.corkedRequestsFree = holder.next;
holder.next = null;
} else {
state.corkedRequestsFree = new CorkedRequest(state);
}
} else {
// Slow case, write chunks one-by-one
while (entry) {
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
break;
}
}
if (entry === null) state.lastBufferedRequest = null;
}
state.bufferedRequestCount = 0;
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new Error('not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished) endWritable(this, state, cb);
};
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function prefinish(stream, state) {
if (!state.prefinished) {
state.prefinished = true;
stream.emit('prefinish');
}
}
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
if (state.pendingcb === 0) {
prefinish(stream, state);
state.finished = true;
stream.emit('finish');
} else {
prefinish(stream, state);
}
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished) processNextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
this.next = null;
this.entry = null;
this.finish = function (err) {
var entry = _this.entry;
_this.entry = null;
while (entry) {
var cb = entry.callback;
state.pendingcb--;
cb(err);
entry = entry.next;
}
if (state.corkedRequestsFree) {
state.corkedRequestsFree.next = _this;
} else {
state.corkedRequestsFree = _this;
}
};
}
}).call(this,require('_process'))
},{"./_stream_duplex":100,"_process":29,"buffer":21,"buffer-shims":106,"core-util-is":107,"events":25,"inherits":63,"process-nextick-args":109,"util-deprecate":111}],105:[function(require,module,exports){
'use strict';
var Buffer = require('buffer').Buffer;
/*<replacement>*/
var bufferShim = require('buffer-shims');
/*</replacement>*/
module.exports = BufferList;
function BufferList() {
this.head = null;
this.tail = null;
this.length = 0;
}
BufferList.prototype.push = function (v) {
var entry = { data: v, next: null };
if (this.length > 0) this.tail.next = entry;else this.head = entry;
this.tail = entry;
++this.length;
};
BufferList.prototype.unshift = function (v) {
var entry = { data: v, next: this.head };
if (this.length === 0) this.tail = entry;
this.head = entry;
++this.length;
};
BufferList.prototype.shift = function () {
if (this.length === 0) return;
var ret = this.head.data;
if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
--this.length;
return ret;
};
BufferList.prototype.clear = function () {
this.head = this.tail = null;
this.length = 0;
};
BufferList.prototype.join = function (s) {
if (this.length === 0) return '';
var p = this.head;
var ret = '' + p.data;
while (p = p.next) {
ret += s + p.data;
}return ret;
};
BufferList.prototype.concat = function (n) {
if (this.length === 0) return bufferShim.alloc(0);
if (this.length === 1) return this.head.data;
var ret = bufferShim.allocUnsafe(n >>> 0);
var p = this.head;
var i = 0;
while (p) {
p.data.copy(ret, i);
i += p.data.length;
p = p.next;
}
return ret;
};
},{"buffer":21,"buffer-shims":106}],106:[function(require,module,exports){
(function (global){
'use strict';
var buffer = require('buffer');
var Buffer = buffer.Buffer;
var SlowBuffer = buffer.SlowBuffer;
var MAX_LEN = buffer.kMaxLength || 2147483647;
exports.alloc = function alloc(size, fill, encoding) {
if (typeof Buffer.alloc === 'function') {
return Buffer.alloc(size, fill, encoding);
}
if (typeof encoding === 'number') {
throw new TypeError('encoding must not be number');
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size > MAX_LEN) {
throw new RangeError('size is too large');
}
var enc = encoding;
var _fill = fill;
if (_fill === undefined) {
enc = undefined;
_fill = 0;
}
var buf = new Buffer(size);
if (typeof _fill === 'string') {
var fillBuf = new Buffer(_fill, enc);
var flen = fillBuf.length;
var i = -1;
while (++i < size) {
buf[i] = fillBuf[i % flen];
}
} else {
buf.fill(_fill);
}
return buf;
}
exports.allocUnsafe = function allocUnsafe(size) {
if (typeof Buffer.allocUnsafe === 'function') {
return Buffer.allocUnsafe(size);
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size > MAX_LEN) {
throw new RangeError('size is too large');
}
return new Buffer(size);
}
exports.from = function from(value, encodingOrOffset, length) {
if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
return Buffer.from(value, encodingOrOffset, length);
}
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number');
}
if (typeof value === 'string') {
return new Buffer(value, encodingOrOffset);
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
var offset = encodingOrOffset;
if (arguments.length === 1) {
return new Buffer(value);
}
if (typeof offset === 'undefined') {
offset = 0;
}
var len = length;
if (typeof len === 'undefined') {
len = value.byteLength - offset;
}
if (offset >= value.byteLength) {
throw new RangeError('\'offset\' is out of bounds');
}
if (len > value.byteLength - offset) {
throw new RangeError('\'length\' is out of bounds');
}
return new Buffer(value.slice(offset, offset + len));
}
if (Buffer.isBuffer(value)) {
var out = new Buffer(value.length);
value.copy(out, 0, 0, value.length);
return out;
}
if (value) {
if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
return new Buffer(value);
}
if (value.type === 'Buffer' && Array.isArray(value.data)) {
return new Buffer(value.data);
}
}
throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
}
exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
if (typeof Buffer.allocUnsafeSlow === 'function') {
return Buffer.allocUnsafeSlow(size);
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size >= MAX_LEN) {
throw new RangeError('size is too large');
}
return new SlowBuffer(size);
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"buffer":21}],107:[function(require,module,exports){
(function (Buffer){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this,{"isBuffer":require("../../../../browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js")})
},{"../../../../browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js":27}],108:[function(require,module,exports){
arguments[4][24][0].apply(exports,arguments)
},{"dup":24}],109:[function(require,module,exports){
(function (process){
'use strict';
if (!process.version ||
process.version.indexOf('v0.') === 0 ||
process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
module.exports = nextTick;
} else {
module.exports = process.nextTick;
}
function nextTick(fn, arg1, arg2, arg3) {
if (typeof fn !== 'function') {
throw new TypeError('"callback" argument must be a function');
}
var len = arguments.length;
var args, i;
switch (len) {
case 0:
case 1:
return process.nextTick(fn);
case 2:
return process.nextTick(function afterTickOne() {
fn.call(null, arg1);
});
case 3:
return process.nextTick(function afterTickTwo() {
fn.call(null, arg1, arg2);
});
case 4:
return process.nextTick(function afterTickThree() {
fn.call(null, arg1, arg2, arg3);
});
default:
args = new Array(len - 1);
i = 0;
while (i < args.length) {
args[i++] = arguments[i];
}
return process.nextTick(function afterTick() {
fn.apply(null, args);
});
}
}
}).call(this,require('_process'))
},{"_process":29}],110:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var Buffer = require('buffer').Buffer;
var isBufferEncoding = Buffer.isEncoding
|| function(encoding) {
switch (encoding && encoding.toLowerCase()) {
case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
default: return false;
}
}
function assertEncoding(encoding) {
if (encoding && !isBufferEncoding(encoding)) {
throw new Error('Unknown encoding: ' + encoding);
}
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters. CESU-8 is handled as part of the UTF-8 encoding.
//
// @TODO Handling all encodings inside a single object makes it very difficult
// to reason about this code, so it should be split up in the future.
// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
// points as used by CESU-8.
var StringDecoder = exports.StringDecoder = function(encoding) {
this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
assertEncoding(encoding);
switch (this.encoding) {
case 'utf8':
// CESU-8 represents each of Surrogate Pair by 3-bytes
this.surrogateSize = 3;
break;
case 'ucs2':
case 'utf16le':
// UTF-16 represents each of Surrogate Pair by 2-bytes
this.surrogateSize = 2;
this.detectIncompleteChar = utf16DetectIncompleteChar;
break;
case 'base64':
// Base-64 stores 3 bytes in 4 chars, and pads the remainder.
this.surrogateSize = 3;
this.detectIncompleteChar = base64DetectIncompleteChar;
break;
default:
this.write = passThroughWrite;
return;
}
// Enough space to store all bytes of a single character. UTF-8 needs 4
// bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
this.charBuffer = new Buffer(6);
// Number of bytes received for the current incomplete multi-byte character.
this.charReceived = 0;
// Number of bytes expected for the current incomplete multi-byte character.
this.charLength = 0;
};
// write decodes the given buffer and returns it as JS string that is
// guaranteed to not contain any partial multi-byte characters. Any partial
// character found at the end of the buffer is buffered up, and will be
// returned when calling write again with the remaining bytes.
//
// Note: Converting a Buffer containing an orphan surrogate to a String
// currently works, but converting a String to a Buffer (via `new Buffer`, or
// Buffer#write) will replace incomplete surrogates with the unicode
// replacement character. See https://codereview.chromium.org/121173009/ .
StringDecoder.prototype.write = function(buffer) {
var charStr = '';
// if our last write ended with an incomplete multibyte character
while (this.charLength) {
// determine how many remaining bytes this buffer has to offer for this char
var available = (buffer.length >= this.charLength - this.charReceived) ?
this.charLength - this.charReceived :
buffer.length;
// add the new bytes to the char buffer
buffer.copy(this.charBuffer, this.charReceived, 0, available);
this.charReceived += available;
if (this.charReceived < this.charLength) {
// still not enough chars in this buffer? wait for more ...
return '';
}
// remove bytes belonging to the current character from the buffer
buffer = buffer.slice(available, buffer.length);
// get the character that was split
charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
var charCode = charStr.charCodeAt(charStr.length - 1);
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
this.charLength += this.surrogateSize;
charStr = '';
continue;
}
this.charReceived = this.charLength = 0;
// if there are no more bytes in this buffer, just emit our char
if (buffer.length === 0) {
return charStr;
}
break;
}
// determine and set charLength / charReceived
this.detectIncompleteChar(buffer);
var end = buffer.length;
if (this.charLength) {
// buffer the incomplete character bytes we got
buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
end -= this.charReceived;
}
charStr += buffer.toString(this.encoding, 0, end);
var end = charStr.length - 1;
var charCode = charStr.charCodeAt(end);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
var size = this.surrogateSize;
this.charLength += size;
this.charReceived += size;
this.charBuffer.copy(this.charBuffer, size, 0, size);
buffer.copy(this.charBuffer, 0, 0, size);
return charStr.substring(0, end);
}
// or just emit the charStr
return charStr;
};
// detectIncompleteChar determines if there is an incomplete UTF-8 character at
// the end of the given buffer. If so, it sets this.charLength to the byte
// length that character, and sets this.charReceived to the number of bytes
// that are available for this character.
StringDecoder.prototype.detectIncompleteChar = function(buffer) {
// determine how many bytes we have to check at the end of this buffer
var i = (buffer.length >= 3) ? 3 : buffer.length;
// Figure out if one of the last i bytes of our buffer announces an
// incomplete char.
for (; i > 0; i--) {
var c = buffer[buffer.length - i];
// See http://en.wikipedia.org/wiki/UTF-8#Description
// 110XXXXX
if (i == 1 && c >> 5 == 0x06) {
this.charLength = 2;
break;
}
// 1110XXXX
if (i <= 2 && c >> 4 == 0x0E) {
this.charLength = 3;
break;
}
// 11110XXX
if (i <= 3 && c >> 3 == 0x1E) {
this.charLength = 4;
break;
}
}
this.charReceived = i;
};
StringDecoder.prototype.end = function(buffer) {
var res = '';
if (buffer && buffer.length)
res = this.write(buffer);
if (this.charReceived) {
var cr = this.charReceived;
var buf = this.charBuffer;
var enc = this.encoding;
res += buf.slice(0, cr).toString(enc);
}
return res;
};
function passThroughWrite(buffer) {
return buffer.toString(this.encoding);
}
function utf16DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 2;
this.charLength = this.charReceived ? 2 : 0;
}
function base64DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 3;
this.charLength = this.charReceived ? 3 : 0;
}
},{"buffer":21}],111:[function(require,module,exports){
(function (global){
/**
* Module exports.
*/
module.exports = deprecate;
/**
* Mark that a method should not be used.
* Returns a modified function which warns once by default.
*
* If `localStorage.noDeprecation = true` is set, then it is a no-op.
*
* If `localStorage.throwDeprecation = true` is set, then deprecated functions
* will throw an Error when invoked.
*
* If `localStorage.traceDeprecation = true` is set, then deprecated functions
* will invoke `console.trace()` instead of `console.error()`.
*
* @param {Function} fn - the function to deprecate
* @param {String} msg - the string to print to the console when `fn` is invoked
* @returns {Function} a new "deprecated" version of `fn`
* @api public
*/
function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
}
/**
* Checks `localStorage` for boolean values for the given `name`.
*
* @param {String} name
* @returns {Boolean}
* @api private
*/
function config (name) {
// accessing global.localStorage can trigger a DOMException in sandboxed iframes
try {
if (!global.localStorage) return false;
} catch (_) {
return false;
}
var val = global.localStorage[name];
if (null == val) return false;
return String(val).toLowerCase() === 'true';
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],112:[function(require,module,exports){
(function (process){
var Stream = (function (){
try {
return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify
} catch(_){}
}());
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = Stream || exports;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) {
module.exports = Stream;
}
}).call(this,require('_process'))
},{"./lib/_stream_duplex.js":100,"./lib/_stream_passthrough.js":101,"./lib/_stream_readable.js":102,"./lib/_stream_transform.js":103,"./lib/_stream_writable.js":104,"_process":29}],113:[function(require,module,exports){
(function (Buffer){
module.exports = Peer
var debug = require('debug')('simple-peer')
var getBrowserRTC = require('get-browser-rtc')
var inherits = require('inherits')
var randombytes = require('randombytes')
var stream = require('readable-stream')
inherits(Peer, stream.Duplex)
/**
* WebRTC peer connection. Same API as node core `net.Socket`, plus a few extra methods.
* Duplex stream.
* @param {Object} opts
*/
function Peer (opts) {
var self = this
if (!(self instanceof Peer)) return new Peer(opts)
self.channelName = opts.initiator
? opts.channelName || randombytes(20).toString('hex')
: null
self._debug('new peer %o', opts)
if (!opts) opts = {}
opts.allowHalfOpen = false
if (opts.highWaterMark == null) opts.highWaterMark = 1024 * 1024
stream.Duplex.call(self, opts)
self.initiator = opts.initiator || false
self.channelConfig = opts.channelConfig || Peer.channelConfig
self.config = opts.config || Peer.config
self.constraints = opts.constraints || Peer.constraints
self.offerConstraints = opts.offerConstraints || {}
self.answerConstraints = opts.answerConstraints || {}
self.reconnectTimer = opts.reconnectTimer || false
self.sdpTransform = opts.sdpTransform || function (sdp) { return sdp }
self.stream = opts.stream || false
self.trickle = opts.trickle !== undefined ? opts.trickle : true
self.destroyed = false
self.connected = false
// so Peer object always has same shape (V8 optimization)
self.remoteAddress = undefined
self.remoteFamily = undefined
self.remotePort = undefined
self.localAddress = undefined
self.localPort = undefined
self._isWrtc = !!opts.wrtc // HACK: to fix `wrtc` bug. See issue: #60
self._wrtc = (opts.wrtc && typeof opts.wrtc === 'object')
? opts.wrtc
: getBrowserRTC()
if (!self._wrtc) {
if (typeof window === 'undefined') {
throw new Error('No WebRTC support: Specify `opts.wrtc` option in this environment')
} else {
throw new Error('No WebRTC support: Not a supported browser')
}
}
self._maxBufferedAmount = opts.highWaterMark
self._pcReady = false
self._channelReady = false
self._iceComplete = false // ice candidate trickle done (got null candidate)
self._channel = null
self._pendingCandidates = []
self._chunk = null
self._cb = null
self._interval = null
self._reconnectTimeout = null
self._pc = new (self._wrtc.RTCPeerConnection)(self.config, self.constraints)
self._pc.oniceconnectionstatechange = function () {
self._onIceConnectionStateChange()
}
self._pc.onsignalingstatechange = function () {
self._onSignalingStateChange()
}
self._pc.onicecandidate = function (event) {
self._onIceCandidate(event)
}
if (self.stream) self._pc.addStream(self.stream)
if ('ontrack' in self._pc) {
// WebRTC Spec, Firefox
self._pc.ontrack = function (event) {
self._onTrack(event)
}
} else {
// Chrome, etc. This can be removed once all browsers support `ontrack`
self._pc.onaddstream = function (event) {
self._onAddStream(event)
}
}
if (self.initiator) {
self._setupData({
channel: self._pc.createDataChannel(self.channelName, self.channelConfig)
})
var createdOffer = false
self._pc.onnegotiationneeded = function () {
if (!createdOffer) self._createOffer()
createdOffer = true
}
// Only Chrome triggers "negotiationneeded"; this is a workaround for other
// implementations
if (typeof window === 'undefined' || !window.webkitRTCPeerConnection) {
self._pc.onnegotiationneeded()
}
} else {
self._pc.ondatachannel = function (event) {
self._setupData(event)
}
}
self.on('finish', function () {
if (self.connected) {
// When local peer is finished writing, close connection to remote peer.
// Half open connections are currently not supported.
// Wait a bit before destroying so the datachannel flushes.
// TODO: is there a more reliable way to accomplish this?
setTimeout(function () {
self._destroy()
}, 100)
} else {
// If data channel is not connected when local peer is finished writing, wait until
// data is flushed to network at "connect" event.
// TODO: is there a more reliable way to accomplish this?
self.once('connect', function () {
setTimeout(function () {
self._destroy()
}, 100)
})
}
})
}
Peer.WEBRTC_SUPPORT = !!getBrowserRTC()
/**
* Expose config, constraints, and data channel config for overriding all Peer
* instances. Otherwise, just set opts.config, opts.constraints, or opts.channelConfig
* when constructing a Peer.
*/
Peer.config = {
iceServers: [
{
url: 'stun:23.21.150.121', // deprecated, replaced by `urls`
urls: 'stun:23.21.150.121'
}
]
}
Peer.constraints = {}
Peer.channelConfig = {}
Object.defineProperty(Peer.prototype, 'bufferSize', {
get: function () {
var self = this
return (self._channel && self._channel.bufferedAmount) || 0
}
})
Peer.prototype.address = function () {
var self = this
return { port: self.localPort, family: 'IPv4', address: self.localAddress }
}
Peer.prototype.signal = function (data) {
var self = this
if (self.destroyed) throw new Error('cannot signal after peer is destroyed')
if (typeof data === 'string') {
try {
data = JSON.parse(data)
} catch (err) {
data = {}
}
}
self._debug('signal()')
function addIceCandidate (candidate) {
try {
self._pc.addIceCandidate(
new self._wrtc.RTCIceCandidate(candidate),
noop,
function (err) { self._onError(err) }
)
} catch (err) {
self._destroy(new Error('error adding candidate: ' + err.message))
}
}
if (data.sdp) {
self._pc.setRemoteDescription(new (self._wrtc.RTCSessionDescription)(data), function () {
if (self.destroyed) return
if (self._pc.remoteDescription.type === 'offer') self._createAnswer()
self._pendingCandidates.forEach(addIceCandidate)
self._pendingCandidates = []
}, function (err) { self._onError(err) })
}
if (data.candidate) {
if (self._pc.remoteDescription) addIceCandidate(data.candidate)
else self._pendingCandidates.push(data.candidate)
}
if (!data.sdp && !data.candidate) {
self._destroy(new Error('signal() called with invalid signal data'))
}
}
/**
* Send text/binary data to the remote peer.
* @param {TypedArrayView|ArrayBuffer|Buffer|string|Blob|Object} chunk
*/
Peer.prototype.send = function (chunk) {
var self = this
// HACK: `wrtc` module doesn't accept node.js buffer. See issue: #60
if (Buffer.isBuffer(chunk) && self._isWrtc) {
chunk = new Uint8Array(chunk)
}
var len = chunk.length || chunk.byteLength || chunk.size
self._channel.send(chunk)
self._debug('write: %d bytes', len)
}
Peer.prototype.destroy = function (onclose) {
var self = this
self._destroy(null, onclose)
}
Peer.prototype._destroy = function (err, onclose) {
var self = this
if (self.destroyed) return
if (onclose) self.once('close', onclose)
self._debug('destroy (error: %s)', err && err.message)
self.readable = self.writable = false
if (!self._readableState.ended) self.push(null)
if (!self._writableState.finished) self.end()
self.destroyed = true
self.connected = false
self._pcReady = false
self._channelReady = false
self._chunk = null
self._cb = null
clearInterval(self._interval)
clearTimeout(self._reconnectTimeout)
if (self._pc) {
try {
self._pc.close()
} catch (err) {}
self._pc.oniceconnectionstatechange = null
self._pc.onsignalingstatechange = null
self._pc.onicecandidate = null
if ('ontrack' in self._pc) {
self._pc.ontrack = null
} else {
self._pc.onaddstream = null
}
self._pc.onnegotiationneeded = null
self._pc.ondatachannel = null
}
if (self._channel) {
try {
self._channel.close()
} catch (err) {}
self._channel.onmessage = null
self._channel.onopen = null
self._channel.onclose = null
}
self._pc = null
self._channel = null
if (err) self.emit('error', err)
self.emit('close')
}
Peer.prototype._setupData = function (event) {
var self = this
self._channel = event.channel
self.channelName = self._channel.label
self._channel.binaryType = 'arraybuffer'
self._channel.onmessage = function (event) {
self._onChannelMessage(event)
}
self._channel.onopen = function () {
self._onChannelOpen()
}
self._channel.onclose = function () {
self._onChannelClose()
}
}
Peer.prototype._read = function () {}
Peer.prototype._write = function (chunk, encoding, cb) {
var self = this
if (self.destroyed) return cb(new Error('cannot write after peer is destroyed'))
if (self.connected) {
try {
self.send(chunk)
} catch (err) {
return self._onError(err)
}
if (self._channel.bufferedAmount > self._maxBufferedAmount) {
self._debug('start backpressure: bufferedAmount %d', self._channel.bufferedAmount)
self._cb = cb
} else {
cb(null)
}
} else {
self._debug('write before connect')
self._chunk = chunk
self._cb = cb
}
}
Peer.prototype._createOffer = function () {
var self = this
if (self.destroyed) return
self._pc.createOffer(function (offer) {
if (self.destroyed) return
offer.sdp = self.sdpTransform(offer.sdp)
self._pc.setLocalDescription(offer, noop, function (err) { self._onError(err) })
var sendOffer = function () {
var signal = self._pc.localDescription || offer
self._debug('signal')
self.emit('signal', {
type: signal.type,
sdp: signal.sdp
})
}
if (self.trickle || self._iceComplete) sendOffer()
else self.once('_iceComplete', sendOffer) // wait for candidates
}, function (err) { self._onError(err) }, self.offerConstraints)
}
Peer.prototype._createAnswer = function () {
var self = this
if (self.destroyed) return
self._pc.createAnswer(function (answer) {
if (self.destroyed) return
answer.sdp = self.sdpTransform(answer.sdp)
self._pc.setLocalDescription(answer, noop, function (err) { self._onError(err) })
var sendAnswer = function () {
var signal = self._pc.localDescription || answer
self._debug('signal')
self.emit('signal', {
type: signal.type,
sdp: signal.sdp
})
}
if (self.trickle || self._iceComplete) sendAnswer()
else self.once('_iceComplete', sendAnswer)
}, function (err) { self._onError(err) }, self.answerConstraints)
}
Peer.prototype._onIceConnectionStateChange = function () {
var self = this
if (self.destroyed) return
var iceGatheringState = self._pc.iceGatheringState
var iceConnectionState = self._pc.iceConnectionState
self._debug('iceConnectionStateChange %s %s', iceGatheringState, iceConnectionState)
self.emit('iceConnectionStateChange', iceGatheringState, iceConnectionState)
if (iceConnectionState === 'connected' || iceConnectionState === 'completed') {
clearTimeout(self._reconnectTimeout)
self._pcReady = true
self._maybeReady()
}
if (iceConnectionState === 'disconnected') {
if (self.reconnectTimer) {
// If user has set `opt.reconnectTimer`, allow time for ICE to attempt a reconnect
clearTimeout(self._reconnectTimeout)
self._reconnectTimeout = setTimeout(function () {
self._destroy()
}, self.reconnectTimer)
} else {
self._destroy()
}
}
if (iceConnectionState === 'failed') {
self._destroy()
}
if (iceConnectionState === 'closed') {
self._destroy()
}
}
Peer.prototype.getStats = function (cb) {
var self = this
if (!self._pc.getStats) { // No ability to call stats
cb([])
} else if (typeof window !== 'undefined' && !!window.mozRTCPeerConnection) { // Mozilla
self._pc.getStats(null, function (res) {
var items = []
res.forEach(function (item) {
items.push(item)
})
cb(items)
}, function (err) { self._onError(err) })
} else {
self._pc.getStats(function (res) { // Chrome
var items = []
res.result().forEach(function (result) {
var item = {}
result.names().forEach(function (name) {
item[name] = result.stat(name)
})
item.id = result.id
item.type = result.type
item.timestamp = result.timestamp
items.push(item)
})
cb(items)
})
}
}
Peer.prototype._maybeReady = function () {
var self = this
self._debug('maybeReady pc %s channel %s', self._pcReady, self._channelReady)
if (self.connected || self._connecting || !self._pcReady || !self._channelReady) return
self._connecting = true
self.getStats(function (items) {
self._connecting = false
self.connected = true
var remoteCandidates = {}
var localCandidates = {}
function setActiveCandidates (item) {
var local = localCandidates[item.localCandidateId]
var remote = remoteCandidates[item.remoteCandidateId]
if (local) {
self.localAddress = local.ipAddress
self.localPort = Number(local.portNumber)
} else if (typeof item.googLocalAddress === 'string') {
// Sometimes `item.id` is undefined in `wrtc` and Chrome
// See: https://github.com/feross/simple-peer/issues/66
local = item.googLocalAddress.split(':')
self.localAddress = local[0]
self.localPort = Number(local[1])
}
self._debug('connect local: %s:%s', self.localAddress, self.localPort)
if (remote) {
self.remoteAddress = remote.ipAddress
self.remotePort = Number(remote.portNumber)
self.remoteFamily = 'IPv4'
} else if (typeof item.googRemoteAddress === 'string') {
remote = item.googRemoteAddress.split(':')
self.remoteAddress = remote[0]
self.remotePort = Number(remote[1])
self.remoteFamily = 'IPv4'
}
self._debug('connect remote: %s:%s', self.remoteAddress, self.remotePort)
}
items.forEach(function (item) {
if (item.type === 'remotecandidate') remoteCandidates[item.id] = item
if (item.type === 'localcandidate') localCandidates[item.id] = item
})
items.forEach(function (item) {
var isCandidatePair = (
(item.type === 'googCandidatePair' && item.googActiveConnection === 'true') ||
(item.type === 'candidatepair' && item.selected)
)
if (isCandidatePair) setActiveCandidates(item)
})
if (self._chunk) {
try {
self.send(self._chunk)
} catch (err) {
return self._onError(err)
}
self._chunk = null
self._debug('sent chunk from "write before connect"')
var cb = self._cb
self._cb = null
cb(null)
}
self._interval = setInterval(function () {
if (!self._cb || !self._channel || self._channel.bufferedAmount > self._maxBufferedAmount) return
self._debug('ending backpressure: bufferedAmount %d', self._channel.bufferedAmount)
var cb = self._cb
self._cb = null
cb(null)
}, 150)
if (self._interval.unref) self._interval.unref()
self._debug('connect')
self.emit('connect')
})
}
Peer.prototype._onSignalingStateChange = function () {
var self = this
if (self.destroyed) return
self._debug('signalingStateChange %s', self._pc.signalingState)
self.emit('signalingStateChange', self._pc.signalingState)
}
Peer.prototype._onIceCandidate = function (event) {
var self = this
if (self.destroyed) return
if (event.candidate && self.trickle) {
self.emit('signal', {
candidate: {
candidate: event.candidate.candidate,
sdpMLineIndex: event.candidate.sdpMLineIndex,
sdpMid: event.candidate.sdpMid
}
})
} else if (!event.candidate) {
self._iceComplete = true
self.emit('_iceComplete')
}
}
Peer.prototype._onChannelMessage = function (event) {
var self = this
if (self.destroyed) return
var data = event.data
self._debug('read: %d bytes', data.byteLength || data.length)
if (data instanceof ArrayBuffer) data = new Buffer(data)
self.push(data)
}
Peer.prototype._onChannelOpen = function () {
var self = this
if (self.connected || self.destroyed) return
self._debug('on channel open')
self._channelReady = true
self._maybeReady()
}
Peer.prototype._onChannelClose = function () {
var self = this
if (self.destroyed) return
self._debug('on channel close')
self._destroy()
}
Peer.prototype._onAddStream = function (event) {
var self = this
if (self.destroyed) return
self._debug('on add stream')
self.emit('stream', event.stream)
}
Peer.prototype._onTrack = function (event) {
var self = this
if (self.destroyed) return
self._debug('on track')
self.emit('stream', event.streams[0])
}
Peer.prototype._onError = function (err) {
var self = this
if (self.destroyed) return
self._debug('error %s', err.message || err)
self._destroy(err)
}
Peer.prototype._debug = function () {
var self = this
var args = [].slice.call(arguments)
var id = self.channelName && self.channelName.substring(0, 7)
args[0] = '[' + id + '] ' + args[0]
debug.apply(null, args)
}
function noop () {}
}).call(this,require("buffer").Buffer)
},{"buffer":21,"debug":114,"get-browser-rtc":117,"inherits":63,"randombytes":118,"readable-stream":112}],114:[function(require,module,exports){
arguments[4][7][0].apply(exports,arguments)
},{"./debug":115,"dup":7}],115:[function(require,module,exports){
arguments[4][8][0].apply(exports,arguments)
},{"dup":8,"ms":116}],116:[function(require,module,exports){
arguments[4][9][0].apply(exports,arguments)
},{"dup":9}],117:[function(require,module,exports){
// originally pulled out of simple-peer
module.exports = function getBrowserRTC () {
if (typeof window === 'undefined') return null
var wrtc = {
RTCPeerConnection: window.RTCPeerConnection || window.mozRTCPeerConnection ||
window.webkitRTCPeerConnection,
RTCSessionDescription: window.RTCSessionDescription ||
window.mozRTCSessionDescription || window.webkitRTCSessionDescription,
RTCIceCandidate: window.RTCIceCandidate || window.mozRTCIceCandidate ||
window.webkitRTCIceCandidate
}
if (!wrtc.RTCPeerConnection) return null
return wrtc
}
},{}],118:[function(require,module,exports){
(function (process,global,Buffer){
'use strict'
function oldBrowser () {
throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
}
var crypto = global.crypto || global.msCrypto
if (crypto && crypto.getRandomValues) {
module.exports = randomBytes
} else {
module.exports = oldBrowser
}
function randomBytes (size, cb) {
// phantomjs needs to throw
if (size > 65536) throw new Error('requested too many random bytes')
// in case browserify isn't using the Uint8Array version
var rawBytes = new global.Uint8Array(size)
// This will not work in older browsers.
// See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
if (size > 0) { // getRandomValues fails on IE if size == 0
crypto.getRandomValues(rawBytes)
}
// phantomjs doesn't like a buffer being passed here
var bytes = new Buffer(rawBytes.buffer)
if (typeof cb === 'function') {
return process.nextTick(function () {
cb(null, bytes)
})
}
return bytes
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
},{"_process":29,"buffer":21}],119:[function(require,module,exports){
(function (Buffer){
/* jshint camelcase: false */
// TODO: ipv6 support
// TODO: parse and send peer flags (currently unused)
// NOTE: addPeer should take in an optional second argument, flags
// TODO: destroy wire if peer sends PEX messages too frequently
var EventEmitter = require('events').EventEmitter
var compact2string = require('compact2string')
var string2compact = require('string2compact')
var bencode = require('bencode')
var inherits = require('inherits')
var PEX_INTERVAL = 65000 // just over one minute
var PEX_MAX_PEERS = 50 // max number of peers to advertise per PEX message
module.exports = function () {
inherits(ut_pex, EventEmitter)
function ut_pex (wire) {
var self = this
EventEmitter.call(self)
self._wire = wire
self._intervalId = null
self.reset()
}
ut_pex.prototype.name = 'ut_pex'
/**
* Start sending regular PEX updates to remote peer.
*/
ut_pex.prototype.start = function () {
var self = this
clearInterval(self._intervalId)
self._intervalId = setInterval(self._sendMessage.bind(self), PEX_INTERVAL)
if (self._intervalId.unref) self._intervalId.unref()
}
/**
* Stop sending PEX updates to the remote peer.
*/
ut_pex.prototype.stop = function () {
var self = this
clearInterval(self._intervalId)
self._intervalId = null
}
/**
* Stops sending updates to the remote peer and resets internal state of peers seen.
*/
ut_pex.prototype.reset = function () {
var self = this
self._remoteAddedPeers = {}
self._remoteDroppedPeers = {}
self._localAddedPeers = {}
self._localDroppedPeers = {}
self.stop()
}
/**
* Adds a peer to the locally discovered peer list for the next PEX message.
*/
ut_pex.prototype.addPeer = function (peer) {
var self = this
if (peer.indexOf(':') < 0) return // disregard invalid peers
if (peer in self._remoteAddedPeers) return // never advertise peer the remote wire already sent us
if (peer in self._localDroppedPeers) delete self._localDroppedPeers[peer]
self._localAddedPeers[peer] = true
}
/**
* Adds a peer to the locally dropped peer list for the next PEX message.
*/
ut_pex.prototype.dropPeer = function (peer) {
var self = this
if (peer.indexOf(':') < 0) return // disregard invalid peers
if (peer in self._remoteDroppedPeers) return // never advertise peer the remote wire already sent us
if (peer in self._localAddedPeers) delete self._localAddedPeers[peer]
self._localDroppedPeers[peer] = true
}
ut_pex.prototype.onExtendedHandshake = function (handshake) {
var self = this
if (!handshake.m || !handshake.m.ut_pex) {
return self.emit('warning', new Error('Peer does not support ut_pex'))
}
}
/**
* PEX messages are bencoded dictionaries with the following keys:
* 'added' : array of peers met since last PEX message
* 'added.f' : array of flags per peer
* '0x01' : peer prefers encryption
* '0x02' : peer is seeder
* 'dropped' : array of peers locally dropped from swarm since last PEX message
* 'added6' : ipv6 version of 'added'
* 'added6.f' : ipv6 version of 'added.f'
* 'dropped.f' : ipv6 version of 'dropped'
*
* @param {Buffer} buf bencoded PEX dictionary
*/
ut_pex.prototype.onMessage = function (buf) {
var self = this
var message
try {
message = bencode.decode(buf)
} catch (err) {
// drop invalid messages
return
}
if (message.added) {
compact2string.multi(message.added).forEach(function (peer) {
delete self._remoteDroppedPeers[peer]
if (!(peer in self._remoteAddedPeers)) {
self._remoteAddedPeers[peer] = true
self.emit('peer', peer)
}
})
}
if (message.dropped) {
compact2string.multi(message.dropped).forEach(function (peer) {
delete self._remoteAddedPeers[peer]
if (!(peer in self._remoteDroppedPeers)) {
self._remoteDroppedPeers[peer] = true
self.emit('dropped', peer)
}
})
}
}
/**
* Sends a PEX message to the remote peer including information about any locally
* added / dropped peers.
*/
ut_pex.prototype._sendMessage = function () {
var self = this
var localAdded = Object.keys(self._localAddedPeers).slice(0, PEX_MAX_PEERS)
var localDropped = Object.keys(self._localDroppedPeers).slice(0, PEX_MAX_PEERS)
var added = Buffer.concat(localAdded.map(string2compact))
var dropped = Buffer.concat(localDropped.map(string2compact))
var addedFlags = Buffer.concat(localAdded.map(function () {
// TODO: support flags
return new Buffer([0])
}))
// update local deltas
localAdded.forEach(function (peer) { delete self._localAddedPeers[peer] })
localDropped.forEach(function (peer) { delete self._localDroppedPeers[peer] })
// send PEX message
self._wire.extended('ut_pex', {
'added': added,
'added.f': addedFlags,
'dropped': dropped,
'added6': new Buffer(0),
'added6.f': new Buffer(0),
'dropped6': new Buffer(0)
})
}
return ut_pex
}
}).call(this,require("buffer").Buffer)
},{"bencode":122,"buffer":21,"compact2string":123,"events":25,"inherits":63,"string2compact":125}],120:[function(require,module,exports){
(function (Buffer){
/**
* Decodes bencoded data.
*
* @param {Buffer} data
* @param {Number} start (optional)
* @param {Number} end (optional)
* @param {String} encoding (optional)
* @return {Object|Array|Buffer|String|Number}
*/
function decode (data, start, end, encoding) {
if (typeof start !== 'number' && encoding == null) {
encoding = start
start = undefined
}
if (typeof end !== 'number' && encoding == null) {
encoding = end
end = undefined
}
decode.position = 0
decode.encoding = encoding || null
decode.data = !(Buffer.isBuffer(data))
? new Buffer(data)
: data.slice(start, end)
decode.bytes = decode.data.length
return decode.next()
}
decode.bytes = 0
decode.position = 0
decode.data = null
decode.encoding = null
decode.next = function () {
switch (decode.data[decode.position]) {
case 0x64:
return decode.dictionary()
case 0x6C:
return decode.list()
case 0x69:
return decode.integer()
default:
return decode.buffer()
}
}
decode.find = function (chr) {
var i = decode.position
var c = decode.data.length
var d = decode.data
while (i < c) {
if (d[i] === chr) return i
i++
}
throw new Error(
'Invalid data: Missing delimiter "' +
String.fromCharCode(chr) + '" [0x' +
chr.toString(16) + ']'
)
}
decode.dictionary = function () {
decode.position++
var dict = {}
while (decode.data[decode.position] !== 0x65) {
dict[decode.buffer()] = decode.next()
}
decode.position++
return dict
}
decode.list = function () {
decode.position++
var lst = []
while (decode.data[decode.position] !== 0x65) {
lst.push(decode.next())
}
decode.position++
return lst
}
decode.integer = function () {
var end = decode.find(0x65)
var number = decode.data.toString('ascii', decode.position + 1, end)
decode.position += end + 1 - decode.position
return parseInt(number, 10)
}
decode.buffer = function () {
var sep = decode.find(0x3A)
var length = parseInt(decode.data.toString('ascii', decode.position, sep), 10)
var end = ++sep + length
decode.position = end
return decode.encoding
? decode.data.toString(decode.encoding, sep, end)
: decode.data.slice(sep, end)
}
module.exports = decode
}).call(this,require("buffer").Buffer)
},{"buffer":21}],121:[function(require,module,exports){
(function (Buffer){
/**
* Encodes data in bencode.
*
* @param {Buffer|Array|String|Object|Number|Boolean} data
* @return {Buffer}
*/
function encode (data, buffer, offset) {
var buffers = []
var result = null
encode._encode(buffers, data)
result = Buffer.concat(buffers)
encode.bytes = result.length
if (Buffer.isBuffer(buffer)) {
result.copy(buffer, offset)
return buffer
}
return result
}
encode.bytes = -1
encode._floatConversionDetected = false
encode._encode = function (buffers, data) {
if (Buffer.isBuffer(data)) {
buffers.push(new Buffer(data.length + ':'))
buffers.push(data)
return
}
switch (typeof data) {
case 'string':
encode.buffer(buffers, data)
break
case 'number':
encode.number(buffers, data)
break
case 'object':
data.constructor === Array
? encode.list(buffers, data)
: encode.dict(buffers, data)
break
case 'boolean':
encode.number(buffers, data ? 1 : 0)
break
}
}
var buffE = new Buffer('e')
var buffD = new Buffer('d')
var buffL = new Buffer('l')
encode.buffer = function (buffers, data) {
buffers.push(new Buffer(Buffer.byteLength(data) + ':' + data))
}
encode.number = function (buffers, data) {
var maxLo = 0x80000000
var hi = (data / maxLo) << 0
var lo = (data % maxLo) << 0
var val = hi * maxLo + lo
buffers.push(new Buffer('i' + val + 'e'))
if (val !== data && !encode._floatConversionDetected) {
encode._floatConversionDetected = true
console.warn(
'WARNING: Possible data corruption detected with value "' + data + '":',
'Bencoding only defines support for integers, value was converted to "' + val + '"'
)
console.trace()
}
}
encode.dict = function (buffers, data) {
buffers.push(buffD)
var j = 0
var k
// fix for issue #13 - sorted dicts
var keys = Object.keys(data).sort()
var kl = keys.length
for (; j < kl; j++) {
k = keys[j]
encode.buffer(buffers, k)
encode._encode(buffers, data[k])
}
buffers.push(buffE)
}
encode.list = function (buffers, data) {
var i = 0
var c = data.length
buffers.push(buffL)
for (; i < c; i++) {
encode._encode(buffers, data[i])
}
buffers.push(buffE)
}
module.exports = encode
}).call(this,require("buffer").Buffer)
},{"buffer":21}],122:[function(require,module,exports){
arguments[4][46][0].apply(exports,arguments)
},{"./decode":120,"./encode":121,"dup":46}],123:[function(require,module,exports){
var ipaddr = require('ipaddr.js');
module.exports = compact2string = function (buf) {
switch(buf.length) {
case 6:
return buf[0] + "." + buf[1] + "." + buf[2] + "." + buf[3] + ":" + buf.readUInt16BE(4);
break;
case 18:
var hexGroups = [];
for(var i = 0; i < 8; i++) {
hexGroups.push(buf.readUInt16BE(i * 2).toString(16));
}
var host = ipaddr.parse(hexGroups.join(":")).toString();
return "[" + host + "]:" + buf.readUInt16BE(16);
default:
throw new Error("Invalid Compact IP/PORT, It should contain 6 or 18 bytes");
}
};
compact2string.multi = function (buf) {
if(buf.length % 6 !== 0)
throw new Error("buf length isn't multiple of compact IP/PORTs (6 bytes)");
var output = [];
for (var i = 0; i <= buf.length - 1; i = i + 6) {
output.push(compact2string(buf.slice(i, i + 6)));
}
return output;
};
compact2string.multi6 = function (buf) {
if(buf.length % 18 !== 0)
throw new Error("buf length isn't multiple of compact IP6/PORTs (18 bytes)");
var output = [];
for (var i = 0; i <= buf.length - 1; i = i + 18) {
output.push(compact2string(buf.slice(i, i + 18)));
}
return output;
};
},{"ipaddr.js":124}],124:[function(require,module,exports){
(function() {
var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root;
ipaddr = {};
root = this;
if ((typeof module !== "undefined" && module !== null) && module.exports) {
module.exports = ipaddr;
} else {
root['ipaddr'] = ipaddr;
}
matchCIDR = function(first, second, partSize, cidrBits) {
var part, shift;
if (first.length !== second.length) {
throw new Error("ipaddr: cannot match CIDR for objects with different lengths");
}
part = 0;
while (cidrBits > 0) {
shift = partSize - cidrBits;
if (shift < 0) {
shift = 0;
}
if (first[part] >> shift !== second[part] >> shift) {
return false;
}
cidrBits -= partSize;
part += 1;
}
return true;
};
ipaddr.subnetMatch = function(address, rangeList, defaultName) {
var rangeName, rangeSubnets, subnet, _i, _len;
if (defaultName == null) {
defaultName = 'unicast';
}
for (rangeName in rangeList) {
rangeSubnets = rangeList[rangeName];
if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) {
rangeSubnets = [rangeSubnets];
}
for (_i = 0, _len = rangeSubnets.length; _i < _len; _i++) {
subnet = rangeSubnets[_i];
if (address.match.apply(address, subnet)) {
return rangeName;
}
}
}
return defaultName;
};
ipaddr.IPv4 = (function() {
function IPv4(octets) {
var octet, _i, _len;
if (octets.length !== 4) {
throw new Error("ipaddr: ipv4 octet count should be 4");
}
for (_i = 0, _len = octets.length; _i < _len; _i++) {
octet = octets[_i];
if (!((0 <= octet && octet <= 255))) {
throw new Error("ipaddr: ipv4 octet should fit in 8 bits");
}
}
this.octets = octets;
}
IPv4.prototype.kind = function() {
return 'ipv4';
};
IPv4.prototype.toString = function() {
return this.octets.join(".");
};
IPv4.prototype.toByteArray = function() {
return this.octets.slice(0);
};
IPv4.prototype.match = function(other, cidrRange) {
var _ref;
if (cidrRange === void 0) {
_ref = other, other = _ref[0], cidrRange = _ref[1];
}
if (other.kind() !== 'ipv4') {
throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");
}
return matchCIDR(this.octets, other.octets, 8, cidrRange);
};
IPv4.prototype.SpecialRanges = {
unspecified: [[new IPv4([0, 0, 0, 0]), 8]],
broadcast: [[new IPv4([255, 255, 255, 255]), 32]],
multicast: [[new IPv4([224, 0, 0, 0]), 4]],
linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],
loopback: [[new IPv4([127, 0, 0, 0]), 8]],
"private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]],
reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]]
};
IPv4.prototype.range = function() {
return ipaddr.subnetMatch(this, this.SpecialRanges);
};
IPv4.prototype.toIPv4MappedAddress = function() {
return ipaddr.IPv6.parse("::ffff:" + (this.toString()));
};
IPv4.prototype.prefixLengthFromSubnetMask = function() {
var cidr, i, octet, stop, zeros, zerotable, _i;
zerotable = {
0: 8,
128: 7,
192: 6,
224: 5,
240: 4,
248: 3,
252: 2,
254: 1,
255: 0
};
cidr = 0;
stop = false;
for (i = _i = 3; _i >= 0; i = _i += -1) {
octet = this.octets[i];
if (octet in zerotable) {
zeros = zerotable[octet];
if (stop && zeros !== 0) {
return null;
}
if (zeros !== 8) {
stop = true;
}
cidr += zeros;
} else {
return null;
}
}
return 32 - cidr;
};
return IPv4;
})();
ipv4Part = "(0?\\d+|0x[a-f0-9]+)";
ipv4Regexes = {
fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'),
longValue: new RegExp("^" + ipv4Part + "$", 'i')
};
ipaddr.IPv4.parser = function(string) {
var match, parseIntAuto, part, shift, value;
parseIntAuto = function(string) {
if (string[0] === "0" && string[1] !== "x") {
return parseInt(string, 8);
} else {
return parseInt(string);
}
};
if (match = string.match(ipv4Regexes.fourOctet)) {
return (function() {
var _i, _len, _ref, _results;
_ref = match.slice(1, 6);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
part = _ref[_i];
_results.push(parseIntAuto(part));
}
return _results;
})();
} else if (match = string.match(ipv4Regexes.longValue)) {
value = parseIntAuto(match[1]);
if (value > 0xffffffff || value < 0) {
throw new Error("ipaddr: address outside defined range");
}
return ((function() {
var _i, _results;
_results = [];
for (shift = _i = 0; _i <= 24; shift = _i += 8) {
_results.push((value >> shift) & 0xff);
}
return _results;
})()).reverse();
} else {
return null;
}
};
ipaddr.IPv6 = (function() {
function IPv6(parts) {
var i, part, _i, _j, _len, _ref;
if (parts.length === 16) {
this.parts = [];
for (i = _i = 0; _i <= 14; i = _i += 2) {
this.parts.push((parts[i] << 8) | parts[i + 1]);
}
} else if (parts.length === 8) {
this.parts = parts;
} else {
throw new Error("ipaddr: ipv6 part count should be 8 or 16");
}
_ref = this.parts;
for (_j = 0, _len = _ref.length; _j < _len; _j++) {
part = _ref[_j];
if (!((0 <= part && part <= 0xffff))) {
throw new Error("ipaddr: ipv6 part should fit in 16 bits");
}
}
}
IPv6.prototype.kind = function() {
return 'ipv6';
};
IPv6.prototype.toString = function() {
var compactStringParts, part, pushPart, state, stringParts, _i, _len;
stringParts = (function() {
var _i, _len, _ref, _results;
_ref = this.parts;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
part = _ref[_i];
_results.push(part.toString(16));
}
return _results;
}).call(this);
compactStringParts = [];
pushPart = function(part) {
return compactStringParts.push(part);
};
state = 0;
for (_i = 0, _len = stringParts.length; _i < _len; _i++) {
part = stringParts[_i];
switch (state) {
case 0:
if (part === '0') {
pushPart('');
} else {
pushPart(part);
}
state = 1;
break;
case 1:
if (part === '0') {
state = 2;
} else {
pushPart(part);
}
break;
case 2:
if (part !== '0') {
pushPart('');
pushPart(part);
state = 3;
}
break;
case 3:
pushPart(part);
}
}
if (state === 2) {
pushPart('');
pushPart('');
}
return compactStringParts.join(":");
};
IPv6.prototype.toByteArray = function() {
var bytes, part, _i, _len, _ref;
bytes = [];
_ref = this.parts;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
part = _ref[_i];
bytes.push(part >> 8);
bytes.push(part & 0xff);
}
return bytes;
};
IPv6.prototype.toNormalizedString = function() {
var part;
return ((function() {
var _i, _len, _ref, _results;
_ref = this.parts;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
part = _ref[_i];
_results.push(part.toString(16));
}
return _results;
}).call(this)).join(":");
};
IPv6.prototype.match = function(other, cidrRange) {
var _ref;
if (cidrRange === void 0) {
_ref = other, other = _ref[0], cidrRange = _ref[1];
}
if (other.kind() !== 'ipv6') {
throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");
}
return matchCIDR(this.parts, other.parts, 16, cidrRange);
};
IPv6.prototype.SpecialRanges = {
unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],
linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],
multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],
loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],
uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],
ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],
rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],
rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],
'6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],
teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],
reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]]
};
IPv6.prototype.range = function() {
return ipaddr.subnetMatch(this, this.SpecialRanges);
};
IPv6.prototype.isIPv4MappedAddress = function() {
return this.range() === 'ipv4Mapped';
};
IPv6.prototype.toIPv4Address = function() {
var high, low, _ref;
if (!this.isIPv4MappedAddress()) {
throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");
}
_ref = this.parts.slice(-2), high = _ref[0], low = _ref[1];
return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);
};
return IPv6;
})();
ipv6Part = "(?:[0-9a-f]+::?)+";
ipv6Regexes = {
"native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?$", 'i'),
transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + ("" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$"), 'i')
};
expandIPv6 = function(string, parts) {
var colonCount, lastColon, part, replacement, replacementCount;
if (string.indexOf('::') !== string.lastIndexOf('::')) {
return null;
}
colonCount = 0;
lastColon = -1;
while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) {
colonCount++;
}
if (string.substr(0, 2) === '::') {
colonCount--;
}
if (string.substr(-2, 2) === '::') {
colonCount--;
}
if (colonCount > parts) {
return null;
}
replacementCount = parts - colonCount;
replacement = ':';
while (replacementCount--) {
replacement += '0:';
}
string = string.replace('::', replacement);
if (string[0] === ':') {
string = string.slice(1);
}
if (string[string.length - 1] === ':') {
string = string.slice(0, -1);
}
return (function() {
var _i, _len, _ref, _results;
_ref = string.split(":");
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
part = _ref[_i];
_results.push(parseInt(part, 16));
}
return _results;
})();
};
ipaddr.IPv6.parser = function(string) {
var match, octet, octets, parts, _i, _len;
if (string.match(ipv6Regexes['native'])) {
return expandIPv6(string, 8);
} else if (match = string.match(ipv6Regexes['transitional'])) {
parts = expandIPv6(match[1].slice(0, -1), 6);
if (parts) {
octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])];
for (_i = 0, _len = octets.length; _i < _len; _i++) {
octet = octets[_i];
if (!((0 <= octet && octet <= 255))) {
return null;
}
}
parts.push(octets[0] << 8 | octets[1]);
parts.push(octets[2] << 8 | octets[3]);
return parts;
}
}
return null;
};
ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) {
return this.parser(string) !== null;
};
ipaddr.IPv4.isValid = function(string) {
var e;
try {
new this(this.parser(string));
return true;
} catch (_error) {
e = _error;
return false;
}
};
ipaddr.IPv4.isValidFourPartDecimal = function(string) {
if (ipaddr.IPv4.isValid(string) && string.match(/^\d+(\.\d+){3}$/)) {
return true;
} else {
return false;
}
};
ipaddr.IPv6.isValid = function(string) {
var e;
if (typeof string === "string" && string.indexOf(":") === -1) {
return false;
}
try {
new this(this.parser(string));
return true;
} catch (_error) {
e = _error;
return false;
}
};
ipaddr.IPv4.parse = ipaddr.IPv6.parse = function(string) {
var parts;
parts = this.parser(string);
if (parts === null) {
throw new Error("ipaddr: string is not formatted like ip address");
}
return new this(parts);
};
ipaddr.IPv4.parseCIDR = function(string) {
var maskLength, match;
if (match = string.match(/^(.+)\/(\d+)$/)) {
maskLength = parseInt(match[2]);
if (maskLength >= 0 && maskLength <= 32) {
return [this.parse(match[1]), maskLength];
}
}
throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range");
};
ipaddr.IPv6.parseCIDR = function(string) {
var maskLength, match;
if (match = string.match(/^(.+)\/(\d+)$/)) {
maskLength = parseInt(match[2]);
if (maskLength >= 0 && maskLength <= 128) {
return [this.parse(match[1]), maskLength];
}
}
throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range");
};
ipaddr.isValid = function(string) {
return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);
};
ipaddr.parse = function(string) {
if (ipaddr.IPv6.isValid(string)) {
return ipaddr.IPv6.parse(string);
} else if (ipaddr.IPv4.isValid(string)) {
return ipaddr.IPv4.parse(string);
} else {
throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format");
}
};
ipaddr.parseCIDR = function(string) {
var e;
try {
return ipaddr.IPv6.parseCIDR(string);
} catch (_error) {
e = _error;
try {
return ipaddr.IPv4.parseCIDR(string);
} catch (_error) {
e = _error;
throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format");
}
}
};
ipaddr.fromByteArray = function(bytes) {
var length;
length = bytes.length;
if (length === 4) {
return new ipaddr.IPv4(bytes);
} else if (length === 16) {
return new ipaddr.IPv6(bytes);
} else {
throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address");
}
};
ipaddr.process = function(string) {
var addr;
addr = this.parse(string);
if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {
return addr.toIPv4Address();
} else {
return addr;
}
};
}).call(this);
},{}],125:[function(require,module,exports){
(function (Buffer){
var addrToIPPort = require('addr-to-ip-port')
var ipaddr = require('ipaddr.js')
module.exports = function (addrs) {
if (typeof addrs === 'string') {
addrs = [ addrs ]
}
return Buffer.concat(addrs.map(function (addr) {
var s = addrToIPPort(addr)
if (s.length !== 2) {
throw new Error('invalid address format, expecting: 10.10.10.5:128')
}
var ip = ipaddr.parse(s[0])
var ipBuf = new Buffer(ip.toByteArray())
var port = Number(s[1])
var portBuf = new Buffer(2)
portBuf.writeUInt16BE(port, 0)
return Buffer.concat([ipBuf, portBuf])
}))
}
/**
* Also support this usage:
* string2compact.multi([ '10.10.10.5:128', '100.56.58.99:28525' ])
*
* for parallelism with the `compact2string` module.
*/
module.exports.multi = module.exports
module.exports.multi6 = module.exports
}).call(this,require("buffer").Buffer)
},{"addr-to-ip-port":126,"buffer":21,"ipaddr.js":127}],126:[function(require,module,exports){
var ADDR_RE = /^\[?([^\]]+)\]?:(\d+)$/ // ipv4/ipv6/hostname + port
var cache = {}
// reset cache when it gets to 100,000 elements (~ 600KB of ipv4 addresses)
// so it will not grow to consume all memory in long-running processes
var size = 0
module.exports = function addrToIPPort (addr) {
if (size === 100000) module.exports.reset()
if (!cache[addr]) {
var m = ADDR_RE.exec(addr)
if (!m) throw new Error('invalid addr: ' + addr)
cache[addr] = [ m[1], Number(m[2]) ]
size += 1
}
return cache[addr]
}
module.exports.reset = function reset () {
cache = {}
size = 0
}
},{}],127:[function(require,module,exports){
arguments[4][124][0].apply(exports,arguments)
},{"dup":124}],128:[function(require,module,exports){
arguments[4][63][0].apply(exports,arguments)
},{"dup":63}],129:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],130:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":129,"_process":29,"inherits":128}],131:[function(require,module,exports){
(function (Buffer){
var bs = require('binary-search')
var EventEmitter = require('events').EventEmitter
var inherits = require('inherits')
var mp4 = require('mp4-stream')
var Box = require('mp4-box-encoding')
var RangeSliceStream = require('range-slice-stream')
module.exports = MP4Remuxer
function MP4Remuxer (file) {
var self = this
EventEmitter.call(self)
self._tracks = []
self._fragmentSequence = 1
self._file = file
self._decoder = null
self._findMoov(0)
}
inherits(MP4Remuxer, EventEmitter)
MP4Remuxer.prototype._findMoov = function (offset) {
var self = this
if (self._decoder) {
self._decoder.destroy()
}
self._decoder = mp4.decode()
var fileStream = self._file.createReadStream({
start: offset
})
fileStream.pipe(self._decoder)
self._decoder.once('box', function (headers) {
if (headers.type === 'moov') {
self._decoder.decode(function (moov) {
fileStream.destroy()
try {
self._processMoov(moov)
} catch (err) {
err.message = 'Cannot parse mp4 file: ' + err.message
self.emit('error', err)
}
})
} else {
fileStream.destroy()
self._findMoov(offset + headers.length)
}
})
}
function RunLengthIndex (entries, countName) {
var self = this
self._entries = entries
self._countName = countName || 'count'
self._index = 0
self._offset = 0
self.value = self._entries[0]
}
RunLengthIndex.prototype.inc = function () {
var self = this
self._offset++
if (self._offset >= self._entries[self._index][self._countName]) {
self._index++
self._offset = 0
}
self.value = self._entries[self._index]
}
MP4Remuxer.prototype._processMoov = function (moov) {
var self = this
var traks = moov.traks
self._tracks = []
self._hasVideo = false
self._hasAudio = false
for (var i = 0; i < traks.length; i++) {
var trak = traks[i]
var stbl = trak.mdia.minf.stbl
var stsdEntry = stbl.stsd.entries[0]
var handlerType = trak.mdia.hdlr.handlerType
var codec
var mime
if (handlerType === 'vide' && stsdEntry.type === 'avc1') {
if (self._hasVideo) {
continue
}
self._hasVideo = true
codec = 'avc1'
if (stsdEntry.avcC) {
codec += '.' + stsdEntry.avcC.mimeCodec
}
mime = 'video/mp4; codecs="' + codec + '"'
} else if (handlerType === 'soun' && stsdEntry.type === 'mp4a') {
if (self._hasAudio) {
continue
}
self._hasAudio = true
codec = 'mp4a'
if (stsdEntry.esds && stsdEntry.esds.mimeCodec) {
codec += '.' + stsdEntry.esds.mimeCodec
}
mime = 'audio/mp4; codecs="' + codec + '"'
} else {
continue
}
var samples = []
var sample = 0
// Chunk/position data
var sampleInChunk = 0
var chunk = 0
var offsetInChunk = 0
var sampleToChunkIndex = 0
// Time data
var dts = 0
var decodingTimeEntry = new RunLengthIndex(stbl.stts.entries)
var presentationOffsetEntry = null
if (stbl.ctts) {
presentationOffsetEntry = new RunLengthIndex(stbl.ctts.entries)
}
// Sync table index
var syncSampleIndex = 0
while (true) {
var currChunkEntry = stbl.stsc.entries[sampleToChunkIndex]
// Compute size
var size = stbl.stsz.entries[sample]
// Compute time data
var duration = decodingTimeEntry.value.duration
var presentationOffset = presentationOffsetEntry ? presentationOffsetEntry.value.compositionOffset : 0
// Compute sync
var sync = true
if (stbl.stss) {
sync = stbl.stss.entries[syncSampleIndex] === sample + 1
}
// Create new sample entry
samples.push({
size: size,
duration: duration,
dts: dts,
presentationOffset: presentationOffset,
sync: sync,
offset: offsetInChunk + stbl.stco.entries[chunk]
})
// Go to next sample
sample++
if (sample >= stbl.stsz.entries.length) {
break
}
// Move position/chunk
sampleInChunk++
offsetInChunk += size
if (sampleInChunk >= currChunkEntry.samplesPerChunk) {
// Move to new chunk
sampleInChunk = 0
offsetInChunk = 0
chunk++
// Move sample to chunk box index
var nextChunkEntry = stbl.stsc.entries[sampleToChunkIndex + 1]
if (nextChunkEntry && chunk + 1 >= nextChunkEntry.firstChunk) {
sampleToChunkIndex++
}
}
// Move time forward
dts += duration
decodingTimeEntry.inc()
presentationOffsetEntry && presentationOffsetEntry.inc()
// Move sync table index
if (sync) {
syncSampleIndex++
}
}
trak.mdia.mdhd.duration = 0
trak.tkhd.duration = 0
var defaultSampleDescriptionIndex = currChunkEntry.sampleDescriptionId
var trackMoov = {
type: 'moov',
mvhd: moov.mvhd,
traks: [{
tkhd: trak.tkhd,
mdia: {
mdhd: trak.mdia.mdhd,
hdlr: trak.mdia.hdlr,
elng: trak.mdia.elng,
minf: {
vmhd: trak.mdia.minf.vmhd,
smhd: trak.mdia.minf.smhd,
dinf: trak.mdia.minf.dinf,
stbl: {
stsd: stbl.stsd,
stts: empty(),
ctts: empty(),
stsc: empty(),
stsz: empty(),
stco: empty(),
stss: empty()
}
}
}
}],
mvex: {
mehd: {
fragmentDuration: moov.mvhd.duration
},
trexs: [{
trackId: trak.tkhd.trackId,
defaultSampleDescriptionIndex: defaultSampleDescriptionIndex,
defaultSampleDuration: 0,
defaultSampleSize: 0,
defaultSampleFlags: 0
}]
}
}
self._tracks.push({
trackId: trak.tkhd.trackId,
timeScale: trak.mdia.mdhd.timeScale,
samples: samples,
currSample: null,
currTime: null,
moov: trackMoov,
mime: mime
})
}
if (self._tracks.length === 0) {
self.emit('error', new Error('no playable tracks'))
return
}
// Must be set last since this is used above
moov.mvhd.duration = 0
self._ftyp = {
type: 'ftyp',
brand: 'iso5',
brandVersion: 0,
compatibleBrands: [
'iso5'
]
}
var ftypBuf = Box.encode(self._ftyp)
var data = self._tracks.map(function (track) {
var moovBuf = Box.encode(track.moov)
return {
mime: track.mime,
init: Buffer.concat([ftypBuf, moovBuf])
}
})
self.emit('ready', data)
}
function empty () {
return {
version: 0,
flags: 0,
entries: []
}
}
MP4Remuxer.prototype.seek = function (time) {
var self = this
if (!self._tracks) {
throw new Error('Not ready yet; wait for \'ready\' event')
}
if (self._fileStream) {
self._fileStream.destroy()
self._fileStream = null
}
var startOffset = -1
self._tracks.map(function (track, i) {
// find the keyframe before the time
// stream from there
if (track.outStream) {
track.outStream.destroy()
}
if (track.inStream) {
track.inStream.destroy()
track.inStream = null
}
var outStream = track.outStream = mp4.encode()
var fragment = self._generateFragment(i, time)
if (!fragment) {
return outStream.finalize()
}
if (startOffset === -1 || fragment.ranges[0].start < startOffset) {
startOffset = fragment.ranges[0].start
}
writeFragment(fragment)
function writeFragment (frag) {
if (outStream.destroyed) return
outStream.box(frag.moof, function (err) {
if (err) return self.emit('error', err)
if (outStream.destroyed) return
var slicedStream = track.inStream.slice(frag.ranges)
slicedStream.pipe(outStream.mediaData(frag.length, function (err) {
if (err) return self.emit('error', err)
if (outStream.destroyed) return
var nextFrag = self._generateFragment(i)
if (!nextFrag) {
return outStream.finalize()
}
writeFragment(nextFrag)
}))
})
}
})
if (startOffset >= 0) {
var fileStream = self._fileStream = self._file.createReadStream({
start: startOffset
})
self._tracks.forEach(function (track) {
track.inStream = new RangeSliceStream(startOffset)
fileStream.pipe(track.inStream)
})
}
return self._tracks.map(function (track) {
return track.outStream
})
}
MP4Remuxer.prototype._findSampleBefore = function (trackInd, time) {
var self = this
var track = self._tracks[trackInd]
var scaledTime = Math.floor(track.timeScale * time)
var sample = bs(track.samples, scaledTime, function (sample, t) {
var pts = sample.dts + sample.presentationOffset// - track.editShift
return pts - t
})
if (sample === -1) {
sample = 0
} else if (sample < 0) {
sample = -sample - 2
}
// sample is now the last sample with dts <= time
// Find the preceeding sync sample
while (!track.samples[sample].sync) {
sample--
}
return sample
}
var MIN_FRAGMENT_DURATION = 1 // second
MP4Remuxer.prototype._generateFragment = function (track, time) {
var self = this
/*
1. Find correct sample
2. Process backward until sync sample found
3. Process forward until next sync sample after MIN_FRAGMENT_DURATION found
*/
var currTrack = self._tracks[track]
var firstSample
if (time !== undefined) {
firstSample = self._findSampleBefore(track, time)
} else {
firstSample = currTrack.currSample
}
if (firstSample >= currTrack.samples.length)
return null
var startDts = currTrack.samples[firstSample].dts
var totalLen = 0
var ranges = []
for (var currSample = firstSample; currSample < currTrack.samples.length; currSample++) {
var sample = currTrack.samples[currSample]
if (sample.sync && sample.dts - startDts >= currTrack.timeScale * MIN_FRAGMENT_DURATION) {
break // This is a reasonable place to end the fragment
}
totalLen += sample.size
var currRange = ranges.length - 1
if (currRange < 0 || ranges[currRange].end !== sample.offset) {
// Push a new range
ranges.push({
start: sample.offset,
end: sample.offset + sample.size
})
} else {
ranges[currRange].end += sample.size
}
}
currTrack.currSample = currSample
return {
moof: self._generateMoof(track, firstSample, currSample),
ranges: ranges,
length: totalLen
}
}
MP4Remuxer.prototype._generateMoof = function (track, firstSample, lastSample) {
var self = this
var currTrack = self._tracks[track]
var entries = []
for (var j = firstSample; j < lastSample; j++) {
var currSample = currTrack.samples[j]
entries.push({
sampleDuration: currSample.duration,
sampleSize: currSample.size,
sampleFlags: currSample.sync ? 0x2000000 : 0x1010000,
sampleCompositionTimeOffset: currSample.presentationOffset
})
}
var moof = {
type: 'moof',
mfhd: {
sequenceNumber: self._fragmentSequence++
},
trafs: [{
tfhd: {
flags: 0x20000, // default-base-is-moof
trackId: currTrack.trackId
},
tfdt: {
baseMediaDecodeTime: currTrack.samples[firstSample].dts
},
trun: {
flags: 0xf01,
dataOffset: 8, // The moof size has to be added to this later as well
entries: entries
}
}]
}
// Update the offset
moof.trafs[0].trun.dataOffset += Box.encodingLength(moof)
return moof
}
}).call(this,require("buffer").Buffer)
},{"binary-search":2,"buffer":21,"events":25,"inherits":63,"mp4-box-encoding":68,"mp4-stream":72,"range-slice-stream":99}],132:[function(require,module,exports){
var MediaElementWrapper = require('mediasource')
var pump = require('pump')
var MP4Remuxer = require('./mp4-remuxer')
module.exports = VideoStream
function VideoStream (file, mediaElem, opts) {
var self = this
if (!(this instanceof VideoStream)) return new VideoStream(file, mediaElem, opts)
opts = opts || {}
self.detailedError = null
self._elem = mediaElem
self._elemWrapper = new MediaElementWrapper(mediaElem)
self._waitingFired = false
self._trackMeta = null
self._file = file
self._tracks = null
if (self._elem.preload !== 'none') {
self._createMuxer()
}
self._onError = function (err) {
self.detailedError = self._elemWrapper.detailedError
self.destroy() // don't pass err though so the user doesn't need to listen for errors
}
self._onWaiting = function () {
self._waitingFired = true
if (!self._muxer) {
self._createMuxer()
} else if (self._tracks) {
self._pump()
}
}
self._elem.addEventListener('waiting', self._onWaiting)
self._elem.addEventListener('error', self._onError)
}
VideoStream.prototype._createMuxer = function () {
var self = this
self._muxer = new MP4Remuxer(self._file)
self._muxer.on('ready', function (data) {
self._tracks = data.map(function (trackData) {
var mediaSource = self._elemWrapper.createWriteStream(trackData.mime)
mediaSource.on('error', function (err) {
self._elemWrapper.error(err)
})
var track = {
muxed: null,
mediaSource: mediaSource,
initFlushed: false,
onInitFlushed: null
}
mediaSource.write(trackData.init, function (err) {
track.initFlushed = true
if (track.onInitFlushed) {
track.onInitFlushed(err)
}
})
return track
})
if (self._waitingFired || self._elem.preload === 'auto') {
self._pump()
}
})
self._muxer.on('error', function (err) {
self._elemWrapper.error(err)
})
}
VideoStream.prototype._pump = function () {
var self = this
var muxed = self._muxer.seek(self._elem.currentTime, !self._tracks)
self._tracks.forEach(function (track, i) {
var pumpTrack = function () {
if (track.muxed) {
track.muxed.destroy()
track.mediaSource = self._elemWrapper.createWriteStream(track.mediaSource)
track.mediaSource.on('error', function (err) {
self._elemWrapper.error(err)
})
}
track.muxed = muxed[i]
pump(track.muxed, track.mediaSource)
}
if (!track.initFlushed) {
track.onInitFlushed = function (err) {
if (err) {
self._elemWrapper.error(err)
return
}
pumpTrack()
}
} else {
pumpTrack()
}
})
}
VideoStream.prototype.destroy = function () {
var self = this
if (self.destroyed) {
return
}
self.destroyed = true
self._elem.removeEventListener('waiting', self._onWaiting)
self._elem.removeEventListener('error', self._onError)
if (self._tracks) {
self._tracks.forEach(function (track) {
track.muxed.destroy()
})
}
self._elem.src = ''
}
},{"./mp4-remuxer":131,"mediasource":64,"pump":93}],133:[function(require,module,exports){
(function (process,global){
module.exports = WebTorrent
var Buffer = require('safe-buffer').Buffer
var concat = require('simple-concat')
var createTorrent = require('create-torrent')
var debug = require('debug')('webtorrent')
var DHT = require('bittorrent-dht/client') // browser exclude
var EventEmitter = require('events').EventEmitter
var extend = require('xtend')
var hat = require('hat')
var inherits = require('inherits')
var loadIPSet = require('load-ip-set') // browser exclude
var parallel = require('run-parallel')
var parseTorrent = require('parse-torrent')
var path = require('path')
var Peer = require('simple-peer')
var speedometer = require('speedometer')
var zeroFill = require('zero-fill')
var TCPPool = require('./lib/tcp-pool') // browser exclude
var Torrent = require('./lib/torrent')
/**
* WebTorrent version.
*/
var VERSION = require('./package.json').version
/**
* Version number in Azureus-style. Generated from major and minor semver version.
* For example:
* '0.16.1' -> '0016'
* '1.2.5' -> '0102'
*/
var VERSION_STR = VERSION.match(/([0-9]+)/g).slice(0, 2).map(zeroFill(2)).join('')
/**
* Version prefix string (used in peer ID). WebTorrent uses the Azureus-style
* encoding: '-', two characters for client id ('WW'), four ascii digits for version
* number, '-', followed by random numbers.
* For example:
* '-WW0102-'...
*/
var VERSION_PREFIX = '-WW' + VERSION_STR + '-'
inherits(WebTorrent, EventEmitter)
/**
* WebTorrent Client
* @param {Object=} opts
*/
function WebTorrent (opts) {
var self = this
if (!(self instanceof WebTorrent)) return new WebTorrent(opts)
EventEmitter.call(self)
if (!opts) opts = {}
if (typeof opts.peerId === 'string') {
self.peerId = opts.peerId
} else if (Buffer.isBuffer(opts.peerId)) {
self.peerId = opts.peerId.toString('hex')
} else {
self.peerId = Buffer.from(VERSION_PREFIX + hat(48))
}
self.peerIdBuffer = Buffer.from(self.peerId, 'hex')
if (typeof opts.nodeId === 'string') {
self.nodeId = opts.nodeId
} else if (Buffer.isBuffer(opts.nodeId)) {
self.nodeId = opts.nodeId.toString('hex')
} else {
self.nodeId = hat(160)
}
self.nodeIdBuffer = Buffer.from(self.nodeId, 'hex')
self.destroyed = false
self.listening = false
self.torrentPort = opts.torrentPort || 0
self.dhtPort = opts.dhtPort || 0
self.tracker = opts.tracker !== undefined ? opts.tracker : {}
self.torrents = []
self.maxConns = Number(opts.maxConns) || 55
if (self.tracker) {
if (typeof self.tracker !== 'object') self.tracker = {}
if (opts.rtcConfig) {
// TODO: remove in v1
console.warn('WebTorrent: opts.rtcConfig is deprecated. Use opts.tracker.rtcConfig instead')
self.tracker.rtcConfig = opts.rtcConfig
}
if (opts.wrtc) {
// TODO: remove in v1
console.warn('WebTorrent: opts.wrtc is deprecated. Use opts.tracker.wrtc instead')
self.tracker.wrtc = opts.wrtc // to support `webtorrent-hybrid` package
}
if (global.WRTC && !self.tracker.wrtc) self.tracker.wrtc = global.WRTC
}
if (typeof TCPPool === 'function') {
self._tcpPool = new TCPPool(self)
} else {
process.nextTick(function () {
self._onListening()
})
}
// stats
self._downloadSpeed = speedometer()
self._uploadSpeed = speedometer()
if (opts.dht !== false && typeof DHT === 'function' /* browser exclude */) {
// use a single DHT instance for all torrents, so the routing table can be reused
self.dht = new DHT(extend({ nodeId: self.nodeId }, opts.dht))
self.dht.once('error', function (err) {
self._destroy(err)
})
self.dht.once('listening', function () {
var address = self.dht.address()
if (address) self.dhtPort = address.port
})
// Ignore warning when there are > 10 torrents in the client
self.dht.setMaxListeners(0)
self.dht.listen(self.dhtPort)
} else {
self.dht = false
}
debug('new webtorrent (peerId %s, nodeId %s)', self.peerId, self.nodeId)
if (typeof loadIPSet === 'function') {
loadIPSet(opts.blocklist, {
headers: {
'user-agent': 'WebTorrent/' + VERSION + ' (https://webtorrent.io)'
}
}, function (err, ipSet) {
if (err) return self.error('Failed to load blocklist: ' + err.message)
self.blocked = ipSet
ready()
})
} else process.nextTick(ready)
function ready () {
if (self.destroyed) return
self.ready = true
self.emit('ready')
}
}
WebTorrent.WEBRTC_SUPPORT = Peer.WEBRTC_SUPPORT
Object.defineProperty(WebTorrent.prototype, 'downloadSpeed', {
get: function () { return this._downloadSpeed() }
})
Object.defineProperty(WebTorrent.prototype, 'uploadSpeed', {
get: function () { return this._uploadSpeed() }
})
Object.defineProperty(WebTorrent.prototype, 'progress', {
get: function () {
var torrents = this.torrents.filter(function (torrent) {
return torrent.progress !== 1
})
var downloaded = torrents.reduce(function (total, torrent) {
return total + torrent.downloaded
}, 0)
var length = torrents.reduce(function (total, torrent) {
return total + (torrent.length || 0)
}, 0) || 1
return downloaded / length
}
})
Object.defineProperty(WebTorrent.prototype, 'ratio', {
get: function () {
var uploaded = this.torrents.reduce(function (total, torrent) {
return total + torrent.uploaded
}, 0)
var received = this.torrents.reduce(function (total, torrent) {
return total + torrent.received
}, 0) || 1
return uploaded / received
}
})
/**
* Returns the torrent with the given `torrentId`. Convenience method. Easier than
* searching through the `client.torrents` array. Returns `null` if no matching torrent
* found.
*
* @param {string|Buffer|Object|Torrent} torrentId
* @return {Torrent|null}
*/
WebTorrent.prototype.get = function (torrentId) {
var self = this
var i, torrent
var len = self.torrents.length
if (torrentId instanceof Torrent) {
for (i = 0; i < len; i++) {
torrent = self.torrents[i]
if (torrent === torrentId) return torrent
}
} else {
var parsed
try { parsed = parseTorrent(torrentId) } catch (err) {}
if (!parsed) return null
if (!parsed.infoHash) throw new Error('Invalid torrent identifier')
for (i = 0; i < len; i++) {
torrent = self.torrents[i]
if (torrent.infoHash === parsed.infoHash) return torrent
}
}
return null
}
// TODO: remove in v1
WebTorrent.prototype.download = function (torrentId, opts, ontorrent) {
console.warn('WebTorrent: client.download() is deprecated. Use client.add() instead')
return this.add(torrentId, opts, ontorrent)
}
/**
* Start downloading a new torrent. Aliased as `client.download`.
* @param {string|Buffer|Object} torrentId
* @param {Object} opts torrent-specific options
* @param {function=} ontorrent called when the torrent is ready (has metadata)
*/
WebTorrent.prototype.add = function (torrentId, opts, ontorrent) {
var self = this
if (self.destroyed) throw new Error('client is destroyed')
if (typeof opts === 'function') return self.add(torrentId, null, opts)
debug('add')
opts = opts ? extend(opts) : {}
var torrent = new Torrent(torrentId, self, opts)
self.torrents.push(torrent)
torrent.once('_infoHash', onInfoHash)
torrent.once('ready', onReady)
torrent.once('close', onClose)
function onInfoHash () {
if (self.destroyed) return
for (var i = 0, len = self.torrents.length; i < len; i++) {
var t = self.torrents[i]
if (t.infoHash === torrent.infoHash && t !== torrent) {
torrent._destroy(new Error('Cannot add duplicate torrent ' + torrent.infoHash))
return
}
}
}
function onReady () {
if (self.destroyed) return
if (typeof ontorrent === 'function') ontorrent(torrent)
self.emit('torrent', torrent)
}
function onClose () {
torrent.removeListener('_infoHash', onInfoHash)
torrent.removeListener('ready', onReady)
torrent.removeListener('close', onClose)
}
return torrent
}
/**
* Start seeding a new file/folder.
* @param {string|File|FileList|Buffer|Array.<string|File|Buffer>} input
* @param {Object=} opts
* @param {function=} onseed called when torrent is seeding
*/
WebTorrent.prototype.seed = function (input, opts, onseed) {
var self = this
if (self.destroyed) throw new Error('client is destroyed')
if (typeof opts === 'function') return self.seed(input, null, opts)
debug('seed')
opts = opts ? extend(opts) : {}
// When seeding from fs path, initialize store from that path to avoid a copy
if (typeof input === 'string') opts.path = path.dirname(input)
if (!opts.createdBy) opts.createdBy = 'WebTorrent/' + VERSION_STR
if (!self.tracker) opts.announce = []
var torrent = self.add(null, opts, onTorrent)
var streams
if (!Array.isArray(input)) input = [ input ]
parallel(input.map(function (item) {
return function (cb) {
if (isReadable(item)) concat(item, cb)
else cb(null, item)
}
}), function (err, input) {
if (self.destroyed) return
if (err) return torrent._destroy(err)
createTorrent.parseInput(input, opts, function (err, files) {
if (self.destroyed) return
if (err) return torrent._destroy(err)
streams = files.map(function (file) {
return file.getStream
})
createTorrent(input, opts, function (err, torrentBuf) {
if (self.destroyed) return
if (err) return torrent._destroy(err)
var existingTorrent = self.get(torrentBuf)
if (existingTorrent) {
torrent._destroy(new Error('Cannot add duplicate torrent ' + existingTorrent.infoHash))
} else {
torrent._onTorrentId(torrentBuf)
}
})
})
})
function onTorrent (torrent) {
var tasks = [
function (cb) {
torrent.load(streams, cb)
}
]
if (self.dht) {
tasks.push(function (cb) {
torrent.once('dhtAnnounce', cb)
})
}
parallel(tasks, function (err) {
if (self.destroyed) return
if (err) return torrent._destroy(err)
_onseed(torrent)
})
}
function _onseed (torrent) {
debug('on seed')
if (typeof onseed === 'function') onseed(torrent)
self.emit('seed', torrent)
}
return torrent
}
/**
* Remove a torrent from the client.
* @param {string|Buffer|Torrent} torrentId
* @param {function} cb
*/
WebTorrent.prototype.remove = function (torrentId, cb) {
debug('remove')
var torrent = this.get(torrentId)
if (!torrent) throw new Error('No torrent with id ' + torrentId)
this._remove(torrentId, cb)
}
WebTorrent.prototype._remove = function (torrentId, cb) {
var torrent = this.get(torrentId)
if (!torrent) return
this.torrents.splice(this.torrents.indexOf(torrent), 1)
torrent.destroy(cb)
}
WebTorrent.prototype.address = function () {
if (!this.listening) return null
return this._tcpPool
? this._tcpPool.server.address()
: { address: '0.0.0.0', family: 'IPv4', port: 0 }
}
/**
* Destroy the client, including all torrents and connections to peers.
* @param {function} cb
*/
WebTorrent.prototype.destroy = function (cb) {
if (this.destroyed) throw new Error('client already destroyed')
this._destroy(null, cb)
}
WebTorrent.prototype._destroy = function (err, cb) {
var self = this
debug('client destroy')
self.destroyed = true
var tasks = self.torrents.map(function (torrent) {
return function (cb) {
torrent.destroy(cb)
}
})
if (self._tcpPool) {
tasks.push(function (cb) {
self._tcpPool.destroy(cb)
})
}
if (self.dht) {
tasks.push(function (cb) {
self.dht.destroy(cb)
})
}
parallel(tasks, cb)
if (err) self.emit('error', err)
self.torrents = []
self._tcpPool = null
self.dht = null
}
WebTorrent.prototype._onListening = function () {
this.listening = true
if (this._tcpPool) {
// Sometimes server.address() returns `null` in Docker.
// WebTorrent issue: https://github.com/feross/bittorrent-swarm/pull/18
var address = this._tcpPool.server.address()
if (address) this.torrentPort = address.port
}
this.emit('listening')
}
/**
* Check if `obj` is a node Readable stream
* @param {*} obj
* @return {boolean}
*/
function isReadable (obj) {
return typeof obj === 'object' && obj != null && typeof obj.pipe === 'function'
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./lib/tcp-pool":20,"./lib/torrent":138,"./package.json":191,"_process":29,"bittorrent-dht/client":20,"create-torrent":43,"debug":150,"events":25,"hat":156,"inherits":63,"load-ip-set":20,"parse-torrent":75,"path":28,"run-parallel":164,"safe-buffer":165,"simple-concat":166,"simple-peer":113,"speedometer":172,"xtend":188,"zero-fill":190}],134:[function(require,module,exports){
module.exports = FileStream
var debug = require('debug')('webtorrent:file-stream')
var inherits = require('inherits')
var stream = require('readable-stream')
inherits(FileStream, stream.Readable)
/**
* Readable stream of a torrent file
*
* @param {File} file
* @param {Object} opts
* @param {number} opts.start stream slice of file, starting from this byte (inclusive)
* @param {number} opts.end stream slice of file, ending with this byte (inclusive)
*/
function FileStream (file, opts) {
stream.Readable.call(this, opts)
this.destroyed = false
this._torrent = file._torrent
var start = (opts && opts.start) || 0
var end = (opts && opts.end && opts.end < file.length)
? opts.end
: file.length - 1
var pieceLength = file._torrent.pieceLength
this._startPiece = (start + file.offset) / pieceLength | 0
this._endPiece = (end + file.offset) / pieceLength | 0
this._piece = this._startPiece
this._offset = (start + file.offset) - (this._startPiece * pieceLength)
this._missing = end - start + 1
this._reading = false
this._notifying = false
this._criticalLength = Math.min((1024 * 1024 / pieceLength) | 0, 2)
}
FileStream.prototype._read = function () {
if (this._reading) return
this._reading = true
this._notify()
}
FileStream.prototype._notify = function () {
var self = this
if (!self._reading || self._missing === 0) return
if (!self._torrent.bitfield.get(self._piece)) {
return self._torrent.critical(self._piece, self._piece + self._criticalLength)
}
if (self._notifying) return
self._notifying = true
var p = self._piece
self._torrent.store.get(p, function (err, buffer) {
self._notifying = false
if (self.destroyed) return
if (err) return self._destroy(err)
debug('read %s (length %s) (err %s)', p, buffer.length, err && err.message)
if (self._offset) {
buffer = buffer.slice(self._offset)
self._offset = 0
}
if (self._missing < buffer.length) {
buffer = buffer.slice(0, self._missing)
}
self._missing -= buffer.length
debug('pushing buffer of length %s', buffer.length)
self._reading = false
self.push(buffer)
if (self._missing === 0) self.push(null)
})
self._piece += 1
}
FileStream.prototype.destroy = function (onclose) {
this._destroy(null, onclose)
}
FileStream.prototype._destroy = function (err, onclose) {
if (this.destroyed) return
this.destroyed = true
if (!this._torrent.destroyed) {
this._torrent.deselect(this._startPiece, this._endPiece, true)
}
if (err) this.emit('error', err)
this.emit('close')
if (onclose) onclose()
}
},{"debug":150,"inherits":63,"readable-stream":112}],135:[function(require,module,exports){
(function (process){
module.exports = File
var eos = require('end-of-stream')
var EventEmitter = require('events').EventEmitter
var FileStream = require('./file-stream')
var inherits = require('inherits')
var path = require('path')
var render = require('render-media')
var stream = require('readable-stream')
var streamToBlobURL = require('stream-to-blob-url')
var streamToBuffer = require('stream-with-known-length-to-buffer')
inherits(File, EventEmitter)
function File (torrent, file) {
EventEmitter.call(this)
this._torrent = torrent
this._destroyed = false
this.name = file.name
this.path = file.path
this.length = file.length
this.offset = file.offset
this.done = false
var start = file.offset
var end = start + file.length - 1
this._startPiece = start / this._torrent.pieceLength | 0
this._endPiece = end / this._torrent.pieceLength | 0
if (this.length === 0) {
this.done = true
this.emit('done')
}
}
File.prototype.select = function (priority) {
if (this.length === 0) return
this._torrent.select(this._startPiece, this._endPiece, priority)
}
File.prototype.deselect = function () {
if (this.length === 0) return
this._torrent.deselect(this._startPiece, this._endPiece, false)
}
File.prototype.createReadStream = function (opts) {
var self = this
if (this.length === 0) {
var empty = new stream.PassThrough()
process.nextTick(function () {
empty.end()
})
return empty
}
var fileStream = new FileStream(self, opts)
self._torrent.select(fileStream._startPiece, fileStream._endPiece, true, function () {
fileStream._notify()
})
eos(fileStream, function () {
if (self._destroyed) return
if (!self._torrent.destroyed) {
self._torrent.deselect(fileStream._startPiece, fileStream._endPiece, true)
}
})
return fileStream
}
File.prototype.getBuffer = function (cb) {
streamToBuffer(this.createReadStream(), this.length, cb)
}
File.prototype.getBlobURL = function (cb) {
if (typeof window === 'undefined') throw new Error('browser-only method')
var mime = render.mime[path.extname(this.name).toLowerCase()]
streamToBlobURL(this.createReadStream(), mime, cb)
}
File.prototype.appendTo = function (elem, cb) {
if (typeof window === 'undefined') throw new Error('browser-only method')
render.append(this, elem, cb)
}
File.prototype.renderTo = function (elem, cb) {
if (typeof window === 'undefined') throw new Error('browser-only method')
render.render(this, elem, cb)
}
File.prototype._destroy = function () {
this._destroyed = true
this._torrent = null
}
}).call(this,require('_process'))
},{"./file-stream":134,"_process":29,"end-of-stream":153,"events":25,"inherits":63,"path":28,"readable-stream":112,"render-media":160,"stream-to-blob-url":173,"stream-with-known-length-to-buffer":177}],136:[function(require,module,exports){
var arrayRemove = require('unordered-array-remove')
var debug = require('debug')('webtorrent:peer')
var Wire = require('bittorrent-protocol')
var WebConn = require('./webconn')
var CONNECT_TIMEOUT_TCP = 5000
var CONNECT_TIMEOUT_WEBRTC = 25000
var HANDSHAKE_TIMEOUT = 25000
/**
* WebRTC peer connections start out connected, because WebRTC peers require an
* "introduction" (i.e. WebRTC signaling), and there's no equivalent to an IP address
* that lets you refer to a WebRTC endpoint.
*/
exports.createWebRTCPeer = function (conn, swarm) {
var peer = new Peer(conn.id, 'webrtc')
peer.conn = conn
peer.swarm = swarm
if (peer.conn.connected) {
peer.onConnect()
} else {
peer.conn.once('connect', function () { peer.onConnect() })
peer.conn.once('error', function (err) { peer.destroy(err) })
peer.startConnectTimeout()
}
return peer
}
/**
* Incoming TCP peers start out connected, because the remote peer connected to the
* listening port of the TCP server. Until the remote peer sends a handshake, we don't
* know what swarm the connection is intended for.
*/
exports.createTCPIncomingPeer = function (conn) {
var addr = conn.remoteAddress + ':' + conn.remotePort
var peer = new Peer(addr, 'tcpIncoming')
peer.conn = conn
peer.addr = addr
peer.onConnect()
return peer
}
/**
* Outgoing TCP peers start out with just an IP address. At some point (when there is an
* available connection), the client can attempt to connect to the address.
*/
exports.createTCPOutgoingPeer = function (addr, swarm) {
var peer = new Peer(addr, 'tcpOutgoing')
peer.addr = addr
peer.swarm = swarm
return peer
}
/**
* Peer that represents a Web Seed (BEP17 / BEP19).
*/
exports.createWebSeedPeer = function (url, swarm) {
var peer = new Peer(url, 'webSeed')
peer.swarm = swarm
peer.conn = new WebConn(url, swarm)
peer.onConnect()
return peer
}
/**
* Peer. Represents a peer in the torrent swarm.
*
* @param {string} id "ip:port" string, peer id (for WebRTC peers), or url (for Web Seeds)
* @param {string} type the type of the peer
*/
function Peer (id, type) {
var self = this
self.id = id
self.type = type
debug('new Peer %s', id)
self.addr = null
self.conn = null
self.swarm = null
self.wire = null
self.connected = false
self.destroyed = false
self.timeout = null // handshake timeout
self.retries = 0 // outgoing TCP connection retry count
self.sentHandshake = false
}
/**
* Called once the peer is connected (i.e. fired 'connect' event)
* @param {Socket} conn
*/
Peer.prototype.onConnect = function () {
var self = this
if (self.destroyed) return
self.connected = true
debug('Peer %s connected', self.id)
clearTimeout(self.connectTimeout)
var conn = self.conn
conn.once('end', function () {
self.destroy()
})
conn.once('close', function () {
self.destroy()
})
conn.once('finish', function () {
self.destroy()
})
conn.once('error', function (err) {
self.destroy(err)
})
var wire = self.wire = new Wire()
wire.type = self.type
wire.once('end', function () {
self.destroy()
})
wire.once('close', function () {
self.destroy()
})
wire.once('finish', function () {
self.destroy()
})
wire.once('error', function (err) {
self.destroy(err)
})
wire.once('handshake', function (infoHash, peerId) {
self.onHandshake(infoHash, peerId)
})
self.startHandshakeTimeout()
conn.pipe(wire).pipe(conn)
if (self.swarm && !self.sentHandshake) self.handshake()
}
/**
* Called when handshake is received from remote peer.
* @param {string} infoHash
* @param {string} peerId
*/
Peer.prototype.onHandshake = function (infoHash, peerId) {
var self = this
if (!self.swarm) return // `self.swarm` not set yet, so do nothing
if (self.destroyed) return
if (self.swarm.destroyed) {
return self.destroy(new Error('swarm already destroyed'))
}
if (infoHash !== self.swarm.infoHash) {
return self.destroy(new Error('unexpected handshake info hash for this swarm'))
}
if (peerId === self.swarm.peerId) {
return self.destroy(new Error('refusing to connect to ourselves'))
}
debug('Peer %s got handshake %s', self.id, infoHash)
clearTimeout(self.handshakeTimeout)
self.retries = 0
var addr = self.addr
if (!addr && self.conn.remoteAddress) {
addr = self.conn.remoteAddress + ':' + self.conn.remotePort
}
self.swarm._onWire(self.wire, addr)
// swarm could be destroyed in user's 'wire' event handler
if (!self.swarm || self.swarm.destroyed) return
if (!self.sentHandshake) self.handshake()
}
Peer.prototype.handshake = function () {
var self = this
var opts = {
dht: self.swarm.private ? false : !!self.swarm.client.dht
}
self.wire.handshake(self.swarm.infoHash, self.swarm.client.peerId, opts)
self.sentHandshake = true
}
Peer.prototype.startConnectTimeout = function () {
var self = this
clearTimeout(self.connectTimeout)
self.connectTimeout = setTimeout(function () {
self.destroy(new Error('connect timeout'))
}, self.type === 'webrtc' ? CONNECT_TIMEOUT_WEBRTC : CONNECT_TIMEOUT_TCP)
if (self.connectTimeout.unref) self.connectTimeout.unref()
}
Peer.prototype.startHandshakeTimeout = function () {
var self = this
clearTimeout(self.handshakeTimeout)
self.handshakeTimeout = setTimeout(function () {
self.destroy(new Error('handshake timeout'))
}, HANDSHAKE_TIMEOUT)
if (self.handshakeTimeout.unref) self.handshakeTimeout.unref()
}
Peer.prototype.destroy = function (err) {
var self = this
if (self.destroyed) return
self.destroyed = true
self.connected = false
debug('destroy %s (error: %s)', self.id, err && (err.message || err))
clearTimeout(self.connectTimeout)
clearTimeout(self.handshakeTimeout)
var swarm = self.swarm
var conn = self.conn
var wire = self.wire
self.swarm = null
self.conn = null
self.wire = null
if (swarm && wire) {
arrayRemove(swarm.wires, swarm.wires.indexOf(wire))
}
if (conn) {
conn.on('error', noop)
conn.destroy()
}
if (wire) wire.destroy()
if (swarm) swarm.removePeer(self.id)
}
function noop () {}
},{"./webconn":139,"bittorrent-protocol":142,"debug":150,"unordered-array-remove":183}],137:[function(require,module,exports){
module.exports = RarityMap
/**
* Mapping of torrent pieces to their respective availability in the torrent swarm. Used
* by the torrent manager for implementing the rarest piece first selection strategy.
*/
function RarityMap (torrent) {
var self = this
self._torrent = torrent
self._numPieces = torrent.pieces.length
self._pieces = []
self._onWire = function (wire) {
self.recalculate()
self._initWire(wire)
}
self._onWireHave = function (index) {
self._pieces[index] += 1
}
self._onWireBitfield = function () {
self.recalculate()
}
self._torrent.wires.forEach(function (wire) {
self._initWire(wire)
})
self._torrent.on('wire', self._onWire)
self.recalculate()
}
/**
* Get the index of the rarest piece. Optionally, pass a filter function to exclude
* certain pieces (for instance, those that we already have).
*
* @param {function} pieceFilterFunc
* @return {number} index of rarest piece, or -1
*/
RarityMap.prototype.getRarestPiece = function (pieceFilterFunc) {
if (!pieceFilterFunc) pieceFilterFunc = trueFn
var candidates = []
var min = Infinity
for (var i = 0; i < this._numPieces; ++i) {
if (!pieceFilterFunc(i)) continue
var availability = this._pieces[i]
if (availability === min) {
candidates.push(i)
} else if (availability < min) {
candidates = [ i ]
min = availability
}
}
if (candidates.length > 0) {
// if there are multiple pieces with the same availability, choose one randomly
return candidates[Math.random() * candidates.length | 0]
} else {
return -1
}
}
RarityMap.prototype.destroy = function () {
var self = this
self._torrent.removeListener('wire', self._onWire)
self._torrent.wires.forEach(function (wire) {
self._cleanupWireEvents(wire)
})
self._torrent = null
self._pieces = null
self._onWire = null
self._onWireHave = null
self._onWireBitfield = null
}
RarityMap.prototype._initWire = function (wire) {
var self = this
wire._onClose = function () {
self._cleanupWireEvents(wire)
for (var i = 0; i < this._numPieces; ++i) {
self._pieces[i] -= wire.peerPieces.get(i)
}
}
wire.on('have', self._onWireHave)
wire.on('bitfield', self._onWireBitfield)
wire.once('close', wire._onClose)
}
/**
* Recalculates piece availability across all peers in the torrent.
*/
RarityMap.prototype.recalculate = function () {
var i
for (i = 0; i < this._numPieces; ++i) {
this._pieces[i] = 0
}
var numWires = this._torrent.wires.length
for (i = 0; i < numWires; ++i) {
var wire = this._torrent.wires[i]
for (var j = 0; j < this._numPieces; ++j) {
this._pieces[j] += wire.peerPieces.get(j)
}
}
}
RarityMap.prototype._cleanupWireEvents = function (wire) {
wire.removeListener('have', this._onWireHave)
wire.removeListener('bitfield', this._onWireBitfield)
if (wire._onClose) wire.removeListener('close', wire._onClose)
wire._onClose = null
}
function trueFn () {
return true
}
},{}],138:[function(require,module,exports){
(function (process,global){
/* global URL, Blob */
module.exports = Torrent
var addrToIPPort = require('addr-to-ip-port')
var BitField = require('bitfield')
var ChunkStoreWriteStream = require('chunk-store-stream/write')
var debug = require('debug')('webtorrent:torrent')
var Discovery = require('torrent-discovery')
var EventEmitter = require('events').EventEmitter
var extend = require('xtend')
var extendMutable = require('xtend/mutable')
var fs = require('fs')
var FSChunkStore = require('fs-chunk-store') // browser: `memory-chunk-store`
var get = require('simple-get')
var ImmediateChunkStore = require('immediate-chunk-store')
var inherits = require('inherits')
var MultiStream = require('multistream')
var net = require('net') // browser exclude
var os = require('os') // browser exclude
var parallel = require('run-parallel')
var parallelLimit = require('run-parallel-limit')
var parseTorrent = require('parse-torrent')
var path = require('path')
var Piece = require('torrent-piece')
var pump = require('pump')
var randomIterate = require('random-iterate')
var sha1 = require('simple-sha1')
var speedometer = require('speedometer')
var uniq = require('uniq')
var utMetadata = require('ut_metadata')
var utPex = require('ut_pex') // browser exclude
var File = require('./file')
var Peer = require('./peer')
var RarityMap = require('./rarity-map')
var Server = require('./server') // browser exclude
var MAX_BLOCK_LENGTH = 128 * 1024
var PIECE_TIMEOUT = 30000
var CHOKE_TIMEOUT = 5000
var SPEED_THRESHOLD = 3 * Piece.BLOCK_LENGTH
var PIPELINE_MIN_DURATION = 0.5
var PIPELINE_MAX_DURATION = 1
var RECHOKE_INTERVAL = 10000 // 10 seconds
var RECHOKE_OPTIMISTIC_DURATION = 2 // 30 seconds
var FILESYSTEM_CONCURRENCY = 2
var RECONNECT_WAIT = [ 1000, 5000, 15000 ]
var VERSION = require('../package.json').version
var TMP
try {
TMP = path.join(fs.statSync('/tmp') && '/tmp', 'webtorrent')
} catch (err) {
TMP = path.join(typeof os.tmpDir === 'function' ? os.tmpDir() : '/', 'webtorrent')
}
inherits(Torrent, EventEmitter)
function Torrent (torrentId, client, opts) {
EventEmitter.call(this)
this.client = client
this._debugId = this.client.peerId.slice(32)
this._debug('new torrent')
this.announce = opts.announce
this.urlList = opts.urlList
this.path = opts.path
this._store = opts.store || FSChunkStore
this._getAnnounceOpts = opts.getAnnounceOpts
this.strategy = opts.strategy || 'sequential'
this.maxWebConns = opts.maxWebConns || 4
this._rechokeNumSlots = (opts.uploads === false || opts.uploads === 0)
? 0
: (+opts.uploads || 10)
this._rechokeOptimisticWire = null
this._rechokeOptimisticTime = 0
this._rechokeIntervalId = null
this.ready = false
this.destroyed = false
this.paused = false
this.done = false
this.metadata = null
this.store = null
this.files = []
this.pieces = []
this._amInterested = false
this._selections = []
this._critical = []
this.wires = [] // open wires (added *after* handshake)
this._queue = [] // queue of outgoing tcp peers to connect to
this._peers = {} // connected peers (addr/peerId -> Peer)
this._peersLength = 0 // number of elements in `this._peers` (cache, for perf)
// stats
this.received = 0
this.uploaded = 0
this._downloadSpeed = speedometer()
this._uploadSpeed = speedometer()
// for cleanup
this._servers = []
this._xsRequests = []
// TODO: remove this and expose a hook instead
// optimization: don't recheck every file if it hasn't changed
this._fileModtimes = opts.fileModtimes
if (torrentId !== null) this._onTorrentId(torrentId)
}
Object.defineProperty(Torrent.prototype, 'timeRemaining', {
get: function () {
if (this.done) return 0
if (this.downloadSpeed === 0) return Infinity
return ((this.length - this.downloaded) / this.downloadSpeed) * 1000
}
})
Object.defineProperty(Torrent.prototype, 'downloaded', {
get: function () {
if (!this.bitfield) return 0
var downloaded = 0
for (var index = 0, len = this.pieces.length; index < len; ++index) {
if (this.bitfield.get(index)) { // verified data
downloaded += (index === len - 1) ? this.lastPieceLength : this.pieceLength
} else { // "in progress" data
var piece = this.pieces[index]
downloaded += (piece.length - piece.missing)
}
}
return downloaded
}
})
// TODO: re-enable this. The number of missing pieces. Used to implement 'end game' mode.
// Object.defineProperty(Storage.prototype, 'numMissing', {
// get: function () {
// var self = this
// var numMissing = self.pieces.length
// for (var index = 0, len = self.pieces.length; index < len; index++) {
// numMissing -= self.bitfield.get(index)
// }
// return numMissing
// }
// })
Object.defineProperty(Torrent.prototype, 'downloadSpeed', {
get: function () { return this._downloadSpeed() }
})
Object.defineProperty(Torrent.prototype, 'uploadSpeed', {
get: function () { return this._uploadSpeed() }
})
Object.defineProperty(Torrent.prototype, 'progress', {
get: function () { return this.length ? this.downloaded / this.length : 0 }
})
Object.defineProperty(Torrent.prototype, 'ratio', {
get: function () { return this.uploaded / (this.received || 1) }
})
Object.defineProperty(Torrent.prototype, 'numPeers', {
get: function () { return this.wires.length }
})
Object.defineProperty(Torrent.prototype, 'torrentFileBlobURL', {
get: function () {
if (typeof window === 'undefined') throw new Error('browser-only property')
if (!this.torrentFile) return null
return URL.createObjectURL(
new Blob([ this.torrentFile ], { type: 'application/x-bittorrent' })
)
}
})
Object.defineProperty(Torrent.prototype, '_numQueued', {
get: function () {
return this._queue.length + (this._peersLength - this._numConns)
}
})
Object.defineProperty(Torrent.prototype, '_numConns', {
get: function () {
var self = this
var numConns = 0
for (var id in self._peers) {
if (self._peers[id].connected) numConns += 1
}
return numConns
}
})
// TODO: remove in v1
Object.defineProperty(Torrent.prototype, 'swarm', {
get: function () {
console.warn('WebTorrent: `torrent.swarm` is deprecated. Use `torrent` directly instead.')
return this
}
})
Torrent.prototype._onTorrentId = function (torrentId) {
var self = this
if (self.destroyed) return
var parsedTorrent
try { parsedTorrent = parseTorrent(torrentId) } catch (err) {}
if (parsedTorrent) {
// Attempt to set infoHash property synchronously
self.infoHash = parsedTorrent.infoHash
process.nextTick(function () {
if (self.destroyed) return
self._onParsedTorrent(parsedTorrent)
})
} else {
// If torrentId failed to parse, it could be in a form that requires an async
// operation, i.e. http/https link, filesystem path, or Blob.
parseTorrent.remote(torrentId, function (err, parsedTorrent) {
if (self.destroyed) return
if (err) return self._destroy(err)
self._onParsedTorrent(parsedTorrent)
})
}
}
Torrent.prototype._onParsedTorrent = function (parsedTorrent) {
var self = this
if (self.destroyed) return
self._processParsedTorrent(parsedTorrent)
if (!self.infoHash) {
return self._destroy(new Error('Malformed torrent data: No info hash'))
}
if (!self.path) self.path = path.join(TMP, self.infoHash)
self._rechokeIntervalId = setInterval(function () {
self._rechoke()
}, RECHOKE_INTERVAL)
if (self._rechokeIntervalId.unref) self._rechokeIntervalId.unref()
// Private 'infoHash' event allows client.add to check for duplicate torrents and
// destroy them before the normal 'infoHash' event is emitted. Prevents user
// applications from needing to deal with duplicate 'infoHash' events.
self.emit('_infoHash', self.infoHash)
if (self.destroyed) return
self.emit('infoHash', self.infoHash)
if (self.destroyed) return // user might destroy torrent in event handler
if (self.client.listening) {
self._onListening()
} else {
self.client.once('listening', function () {
self._onListening()
})
}
}
Torrent.prototype._processParsedTorrent = function (parsedTorrent) {
if (this.announce) {
// Allow specifying trackers via `opts` parameter
parsedTorrent.announce = parsedTorrent.announce.concat(this.announce)
}
if (this.client.tracker && global.WEBTORRENT_ANNOUNCE && !this.private) {
// So `webtorrent-hybrid` can force specific trackers to be used
parsedTorrent.announce = parsedTorrent.announce.concat(global.WEBTORRENT_ANNOUNCE)
}
if (this.urlList) {
// Allow specifying web seeds via `opts` parameter
parsedTorrent.urlList = parsedTorrent.urlList.concat(this.urlList)
}
uniq(parsedTorrent.announce)
uniq(parsedTorrent.urlList)
extendMutable(this, parsedTorrent)
this.magnetURI = parseTorrent.toMagnetURI(parsedTorrent)
this.torrentFile = parseTorrent.toTorrentFile(parsedTorrent)
}
Torrent.prototype._onListening = function () {
var self = this
if (self.discovery || self.destroyed) return
var trackerOpts = self.client.tracker
if (trackerOpts) {
trackerOpts = extend(self.client.tracker, {
getAnnounceOpts: function () {
var opts = {
uploaded: self.uploaded,
downloaded: self.downloaded,
left: Math.max(self.length - self.downloaded, 0)
}
if (self.client.tracker.getAnnounceOpts) {
extendMutable(opts, self.client.tracker.getAnnounceOpts())
}
if (self._getAnnounceOpts) {
// TODO: consider deprecating this, as it's redundant with the former case
extendMutable(opts, self._getAnnounceOpts())
}
return opts
}
})
}
// begin discovering peers via DHT and trackers
self.discovery = new Discovery({
infoHash: self.infoHash,
announce: self.announce,
peerId: self.client.peerId,
dht: !self.private && self.client.dht,
tracker: trackerOpts,
port: self.client.torrentPort
})
self.discovery.on('error', onError)
self.discovery.on('peer', onPeer)
self.discovery.on('trackerAnnounce', onTrackerAnnounce)
self.discovery.on('dhtAnnounce', onDHTAnnounce)
self.discovery.on('warning', onWarning)
function onError (err) {
self._destroy(err)
}
function onPeer (peer) {
// Don't create new outgoing TCP connections when torrent is done
if (typeof peer === 'string' && self.done) return
self.addPeer(peer)
}
function onTrackerAnnounce () {
self.emit('trackerAnnounce')
if (self.numPeers === 0) self.emit('noPeers', 'tracker')
}
function onDHTAnnounce () {
self.emit('dhtAnnounce')
if (self.numPeers === 0) self.emit('noPeers', 'dht')
}
function onWarning (err) {
self.emit('warning', err)
}
if (self.info) {
// if full metadata was included in initial torrent id, use it immediately. Otherwise,
// wait for torrent-discovery to find peers and ut_metadata to get the metadata.
self._onMetadata(self)
} else if (self.xs) {
self._getMetadataFromServer()
}
}
Torrent.prototype._getMetadataFromServer = function () {
var self = this
var urls = Array.isArray(self.xs) ? self.xs : [ self.xs ]
var tasks = urls.map(function (url) {
return function (cb) {
getMetadataFromURL(url, cb)
}
})
parallel(tasks)
function getMetadataFromURL (url, cb) {
if (url.indexOf('http://') !== 0 && url.indexOf('https://') !== 0) {
self._debug('skipping non-http xs param: %s', url)
return cb(null)
}
var opts = {
url: url,
method: 'GET',
headers: {
'user-agent': 'WebTorrent/' + VERSION + ' (https://webtorrent.io)'
}
}
var req
try {
req = get.concat(opts, onResponse)
} catch (err) {
self._debug('skipping invalid url xs param: %s', url)
return cb(null)
}
self._xsRequests.push(req)
function onResponse (err, res, torrent) {
if (self.destroyed) return cb(null)
if (self.metadata) return cb(null)
if (err) {
self._debug('http error from xs param: %s', url)
return cb(null)
}
if (res.statusCode !== 200) {
self._debug('non-200 status code %s from xs param: %s', res.statusCode, url)
return cb(null)
}
var parsedTorrent
try {
parsedTorrent = parseTorrent(torrent)
} catch (err) {}
if (!parsedTorrent) {
self._debug('got invalid torrent file from xs param: %s', url)
return cb(null)
}
if (parsedTorrent.infoHash !== self.infoHash) {
self._debug('got torrent file with incorrect info hash from xs param: %s', url)
return cb(null)
}
self._onMetadata(parsedTorrent)
cb(null)
}
}
}
/**
* Called when the full torrent metadata is received.
*/
Torrent.prototype._onMetadata = function (metadata) {
var self = this
if (self.metadata || self.destroyed) return
self._debug('got metadata')
self._xsRequests.forEach(function (req) {
req.abort()
})
self._xsRequests = []
var parsedTorrent
if (metadata && metadata.infoHash) {
// `metadata` is a parsed torrent (from parse-torrent module)
parsedTorrent = metadata
} else {
try {
parsedTorrent = parseTorrent(metadata)
} catch (err) {
return self._destroy(err)
}
}
self._processParsedTorrent(parsedTorrent)
self.metadata = self.torrentFile
// add web seed urls (BEP19)
self.urlList.forEach(function (url) {
self.addWebSeed(url)
})
self._rarityMap = new RarityMap(self)
self.store = new ImmediateChunkStore(
new self._store(self.pieceLength, {
torrent: {
infoHash: self.infoHash
},
files: self.files.map(function (file) {
return {
path: path.join(self.path, file.path),
length: file.length,
offset: file.offset
}
}),
length: self.length
})
)
self.files = self.files.map(function (file) {
return new File(self, file)
})
self._hashes = self.pieces
self.pieces = self.pieces.map(function (hash, i) {
var pieceLength = (i === self.pieces.length - 1)
? self.lastPieceLength
: self.pieceLength
return new Piece(pieceLength)
})
self._reservations = self.pieces.map(function () {
return []
})
self.bitfield = new BitField(self.pieces.length)
self.wires.forEach(function (wire) {
// If we didn't have the metadata at the time ut_metadata was initialized for this
// wire, we still want to make it available to the peer in case they request it.
if (wire.ut_metadata) wire.ut_metadata.setMetadata(self.metadata)
self._onWireWithMetadata(wire)
})
self._debug('verifying existing torrent data')
if (self._fileModtimes && self._store === FSChunkStore) {
// don't verify if the files haven't been modified since we last checked
self.getFileModtimes(function (err, fileModtimes) {
if (err) return self._destroy(err)
var unchanged = self.files.map(function (_, index) {
return fileModtimes[index] === self._fileModtimes[index]
}).every(function (x) {
return x
})
if (unchanged) {
for (var index = 0; index < self.pieces.length; index++) {
self._markVerified(index)
}
self._onStore()
} else {
self._verifyPieces()
}
})
} else {
self._verifyPieces()
}
self.emit('metadata')
}
/*
* TODO: remove this
* Gets the last modified time of every file on disk for this torrent.
* Only valid in Node, not in the browser.
*/
Torrent.prototype.getFileModtimes = function (cb) {
var self = this
var ret = []
parallelLimit(self.files.map(function (file, index) {
return function (cb) {
fs.stat(path.join(self.path, file.path), function (err, stat) {
if (err && err.code !== 'ENOENT') return cb(err)
ret[index] = stat && stat.mtime.getTime()
cb(null)
})
}
}), FILESYSTEM_CONCURRENCY, function (err) {
self._debug('done getting file modtimes')
cb(err, ret)
})
}
Torrent.prototype._verifyPieces = function () {
var self = this
parallelLimit(self.pieces.map(function (_, index) {
return function (cb) {
if (self.destroyed) return cb(new Error('torrent is destroyed'))
self.store.get(index, function (err, buf) {
if (err) return cb(null) // ignore error
sha1(buf, function (hash) {
if (hash === self._hashes[index]) {
if (!self.pieces[index]) return
self._debug('piece verified %s', index)
self._markVerified(index)
} else {
self._debug('piece invalid %s', index)
}
cb(null)
})
})
}
}), FILESYSTEM_CONCURRENCY, function (err) {
if (err) return self._destroy(err)
self._debug('done verifying')
self._onStore()
})
}
Torrent.prototype._markVerified = function (index) {
this.pieces[index] = null
this._reservations[index] = null
this.bitfield.set(index, true)
}
/**
* Called when the metadata, listening server, and underlying chunk store is initialized.
*/
Torrent.prototype._onStore = function () {
var self = this
if (self.destroyed) return
self._debug('on store')
// start off selecting the entire torrent with low priority
if (self.pieces.length !== 0) {
self.select(0, self.pieces.length - 1, false)
}
self.ready = true
self.emit('ready')
// Files may start out done if the file was already in the store
self._checkDone()
// In case any selections were made before torrent was ready
self._updateSelections()
}
Torrent.prototype.destroy = function (cb) {
var self = this
self._destroy(null, cb)
}
Torrent.prototype._destroy = function (err, cb) {
var self = this
if (self.destroyed) return
self.destroyed = true
self._debug('destroy')
self.client._remove(self)
clearInterval(self._rechokeIntervalId)
self._xsRequests.forEach(function (req) {
req.abort()
})
if (self._rarityMap) {
self._rarityMap.destroy()
}
for (var id in self._peers) {
self.removePeer(id)
}
self.files.forEach(function (file) {
if (file instanceof File) file._destroy()
})
var tasks = self._servers.map(function (server) {
return function (cb) {
server.destroy(cb)
}
})
if (self.discovery) {
tasks.push(function (cb) {
self.discovery.destroy(cb)
})
}
if (self.store) {
tasks.push(function (cb) {
self.store.close(cb)
})
}
parallel(tasks, cb)
if (err) {
// Torrent errors are emitted at `torrent.on('error')`. If there are no 'error' event
// handlers on the torrent instance, the error will be emitted at
// `client.on('error')`. This prevents crashing the user's program, but it makes it
// impossible to determine a client error versus a torrent error (where the client
// is still usable afterwards). Users are recommended for errors in both places
// to distinguish between the error types.
if (self.listenerCount('error') === 0) {
self.client.emit('error', err)
} else {
self.emit('error', err)
}
}
self.emit('close')
self.client = null
self.files = []
self.discovery = null
self.store = null
self._rarityMap = null
self._peers = null
self._servers = null
self._xsRequests = null
}
Torrent.prototype.addPeer = function (peer) {
var self = this
if (self.destroyed) throw new Error('torrent is destroyed')
if (!self.infoHash) throw new Error('addPeer() must not be called before the `infoHash` event')
if (self.client.blocked) {
var host
if (typeof peer === 'string') {
var parts
try {
parts = addrToIPPort(peer)
} catch (e) {
self._debug('ignoring peer: invalid %s', peer)
self.emit('invalidPeer', peer)
return false
}
host = parts[0]
} else if (typeof peer.remoteAddress === 'string') {
host = peer.remoteAddress
}
if (host && self.client.blocked.contains(host)) {
self._debug('ignoring peer: blocked %s', peer)
if (typeof peer !== 'string') peer.destroy()
self.emit('blockedPeer', peer)
return false
}
}
var wasAdded = !!self._addPeer(peer)
if (wasAdded) {
self.emit('peer', peer)
} else {
self.emit('invalidPeer', peer)
}
return wasAdded
}
Torrent.prototype._addPeer = function (peer) {
var self = this
if (self.destroyed) {
self._debug('ignoring peer: torrent is destroyed')
if (typeof peer !== 'string') peer.destroy()
return null
}
if (typeof peer === 'string' && !self._validAddr(peer)) {
self._debug('ignoring peer: invalid %s', peer)
return null
}
var id = (peer && peer.id) || peer
if (self._peers[id]) {
self._debug('ignoring peer: duplicate (%s)', id)
if (typeof peer !== 'string') peer.destroy()
return null
}
if (self.paused) {
self._debug('ignoring peer: torrent is paused')
if (typeof peer !== 'string') peer.destroy()
return null
}
self._debug('add peer %s', id)
var newPeer
if (typeof peer === 'string') {
// `peer` is an addr ("ip:port" string)
newPeer = Peer.createTCPOutgoingPeer(peer, self)
} else {
// `peer` is a WebRTC connection (simple-peer)
newPeer = Peer.createWebRTCPeer(peer, self)
}
self._peers[newPeer.id] = newPeer
self._peersLength += 1
if (typeof peer === 'string') {
// `peer` is an addr ("ip:port" string)
self._queue.push(newPeer)
self._drain()
}
return newPeer
}
Torrent.prototype.addWebSeed = function (url) {
if (this.destroyed) throw new Error('torrent is destroyed')
if (!/^https?:\/\/.+/.test(url)) {
this._debug('ignoring invalid web seed %s', url)
this.emit('invalidPeer', url)
return
}
if (this._peers[url]) {
this._debug('ignoring duplicate web seed %s', url)
this.emit('invalidPeer', url)
return
}
this._debug('add web seed %s', url)
var newPeer = Peer.createWebSeedPeer(url, this)
this._peers[newPeer.id] = newPeer
this._peersLength += 1
this.emit('peer', url)
}
/**
* Called whenever a new incoming TCP peer connects to this torrent swarm. Called with a
* peer that has already sent a handshake.
*/
Torrent.prototype._addIncomingPeer = function (peer) {
var self = this
if (self.destroyed) return peer.destroy(new Error('torrent is destroyed'))
if (self.paused) return peer.destroy(new Error('torrent is paused'))
this._debug('add incoming peer %s', peer.id)
self._peers[peer.id] = peer
self._peersLength += 1
}
Torrent.prototype.removePeer = function (peer) {
var self = this
var id = (peer && peer.id) || peer
peer = self._peers[id]
if (!peer) return
this._debug('removePeer %s', id)
delete self._peers[id]
self._peersLength -= 1
peer.destroy()
// If torrent swarm was at capacity before, try to open a new connection now
self._drain()
}
Torrent.prototype.select = function (start, end, priority, notify) {
var self = this
if (self.destroyed) throw new Error('torrent is destroyed')
if (start < 0 || end < start || self.pieces.length <= end) {
throw new Error('invalid selection ', start, ':', end)
}
priority = Number(priority) || 0
self._debug('select %s-%s (priority %s)', start, end, priority)
self._selections.push({
from: start,
to: end,
offset: 0,
priority: priority,
notify: notify || noop
})
self._selections.sort(function (a, b) {
return b.priority - a.priority
})
self._updateSelections()
}
Torrent.prototype.deselect = function (start, end, priority) {
var self = this
if (self.destroyed) throw new Error('torrent is destroyed')
priority = Number(priority) || 0
self._debug('deselect %s-%s (priority %s)', start, end, priority)
for (var i = 0; i < self._selections.length; ++i) {
var s = self._selections[i]
if (s.from === start && s.to === end && s.priority === priority) {
self._selections.splice(i--, 1)
break
}
}
self._updateSelections()
}
Torrent.prototype.critical = function (start, end) {
var self = this
if (self.destroyed) throw new Error('torrent is destroyed')
self._debug('critical %s-%s', start, end)
for (var i = start; i <= end; ++i) {
self._critical[i] = true
}
self._updateSelections()
}
Torrent.prototype._onWire = function (wire, addr) {
var self = this
self._debug('got wire %s (%s)', wire._debugId, addr || 'Unknown')
wire.on('download', function (downloaded) {
if (self.destroyed) return
self.received += downloaded
self._downloadSpeed(downloaded)
self.client._downloadSpeed(downloaded)
self.emit('download', downloaded)
self.client.emit('download', downloaded)
})
wire.on('upload', function (uploaded) {
if (self.destroyed) return
self.uploaded += uploaded
self._uploadSpeed(uploaded)
self.client._uploadSpeed(uploaded)
self.emit('upload', uploaded)
self.client.emit('upload', uploaded)
})
self.wires.push(wire)
if (addr) {
// Sometimes RTCPeerConnection.getStats() doesn't return an ip:port for peers
var parts = addrToIPPort(addr)
wire.remoteAddress = parts[0]
wire.remotePort = parts[1]
}
// When peer sends PORT message, add that DHT node to routing table
if (self.client.dht && self.client.dht.listening) {
wire.on('port', function (port) {
if (self.destroyed || self.client.dht.destroyed) {
return
}
if (!wire.remoteAddress) {
return self._debug('ignoring PORT from peer with no address')
}
if (port === 0 || port > 65536) {
return self._debug('ignoring invalid PORT from peer')
}
self._debug('port: %s (from %s)', port, addr)
self.client.dht.addNode({ host: wire.remoteAddress, port: port })
})
}
wire.on('timeout', function () {
self._debug('wire timeout (%s)', addr)
// TODO: this might be destroying wires too eagerly
wire.destroy()
})
// Timeout for piece requests to this peer
wire.setTimeout(PIECE_TIMEOUT, true)
// Send KEEP-ALIVE (every 60s) so peers will not disconnect the wire
wire.setKeepAlive(true)
// use ut_metadata extension
wire.use(utMetadata(self.metadata))
wire.ut_metadata.on('warning', function (err) {
self._debug('ut_metadata warning: %s', err.message)
})
if (!self.metadata) {
wire.ut_metadata.on('metadata', function (metadata) {
self._debug('got metadata via ut_metadata')
self._onMetadata(metadata)
})
wire.ut_metadata.fetch()
}
// use ut_pex extension if the torrent is not flagged as private
if (typeof utPex === 'function' && !self.private) {
wire.use(utPex())
wire.ut_pex.on('peer', function (peer) {
// Only add potential new peers when we're not seeding
if (self.done) return
self._debug('ut_pex: got peer: %s (from %s)', peer, addr)
self.addPeer(peer)
})
wire.ut_pex.on('dropped', function (peer) {
// the remote peer believes a given peer has been dropped from the torrent swarm.
// if we're not currently connected to it, then remove it from the queue.
var peerObj = self._peers[peer]
if (peerObj && !peerObj.connected) {
self._debug('ut_pex: dropped peer: %s (from %s)', peer, addr)
self.removePeer(peer)
}
})
wire.once('close', function () {
// Stop sending updates to remote peer
wire.ut_pex.reset()
})
}
// Hook to allow user-defined `bittorrent-protocol` extensions
// More info: https://github.com/feross/bittorrent-protocol#extension-api
self.emit('wire', wire, addr)
if (self.metadata) {
process.nextTick(function () {
// This allows wire.handshake() to be called (by Peer.onHandshake) before any
// messages get sent on the wire
self._onWireWithMetadata(wire)
})
}
}
Torrent.prototype._onWireWithMetadata = function (wire) {
var self = this
var timeoutId = null
function onChokeTimeout () {
if (self.destroyed || wire.destroyed) return
if (self._numQueued > 2 * (self._numConns - self.numPeers) &&
wire.amInterested) {
wire.destroy()
} else {
timeoutId = setTimeout(onChokeTimeout, CHOKE_TIMEOUT)
if (timeoutId.unref) timeoutId.unref()
}
}
var i = 0
function updateSeedStatus () {
if (wire.peerPieces.length !== self.pieces.length) return
for (; i < self.pieces.length; ++i) {
if (!wire.peerPieces.get(i)) return
}
wire.isSeeder = true
wire.choke() // always choke seeders
}
wire.on('bitfield', function () {
updateSeedStatus()
self._update()
})
wire.on('have', function () {
updateSeedStatus()
self._update()
})
wire.once('interested', function () {
wire.unchoke()
})
wire.once('close', function () {
clearTimeout(timeoutId)
})
wire.on('choke', function () {
clearTimeout(timeoutId)
timeoutId = setTimeout(onChokeTimeout, CHOKE_TIMEOUT)
if (timeoutId.unref) timeoutId.unref()
})
wire.on('unchoke', function () {
clearTimeout(timeoutId)
self._update()
})
wire.on('request', function (index, offset, length, cb) {
if (length > MAX_BLOCK_LENGTH) {
// Per spec, disconnect from peers that request >128KB
return wire.destroy()
}
if (self.pieces[index]) return
self.store.get(index, { offset: offset, length: length }, cb)
})
wire.bitfield(self.bitfield) // always send bitfield (required)
wire.interested() // always start out interested
// Send PORT message to peers that support DHT
if (wire.peerExtensions.dht && self.client.dht && self.client.dht.listening) {
wire.port(self.client.dht.address().port)
}
timeoutId = setTimeout(onChokeTimeout, CHOKE_TIMEOUT)
if (timeoutId.unref) timeoutId.unref()
wire.isSeeder = false
updateSeedStatus()
}
/**
* Called on selection changes.
*/
Torrent.prototype._updateSelections = function () {
var self = this
if (!self.ready || self.destroyed) return
process.nextTick(function () {
self._gcSelections()
})
self._updateInterest()
self._update()
}
/**
* Garbage collect selections with respect to the store's current state.
*/
Torrent.prototype._gcSelections = function () {
var self = this
for (var i = 0; i < self._selections.length; i++) {
var s = self._selections[i]
var oldOffset = s.offset
// check for newly downloaded pieces in selection
while (self.bitfield.get(s.from + s.offset) && s.from + s.offset < s.to) {
s.offset++
}
if (oldOffset !== s.offset) s.notify()
if (s.to !== s.from + s.offset) continue
if (!self.bitfield.get(s.from + s.offset)) continue
// remove fully downloaded selection
self._selections.splice(i--, 1) // decrement i to offset splice
s.notify() // TODO: this may notify twice in a row. is this a problem?
self._updateInterest()
}
if (!self._selections.length) self.emit('idle')
}
/**
* Update interested status for all peers.
*/
Torrent.prototype._updateInterest = function () {
var self = this
var prev = self._amInterested
self._amInterested = !!self._selections.length
self.wires.forEach(function (wire) {
// TODO: only call wire.interested if the wire has at least one piece we need
if (self._amInterested) wire.interested()
else wire.uninterested()
})
if (prev === self._amInterested) return
if (self._amInterested) self.emit('interested')
else self.emit('uninterested')
}
/**
* Heartbeat to update all peers and their requests.
*/
Torrent.prototype._update = function () {
var self = this
if (self.destroyed) return
// update wires in random order for better request distribution
var ite = randomIterate(self.wires)
var wire
while ((wire = ite())) {
self._updateWire(wire)
}
}
/**
* Attempts to update a peer's requests
*/
Torrent.prototype._updateWire = function (wire) {
var self = this
if (wire.peerChoking) return
if (!wire.downloaded) return validateWire()
var minOutstandingRequests = getBlockPipelineLength(wire, PIPELINE_MIN_DURATION)
if (wire.requests.length >= minOutstandingRequests) return
var maxOutstandingRequests = getBlockPipelineLength(wire, PIPELINE_MAX_DURATION)
trySelectWire(false) || trySelectWire(true)
function genPieceFilterFunc (start, end, tried, rank) {
return function (i) {
return i >= start && i <= end && !(i in tried) && wire.peerPieces.get(i) && (!rank || rank(i))
}
}
// TODO: Do we need both validateWire and trySelectWire?
function validateWire () {
if (wire.requests.length) return
var i = self._selections.length
while (i--) {
var next = self._selections[i]
var piece
if (self.strategy === 'rarest') {
var start = next.from + next.offset
var end = next.to
var len = end - start + 1
var tried = {}
var tries = 0
var filter = genPieceFilterFunc(start, end, tried)
while (tries < len) {
piece = self._rarityMap.getRarestPiece(filter)
if (piece < 0) break
if (self._request(wire, piece, false)) return
tried[piece] = true
tries += 1
}
} else {
for (piece = next.to; piece >= next.from + next.offset; --piece) {
if (!wire.peerPieces.get(piece)) continue
if (self._request(wire, piece, false)) return
}
}
}
// TODO: wire failed to validate as useful; should we close it?
// probably not, since 'have' and 'bitfield' messages might be coming
}
function speedRanker () {
var speed = wire.downloadSpeed() || 1
if (speed > SPEED_THRESHOLD) return function () { return true }
var secs = Math.max(1, wire.requests.length) * Piece.BLOCK_LENGTH / speed
var tries = 10
var ptr = 0
return function (index) {
if (!tries || self.bitfield.get(index)) return true
var missing = self.pieces[index].missing
for (; ptr < self.wires.length; ptr++) {
var otherWire = self.wires[ptr]
var otherSpeed = otherWire.downloadSpeed()
if (otherSpeed < SPEED_THRESHOLD) continue
if (otherSpeed <= speed) continue
if (!otherWire.peerPieces.get(index)) continue
if ((missing -= otherSpeed * secs) > 0) continue
tries--
return false
}
return true
}
}
function shufflePriority (i) {
var last = i
for (var j = i; j < self._selections.length && self._selections[j].priority; j++) {
last = j
}
var tmp = self._selections[i]
self._selections[i] = self._selections[last]
self._selections[last] = tmp
}
function trySelectWire (hotswap) {
if (wire.requests.length >= maxOutstandingRequests) return true
var rank = speedRanker()
for (var i = 0; i < self._selections.length; i++) {
var next = self._selections[i]
var piece
if (self.strategy === 'rarest') {
var start = next.from + next.offset
var end = next.to
var len = end - start + 1
var tried = {}
var tries = 0
var filter = genPieceFilterFunc(start, end, tried, rank)
while (tries < len) {
piece = self._rarityMap.getRarestPiece(filter)
if (piece < 0) break
// request all non-reserved blocks in this piece
while (self._request(wire, piece, self._critical[piece] || hotswap)) {}
if (wire.requests.length < maxOutstandingRequests) {
tried[piece] = true
tries++
continue
}
if (next.priority) shufflePriority(i)
return true
}
} else {
for (piece = next.from + next.offset; piece <= next.to; piece++) {
if (!wire.peerPieces.get(piece) || !rank(piece)) continue
// request all non-reserved blocks in piece
while (self._request(wire, piece, self._critical[piece] || hotswap)) {}
if (wire.requests.length < maxOutstandingRequests) continue
if (next.priority) shufflePriority(i)
return true
}
}
}
return false
}
}
/**
* Called periodically to update the choked status of all peers, handling optimistic
* unchoking as described in BEP3.
*/
Torrent.prototype._rechoke = function () {
var self = this
if (!self.ready) return
if (self._rechokeOptimisticTime > 0) self._rechokeOptimisticTime -= 1
else self._rechokeOptimisticWire = null
var peers = []
self.wires.forEach(function (wire) {
if (!wire.isSeeder && wire !== self._rechokeOptimisticWire) {
peers.push({
wire: wire,
downloadSpeed: wire.downloadSpeed(),
uploadSpeed: wire.uploadSpeed(),
salt: Math.random(),
isChoked: true
})
}
})
peers.sort(rechokeSort)
var unchokeInterested = 0
var i = 0
for (; i < peers.length && unchokeInterested < self._rechokeNumSlots; ++i) {
peers[i].isChoked = false
if (peers[i].wire.peerInterested) unchokeInterested += 1
}
// Optimistically unchoke a peer
if (!self._rechokeOptimisticWire && i < peers.length && self._rechokeNumSlots) {
var candidates = peers.slice(i).filter(function (peer) { return peer.wire.peerInterested })
var optimistic = candidates[randomInt(candidates.length)]
if (optimistic) {
optimistic.isChoked = false
self._rechokeOptimisticWire = optimistic.wire
self._rechokeOptimisticTime = RECHOKE_OPTIMISTIC_DURATION
}
}
// Unchoke best peers
peers.forEach(function (peer) {
if (peer.wire.amChoking !== peer.isChoked) {
if (peer.isChoked) peer.wire.choke()
else peer.wire.unchoke()
}
})
function rechokeSort (peerA, peerB) {
// Prefer higher download speed
if (peerA.downloadSpeed !== peerB.downloadSpeed) {
return peerB.downloadSpeed - peerA.downloadSpeed
}
// Prefer higher upload speed
if (peerA.uploadSpeed !== peerB.uploadSpeed) {
return peerB.uploadSpeed - peerA.uploadSpeed
}
// Prefer unchoked
if (peerA.wire.amChoking !== peerB.wire.amChoking) {
return peerA.wire.amChoking ? 1 : -1
}
// Random order
return peerA.salt - peerB.salt
}
}
/**
* Attempts to cancel a slow block request from another wire such that the
* given wire may effectively swap out the request for one of its own.
*/
Torrent.prototype._hotswap = function (wire, index) {
var self = this
var speed = wire.downloadSpeed()
if (speed < Piece.BLOCK_LENGTH) return false
if (!self._reservations[index]) return false
var r = self._reservations[index]
if (!r) {
return false
}
var minSpeed = Infinity
var minWire
var i
for (i = 0; i < r.length; i++) {
var otherWire = r[i]
if (!otherWire || otherWire === wire) continue
var otherSpeed = otherWire.downloadSpeed()
if (otherSpeed >= SPEED_THRESHOLD) continue
if (2 * otherSpeed > speed || otherSpeed > minSpeed) continue
minWire = otherWire
minSpeed = otherSpeed
}
if (!minWire) return false
for (i = 0; i < r.length; i++) {
if (r[i] === minWire) r[i] = null
}
for (i = 0; i < minWire.requests.length; i++) {
var req = minWire.requests[i]
if (req.piece !== index) continue
self.pieces[index].cancel((req.offset / Piece.BLOCK_LENGTH) | 0)
}
self.emit('hotswap', minWire, wire, index)
return true
}
/**
* Attempts to request a block from the given wire.
*/
Torrent.prototype._request = function (wire, index, hotswap) {
var self = this
var numRequests = wire.requests.length
var isWebSeed = wire.type === 'webSeed'
if (self.bitfield.get(index)) return false
var maxOutstandingRequests = isWebSeed
? Math.min(
getPiecePipelineLength(wire, PIPELINE_MAX_DURATION, self.pieceLength),
self.maxWebConns
)
: getBlockPipelineLength(wire, PIPELINE_MAX_DURATION)
if (numRequests >= maxOutstandingRequests) return false
// var endGame = (wire.requests.length === 0 && self.store.numMissing < 30)
var piece = self.pieces[index]
var reservation = isWebSeed ? piece.reserveRemaining() : piece.reserve()
if (reservation === -1 && hotswap && self._hotswap(wire, index)) {
reservation = isWebSeed ? piece.reserveRemaining() : piece.reserve()
}
if (reservation === -1) return false
var r = self._reservations[index]
if (!r) r = self._reservations[index] = []
var i = r.indexOf(null)
if (i === -1) i = r.length
r[i] = wire
var chunkOffset = piece.chunkOffset(reservation)
var chunkLength = isWebSeed ? piece.chunkLengthRemaining(reservation) : piece.chunkLength(reservation)
wire.request(index, chunkOffset, chunkLength, function onChunk (err, chunk) {
// TODO: what is this for?
if (!self.ready) return self.once('ready', function () { onChunk(err, chunk) })
if (r[i] === wire) r[i] = null
if (piece !== self.pieces[index]) return onUpdateTick()
if (err) {
self._debug(
'error getting piece %s (offset: %s length: %s) from %s: %s',
index, chunkOffset, chunkLength, wire.remoteAddress + ':' + wire.remotePort,
err.message
)
isWebSeed ? piece.cancelRemaining(reservation) : piece.cancel(reservation)
onUpdateTick()
return
}
self._debug(
'got piece %s (offset: %s length: %s) from %s',
index, chunkOffset, chunkLength, wire.remoteAddress + ':' + wire.remotePort
)
if (!piece.set(reservation, chunk, wire)) return onUpdateTick()
var buf = piece.flush()
// TODO: might need to set self.pieces[index] = null here since sha1 is async
sha1(buf, function (hash) {
if (hash === self._hashes[index]) {
if (!self.pieces[index]) return
self._debug('piece verified %s', index)
self.pieces[index] = null
self._reservations[index] = null
self.bitfield.set(index, true)
self.store.put(index, buf)
self.wires.forEach(function (wire) {
wire.have(index)
})
self._checkDone()
} else {
self.pieces[index] = new Piece(piece.length)
self.emit('warning', new Error('Piece ' + index + ' failed verification'))
}
onUpdateTick()
})
})
function onUpdateTick () {
process.nextTick(function () { self._update() })
}
return true
}
Torrent.prototype._checkDone = function () {
var self = this
if (self.destroyed) return
// are any new files done?
self.files.forEach(function (file) {
if (file.done) return
for (var i = file._startPiece; i <= file._endPiece; ++i) {
if (!self.bitfield.get(i)) return
}
file.done = true
file.emit('done')
self._debug('file done: ' + file.name)
})
// is the torrent done? (if all current selections are satisfied, or there are
// no selections, then torrent is done)
var done = true
for (var i = 0; i < self._selections.length; i++) {
var selection = self._selections[i]
for (var piece = selection.from; piece <= selection.to; piece++) {
if (!self.bitfield.get(piece)) {
done = false
break
}
}
if (!done) break
}
if (!self.done && done) {
self.done = true
self._debug('torrent done: ' + self.infoHash)
if (self.discovery.tracker) {
self.discovery.tracker.complete()
}
self.emit('done')
}
self._gcSelections()
}
Torrent.prototype.load = function (streams, cb) {
var self = this
if (self.destroyed) throw new Error('torrent is destroyed')
if (!self.ready) return self.once('ready', function () { self.load(streams, cb) })
if (!Array.isArray(streams)) streams = [ streams ]
if (!cb) cb = noop
var readable = new MultiStream(streams)
var writable = new ChunkStoreWriteStream(self.store, self.pieceLength)
pump(readable, writable, function (err) {
if (err) return cb(err)
self.pieces.forEach(function (piece, index) {
self.pieces[index] = null
self._reservations[index] = null
self.bitfield.set(index, true)
})
self._checkDone()
cb(null)
})
}
Torrent.prototype.createServer = function (opts) {
if (typeof Server !== 'function') throw new Error('node.js-only method')
if (this.destroyed) throw new Error('torrent is destroyed')
var server = new Server(this, opts)
this._servers.push(server)
return server
}
Torrent.prototype.pause = function () {
if (this.destroyed) return
this._debug('pause')
this.paused = true
}
Torrent.prototype.resume = function () {
if (this.destroyed) return
this._debug('resume')
this.paused = false
this._drain()
}
Torrent.prototype._debug = function () {
var args = [].slice.call(arguments)
args[0] = '[' + this._debugId + '] ' + args[0]
debug.apply(null, args)
}
/**
* Pop a peer off the FIFO queue and connect to it. When _drain() gets called,
* the queue will usually have only one peer in it, except when there are too
* many peers (over `this.maxConns`) in which case they will just sit in the
* queue until another connection closes.
*/
Torrent.prototype._drain = function () {
var self = this
this._debug('_drain numConns %s maxConns %s', self._numConns, self.client.maxConns)
if (typeof net.connect !== 'function' || self.destroyed || self.paused ||
self._numConns >= self.client.maxConns) {
return
}
this._debug('drain (%s queued, %s/%s peers)', self._numQueued, self.numPeers, self.client.maxConns)
var peer = self._queue.shift()
if (!peer) return // queue could be empty
this._debug('tcp connect attempt to %s', peer.addr)
var parts = addrToIPPort(peer.addr)
var opts = {
host: parts[0],
port: parts[1]
}
var conn = peer.conn = net.connect(opts)
conn.once('connect', function () { peer.onConnect() })
conn.once('error', function (err) { peer.destroy(err) })
peer.startConnectTimeout()
// When connection closes, attempt reconnect after timeout (with exponential backoff)
conn.on('close', function () {
if (self.destroyed) return
// TODO: If torrent is done, do not try to reconnect after a timeout
if (peer.retries >= RECONNECT_WAIT.length) {
self._debug(
'conn %s closed: will not re-add (max %s attempts)',
peer.addr, RECONNECT_WAIT.length
)
return
}
var ms = RECONNECT_WAIT[peer.retries]
self._debug(
'conn %s closed: will re-add to queue in %sms (attempt %s)',
peer.addr, ms, peer.retries + 1
)
var reconnectTimeout = setTimeout(function reconnectTimeout () {
var newPeer = self._addPeer(peer.addr)
if (newPeer) newPeer.retries = peer.retries + 1
}, ms)
if (reconnectTimeout.unref) reconnectTimeout.unref()
})
}
/**
* Returns `true` if string is valid IPv4/6 address.
* @param {string} addr
* @return {boolean}
*/
Torrent.prototype._validAddr = function (addr) {
var parts
try {
parts = addrToIPPort(addr)
} catch (e) {
return false
}
var host = parts[0]
var port = parts[1]
return port > 0 && port < 65535 &&
!(host === '127.0.0.1' && port === this.client.torrentPort)
}
function getBlockPipelineLength (wire, duration) {
return 2 + Math.ceil(duration * wire.downloadSpeed() / Piece.BLOCK_LENGTH)
}
function getPiecePipelineLength (wire, duration, pieceLength) {
return 1 + Math.ceil(duration * wire.downloadSpeed() / pieceLength)
}
/**
* Returns a random integer in [0,high)
*/
function randomInt (high) {
return Math.random() * high | 0
}
function noop () {}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../package.json":191,"./file":135,"./peer":136,"./rarity-map":137,"./server":20,"_process":29,"addr-to-ip-port":140,"bitfield":141,"chunk-store-stream/write":149,"debug":150,"events":25,"fs":19,"fs-chunk-store":158,"immediate-chunk-store":157,"inherits":63,"multistream":74,"net":20,"os":20,"parse-torrent":75,"path":28,"pump":93,"random-iterate":159,"run-parallel":164,"run-parallel-limit":163,"simple-get":167,"simple-sha1":170,"speedometer":172,"torrent-discovery":180,"torrent-piece":181,"uniq":182,"ut_metadata":184,"ut_pex":20,"xtend":188,"xtend/mutable":189}],139:[function(require,module,exports){
module.exports = WebConn
var BitField = require('bitfield')
var Buffer = require('safe-buffer').Buffer
var debug = require('debug')('webtorrent:webconn')
var get = require('simple-get')
var inherits = require('inherits')
var sha1 = require('simple-sha1')
var Wire = require('bittorrent-protocol')
var VERSION = require('../package.json').version
inherits(WebConn, Wire)
/**
* Converts requests for torrent blocks into http range requests.
* @param {string} url web seed url
* @param {Object} torrent
*/
function WebConn (url, torrent) {
Wire.call(this)
this.url = url
this.webPeerId = sha1.sync(url)
this._torrent = torrent
this._init()
}
WebConn.prototype._init = function () {
var self = this
self.setKeepAlive(true)
self.once('handshake', function (infoHash, peerId) {
if (self.destroyed) return
self.handshake(infoHash, self.webPeerId)
var numPieces = self._torrent.pieces.length
var bitfield = new BitField(numPieces)
for (var i = 0; i <= numPieces; i++) {
bitfield.set(i, true)
}
self.bitfield(bitfield)
})
self.once('interested', function () {
debug('interested')
self.unchoke()
})
self.on('uninterested', function () { debug('uninterested') })
self.on('choke', function () { debug('choke') })
self.on('unchoke', function () { debug('unchoke') })
self.on('bitfield', function () { debug('bitfield') })
self.on('request', function (pieceIndex, offset, length, callback) {
debug('request pieceIndex=%d offset=%d length=%d', pieceIndex, offset, length)
self.httpRequest(pieceIndex, offset, length, callback)
})
}
WebConn.prototype.httpRequest = function (pieceIndex, offset, length, cb) {
var self = this
var pieceOffset = pieceIndex * self._torrent.pieceLength
var rangeStart = pieceOffset + offset /* offset within whole torrent */
var rangeEnd = rangeStart + length - 1
// Web seed URL format:
// For single-file torrents, make HTTP range requests directly to the web seed URL
// For multi-file torrents, add the torrent folder and file name to the URL
var files = self._torrent.files
var requests
if (files.length <= 1) {
requests = [{
url: self.url,
start: rangeStart,
end: rangeEnd
}]
} else {
var requestedFiles = files.filter(function (file) {
return file.offset <= rangeEnd && (file.offset + file.length) > rangeStart
})
if (requestedFiles.length < 1) {
return cb(new Error('Could not find file corresponnding to web seed range request'))
}
requests = requestedFiles.map(function (requestedFile) {
var fileEnd = requestedFile.offset + requestedFile.length - 1
var url = self.url +
(self.url[self.url.length - 1] === '/' ? '' : '/') +
requestedFile.path
return {
url: url,
fileOffsetInRange: Math.max(requestedFile.offset - rangeStart, 0),
start: Math.max(rangeStart - requestedFile.offset, 0),
end: Math.min(fileEnd, rangeEnd - requestedFile.offset)
}
})
}
// Now make all the HTTP requests we need in order to load this piece
// Usually that's one requests, but sometimes it will be multiple
// Send requests in parallel and wait for them all to come back
var numRequestsSucceeded = 0
var hasError = false
var ret
if (requests.length > 1) {
ret = Buffer.alloc(length)
}
requests.forEach(function (request) {
var url = request.url
var start = request.start
var end = request.end
debug(
'Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d',
url, pieceIndex, offset, length, start, end
)
var opts = {
url: url,
method: 'GET',
headers: {
'user-agent': 'WebTorrent/' + VERSION + ' (https://webtorrent.io)',
range: 'bytes=' + start + '-' + end
}
}
get.concat(opts, function (err, res, data) {
if (hasError) return
if (err) {
hasError = true
return cb(err)
}
if (res.statusCode < 200 || res.statusCode >= 300) {
hasError = true
return cb(new Error('Unexpected HTTP status code ' + res.statusCode))
}
debug('Got data of length %d', data.length)
if (requests.length === 1) {
// Common case: fetch piece in a single HTTP request, return directly
cb(null, data)
} else {
// Rare case: reconstruct multiple HTTP requests across 2+ files into one
// piece buffer
data.copy(ret, request.fileOffsetInRange)
if (++numRequestsSucceeded === requests.length) {
cb(null, ret)
}
}
})
})
}
WebConn.prototype.destroy = function () {
Wire.prototype.destroy.call(this)
this._torrent = null
}
},{"../package.json":191,"bitfield":141,"bittorrent-protocol":142,"debug":150,"inherits":63,"safe-buffer":165,"simple-get":167,"simple-sha1":170}],140:[function(require,module,exports){
arguments[4][126][0].apply(exports,arguments)
},{"dup":126}],141:[function(require,module,exports){
(function (Buffer){
var Container = typeof Buffer !== "undefined" ? Buffer //in node, use buffers
: typeof Int8Array !== "undefined" ? Int8Array //in newer browsers, use webgl int8arrays
: function(l){ var a = new Array(l); for(var i = 0; i < l; i++) a[i]=0; }; //else, do something similar
function BitField(data, opts){
if(!(this instanceof BitField)) {
return new BitField(data, opts);
}
if(arguments.length === 0){
data = 0;
}
this.grow = opts && (isFinite(opts.grow) && getByteSize(opts.grow) || opts.grow) || 0;
if(typeof data === "number" || data === undefined){
data = new Container(getByteSize(data));
if(data.fill && !data._isBuffer) data.fill(0); // clear node buffers of garbage
}
this.buffer = data;
}
function getByteSize(num){
var out = num >> 3;
if(num % 8 !== 0) out++;
return out;
}
BitField.prototype.get = function(i){
var j = i >> 3;
return (j < this.buffer.length) &&
!!(this.buffer[j] & (128 >> (i % 8)));
};
BitField.prototype.set = function(i, b){
var j = i >> 3;
if (b || arguments.length === 1){
if (this.buffer.length < j + 1) this._grow(Math.max(j + 1, Math.min(2 * this.buffer.length, this.grow)));
// Set
this.buffer[j] |= 128 >> (i % 8);
} else if (j < this.buffer.length) {
/// Clear
this.buffer[j] &= ~(128 >> (i % 8));
}
};
BitField.prototype._grow = function(length) {
if (this.buffer.length < length && length <= this.grow) {
var newBuffer = new Container(length);
if (newBuffer.fill) newBuffer.fill(0);
if (this.buffer.copy) this.buffer.copy(newBuffer, 0);
else {
for(var i = 0; i < this.buffer.length; i++) {
newBuffer[i] = this.buffer[i];
}
}
this.buffer = newBuffer;
}
};
if(typeof module !== "undefined") module.exports = BitField;
}).call(this,require("buffer").Buffer)
},{"buffer":21}],142:[function(require,module,exports){
module.exports = Wire
var bencode = require('bencode')
var BitField = require('bitfield')
var Buffer = require('safe-buffer').Buffer
var debug = require('debug')('bittorrent-protocol')
var extend = require('xtend')
var inherits = require('inherits')
var randombytes = require('randombytes')
var speedometer = require('speedometer')
var stream = require('readable-stream')
var BITFIELD_GROW = 400000
var KEEP_ALIVE_TIMEOUT = 55000
var MESSAGE_PROTOCOL = Buffer.from('\u0013BitTorrent protocol')
var MESSAGE_KEEP_ALIVE = Buffer.from([0x00, 0x00, 0x00, 0x00])
var MESSAGE_CHOKE = Buffer.from([0x00, 0x00, 0x00, 0x01, 0x00])
var MESSAGE_UNCHOKE = Buffer.from([0x00, 0x00, 0x00, 0x01, 0x01])
var MESSAGE_INTERESTED = Buffer.from([0x00, 0x00, 0x00, 0x01, 0x02])
var MESSAGE_UNINTERESTED = Buffer.from([0x00, 0x00, 0x00, 0x01, 0x03])
var MESSAGE_RESERVED = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
var MESSAGE_PORT = [0x00, 0x00, 0x00, 0x03, 0x09, 0x00, 0x00]
function Request (piece, offset, length, callback) {
this.piece = piece
this.offset = offset
this.length = length
this.callback = callback
}
inherits(Wire, stream.Duplex)
function Wire () {
if (!(this instanceof Wire)) return new Wire()
stream.Duplex.call(this)
this._debugId = randombytes(4).toString('hex')
this._debug('new wire')
this.peerId = null // remote peer id (hex string)
this.peerIdBuffer = null // remote peer id (buffer)
this.type = null // connection type ('webrtc', 'tcpIncoming', 'tcpOutgoing', 'webSeed')
this.amChoking = true // are we choking the peer?
this.amInterested = false // are we interested in the peer?
this.peerChoking = true // is the peer choking us?
this.peerInterested = false // is the peer interested in us?
// The largest torrent that I know of (the Geocities archive) is ~641 GB and has
// ~41,000 pieces. Therefore, cap bitfield to 10x larger (400,000 bits) to support all
// possible torrents but prevent malicious peers from growing bitfield to fill memory.
this.peerPieces = new BitField(0, { grow: BITFIELD_GROW })
this.peerExtensions = {}
this.requests = [] // outgoing
this.peerRequests = [] // incoming
this.extendedMapping = {} // number -> string, ex: 1 -> 'ut_metadata'
this.peerExtendedMapping = {} // string -> number, ex: 9 -> 'ut_metadata'
// The extended handshake to send, minus the "m" field, which gets automatically
// filled from `this.extendedMapping`
this.extendedHandshake = {}
this.peerExtendedHandshake = {} // remote peer's extended handshake
this._ext = {} // string -> function, ex 'ut_metadata' -> ut_metadata()
this._nextExt = 1
this.uploaded = 0
this.downloaded = 0
this.uploadSpeed = speedometer()
this.downloadSpeed = speedometer()
this._keepAliveInterval = null
this._timeout = null
this._timeoutMs = 0
this.destroyed = false // was the wire ended by calling `destroy`?
this._finished = false
this._parserSize = 0 // number of needed bytes to parse next message from remote peer
this._parser = null // function to call once `this._parserSize` bytes are available
this._buffer = [] // incomplete message data
this._bufferSize = 0 // cached total length of buffers in `this._buffer`
this.on('finish', this._onFinish)
this._parseHandshake()
}
/**
* Set whether to send a "keep-alive" ping (sent every 55s)
* @param {boolean} enable
*/
Wire.prototype.setKeepAlive = function (enable) {
var self = this
self._debug('setKeepAlive %s', enable)
clearInterval(self._keepAliveInterval)
if (enable === false) return
self._keepAliveInterval = setInterval(function () {
self.keepAlive()
}, KEEP_ALIVE_TIMEOUT)
}
/**
* Set the amount of time to wait before considering a request to be "timed out"
* @param {number} ms
* @param {boolean=} unref (should the timer be unref'd? default: false)
*/
Wire.prototype.setTimeout = function (ms, unref) {
this._debug('setTimeout ms=%d unref=%s', ms, unref)
this._clearTimeout()
this._timeoutMs = ms
this._timeoutUnref = !!unref
this._updateTimeout()
}
Wire.prototype.destroy = function () {
if (this.destroyed) return
this.destroyed = true
this._debug('destroy')
this.emit('close')
this.end()
}
Wire.prototype.end = function () {
this._debug('end')
this._onUninterested()
this._onChoke()
stream.Duplex.prototype.end.apply(this, arguments)
}
/**
* Use the specified protocol extension.
* @param {function} Extension
*/
Wire.prototype.use = function (Extension) {
var name = Extension.prototype.name
if (!name) {
throw new Error('Extension class requires a "name" property on the prototype')
}
this._debug('use extension.name=%s', name)
var ext = this._nextExt
var handler = new Extension(this)
function noop () {}
if (typeof handler.onHandshake !== 'function') {
handler.onHandshake = noop
}
if (typeof handler.onExtendedHandshake !== 'function') {
handler.onExtendedHandshake = noop
}
if (typeof handler.onMessage !== 'function') {
handler.onMessage = noop
}
this.extendedMapping[ext] = name
this._ext[name] = handler
this[name] = handler
this._nextExt += 1
}
//
// OUTGOING MESSAGES
//
/**
* Message "keep-alive": <len=0000>
*/
Wire.prototype.keepAlive = function () {
this._debug('keep-alive')
this._push(MESSAGE_KEEP_ALIVE)
}
/**
* Message: "handshake" <pstrlen><pstr><reserved><info_hash><peer_id>
* @param {Buffer|string} infoHash (as Buffer or *hex* string)
* @param {Buffer|string} peerId
* @param {Object} extensions
*/
Wire.prototype.handshake = function (infoHash, peerId, extensions) {
var infoHashBuffer, peerIdBuffer
if (typeof infoHash === 'string') {
infoHashBuffer = Buffer.from(infoHash, 'hex')
} else {
infoHashBuffer = infoHash
infoHash = infoHashBuffer.toString('hex')
}
if (typeof peerId === 'string') {
peerIdBuffer = Buffer.from(peerId, 'hex')
} else {
peerIdBuffer = peerId
peerId = peerIdBuffer.toString('hex')
}
if (infoHashBuffer.length !== 20 || peerIdBuffer.length !== 20) {
throw new Error('infoHash and peerId MUST have length 20')
}
this._debug('handshake i=%s p=%s exts=%o', infoHash, peerId, extensions)
var reserved = Buffer.from(MESSAGE_RESERVED)
// enable extended message
reserved[5] |= 0x10
if (extensions && extensions.dht) reserved[7] |= 1
this._push(Buffer.concat([MESSAGE_PROTOCOL, reserved, infoHashBuffer, peerIdBuffer]))
this._handshakeSent = true
if (this.peerExtensions.extended && !this._extendedHandshakeSent) {
// Peer's handshake indicated support already
// (incoming connection)
this._sendExtendedHandshake()
}
}
/* Peer supports BEP-0010, send extended handshake.
*
* This comes after the 'handshake' event to give the user a chance to populate
* `this.extendedHandshake` and `this.extendedMapping` before the extended handshake
* is sent to the remote peer.
*/
Wire.prototype._sendExtendedHandshake = function () {
// Create extended message object from registered extensions
var msg = extend(this.extendedHandshake)
msg.m = {}
for (var ext in this.extendedMapping) {
var name = this.extendedMapping[ext]
msg.m[name] = Number(ext)
}
// Send extended handshake
this.extended(0, bencode.encode(msg))
this._extendedHandshakeSent = true
}
/**
* Message "choke": <len=0001><id=0>
*/
Wire.prototype.choke = function () {
if (this.amChoking) return
this.amChoking = true
this._debug('choke')
this.peerRequests.splice(0, this.peerRequests.length)
this._push(MESSAGE_CHOKE)
}
/**
* Message "unchoke": <len=0001><id=1>
*/
Wire.prototype.unchoke = function () {
if (!this.amChoking) return
this.amChoking = false
this._debug('unchoke')
this._push(MESSAGE_UNCHOKE)
}
/**
* Message "interested": <len=0001><id=2>
*/
Wire.prototype.interested = function () {
if (this.amInterested) return
this.amInterested = true
this._debug('interested')
this._push(MESSAGE_INTERESTED)
}
/**
* Message "uninterested": <len=0001><id=3>
*/
Wire.prototype.uninterested = function () {
if (!this.amInterested) return
this.amInterested = false
this._debug('uninterested')
this._push(MESSAGE_UNINTERESTED)
}
/**
* Message "have": <len=0005><id=4><piece index>
* @param {number} index
*/
Wire.prototype.have = function (index) {
this._debug('have %d', index)
this._message(4, [index], null)
}
/**
* Message "bitfield": <len=0001+X><id=5><bitfield>
* @param {BitField|Buffer} bitfield
*/
Wire.prototype.bitfield = function (bitfield) {
this._debug('bitfield')
if (!Buffer.isBuffer(bitfield)) bitfield = bitfield.buffer
this._message(5, [], bitfield)
}
/**
* Message "request": <len=0013><id=6><index><begin><length>
* @param {number} index
* @param {number} offset
* @param {number} length
* @param {function} cb
*/
Wire.prototype.request = function (index, offset, length, cb) {
if (!cb) cb = function () {}
if (this._finished) return cb(new Error('wire is closed'))
if (this.peerChoking) return cb(new Error('peer is choking'))
this._debug('request index=%d offset=%d length=%d', index, offset, length)
this.requests.push(new Request(index, offset, length, cb))
this._updateTimeout()
this._message(6, [index, offset, length], null)
}
/**
* Message "piece": <len=0009+X><id=7><index><begin><block>
* @param {number} index
* @param {number} offset
* @param {Buffer} buffer
*/
Wire.prototype.piece = function (index, offset, buffer) {
this._debug('piece index=%d offset=%d', index, offset)
this.uploaded += buffer.length
this.uploadSpeed(buffer.length)
this.emit('upload', buffer.length)
this._message(7, [index, offset], buffer)
}
/**
* Message "cancel": <len=0013><id=8><index><begin><length>
* @param {number} index
* @param {number} offset
* @param {number} length
*/
Wire.prototype.cancel = function (index, offset, length) {
this._debug('cancel index=%d offset=%d length=%d', index, offset, length)
this._callback(
pull(this.requests, index, offset, length),
new Error('request was cancelled'),
null
)
this._message(8, [index, offset, length], null)
}
/**
* Message: "port" <len=0003><id=9><listen-port>
* @param {Number} port
*/
Wire.prototype.port = function (port) {
this._debug('port %d', port)
var message = Buffer.from(MESSAGE_PORT)
message.writeUInt16BE(port, 5)
this._push(message)
}
/**
* Message: "extended" <len=0005+X><id=20><ext-number><payload>
* @param {number|string} ext
* @param {Object} obj
*/
Wire.prototype.extended = function (ext, obj) {
this._debug('extended ext=%s', ext)
if (typeof ext === 'string' && this.peerExtendedMapping[ext]) {
ext = this.peerExtendedMapping[ext]
}
if (typeof ext === 'number') {
var extId = Buffer.from([ext])
var buf = Buffer.isBuffer(obj) ? obj : bencode.encode(obj)
this._message(20, [], Buffer.concat([extId, buf]))
} else {
throw new Error('Unrecognized extension: ' + ext)
}
}
/**
* Duplex stream method. Called whenever the remote peer stream wants data. No-op
* since we'll just push data whenever we get it.
*/
Wire.prototype._read = function () {}
/**
* Send a message to the remote peer.
*/
Wire.prototype._message = function (id, numbers, data) {
var dataLength = data ? data.length : 0
var buffer = Buffer.allocUnsafe(5 + 4 * numbers.length)
buffer.writeUInt32BE(buffer.length + dataLength - 4, 0)
buffer[4] = id
for (var i = 0; i < numbers.length; i++) {
buffer.writeUInt32BE(numbers[i], 5 + 4 * i)
}
this._push(buffer)
if (data) this._push(data)
}
Wire.prototype._push = function (data) {
if (this._finished) return
return this.push(data)
}
//
// INCOMING MESSAGES
//
Wire.prototype._onKeepAlive = function () {
this._debug('got keep-alive')
this.emit('keep-alive')
}
Wire.prototype._onHandshake = function (infoHashBuffer, peerIdBuffer, extensions) {
var infoHash = infoHashBuffer.toString('hex')
var peerId = peerIdBuffer.toString('hex')
this._debug('got handshake i=%s p=%s exts=%o', infoHash, peerId, extensions)
this.peerId = peerId
this.peerIdBuffer = peerIdBuffer
this.peerExtensions = extensions
this.emit('handshake', infoHash, peerId, extensions)
var name
for (name in this._ext) {
this._ext[name].onHandshake(infoHash, peerId, extensions)
}
if (extensions.extended && this._handshakeSent &&
!this._extendedHandshakeSent) {
// outgoing connection
this._sendExtendedHandshake()
}
}
Wire.prototype._onChoke = function () {
this.peerChoking = true
this._debug('got choke')
this.emit('choke')
while (this.requests.length) {
this._callback(this.requests.shift(), new Error('peer is choking'), null)
}
}
Wire.prototype._onUnchoke = function () {
this.peerChoking = false
this._debug('got unchoke')
this.emit('unchoke')
}
Wire.prototype._onInterested = function () {
this.peerInterested = true
this._debug('got interested')
this.emit('interested')
}
Wire.prototype._onUninterested = function () {
this.peerInterested = false
this._debug('got uninterested')
this.emit('uninterested')
}
Wire.prototype._onHave = function (index) {
if (this.peerPieces.get(index)) return
this._debug('got have %d', index)
this.peerPieces.set(index, true)
this.emit('have', index)
}
Wire.prototype._onBitField = function (buffer) {
this.peerPieces = new BitField(buffer)
this._debug('got bitfield')
this.emit('bitfield', this.peerPieces)
}
Wire.prototype._onRequest = function (index, offset, length) {
var self = this
if (self.amChoking) return
self._debug('got request index=%d offset=%d length=%d', index, offset, length)
var respond = function (err, buffer) {
if (request !== pull(self.peerRequests, index, offset, length)) return
if (err) return self._debug('error satisfying request index=%d offset=%d length=%d (%s)', index, offset, length, err.message)
self.piece(index, offset, buffer)
}
var request = new Request(index, offset, length, respond)
self.peerRequests.push(request)
self.emit('request', index, offset, length, respond)
}
Wire.prototype._onPiece = function (index, offset, buffer) {
this._debug('got piece index=%d offset=%d', index, offset)
this._callback(pull(this.requests, index, offset, buffer.length), null, buffer)
this.downloaded += buffer.length
this.downloadSpeed(buffer.length)
this.emit('download', buffer.length)
this.emit('piece', index, offset, buffer)
}
Wire.prototype._onCancel = function (index, offset, length) {
this._debug('got cancel index=%d offset=%d length=%d', index, offset, length)
pull(this.peerRequests, index, offset, length)
this.emit('cancel', index, offset, length)
}
Wire.prototype._onPort = function (port) {
this._debug('got port %d', port)
this.emit('port', port)
}
Wire.prototype._onExtended = function (ext, buf) {
if (ext === 0) {
var info
try {
info = bencode.decode(buf)
} catch (err) {
this._debug('ignoring invalid extended handshake: %s', err.message || err)
}
if (!info) return
this.peerExtendedHandshake = info
var name
if (typeof info.m === 'object') {
for (name in info.m) {
this.peerExtendedMapping[name] = Number(info.m[name].toString())
}
}
for (name in this._ext) {
if (this.peerExtendedMapping[name]) {
this._ext[name].onExtendedHandshake(this.peerExtendedHandshake)
}
}
this._debug('got extended handshake')
this.emit('extended', 'handshake', this.peerExtendedHandshake)
} else {
if (this.extendedMapping[ext]) {
ext = this.extendedMapping[ext] // friendly name for extension
if (this._ext[ext]) {
// there is an registered extension handler, so call it
this._ext[ext].onMessage(buf)
}
}
this._debug('got extended message ext=%s', ext)
this.emit('extended', ext, buf)
}
}
Wire.prototype._onTimeout = function () {
this._debug('request timed out')
this._callback(this.requests.shift(), new Error('request has timed out'), null)
this.emit('timeout')
}
/**
* Duplex stream method. Called whenever the remote peer has data for us. Data that the
* remote peer sends gets buffered (i.e. not actually processed) until the right number
* of bytes have arrived, determined by the last call to `this._parse(number, callback)`.
* Once enough bytes have arrived to process the message, the callback function
* (i.e. `this._parser`) gets called with the full buffer of data.
* @param {Buffer} data
* @param {string} encoding
* @param {function} cb
*/
Wire.prototype._write = function (data, encoding, cb) {
this._bufferSize += data.length
this._buffer.push(data)
while (this._bufferSize >= this._parserSize) {
var buffer = (this._buffer.length === 1)
? this._buffer[0]
: Buffer.concat(this._buffer)
this._bufferSize -= this._parserSize
this._buffer = this._bufferSize
? [buffer.slice(this._parserSize)]
: []
this._parser(buffer.slice(0, this._parserSize))
}
cb(null) // Signal that we're ready for more data
}
Wire.prototype._callback = function (request, err, buffer) {
if (!request) return
this._clearTimeout()
if (!this.peerChoking && !this._finished) this._updateTimeout()
request.callback(err, buffer)
}
Wire.prototype._clearTimeout = function () {
if (!this._timeout) return
clearTimeout(this._timeout)
this._timeout = null
}
Wire.prototype._updateTimeout = function () {
var self = this
if (!self._timeoutMs || !self.requests.length || self._timeout) return
self._timeout = setTimeout(function () {
self._onTimeout()
}, self._timeoutMs)
if (self._timeoutUnref && self._timeout.unref) self._timeout.unref()
}
/**
* Takes a number of bytes that the local peer is waiting to receive from the remote peer
* in order to parse a complete message, and a callback function to be called once enough
* bytes have arrived.
* @param {number} size
* @param {function} parser
*/
Wire.prototype._parse = function (size, parser) {
this._parserSize = size
this._parser = parser
}
/**
* Handle the first 4 bytes of a message, to determine the length of bytes that must be
* waited for in order to have the whole message.
* @param {Buffer} buffer
*/
Wire.prototype._onMessageLength = function (buffer) {
var length = buffer.readUInt32BE(0)
if (length > 0) {
this._parse(length, this._onMessage)
} else {
this._onKeepAlive()
this._parse(4, this._onMessageLength)
}
}
/**
* Handle a message from the remote peer.
* @param {Buffer} buffer
*/
Wire.prototype._onMessage = function (buffer) {
this._parse(4, this._onMessageLength)
switch (buffer[0]) {
case 0:
return this._onChoke()
case 1:
return this._onUnchoke()
case 2:
return this._onInterested()
case 3:
return this._onUninterested()
case 4:
return this._onHave(buffer.readUInt32BE(1))
case 5:
return this._onBitField(buffer.slice(1))
case 6:
return this._onRequest(buffer.readUInt32BE(1),
buffer.readUInt32BE(5), buffer.readUInt32BE(9))
case 7:
return this._onPiece(buffer.readUInt32BE(1),
buffer.readUInt32BE(5), buffer.slice(9))
case 8:
return this._onCancel(buffer.readUInt32BE(1),
buffer.readUInt32BE(5), buffer.readUInt32BE(9))
case 9:
return this._onPort(buffer.readUInt16BE(1))
case 20:
return this._onExtended(buffer.readUInt8(1), buffer.slice(2))
default:
this._debug('got unknown message')
return this.emit('unknownmessage', buffer)
}
}
Wire.prototype._parseHandshake = function () {
var self = this
self._parse(1, function (buffer) {
var pstrlen = buffer.readUInt8(0)
self._parse(pstrlen + 48, function (handshake) {
var protocol = handshake.slice(0, pstrlen)
if (protocol.toString() !== 'BitTorrent protocol') {
self._debug('Error: wire not speaking BitTorrent protocol (%s)', protocol.toString())
self.end()
return
}
handshake = handshake.slice(pstrlen)
self._onHandshake(handshake.slice(8, 28), handshake.slice(28, 48), {
dht: !!(handshake[7] & 0x01), // see bep_0005
extended: !!(handshake[5] & 0x10) // see bep_0010
})
self._parse(4, self._onMessageLength)
})
})
}
Wire.prototype._onFinish = function () {
this._finished = true
this.push(null) // stream cannot be half open, so signal the end of it
while (this.read()) {} // consume and discard the rest of the stream data
clearInterval(this._keepAliveInterval)
this._parse(Number.MAX_VALUE, function () {})
this.peerRequests = []
while (this.requests.length) {
this._callback(this.requests.shift(), new Error('wire was closed'), null)
}
}
Wire.prototype._debug = function () {
var args = [].slice.call(arguments)
args[0] = '[' + this._debugId + '] ' + args[0]
debug.apply(null, args)
}
function pull (requests, piece, offset, length) {
for (var i = 0; i < requests.length; i++) {
var req = requests[i]
if (req.piece !== piece || req.offset !== offset || req.length !== length) continue
if (i === 0) requests.shift()
else requests.splice(i, 1)
return req
}
return null
}
},{"bencode":145,"bitfield":141,"debug":150,"inherits":63,"randombytes":146,"readable-stream":112,"safe-buffer":165,"speedometer":172,"xtend":188}],143:[function(require,module,exports){
(function (Buffer){
/**
* Decodes bencoded data.
*
* @param {Buffer} data
* @param {Number} start (optional)
* @param {Number} end (optional)
* @param {String} encoding (optional)
* @return {Object|Array|Buffer|String|Number}
*/
function decode (data, start, end, encoding) {
if (typeof start !== 'number' && encoding == null) {
encoding = start
start = undefined
}
if (typeof end !== 'number' && encoding == null) {
encoding = end
end = undefined
}
decode.position = 0
decode.encoding = encoding || null
decode.data = !(Buffer.isBuffer(data))
? new Buffer(data)
: data.slice(start, end)
decode.bytes = decode.data.length
return decode.next()
}
decode.bytes = 0
decode.position = 0
decode.data = null
decode.encoding = null
decode.next = function () {
switch (decode.data[decode.position]) {
case 0x64:
return decode.dictionary()
case 0x6C:
return decode.list()
case 0x69:
return decode.integer()
default:
return decode.buffer()
}
}
decode.find = function (chr) {
var i = decode.position
var c = decode.data.length
var d = decode.data
while (i < c) {
if (d[i] === chr) return i
i++
}
throw new Error(
'Invalid data: Missing delimiter "' +
String.fromCharCode(chr) + '" [0x' +
chr.toString(16) + ']'
)
}
decode.dictionary = function () {
decode.position++
var dict = {}
while (decode.data[decode.position] !== 0x65) {
dict[decode.buffer()] = decode.next()
}
decode.position++
return dict
}
decode.list = function () {
decode.position++
var lst = []
while (decode.data[decode.position] !== 0x65) {
lst.push(decode.next())
}
decode.position++
return lst
}
decode.integer = function () {
var end = decode.find(0x65)
var number = decode.data.toString('ascii', decode.position + 1, end)
decode.position += end + 1 - decode.position
return parseInt(number, 10)
}
decode.buffer = function () {
var sep = decode.find(0x3A)
var length = parseInt(decode.data.toString('ascii', decode.position, sep), 10)
var end = ++sep + length
decode.position = end
return decode.encoding
? decode.data.toString(decode.encoding, sep, end)
: decode.data.slice(sep, end)
}
module.exports = decode
}).call(this,require("buffer").Buffer)
},{"buffer":21}],144:[function(require,module,exports){
(function (Buffer){
/**
* Encodes data in bencode.
*
* @param {Buffer|Array|String|Object|Number|Boolean} data
* @return {Buffer}
*/
function encode (data, buffer, offset) {
var buffers = []
var result = null
encode._encode(buffers, data)
result = Buffer.concat(buffers)
encode.bytes = result.length
if (Buffer.isBuffer(buffer)) {
result.copy(buffer, offset)
return buffer
}
return result
}
encode.bytes = -1
encode._floatConversionDetected = false
encode._encode = function (buffers, data) {
if (Buffer.isBuffer(data)) {
buffers.push(new Buffer(data.length + ':'))
buffers.push(data)
return
}
switch (typeof data) {
case 'string':
encode.buffer(buffers, data)
break
case 'number':
encode.number(buffers, data)
break
case 'object':
data.constructor === Array
? encode.list(buffers, data)
: encode.dict(buffers, data)
break
case 'boolean':
encode.number(buffers, data ? 1 : 0)
break
}
}
var buffE = new Buffer('e')
var buffD = new Buffer('d')
var buffL = new Buffer('l')
encode.buffer = function (buffers, data) {
buffers.push(new Buffer(Buffer.byteLength(data) + ':' + data))
}
encode.number = function (buffers, data) {
var maxLo = 0x80000000
var hi = (data / maxLo) << 0
var lo = (data % maxLo) << 0
var val = hi * maxLo + lo
buffers.push(new Buffer('i' + val + 'e'))
if (val !== data && !encode._floatConversionDetected) {
encode._floatConversionDetected = true
console.warn(
'WARNING: Possible data corruption detected with value "' + data + '":',
'Bencoding only defines support for integers, value was converted to "' + val + '"'
)
console.trace()
}
}
encode.dict = function (buffers, data) {
buffers.push(buffD)
var j = 0
var k
// fix for issue #13 - sorted dicts
var keys = Object.keys(data).sort()
var kl = keys.length
for (; j < kl; j++) {
k = keys[j]
encode.buffer(buffers, k)
encode._encode(buffers, data[k])
}
buffers.push(buffE)
}
encode.list = function (buffers, data) {
var i = 0
var c = data.length
buffers.push(buffL)
for (; i < c; i++) {
encode._encode(buffers, data[i])
}
buffers.push(buffE)
}
module.exports = encode
}).call(this,require("buffer").Buffer)
},{"buffer":21}],145:[function(require,module,exports){
arguments[4][46][0].apply(exports,arguments)
},{"./decode":143,"./encode":144,"dup":46}],146:[function(require,module,exports){
(function (process,global,Buffer){
'use strict'
function oldBrowser () {
throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
}
var crypto = global.crypto || global.msCrypto
if (crypto && crypto.getRandomValues) {
module.exports = randomBytes
} else {
module.exports = oldBrowser
}
function randomBytes (size, cb) {
// phantomjs needs to throw
if (size > 65536) throw new Error('requested too many random bytes')
// in case browserify isn't using the Uint8Array version
var rawBytes = new global.Uint8Array(size)
// This will not work in older browsers.
// See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
if (size > 0) { // getRandomValues fails on IE if size == 0
crypto.getRandomValues(rawBytes)
}
// phantomjs doesn't like a buffer being passed here
var bytes = new Buffer(rawBytes.buffer)
if (typeof cb === 'function') {
return process.nextTick(function () {
cb(null, bytes)
})
}
return bytes
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
},{"_process":29,"buffer":21}],147:[function(require,module,exports){
(function (Buffer){
var inherits = require('inherits');
var Transform = require('readable-stream').Transform;
var defined = require('defined');
module.exports = Block;
inherits(Block, Transform);
function Block (size, opts) {
if (!(this instanceof Block)) return new Block(size, opts);
Transform.call(this);
if (!opts) opts = {};
if (typeof size === 'object') {
opts = size;
size = opts.size;
}
this.size = size || 512;
if (opts.nopad) this._zeroPadding = false;
else this._zeroPadding = defined(opts.zeroPadding, true);
this._buffered = [];
this._bufferedBytes = 0;
}
Block.prototype._transform = function (buf, enc, next) {
this._bufferedBytes += buf.length;
this._buffered.push(buf);
while (this._bufferedBytes >= this.size) {
var b = Buffer.concat(this._buffered);
this._bufferedBytes -= this.size;
this.push(b.slice(0, this.size));
this._buffered = [ b.slice(this.size, b.length) ];
}
next();
};
Block.prototype._flush = function () {
if (this._bufferedBytes && this._zeroPadding) {
var zeroes = new Buffer(this.size - this._bufferedBytes);
zeroes.fill(0);
this._buffered.push(zeroes);
this.push(Buffer.concat(this._buffered));
this._buffered = null;
}
else if (this._bufferedBytes) {
this.push(Buffer.concat(this._buffered));
this._buffered = null;
}
this.push(null);
};
}).call(this,require("buffer").Buffer)
},{"buffer":21,"defined":148,"inherits":63,"readable-stream":112}],148:[function(require,module,exports){
arguments[4][48][0].apply(exports,arguments)
},{"dup":48}],149:[function(require,module,exports){
module.exports = ChunkStoreWriteStream
var BlockStream = require('block-stream2')
var inherits = require('inherits')
var stream = require('readable-stream')
inherits(ChunkStoreWriteStream, stream.Writable)
function ChunkStoreWriteStream (store, chunkLength, opts) {
var self = this
if (!(self instanceof ChunkStoreWriteStream)) {
return new ChunkStoreWriteStream(store, chunkLength, opts)
}
stream.Writable.call(self, opts)
if (!opts) opts = {}
if (!store || !store.put || !store.get) {
throw new Error('First argument must be an abstract-chunk-store compliant store')
}
chunkLength = Number(chunkLength)
if (!chunkLength) throw new Error('Second argument must be a chunk length')
self._blockstream = new BlockStream(chunkLength, { zeroPadding: false })
self._blockstream
.on('data', onData)
.on('error', function (err) { self.destroy(err) })
var index = 0
function onData (chunk) {
if (self.destroyed) return
store.put(index, chunk)
index += 1
}
self.on('finish', function () { this._blockstream.end() })
}
ChunkStoreWriteStream.prototype._write = function (chunk, encoding, callback) {
this._blockstream.write(chunk, encoding, callback)
}
ChunkStoreWriteStream.prototype.destroy = function (err) {
if (this.destroyed) return
this.destroyed = true
if (err) this.emit('error', err)
this.emit('close')
}
},{"block-stream2":147,"inherits":63,"readable-stream":112}],150:[function(require,module,exports){
arguments[4][7][0].apply(exports,arguments)
},{"./debug":151,"dup":7}],151:[function(require,module,exports){
arguments[4][8][0].apply(exports,arguments)
},{"dup":8,"ms":152}],152:[function(require,module,exports){
arguments[4][9][0].apply(exports,arguments)
},{"dup":9}],153:[function(require,module,exports){
arguments[4][94][0].apply(exports,arguments)
},{"dup":94,"once":155}],154:[function(require,module,exports){
arguments[4][10][0].apply(exports,arguments)
},{"dup":10}],155:[function(require,module,exports){
arguments[4][96][0].apply(exports,arguments)
},{"dup":96,"wrappy":154}],156:[function(require,module,exports){
var hat = module.exports = function (bits, base) {
if (!base) base = 16;
if (bits === undefined) bits = 128;
if (bits <= 0) return '0';
var digits = Math.log(Math.pow(2, bits)) / Math.log(base);
for (var i = 2; digits === Infinity; i *= 2) {
digits = Math.log(Math.pow(2, bits / i)) / Math.log(base) * i;
}
var rem = digits - Math.floor(digits);
var res = '';
for (var i = 0; i < Math.floor(digits); i++) {
var x = Math.floor(Math.random() * base).toString(base);
res = x + res;
}
if (rem) {
var b = Math.pow(base, rem);
var x = Math.floor(Math.random() * b).toString(base);
res = x + res;
}
var parsed = parseInt(res, base);
if (parsed !== Infinity && parsed >= Math.pow(2, bits)) {
return hat(bits, base)
}
else return res;
};
hat.rack = function (bits, base, expandBy) {
var fn = function (data) {
var iters = 0;
do {
if (iters ++ > 10) {
if (expandBy) bits += expandBy;
else throw new Error('too many ID collisions, use more bits')
}
var id = hat(bits, base);
} while (Object.hasOwnProperty.call(hats, id));
hats[id] = data;
return id;
};
var hats = fn.hats = {};
fn.get = function (id) {
return fn.hats[id];
};
fn.set = function (id, value) {
fn.hats[id] = value;
return fn;
};
fn.bits = bits || 128;
fn.base = base || 16;
return fn;
};
},{}],157:[function(require,module,exports){
(function (process){
module.exports = ImmediateStore
function ImmediateStore (store) {
if (!(this instanceof ImmediateStore)) return new ImmediateStore(store)
this.store = store
this.chunkLength = store.chunkLength
if (!this.store || !this.store.get || !this.store.put) {
throw new Error('First argument must be abstract-chunk-store compliant')
}
this.mem = []
}
ImmediateStore.prototype.put = function (index, buf, cb) {
var self = this
self.mem[index] = buf
self.store.put(index, buf, function (err) {
self.mem[index] = null
if (cb) cb(err)
})
}
ImmediateStore.prototype.get = function (index, opts, cb) {
if (typeof opts === 'function') return this.get(index, null, opts)
var start = (opts && opts.offset) || 0
var end = opts && opts.length && (start + opts.length)
var buf = this.mem[index]
if (buf) return nextTick(cb, null, opts ? buf.slice(start, end) : buf)
this.store.get(index, opts, cb)
}
ImmediateStore.prototype.close = function (cb) {
this.store.close(cb)
}
ImmediateStore.prototype.destroy = function (cb) {
this.store.destroy(cb)
}
function nextTick (cb, err, val) {
process.nextTick(function () {
if (cb) cb(err, val)
})
}
}).call(this,require('_process'))
},{"_process":29}],158:[function(require,module,exports){
(function (process){
module.exports = Storage
function Storage (chunkLength, opts) {
if (!(this instanceof Storage)) return new Storage(chunkLength, opts)
if (!opts) opts = {}
this.chunkLength = Number(chunkLength)
if (!this.chunkLength) throw new Error('First argument must be a chunk length')
this.chunks = []
this.closed = false
this.length = Number(opts.length) || Infinity
if (this.length !== Infinity) {
this.lastChunkLength = (this.length % this.chunkLength) || this.chunkLength
this.lastChunkIndex = Math.ceil(this.length / this.chunkLength) - 1
}
}
Storage.prototype.put = function (index, buf, cb) {
if (this.closed) return nextTick(cb, new Error('Storage is closed'))
var isLastChunk = (index === this.lastChunkIndex)
if (isLastChunk && buf.length !== this.lastChunkLength) {
return nextTick(cb, new Error('Last chunk length must be ' + this.lastChunkLength))
}
if (!isLastChunk && buf.length !== this.chunkLength) {
return nextTick(cb, new Error('Chunk length must be ' + this.chunkLength))
}
this.chunks[index] = buf
nextTick(cb, null)
}
Storage.prototype.get = function (index, opts, cb) {
if (typeof opts === 'function') return this.get(index, null, opts)
if (this.closed) return nextTick(cb, new Error('Storage is closed'))
var buf = this.chunks[index]
if (!buf) return nextTick(cb, new Error('Chunk not found'))
if (!opts) return nextTick(cb, null, buf)
var offset = opts.offset || 0
var len = opts.length || (buf.length - offset)
nextTick(cb, null, buf.slice(offset, len + offset))
}
Storage.prototype.close = Storage.prototype.destroy = function (cb) {
if (this.closed) return nextTick(cb, new Error('Storage is closed'))
this.closed = true
this.chunks = null
nextTick(cb, null)
}
function nextTick (cb, err, val) {
process.nextTick(function () {
if (cb) cb(err, val)
})
}
}).call(this,require('_process'))
},{"_process":29}],159:[function(require,module,exports){
var iterate = function (list) {
var offset = 0
return function () {
if (offset === list.length) return null
var len = list.length - offset
var i = (Math.random() * len) | 0
var el = list[offset + i]
var tmp = list[offset]
list[offset] = el
list[offset + i] = tmp
offset++
return el
}
}
module.exports = iterate
},{}],160:[function(require,module,exports){
exports.render = render
exports.append = append
exports.mime = require('./lib/mime.json')
var debug = require('debug')('render-media')
var isAscii = require('is-ascii')
var MediaElementWrapper = require('mediasource')
var path = require('path')
var streamToBlobURL = require('stream-to-blob-url')
var videostream = require('videostream')
var VIDEOSTREAM_EXTS = [
'.m4a',
'.m4v',
'.mp4'
]
var MEDIASOURCE_VIDEO_EXTS = [
'.m4v',
'.mkv',
'.mp4',
'.webm'
]
var MEDIASOURCE_AUDIO_EXTS = [
'.m4a',
'.mp3'
]
var MEDIASOURCE_EXTS = [].concat(
MEDIASOURCE_VIDEO_EXTS,
MEDIASOURCE_AUDIO_EXTS
)
var AUDIO_EXTS = [
'.aac',
'.oga',
'.ogg',
'.wav'
]
var IMAGE_EXTS = [
'.bmp',
'.gif',
'.jpeg',
'.jpg',
'.png'
]
var IFRAME_EXTS = [
'.css',
'.html',
'.js',
'.md',
'.pdf',
'.txt'
]
// Maximum file length for which the Blob URL strategy will be attempted
// See: https://github.com/feross/render-media/issues/18
var MAX_BLOB_LENGTH = 200 * 1000 * 1000 // 200 MB
var MediaSource = typeof window !== 'undefined' && window.MediaSource
function render (file, elem, opts, cb) {
if (typeof opts === 'function') {
cb = opts
opts = {}
}
if (!opts) opts = {}
if (!cb) cb = function () {}
validateFile(file)
parseOpts(opts)
if (typeof elem === 'string') elem = document.querySelector(elem)
renderMedia(file, function (tagName) {
if (elem.nodeName !== tagName.toUpperCase()) {
var extname = path.extname(file.name).toLowerCase()
throw new Error(
'Cannot render "' + extname + '" inside a "' +
elem.nodeName.toLowerCase() + '" element, expected "' + tagName + '"'
)
}
return elem
}, opts, cb)
}
function append (file, rootElem, opts, cb) {
if (typeof opts === 'function') {
cb = opts
opts = {}
}
if (!opts) opts = {}
if (!cb) cb = function () {}
validateFile(file)
parseOpts(opts)
if (typeof rootElem === 'string') rootElem = document.querySelector(rootElem)
if (rootElem && (rootElem.nodeName === 'VIDEO' || rootElem.nodeName === 'AUDIO')) {
throw new Error(
'Invalid video/audio node argument. Argument must be root element that ' +
'video/audio tag will be appended to.'
)
}
renderMedia(file, getElem, opts, done)
function getElem (tagName) {
if (tagName === 'video' || tagName === 'audio') return createMedia(tagName)
else return createElem(tagName)
}
function createMedia (tagName) {
var elem = createElem(tagName)
if (opts.controls) elem.controls = true
if (opts.autoplay) elem.autoplay = true
rootElem.appendChild(elem)
return elem
}
function createElem (tagName) {
var elem = document.createElement(tagName)
rootElem.appendChild(elem)
return elem
}
function done (err, elem) {
if (err && elem) elem.remove()
cb(err, elem)
}
}
function renderMedia (file, getElem, opts, cb) {
var extname = path.extname(file.name).toLowerCase()
var currentTime = 0
var elem
if (MEDIASOURCE_EXTS.indexOf(extname) >= 0) {
renderMediaSource()
} else if (AUDIO_EXTS.indexOf(extname) >= 0) {
renderAudio()
} else if (IMAGE_EXTS.indexOf(extname) >= 0) {
renderImage()
} else if (IFRAME_EXTS.indexOf(extname) >= 0) {
renderIframe()
} else {
tryRenderIframe()
}
function renderMediaSource () {
var tagName = MEDIASOURCE_VIDEO_EXTS.indexOf(extname) >= 0 ? 'video' : 'audio'
if (MediaSource) {
if (VIDEOSTREAM_EXTS.indexOf(extname) >= 0) {
useVideostream()
} else {
useMediaSource()
}
} else {
useBlobURL()
}
function useVideostream () {
debug('Use `videostream` package for ' + file.name)
prepareElem()
elem.addEventListener('error', fallbackToMediaSource)
elem.addEventListener('loadstart', onLoadStart)
elem.addEventListener('canplay', onCanPlay)
videostream(file, elem)
}
function useMediaSource () {
debug('Use MediaSource API for ' + file.name)
prepareElem()
elem.addEventListener('error', fallbackToBlobURL)
elem.addEventListener('loadstart', onLoadStart)
elem.addEventListener('canplay', onCanPlay)
var wrapper = new MediaElementWrapper(elem)
var writable = wrapper.createWriteStream(getCodec(file.name))
file.createReadStream().pipe(writable)
if (currentTime) elem.currentTime = currentTime
}
function useBlobURL () {
debug('Use Blob URL for ' + file.name)
prepareElem()
elem.addEventListener('error', fatalError)
elem.addEventListener('loadstart', onLoadStart)
elem.addEventListener('canplay', onCanPlay)
getBlobURL(file, function (err, url) {
if (err) return fatalError(err)
elem.src = url
if (currentTime) elem.currentTime = currentTime
})
}
function fallbackToMediaSource (err) {
debug('videostream error: fallback to MediaSource API: %o', err.message || err)
elem.removeEventListener('error', fallbackToMediaSource)
elem.removeEventListener('canplay', onCanPlay)
useMediaSource()
}
function fallbackToBlobURL (err) {
debug('MediaSource API error: fallback to Blob URL: %o', err.message || err)
if (typeof file.length === 'number' && file.length > opts.maxBlobLength) {
debug(
'File length too large for Blob URL approach: %d (max: %d)',
file.length, opts.maxBlobLength
)
return fatalError(new Error(
'File length too large for Blob URL approach: ' + file.length +
' (max: ' + opts.maxBlobLength + ')'
))
}
elem.removeEventListener('error', fallbackToBlobURL)
elem.removeEventListener('canplay', onCanPlay)
useBlobURL()
}
function prepareElem () {
if (!elem) {
elem = getElem(tagName)
elem.addEventListener('progress', function () {
currentTime = elem.currentTime
})
}
}
}
function renderAudio () {
elem = getElem('audio')
getBlobURL(file, function (err, url) {
if (err) return fatalError(err)
elem.addEventListener('error', fatalError)
elem.addEventListener('loadstart', onLoadStart)
elem.addEventListener('canplay', onCanPlay)
elem.src = url
})
}
function onLoadStart () {
elem.removeEventListener('loadstart', onLoadStart)
if (opts.autoplay) elem.play()
}
function onCanPlay () {
elem.removeEventListener('canplay', onCanPlay)
cb(null, elem)
}
function renderImage () {
elem = getElem('img')
getBlobURL(file, function (err, url) {
if (err) return fatalError(err)
elem.src = url
elem.alt = file.name
cb(null, elem)
})
}
function renderIframe () {
elem = getElem('iframe')
getBlobURL(file, function (err, url) {
if (err) return fatalError(err)
elem.src = url
if (extname !== '.pdf') elem.sandbox = 'allow-forms allow-scripts'
cb(null, elem)
})
}
function tryRenderIframe () {
debug('Unknown file extension "%s" - will attempt to render into iframe', extname)
var str = ''
file.createReadStream({ start: 0, end: 1000 })
.setEncoding('utf8')
.on('data', function (chunk) {
str += chunk
})
.on('end', done)
.on('error', cb)
function done () {
if (isAscii(str)) {
debug('File extension "%s" appears ascii, so will render.', extname)
renderIframe()
} else {
debug('File extension "%s" appears non-ascii, will not render.', extname)
cb(new Error('Unsupported file type "' + extname + '": Cannot append to DOM'))
}
}
}
function fatalError (err) {
err.message = 'Error rendering file "' + file.name + '": ' + err.message
debug(err.message)
cb(err)
}
}
function getBlobURL (file, cb) {
var extname = path.extname(file.name).toLowerCase()
streamToBlobURL(file.createReadStream(), exports.mime[extname], cb)
}
function validateFile (file) {
if (file == null) {
throw new Error('file cannot be null or undefined')
}
if (typeof file.name !== 'string') {
throw new Error('missing or invalid file.name property')
}
if (typeof file.createReadStream !== 'function') {
throw new Error('missing or invalid file.createReadStream property')
}
}
function getCodec (name) {
var extname = path.extname(name).toLowerCase()
return {
'.m4a': 'audio/mp4; codecs="mp4a.40.5"',
'.m4v': 'video/mp4; codecs="avc1.640029, mp4a.40.5"',
'.mkv': 'video/webm; codecs="avc1.640029, mp4a.40.5"',
'.mp3': 'audio/mpeg',
'.mp4': 'video/mp4; codecs="avc1.640029, mp4a.40.5"',
'.webm': 'video/webm; codecs="vorbis, vp8"'
}[extname]
}
function parseOpts (opts) {
if (opts.autoplay == null) opts.autoplay = true
if (opts.controls == null) opts.controls = true
if (opts.maxBlobLength == null) opts.maxBlobLength = MAX_BLOB_LENGTH
}
},{"./lib/mime.json":161,"debug":150,"is-ascii":162,"mediasource":64,"path":28,"stream-to-blob-url":173,"videostream":132}],161:[function(require,module,exports){
module.exports={
".3gp": "video/3gpp",
".aac": "audio/aac",
".aif": "audio/x-aiff",
".aiff": "audio/x-aiff",
".atom": "application/atom+xml",
".avi": "video/x-msvideo",
".bmp": "image/bmp",
".bz2": "application/x-bzip2",
".conf": "text/plain",
".css": "text/css",
".csv": "text/csv",
".diff": "text/x-diff",
".doc": "application/msword",
".flv": "video/x-flv",
".gif": "image/gif",
".gz": "application/x-gzip",
".htm": "text/html",
".html": "text/html",
".ico": "image/vnd.microsoft.icon",
".ics": "text/calendar",
".iso": "application/octet-stream",
".jar": "application/java-archive",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".js": "application/javascript",
".json": "application/json",
".less": "text/css",
".log": "text/plain",
".m3u": "audio/x-mpegurl",
".m4a": "audio/mp4",
".m4v": "video/mp4",
".manifest": "text/cache-manifest",
".markdown": "text/x-markdown",
".mathml": "application/mathml+xml",
".md": "text/x-markdown",
".mid": "audio/midi",
".midi": "audio/midi",
".mov": "video/quicktime",
".mp3": "audio/mpeg",
".mp4": "video/mp4",
".mp4v": "video/mp4",
".mpeg": "video/mpeg",
".mpg": "video/mpeg",
".odp": "application/vnd.oasis.opendocument.presentation",
".ods": "application/vnd.oasis.opendocument.spreadsheet",
".odt": "application/vnd.oasis.opendocument.text",
".oga": "audio/ogg",
".ogg": "application/ogg",
".pdf": "application/pdf",
".png": "image/png",
".pps": "application/vnd.ms-powerpoint",
".ppt": "application/vnd.ms-powerpoint",
".ps": "application/postscript",
".psd": "image/vnd.adobe.photoshop",
".qt": "video/quicktime",
".rar": "application/x-rar-compressed",
".rdf": "application/rdf+xml",
".rss": "application/rss+xml",
".rtf": "application/rtf",
".svg": "image/svg+xml",
".svgz": "image/svg+xml",
".swf": "application/x-shockwave-flash",
".tar": "application/x-tar",
".tbz": "application/x-bzip-compressed-tar",
".text": "text/plain",
".tif": "image/tiff",
".tiff": "image/tiff",
".torrent": "application/x-bittorrent",
".ttf": "application/x-font-ttf",
".txt": "text/plain",
".wav": "audio/wav",
".webm": "video/webm",
".wma": "audio/x-ms-wma",
".wmv": "video/x-ms-wmv",
".xls": "application/vnd.ms-excel",
".xml": "application/xml",
".yaml": "text/yaml",
".yml": "text/yaml",
".zip": "application/zip"
}
},{}],162:[function(require,module,exports){
/* (c) 2016 Ari Porad (@ariporad) <http://ariporad.com>. License: ariporad.mit-license.org */
// Partially from http://stackoverflow.com/a/94049/1928484, and from another SO answer, which told me that the highest
// char code that's ascii is 127, but I can't find the link for. Sorry.
var MAX_ASCII_CHAR_CODE = 127;
module.exports = function isAscii(str) {
for (var i = 0, strLen = str.length; i < strLen; ++i) {
if (str.charCodeAt(i) > MAX_ASCII_CHAR_CODE) return false;
}
return true;
};
},{}],163:[function(require,module,exports){
(function (process){
module.exports = function (tasks, limit, cb) {
if (typeof limit !== 'number') throw new Error('second argument must be a Number')
var results, len, pending, keys, isErrored
var isSync = true
if (Array.isArray(tasks)) {
results = []
pending = len = tasks.length
} else {
keys = Object.keys(tasks)
results = {}
pending = len = keys.length
}
function done (err) {
function end () {
if (cb) cb(err, results)
cb = null
}
if (isSync) process.nextTick(end)
else end()
}
function each (i, err, result) {
results[i] = result
if (err) isErrored = true
if (--pending === 0 || err) {
done(err)
} else if (!isErrored && next < len) {
var key
if (keys) {
key = keys[next]
next += 1
tasks[key](function (err, result) { each(key, err, result) })
} else {
key = next
next += 1
tasks[key](function (err, result) { each(key, err, result) })
}
}
}
var next = limit
if (!pending) {
// empty
done(null)
} else if (keys) {
// object
keys.some(function (key, i) {
tasks[key](function (err, result) { each(key, err, result) })
if (i === limit - 1) return true // early return
})
} else {
// array
tasks.some(function (task, i) {
task(function (err, result) { each(i, err, result) })
if (i === limit - 1) return true // early return
})
}
isSync = false
}
}).call(this,require('_process'))
},{"_process":29}],164:[function(require,module,exports){
(function (process){
module.exports = function (tasks, cb) {
var results, pending, keys
var isSync = true
if (Array.isArray(tasks)) {
results = []
pending = tasks.length
} else {
keys = Object.keys(tasks)
results = {}
pending = keys.length
}
function done (err) {
function end () {
if (cb) cb(err, results)
cb = null
}
if (isSync) process.nextTick(end)
else end()
}
function each (i, err, result) {
results[i] = result
if (--pending === 0 || err) {
done(err)
}
}
if (!pending) {
// empty
done(null)
} else if (keys) {
// object
keys.forEach(function (key) {
tasks[key](function (err, result) { each(key, err, result) })
})
} else {
// array
tasks.forEach(function (task, i) {
task(function (err, result) { each(i, err, result) })
})
}
isSync = false
}
}).call(this,require('_process'))
},{"_process":29}],165:[function(require,module,exports){
arguments[4][14][0].apply(exports,arguments)
},{"buffer":21,"dup":14}],166:[function(require,module,exports){
(function (Buffer){
module.exports = function (stream, cb) {
var chunks = []
stream.on('data', function (chunk) {
chunks.push(chunk)
})
stream.once('end', function () {
if (cb) cb(null, Buffer.concat(chunks))
cb = null
})
stream.once('error', function (err) {
if (cb) cb(err)
cb = null
})
}
}).call(this,require("buffer").Buffer)
},{"buffer":21}],167:[function(require,module,exports){
(function (Buffer){
module.exports = simpleGet
var concat = require('simple-concat')
var http = require('http')
var https = require('https')
var once = require('once')
var querystring = require('querystring')
var unzipResponse = require('unzip-response') // excluded from browser build
var url = require('url')
function simpleGet (opts, cb) {
opts = typeof opts === 'string' ? {url: opts} : Object.assign({}, opts)
cb = once(cb)
if (opts.url) parseOptsUrl(opts)
if (opts.headers == null) opts.headers = {}
if (opts.maxRedirects == null) opts.maxRedirects = 10
var body
if (opts.form) body = typeof opts.form === 'string' ? opts.form : querystring.stringify(opts.form)
if (opts.body) body = opts.json ? JSON.stringify(opts.body) : opts.body
if (opts.json) opts.headers.accept = 'application/json'
if (opts.json && body) opts.headers['content-type'] = 'application/json'
if (opts.form) opts.headers['content-type'] = 'application/x-www-form-urlencoded'
if (body) opts.headers['content-length'] = Buffer.byteLength(body)
delete opts.body; delete opts.form
if (body && !opts.method) opts.method = 'POST'
if (opts.method) opts.method = opts.method.toUpperCase()
// Request gzip/deflate
var customAcceptEncoding = Object.keys(opts.headers).some(function (h) {
return h.toLowerCase() === 'accept-encoding'
})
if (!customAcceptEncoding) opts.headers['accept-encoding'] = 'gzip, deflate'
// Support http/https urls
var protocol = opts.protocol === 'https:' ? https : http
var req = protocol.request(opts, function (res) {
// Follow 3xx redirects
if (res.statusCode >= 300 && res.statusCode < 400 && 'location' in res.headers) {
opts.url = res.headers.location
parseOptsUrl(opts)
res.resume() // Discard response
opts.maxRedirects -= 1
if (opts.maxRedirects > 0) simpleGet(opts, cb)
else cb(new Error('too many redirects'))
return
}
var tryUnzip = typeof unzipResponse === 'function' && opts.method !== 'HEAD'
cb(null, tryUnzip ? unzipResponse(res) : res)
})
req.on('error', cb)
req.end(body)
return req
}
simpleGet.concat = function (opts, cb) {
return simpleGet(opts, function (err, res) {
if (err) return cb(err)
concat(res, function (err, data) {
if (err) return cb(err)
if (opts.json) {
try {
data = JSON.parse(data.toString())
} catch (err) {
return cb(err, res, data)
}
}
cb(null, res, data)
})
})
}
;['get', 'post', 'put', 'patch', 'head', 'delete'].forEach(function (method) {
simpleGet[method] = function (opts, cb) {
if (typeof opts === 'string') opts = {url: opts}
opts.method = method.toUpperCase()
return simpleGet(opts, cb)
}
})
function parseOptsUrl (opts) {
var loc = url.parse(opts.url)
if (loc.hostname) opts.hostname = loc.hostname
if (loc.port) opts.port = loc.port
if (loc.protocol) opts.protocol = loc.protocol
if (loc.auth) opts.auth = loc.auth
opts.path = loc.path
delete opts.url
}
}).call(this,require("buffer").Buffer)
},{"buffer":21,"http":34,"https":26,"once":169,"querystring":33,"simple-concat":166,"unzip-response":20,"url":40}],168:[function(require,module,exports){
arguments[4][10][0].apply(exports,arguments)
},{"dup":10}],169:[function(require,module,exports){
arguments[4][11][0].apply(exports,arguments)
},{"dup":11,"wrappy":168}],170:[function(require,module,exports){
arguments[4][60][0].apply(exports,arguments)
},{"dup":60,"rusha":171}],171:[function(require,module,exports){
(function (global){
(function () {
var /*
* Rusha, a JavaScript implementation of the Secure Hash Algorithm, SHA-1,
* as defined in FIPS PUB 180-1, tuned for high performance with large inputs.
* (http://github.com/srijs/rusha)
*
* Inspired by Paul Johnstons implementation (http://pajhome.org.uk/crypt/md5).
*
* Copyright (c) 2013 Sam Rijs (http://awesam.de).
* Released under the terms of the MIT license as follows:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
util = {
getDataType: function (data) {
if (typeof data === 'string') {
return 'string';
}
if (data instanceof Array) {
return 'array';
}
if (typeof global !== 'undefined' && global.Buffer && global.Buffer.isBuffer(data)) {
return 'buffer';
}
if (data instanceof ArrayBuffer) {
return 'arraybuffer';
}
if (data.buffer instanceof ArrayBuffer) {
return 'view';
}
if (data instanceof Blob) {
return 'blob';
}
throw new Error('Unsupported data type.');
}
};
function Rusha(chunkSize) {
'use strict';
var // Private object structure.
self$2 = { fill: 0 };
var // Calculate the length of buffer that the sha1 routine uses
// including the padding.
padlen = function (len) {
for (len += 9; len % 64 > 0; len += 1);
return len;
};
var padZeroes = function (bin, len) {
for (var i$2 = len >> 2; i$2 < bin.length; i$2++)
bin[i$2] = 0;
};
var padData = function (bin, chunkLen, msgLen) {
bin[chunkLen >> 2] |= 128 << 24 - (chunkLen % 4 << 3);
// To support msgLen >= 2 GiB, use a float division when computing the
// high 32-bits of the big-endian message length in bits.
bin[((chunkLen >> 2) + 2 & ~15) + 14] = msgLen / (1 << 29) | 0;
bin[((chunkLen >> 2) + 2 & ~15) + 15] = msgLen << 3;
};
var // Convert a binary string and write it to the heap.
// A binary string is expected to only contain char codes < 256.
convStr = function (H8, H32, start, len, off) {
var str = this, i$2, om = off % 4, lm = len % 4, j = len - lm;
if (j > 0) {
switch (om) {
case 0:
H8[off + 3 | 0] = str.charCodeAt(start);
case 1:
H8[off + 2 | 0] = str.charCodeAt(start + 1);
case 2:
H8[off + 1 | 0] = str.charCodeAt(start + 2);
case 3:
H8[off | 0] = str.charCodeAt(start + 3);
}
}
for (i$2 = om; i$2 < j; i$2 = i$2 + 4 | 0) {
H32[off + i$2 >> 2] = str.charCodeAt(start + i$2) << 24 | str.charCodeAt(start + i$2 + 1) << 16 | str.charCodeAt(start + i$2 + 2) << 8 | str.charCodeAt(start + i$2 + 3);
}
switch (lm) {
case 3:
H8[off + j + 1 | 0] = str.charCodeAt(start + j + 2);
case 2:
H8[off + j + 2 | 0] = str.charCodeAt(start + j + 1);
case 1:
H8[off + j + 3 | 0] = str.charCodeAt(start + j);
}
};
var // Convert a buffer or array and write it to the heap.
// The buffer or array is expected to only contain elements < 256.
convBuf = function (H8, H32, start, len, off) {
var buf = this, i$2, om = off % 4, lm = len % 4, j = len - lm;
if (j > 0) {
switch (om) {
case 0:
H8[off + 3 | 0] = buf[start];
case 1:
H8[off + 2 | 0] = buf[start + 1];
case 2:
H8[off + 1 | 0] = buf[start + 2];
case 3:
H8[off | 0] = buf[start + 3];
}
}
for (i$2 = 4 - om; i$2 < j; i$2 = i$2 += 4 | 0) {
H32[off + i$2 >> 2] = buf[start + i$2] << 24 | buf[start + i$2 + 1] << 16 | buf[start + i$2 + 2] << 8 | buf[start + i$2 + 3];
}
switch (lm) {
case 3:
H8[off + j + 1 | 0] = buf[start + j + 2];
case 2:
H8[off + j + 2 | 0] = buf[start + j + 1];
case 1:
H8[off + j + 3 | 0] = buf[start + j];
}
};
var convBlob = function (H8, H32, start, len, off) {
var blob = this, i$2, om = off % 4, lm = len % 4, j = len - lm;
var buf = new Uint8Array(reader.readAsArrayBuffer(blob.slice(start, start + len)));
if (j > 0) {
switch (om) {
case 0:
H8[off + 3 | 0] = buf[0];
case 1:
H8[off + 2 | 0] = buf[1];
case 2:
H8[off + 1 | 0] = buf[2];
case 3:
H8[off | 0] = buf[3];
}
}
for (i$2 = 4 - om; i$2 < j; i$2 = i$2 += 4 | 0) {
H32[off + i$2 >> 2] = buf[i$2] << 24 | buf[i$2 + 1] << 16 | buf[i$2 + 2] << 8 | buf[i$2 + 3];
}
switch (lm) {
case 3:
H8[off + j + 1 | 0] = buf[j + 2];
case 2:
H8[off + j + 2 | 0] = buf[j + 1];
case 1:
H8[off + j + 3 | 0] = buf[j];
}
};
var convFn = function (data) {
switch (util.getDataType(data)) {
case 'string':
return convStr.bind(data);
case 'array':
return convBuf.bind(data);
case 'buffer':
return convBuf.bind(data);
case 'arraybuffer':
return convBuf.bind(new Uint8Array(data));
case 'view':
return convBuf.bind(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
case 'blob':
return convBlob.bind(data);
}
};
var slice = function (data, offset) {
switch (util.getDataType(data)) {
case 'string':
return data.slice(offset);
case 'array':
return data.slice(offset);
case 'buffer':
return data.slice(offset);
case 'arraybuffer':
return data.slice(offset);
case 'view':
return data.buffer.slice(offset);
}
};
var // Precompute 00 - ff strings
precomputedHex = new Array(256);
for (var i = 0; i < 256; i++) {
precomputedHex[i] = (i < 16 ? '0' : '') + i.toString(16);
}
var // Convert an ArrayBuffer into its hexadecimal string representation.
hex = function (arrayBuffer) {
var binarray = new Uint8Array(arrayBuffer);
var res = new Array(arrayBuffer.byteLength);
for (var i$2 = 0; i$2 < res.length; i$2++) {
res[i$2] = precomputedHex[binarray[i$2]];
}
return res.join('');
};
var ceilHeapSize = function (v) {
// The asm.js spec says:
// The heap object's byteLength must be either
// 2^n for n in [12, 24) or 2^24 * n for n ≥ 1.
// Also, byteLengths smaller than 2^16 are deprecated.
var p;
if (// If v is smaller than 2^16, the smallest possible solution
// is 2^16.
v <= 65536)
return 65536;
if (// If v < 2^24, we round up to 2^n,
// otherwise we round up to 2^24 * n.
v < 16777216) {
for (p = 1; p < v; p = p << 1);
} else {
for (p = 16777216; p < v; p += 16777216);
}
return p;
};
var // Initialize the internal data structures to a new capacity.
init = function (size) {
if (size % 64 > 0) {
throw new Error('Chunk size must be a multiple of 128 bit');
}
self$2.maxChunkLen = size;
self$2.padMaxChunkLen = padlen(size);
// The size of the heap is the sum of:
// 1. The padded input message size
// 2. The extended space the algorithm needs (320 byte)
// 3. The 160 bit state the algoritm uses
self$2.heap = new ArrayBuffer(ceilHeapSize(self$2.padMaxChunkLen + 320 + 20));
self$2.h32 = new Int32Array(self$2.heap);
self$2.h8 = new Int8Array(self$2.heap);
self$2.core = new Rusha._core({
Int32Array: Int32Array,
DataView: DataView
}, {}, self$2.heap);
self$2.buffer = null;
};
// Iinitializethe datastructures according
// to a chunk siyze.
init(chunkSize || 64 * 1024);
var initState = function (heap, padMsgLen) {
var io = new Int32Array(heap, padMsgLen + 320, 5);
io[0] = 1732584193;
io[1] = -271733879;
io[2] = -1732584194;
io[3] = 271733878;
io[4] = -1009589776;
};
var padChunk = function (chunkLen, msgLen) {
var padChunkLen = padlen(chunkLen);
var view = new Int32Array(self$2.heap, 0, padChunkLen >> 2);
padZeroes(view, chunkLen);
padData(view, chunkLen, msgLen);
return padChunkLen;
};
var // Write data to the heap.
write = function (data, chunkOffset, chunkLen) {
convFn(data)(self$2.h8, self$2.h32, chunkOffset, chunkLen, 0);
};
var // Initialize and call the RushaCore,
// assuming an input buffer of length len * 4.
coreCall = function (data, chunkOffset, chunkLen, msgLen, finalize) {
var padChunkLen = chunkLen;
if (finalize) {
padChunkLen = padChunk(chunkLen, msgLen);
}
write(data, chunkOffset, chunkLen);
self$2.core.hash(padChunkLen, self$2.padMaxChunkLen);
};
var getRawDigest = function (heap, padMaxChunkLen) {
var io = new Int32Array(heap, padMaxChunkLen + 320, 5);
var out = new Int32Array(5);
var arr = new DataView(out.buffer);
arr.setInt32(0, io[0], false);
arr.setInt32(4, io[1], false);
arr.setInt32(8, io[2], false);
arr.setInt32(12, io[3], false);
arr.setInt32(16, io[4], false);
return out;
};
var // Calculate the hash digest as an array of 5 32bit integers.
rawDigest = this.rawDigest = function (str) {
var msgLen = str.byteLength || str.length || str.size || 0;
initState(self$2.heap, self$2.padMaxChunkLen);
var chunkOffset = 0, chunkLen = self$2.maxChunkLen, last;
for (chunkOffset = 0; msgLen > chunkOffset + chunkLen; chunkOffset += chunkLen) {
coreCall(str, chunkOffset, chunkLen, msgLen, false);
}
coreCall(str, chunkOffset, msgLen - chunkOffset, msgLen, true);
return getRawDigest(self$2.heap, self$2.padMaxChunkLen);
};
// The digest and digestFrom* interface returns the hash digest
// as a hex string.
this.digest = this.digestFromString = this.digestFromBuffer = this.digestFromArrayBuffer = function (str) {
return hex(rawDigest(str).buffer);
};
}
;
// The low-level RushCore module provides the heart of Rusha,
// a high-speed sha1 implementation working on an Int32Array heap.
// At first glance, the implementation seems complicated, however
// with the SHA1 spec at hand, it is obvious this almost a textbook
// implementation that has a few functions hand-inlined and a few loops
// hand-unrolled.
Rusha._core = function RushaCore(stdlib, foreign, heap) {
'use asm';
var H = new stdlib.Int32Array(heap);
function hash(k, x) {
// k in bytes
k = k | 0;
x = x | 0;
var i = 0, j = 0, y0 = 0, z0 = 0, y1 = 0, z1 = 0, y2 = 0, z2 = 0, y3 = 0, z3 = 0, y4 = 0, z4 = 0, t0 = 0, t1 = 0;
y0 = H[x + 320 >> 2] | 0;
y1 = H[x + 324 >> 2] | 0;
y2 = H[x + 328 >> 2] | 0;
y3 = H[x + 332 >> 2] | 0;
y4 = H[x + 336 >> 2] | 0;
for (i = 0; (i | 0) < (k | 0); i = i + 64 | 0) {
z0 = y0;
z1 = y1;
z2 = y2;
z3 = y3;
z4 = y4;
for (j = 0; (j | 0) < 64; j = j + 4 | 0) {
t1 = H[i + j >> 2] | 0;
t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | ~y1 & y3) | 0) + ((t1 + y4 | 0) + 1518500249 | 0) | 0;
y4 = y3;
y3 = y2;
y2 = y1 << 30 | y1 >>> 2;
y1 = y0;
y0 = t0;
H[k + j >> 2] = t1;
}
for (j = k + 64 | 0; (j | 0) < (k + 80 | 0); j = j + 4 | 0) {
t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31;
t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | ~y1 & y3) | 0) + ((t1 + y4 | 0) + 1518500249 | 0) | 0;
y4 = y3;
y3 = y2;
y2 = y1 << 30 | y1 >>> 2;
y1 = y0;
y0 = t0;
H[j >> 2] = t1;
}
for (j = k + 80 | 0; (j | 0) < (k + 160 | 0); j = j + 4 | 0) {
t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31;
t0 = ((y0 << 5 | y0 >>> 27) + (y1 ^ y2 ^ y3) | 0) + ((t1 + y4 | 0) + 1859775393 | 0) | 0;
y4 = y3;
y3 = y2;
y2 = y1 << 30 | y1 >>> 2;
y1 = y0;
y0 = t0;
H[j >> 2] = t1;
}
for (j = k + 160 | 0; (j | 0) < (k + 240 | 0); j = j + 4 | 0) {
t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31;
t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | y1 & y3 | y2 & y3) | 0) + ((t1 + y4 | 0) - 1894007588 | 0) | 0;
y4 = y3;
y3 = y2;
y2 = y1 << 30 | y1 >>> 2;
y1 = y0;
y0 = t0;
H[j >> 2] = t1;
}
for (j = k + 240 | 0; (j | 0) < (k + 320 | 0); j = j + 4 | 0) {
t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31;
t0 = ((y0 << 5 | y0 >>> 27) + (y1 ^ y2 ^ y3) | 0) + ((t1 + y4 | 0) - 899497514 | 0) | 0;
y4 = y3;
y3 = y2;
y2 = y1 << 30 | y1 >>> 2;
y1 = y0;
y0 = t0;
H[j >> 2] = t1;
}
y0 = y0 + z0 | 0;
y1 = y1 + z1 | 0;
y2 = y2 + z2 | 0;
y3 = y3 + z3 | 0;
y4 = y4 + z4 | 0;
}
H[x + 320 >> 2] = y0;
H[x + 324 >> 2] = y1;
H[x + 328 >> 2] = y2;
H[x + 332 >> 2] = y3;
H[x + 336 >> 2] = y4;
}
return { hash: hash };
};
if (// If we'e running in Node.JS, export a module.
typeof module !== 'undefined') {
module.exports = Rusha;
} else if (// If we're running in a DOM context, export
// the Rusha object to toplevel.
typeof window !== 'undefined') {
window.Rusha = Rusha;
}
if (// If we're running in a webworker, accept
// messages containing a jobid and a buffer
// or blob object, and return the hash result.
typeof FileReaderSync !== 'undefined') {
var reader = new FileReaderSync(), hasher = new Rusha(4 * 1024 * 1024);
self.onmessage = function onMessage(event) {
var hash, data = event.data.data;
try {
hash = hasher.digest(data);
self.postMessage({
id: event.data.id,
hash: hash
});
} catch (e) {
self.postMessage({
id: event.data.id,
error: e.name
});
}
};
}
}());
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],172:[function(require,module,exports){
var tick = 1
var maxTick = 65535
var resolution = 4
var inc = function () {
tick = (tick + 1) & maxTick
}
var timer = setInterval(inc, (1000 / resolution) | 0)
if (timer.unref) timer.unref()
module.exports = function (seconds) {
var size = resolution * (seconds || 5)
var buffer = [0]
var pointer = 1
var last = (tick - 1) & maxTick
return function (delta) {
var dist = (tick - last) & maxTick
if (dist > size) dist = size
last = tick
while (dist--) {
if (pointer === size) pointer = 0
buffer[pointer] = buffer[pointer === 0 ? size - 1 : pointer - 1]
pointer++
}
if (delta) buffer[pointer - 1] += delta
var top = buffer[pointer - 1]
var btm = buffer.length < size ? 0 : buffer[pointer === size ? 0 : pointer]
return buffer.length < resolution ? top : (top - btm) * resolution / buffer.length
}
}
},{}],173:[function(require,module,exports){
/* global URL */
var getBlob = require('stream-to-blob')
module.exports = function getBlobURL (stream, mimeType, cb) {
if (typeof mimeType === 'function') return getBlobURL(stream, null, mimeType)
getBlob(stream, mimeType, function (err, blob) {
if (err) return cb(err)
var url = URL.createObjectURL(blob)
cb(null, url)
})
}
},{"stream-to-blob":174}],174:[function(require,module,exports){
/* global Blob */
var once = require('once')
module.exports = function getBlob (stream, mimeType, cb) {
if (typeof mimeType === 'function') return getBlob(stream, null, mimeType)
cb = once(cb)
var chunks = []
stream
.on('data', function (chunk) {
chunks.push(chunk)
})
.on('end', function () {
var blob = mimeType
? new Blob(chunks, { type: mimeType })
: new Blob(chunks)
cb(null, blob)
})
.on('error', cb)
}
},{"once":176}],175:[function(require,module,exports){
arguments[4][10][0].apply(exports,arguments)
},{"dup":10}],176:[function(require,module,exports){
arguments[4][11][0].apply(exports,arguments)
},{"dup":11,"wrappy":175}],177:[function(require,module,exports){
(function (Buffer){
var once = require('once')
module.exports = function getBuffer (stream, length, cb) {
cb = once(cb)
var buf = new Buffer(length)
var offset = 0
stream
.on('data', function (chunk) {
chunk.copy(buf, offset)
offset += chunk.length
})
.on('end', function () { cb(null, buf) })
.on('error', cb)
}
}).call(this,require("buffer").Buffer)
},{"buffer":21,"once":179}],178:[function(require,module,exports){
arguments[4][10][0].apply(exports,arguments)
},{"dup":10}],179:[function(require,module,exports){
arguments[4][11][0].apply(exports,arguments)
},{"dup":11,"wrappy":178}],180:[function(require,module,exports){
(function (process){
module.exports = Discovery
var debug = require('debug')('torrent-discovery')
var DHT = require('bittorrent-dht/client') // empty object in browser
var EventEmitter = require('events').EventEmitter
var extend = require('xtend')
var inherits = require('inherits')
var parallel = require('run-parallel')
var Tracker = require('bittorrent-tracker/client')
inherits(Discovery, EventEmitter)
function Discovery (opts) {
var self = this
if (!(self instanceof Discovery)) return new Discovery(opts)
EventEmitter.call(self)
if (!opts.peerId) throw new Error('Option `peerId` is required')
if (!opts.infoHash) throw new Error('Option `infoHash` is required')
if (!process.browser && !opts.port) throw new Error('Option `port` is required')
self.peerId = typeof opts.peerId === 'string'
? opts.peerId
: opts.peerId.toString('hex')
self.infoHash = typeof opts.infoHash === 'string'
? opts.infoHash
: opts.infoHash.toString('hex')
self._port = opts.port // torrent port
self.destroyed = false
self._announce = opts.announce || []
self._intervalMs = opts.intervalMs || (15 * 60 * 1000)
self._trackerOpts = null
self._dhtAnnouncing = false
self._dhtTimeout = false
self._internalDHT = false // is the DHT created internally?
self._onWarning = function (err) {
self.emit('warning', err)
}
self._onError = function (err) {
self.emit('error', err)
}
self._onDHTPeer = function (peer, infoHash) {
if (infoHash.toString('hex') !== self.infoHash) return
self.emit('peer', peer.host + ':' + peer.port)
}
self._onTrackerPeer = function (peer) {
self.emit('peer', peer)
}
self._onTrackerAnnounce = function () {
self.emit('trackerAnnounce')
}
if (opts.tracker === false) {
self.tracker = null
} else if (opts.tracker && typeof opts.tracker === 'object') {
self._trackerOpts = extend(opts.tracker)
self.tracker = self._createTracker()
} else {
self.tracker = self._createTracker()
}
if (opts.dht === false || typeof DHT !== 'function') {
self.dht = null
} else if (opts.dht && typeof opts.dht.addNode === 'function') {
self.dht = opts.dht
} else if (opts.dht && typeof opts.dht === 'object') {
self.dht = createDHT(opts.dhtPort, opts.dht)
} else {
self.dht = createDHT(opts.dhtPort)
}
if (self.dht) {
self.dht.on('peer', self._onDHTPeer)
self._dhtAnnounce()
}
function createDHT (port, opts) {
var dht = new DHT(opts)
dht.on('warning', self._onWarning)
dht.on('error', self._onError)
dht.listen(port)
self._internalDHT = true
return dht
}
}
Discovery.prototype.updatePort = function (port) {
var self = this
if (port === self._port) return
self._port = port
if (self.dht) self._dhtAnnounce()
if (self.tracker) {
self.tracker.stop()
self.tracker.destroy(function () {
self.tracker = self._createTracker()
})
}
}
Discovery.prototype.complete = function (opts) {
if (this.tracker) {
this.tracker.complete(opts)
}
}
Discovery.prototype.destroy = function (cb) {
var self = this
if (self.destroyed) return
self.destroyed = true
clearTimeout(self._dhtTimeout)
var tasks = []
if (self.tracker) {
self.tracker.stop()
self.tracker.removeListener('warning', self._onWarning)
self.tracker.removeListener('error', self._onError)
self.tracker.removeListener('peer', self._onTrackerPeer)
self.tracker.removeListener('update', self._onTrackerAnnounce)
tasks.push(function (cb) {
self.tracker.destroy(cb)
})
}
if (self.dht) {
self.dht.removeListener('peer', self._onDHTPeer)
}
if (self._internalDHT) {
self.dht.removeListener('warning', self._onWarning)
self.dht.removeListener('error', self._onError)
tasks.push(function (cb) {
self.dht.destroy(cb)
})
}
parallel(tasks, cb)
// cleanup
self.dht = null
self.tracker = null
self._announce = null
}
Discovery.prototype._createTracker = function () {
var opts = extend(this._trackerOpts, {
infoHash: this.infoHash,
announce: this._announce,
peerId: this.peerId,
port: this._port
})
var tracker = new Tracker(opts)
tracker.on('warning', this._onWarning)
tracker.on('error', this._onError)
tracker.on('peer', this._onTrackerPeer)
tracker.on('update', this._onTrackerAnnounce)
tracker.setInterval(this._intervalMs)
tracker.start()
return tracker
}
Discovery.prototype._dhtAnnounce = function () {
var self = this
if (self._dhtAnnouncing) return
debug('dht announce')
self._dhtAnnouncing = true
clearTimeout(self._dhtTimeout)
self.dht.announce(self.infoHash, self._port, function (err) {
self._dhtAnnouncing = false
debug('dht announce complete')
if (err) self.emit('warning', err)
self.emit('dhtAnnounce')
if (!self.destroyed) {
self._dhtTimeout = setTimeout(function () {
self._dhtAnnounce()
}, getRandomTimeout())
if (self._dhtTimeout.unref) self._dhtTimeout.unref()
}
})
// Returns timeout interval, with some random jitter
function getRandomTimeout () {
return self._intervalMs + Math.floor(Math.random() * self._intervalMs / 5)
}
}
}).call(this,require('_process'))
},{"_process":29,"bittorrent-dht/client":20,"bittorrent-tracker/client":3,"debug":150,"events":25,"inherits":63,"run-parallel":164,"xtend":188}],181:[function(require,module,exports){
(function (Buffer){
module.exports = Piece
var BLOCK_LENGTH = 1 << 14
function Piece (length) {
if (!(this instanceof Piece)) return new Piece(length)
this.length = length
this.missing = length
this.sources = null
this._chunks = Math.ceil(length / BLOCK_LENGTH)
this._remainder = (length % BLOCK_LENGTH) || BLOCK_LENGTH
this._buffered = 0
this._buffer = null
this._cancellations = null
this._reservations = 0
this._flushed = false
}
Piece.BLOCK_LENGTH = BLOCK_LENGTH
Piece.prototype.chunkLength = function (i) {
return i === this._chunks - 1 ? this._remainder : BLOCK_LENGTH
}
Piece.prototype.chunkLengthRemaining = function (i) {
return this.length - (i * BLOCK_LENGTH)
}
Piece.prototype.chunkOffset = function (i) {
return i * BLOCK_LENGTH
}
Piece.prototype.reserve = function () {
if (!this.init()) return -1
if (this._cancellations.length) return this._cancellations.pop()
if (this._reservations < this._chunks) return this._reservations++
return -1
}
Piece.prototype.reserveRemaining = function () {
if (!this.init()) return -1
if (this._reservations < this._chunks) {
var min = this._reservations
this._reservations = this._chunks
return min
}
return -1
}
Piece.prototype.cancel = function (i) {
if (!this.init()) return
this._cancellations.push(i)
}
Piece.prototype.cancelRemaining = function (i) {
if (!this.init()) return
this._reservations = i
}
Piece.prototype.get = function (i) {
if (!this.init()) return null
return this._buffer[i]
}
Piece.prototype.set = function (i, data, source) {
if (!this.init()) return false
var len = data.length
var blocks = Math.ceil(len / BLOCK_LENGTH)
for (var j = 0; j < blocks; j++) {
if (!this._buffer[i + j]) {
var offset = j * BLOCK_LENGTH
var splitData = data.slice(offset, offset + BLOCK_LENGTH)
this._buffered++
this._buffer[i + j] = splitData
this.missing -= splitData.length
if (this.sources.indexOf(source) === -1) {
this.sources.push(source)
}
}
}
return this._buffered === this._chunks
}
Piece.prototype.flush = function () {
if (!this._buffer || this._chunks !== this._buffered) return null
var buffer = Buffer.concat(this._buffer, this.length)
this._buffer = null
this._cancellations = null
this.sources = null
this._flushed = true
return buffer
}
Piece.prototype.init = function () {
if (this._flushed) return false
if (this._buffer) return true
this._buffer = new Array(this._chunks)
this._cancellations = []
this.sources = []
return true
}
}).call(this,require("buffer").Buffer)
},{"buffer":21}],182:[function(require,module,exports){
arguments[4][16][0].apply(exports,arguments)
},{"dup":16}],183:[function(require,module,exports){
module.exports = remove
function remove (arr, i) {
if (i >= arr.length || i < 0) return
var last = arr.pop()
if (i < arr.length) {
var tmp = arr[i]
arr[i] = last
return tmp
}
return last
}
},{}],184:[function(require,module,exports){
var bencode = require('bencode')
var BitField = require('bitfield')
var Buffer = require('safe-buffer').Buffer
var debug = require('debug')('ut_metadata')
var EventEmitter = require('events').EventEmitter
var inherits = require('inherits')
var sha1 = require('simple-sha1')
var MAX_METADATA_SIZE = 10000000 // 10MB
var BITFIELD_GROW = 1000
var PIECE_LENGTH = 16 * 1024
module.exports = function (metadata) {
inherits(utMetadata, EventEmitter)
function utMetadata (wire) {
EventEmitter.call(this)
this._wire = wire
this._metadataComplete = false
this._metadataSize = null
this._remainingRejects = null // how many reject messages to tolerate before quitting
this._fetching = false
// The largest .torrent file that I know of is ~1-2MB, which is ~100 pieces.
// Therefore, cap the bitfield to 10x that (1000 pieces) so a malicious peer can't
// make it grow to fill all memory.
this._bitfield = new BitField(0, { grow: BITFIELD_GROW })
if (Buffer.isBuffer(metadata)) {
this.setMetadata(metadata)
}
}
// Name of the bittorrent-protocol extension
utMetadata.prototype.name = 'ut_metadata'
utMetadata.prototype.onHandshake = function (infoHash, peerId, extensions) {
this._infoHash = infoHash
}
utMetadata.prototype.onExtendedHandshake = function (handshake) {
if (!handshake.m || !handshake.m.ut_metadata) {
return this.emit('warning', new Error('Peer does not support ut_metadata'))
}
if (!handshake.metadata_size) {
return this.emit('warning', new Error('Peer does not have metadata'))
}
if (typeof handshake.metadata_size !== 'number' ||
MAX_METADATA_SIZE < handshake.metadata_size ||
handshake.metadata_size <= 0) {
return this.emit('warning', new Error('Peer gave invalid metadata size'))
}
this._metadataSize = handshake.metadata_size
this._numPieces = Math.ceil(this._metadataSize / PIECE_LENGTH)
this._remainingRejects = this._numPieces * 2
if (this._fetching) {
this._requestPieces()
}
}
utMetadata.prototype.onMessage = function (buf) {
var dict, trailer
try {
var str = buf.toString()
var trailerIndex = str.indexOf('ee') + 2
dict = bencode.decode(str.substring(0, trailerIndex))
trailer = buf.slice(trailerIndex)
} catch (err) {
// drop invalid messages
return
}
switch (dict.msg_type) {
case 0:
// ut_metadata request (from peer)
// example: { 'msg_type': 0, 'piece': 0 }
this._onRequest(dict.piece)
break
case 1:
// ut_metadata data (in response to our request)
// example: { 'msg_type': 1, 'piece': 0, 'total_size': 3425 }
this._onData(dict.piece, trailer, dict.total_size)
break
case 2:
// ut_metadata reject (peer doesn't have piece we requested)
// { 'msg_type': 2, 'piece': 0 }
this._onReject(dict.piece)
break
}
}
/**
* Ask the peer to send metadata.
* @public
*/
utMetadata.prototype.fetch = function () {
if (this._metadataComplete) {
return
}
this._fetching = true
if (this._metadataSize) {
this._requestPieces()
}
}
/**
* Stop asking the peer to send metadata.
* @public
*/
utMetadata.prototype.cancel = function () {
this._fetching = false
}
utMetadata.prototype.setMetadata = function (metadata) {
if (this._metadataComplete) return true
debug('set metadata')
// if full torrent dictionary was passed in, pull out just `info` key
try {
var info = bencode.decode(metadata).info
if (info) {
metadata = bencode.encode(info)
}
} catch (err) {}
// check hash
if (this._infoHash && this._infoHash !== sha1.sync(metadata)) {
return false
}
this.cancel()
this.metadata = metadata
this._metadataComplete = true
this._metadataSize = this.metadata.length
this._wire.extendedHandshake.metadata_size = this._metadataSize
this.emit('metadata', bencode.encode({ info: bencode.decode(this.metadata) }))
return true
}
utMetadata.prototype._send = function (dict, trailer) {
var buf = bencode.encode(dict)
if (Buffer.isBuffer(trailer)) {
buf = Buffer.concat([buf, trailer])
}
this._wire.extended('ut_metadata', buf)
}
utMetadata.prototype._request = function (piece) {
this._send({ msg_type: 0, piece: piece })
}
utMetadata.prototype._data = function (piece, buf, totalSize) {
var msg = { msg_type: 1, piece: piece }
if (typeof totalSize === 'number') {
msg.total_size = totalSize
}
this._send(msg, buf)
}
utMetadata.prototype._reject = function (piece) {
this._send({ msg_type: 2, piece: piece })
}
utMetadata.prototype._onRequest = function (piece) {
if (!this._metadataComplete) {
this._reject(piece)
return
}
var start = piece * PIECE_LENGTH
var end = start + PIECE_LENGTH
if (end > this._metadataSize) {
end = this._metadataSize
}
var buf = this.metadata.slice(start, end)
this._data(piece, buf, this._metadataSize)
}
utMetadata.prototype._onData = function (piece, buf, totalSize) {
if (buf.length > PIECE_LENGTH) {
return
}
buf.copy(this.metadata, piece * PIECE_LENGTH)
this._bitfield.set(piece)
this._checkDone()
}
utMetadata.prototype._onReject = function (piece) {
if (this._remainingRejects > 0 && this._fetching) {
// If we haven't been rejected too much, then try to request the piece again
this._request(piece)
this._remainingRejects -= 1
} else {
this.emit('warning', new Error('Peer sent "reject" too much'))
}
}
utMetadata.prototype._requestPieces = function () {
this.metadata = Buffer.alloc(this._metadataSize)
for (var piece = 0; piece < this._numPieces; piece++) {
this._request(piece)
}
}
utMetadata.prototype._checkDone = function () {
var done = true
for (var piece = 0; piece < this._numPieces; piece++) {
if (!this._bitfield.get(piece)) {
done = false
break
}
}
if (!done) return
// attempt to set metadata -- may fail sha1 check
var success = this.setMetadata(this.metadata)
if (!success) {
this._failedMetadata()
}
}
utMetadata.prototype._failedMetadata = function () {
// reset bitfield & try again
this._bitfield = new BitField(0, { grow: BITFIELD_GROW })
this._remainingRejects -= this._numPieces
if (this._remainingRejects > 0) {
this._requestPieces()
} else {
this.emit('warning', new Error('Peer sent invalid metadata'))
}
}
return utMetadata
}
},{"bencode":187,"bitfield":141,"debug":150,"events":25,"inherits":63,"safe-buffer":165,"simple-sha1":170}],185:[function(require,module,exports){
(function (Buffer){
/**
* Decodes bencoded data.
*
* @param {Buffer} data
* @param {Number} start (optional)
* @param {Number} end (optional)
* @param {String} encoding (optional)
* @return {Object|Array|Buffer|String|Number}
*/
function decode (data, start, end, encoding) {
if (typeof start !== 'number' && encoding == null) {
encoding = start
start = undefined
}
if (typeof end !== 'number' && encoding == null) {
encoding = end
end = undefined
}
decode.position = 0
decode.encoding = encoding || null
decode.data = !(Buffer.isBuffer(data))
? new Buffer(data)
: data.slice(start, end)
decode.bytes = decode.data.length
return decode.next()
}
decode.bytes = 0
decode.position = 0
decode.data = null
decode.encoding = null
decode.next = function () {
switch (decode.data[decode.position]) {
case 0x64:
return decode.dictionary()
case 0x6C:
return decode.list()
case 0x69:
return decode.integer()
default:
return decode.buffer()
}
}
decode.find = function (chr) {
var i = decode.position
var c = decode.data.length
var d = decode.data
while (i < c) {
if (d[i] === chr) return i
i++
}
throw new Error(
'Invalid data: Missing delimiter "' +
String.fromCharCode(chr) + '" [0x' +
chr.toString(16) + ']'
)
}
decode.dictionary = function () {
decode.position++
var dict = {}
while (decode.data[decode.position] !== 0x65) {
dict[decode.buffer()] = decode.next()
}
decode.position++
return dict
}
decode.list = function () {
decode.position++
var lst = []
while (decode.data[decode.position] !== 0x65) {
lst.push(decode.next())
}
decode.position++
return lst
}
decode.integer = function () {
var end = decode.find(0x65)
var number = decode.data.toString('ascii', decode.position + 1, end)
decode.position += end + 1 - decode.position
return parseInt(number, 10)
}
decode.buffer = function () {
var sep = decode.find(0x3A)
var length = parseInt(decode.data.toString('ascii', decode.position, sep), 10)
var end = ++sep + length
decode.position = end
return decode.encoding
? decode.data.toString(decode.encoding, sep, end)
: decode.data.slice(sep, end)
}
module.exports = decode
}).call(this,require("buffer").Buffer)
},{"buffer":21}],186:[function(require,module,exports){
(function (Buffer){
/**
* Encodes data in bencode.
*
* @param {Buffer|Array|String|Object|Number|Boolean} data
* @return {Buffer}
*/
function encode (data, buffer, offset) {
var buffers = []
var result = null
encode._encode(buffers, data)
result = Buffer.concat(buffers)
encode.bytes = result.length
if (Buffer.isBuffer(buffer)) {
result.copy(buffer, offset)
return buffer
}
return result
}
encode.bytes = -1
encode._floatConversionDetected = false
encode._encode = function (buffers, data) {
if (Buffer.isBuffer(data)) {
buffers.push(new Buffer(data.length + ':'))
buffers.push(data)
return
}
switch (typeof data) {
case 'string':
encode.buffer(buffers, data)
break
case 'number':
encode.number(buffers, data)
break
case 'object':
data.constructor === Array
? encode.list(buffers, data)
: encode.dict(buffers, data)
break
case 'boolean':
encode.number(buffers, data ? 1 : 0)
break
}
}
var buffE = new Buffer('e')
var buffD = new Buffer('d')
var buffL = new Buffer('l')
encode.buffer = function (buffers, data) {
buffers.push(new Buffer(Buffer.byteLength(data) + ':' + data))
}
encode.number = function (buffers, data) {
var maxLo = 0x80000000
var hi = (data / maxLo) << 0
var lo = (data % maxLo) << 0
var val = hi * maxLo + lo
buffers.push(new Buffer('i' + val + 'e'))
if (val !== data && !encode._floatConversionDetected) {
encode._floatConversionDetected = true
console.warn(
'WARNING: Possible data corruption detected with value "' + data + '":',
'Bencoding only defines support for integers, value was converted to "' + val + '"'
)
console.trace()
}
}
encode.dict = function (buffers, data) {
buffers.push(buffD)
var j = 0
var k
// fix for issue #13 - sorted dicts
var keys = Object.keys(data).sort()
var kl = keys.length
for (; j < kl; j++) {
k = keys[j]
encode.buffer(buffers, k)
encode._encode(buffers, data[k])
}
buffers.push(buffE)
}
encode.list = function (buffers, data) {
var i = 0
var c = data.length
buffers.push(buffL)
for (; i < c; i++) {
encode._encode(buffers, data[i])
}
buffers.push(buffE)
}
module.exports = encode
}).call(this,require("buffer").Buffer)
},{"buffer":21}],187:[function(require,module,exports){
arguments[4][46][0].apply(exports,arguments)
},{"./decode":185,"./encode":186,"dup":46}],188:[function(require,module,exports){
arguments[4][17][0].apply(exports,arguments)
},{"dup":17}],189:[function(require,module,exports){
arguments[4][18][0].apply(exports,arguments)
},{"dup":18}],190:[function(require,module,exports){
/**
* Given a number, return a zero-filled string.
* From http://stackoverflow.com/questions/1267283/
* @param {number} width
* @param {number} number
* @return {string}
*/
module.exports = function zeroFill (width, number, pad) {
if (number === undefined) {
return function (number, pad) {
return zeroFill(width, number, pad)
}
}
if (pad === undefined) pad = '0'
width -= number.toString().length
if (width > 0) return new Array(width + (/\./.test(number) ? 2 : 1)).join(pad) + number
return number + ''
}
},{}],191:[function(require,module,exports){
module.exports={"version":"0.94.4"}
},{}],192:[function(require,module,exports){
(function (Buffer){
'use strict';
var http = require('http');
var MultiStream = require('multistream');
var util = require('util');
var readableStream = require('readable-stream');
var Videostream = require('videostream');
var ut_pex = require('ut_pex');
var WebTorrent = require('webtorrent');
var SimplePeer = require('simple-peer');
module.exports = OakStreaming;
function OakStreaming(OakName) {
var self = this;
(function () {
var OakName = OakName || Math.floor(Math.random() * Math.pow(10, 300) + 1);
// Every method should have access to these variables.
// Therefore, they are defined at this high scope.
var simplePeerCreationCounter = 0;
var connectionsWaitingForSignalingData = [];
var theTorrentSession = null;
var wtorrentFile = null; // WebTorrent API object which represents the respective shared (video) file.
var peersToAdd = [];
var bytesReceivedFromServer = 0;
var notificationsBecauseNewWire = 0;
var SIZE_VIDEO_FILE = 0;
var webtorrentClient = null;
self.destroy = function (callback) {
if (webtorrentClient) {
webtorrentClient.destroy(function (err) {
if (err) {
console.log("ERROR: " + err.message);
}
if (callback) {
callback();
}
});
} else {
if (callback) {
callback();
}
}
};
// Only methods should be part of the OakStreaming API, i.e. only methods should be publically accessible.
// The OakStreaming API comprises only the OakStreaming constructor and all public methods of the object that
// the constructor creates. In this paragraph, all keys (i.e. properties) of the object that the OakStreaming
// constructor creates are set.
self.create_stream = create_stream;
self.receive_stream = receive_stream;
self.forTesting_connectedToNewWtorrentPeer = null;
// The methods whose name begin with "get" return statistical data about the streaming session.
// A (new) streaming session begins when the create_stream or receive_stream method is called.
self.get_number_of_bytes_downloaded_from_server = function () {
return bytesReceivedFromServer;
};
self.get_number_of_bytes_downloaded_P2P = function () {
if (theTorrentSession) {
return theTorrentSession.downloaded;
} else {
return 0;
}
};
// For testing
self.get_size_of_swarm = function () {
if (theTorrentSession) {
return theTorrentSession.numPeers;
} else {
return -1;
}
};
self.get_number_of_bytes_uploaded_P2P = function () {
if (theTorrentSession) {
return theTorrentSession.uploaded;
} else {
return 0;
}
};
self.get_percentage_downloaded_of_torrent = function () {
if (theTorrentSession) {
return theTorrentSession.progress;
} else {
return 0;
}
};
self.get_file_size = function () {
return SIZE_VIDEO_FILE;
};
self.signaling1 = function (callback) {
var alreadyCalledCallback = false;
var oakNumber = simplePeerCreationCounter;
simplePeerCreationCounter++;
connectionsWaitingForSignalingData[oakNumber] = new SimplePeer({ initiator: true,
trickle: false, config: { iceServers: [{ url: 'stun:23.21.150.121' }] } });
connectionsWaitingForSignalingData[oakNumber].on('signal', function (signalingData) {
if (!alreadyCalledCallback) {
alreadyCalledCallback = true;
signalingData.oakNumber = oakNumber;
callback(signalingData);
}
});
};
// This method creates (WebRTC-)signaling data as a response to signaling data of a signaling1 call of
// another OakStreaming instance. This method returns new (WebRTC-)signaling data which has to be put into
// signaling3 method of the OakStreaming instance which created the original signaling data.
self.signaling2 = function (signalingData, callback) {
var oakNumber = signalingData.oakNumber;
signalingData.oakNumber = undefined;
var simplePeer = new SimplePeer({ initiator: false, trickle: false, config: {
iceServers: [{ url: 'stun:23.21.150.121' }] } });
var index = simplePeerCreationCounter;
simplePeerCreationCounter++;
connectionsWaitingForSignalingData[index] = simplePeer;
simplePeer.on('signal', function (answerSignalingData) {
answerSignalingData.oakNumber = oakNumber;
callback(answerSignalingData);
});
simplePeer.signal(signalingData);
simplePeer.on('connect', function () {
addP2pConnectionToWtorrent(connectionsWaitingForSignalingData[index], function () {});
connectionsWaitingForSignalingData[index] = undefined;
});
};
// This method finally establishes a WebRTC connection between both OakStreaming instances.
// From now on, both OakStreaming instances exchange video fragments.
self.signaling3 = function (signalingData, callback) {
var oakNumber = signalingData.oakNumber;
signalingData.oakNumber = undefined;
connectionsWaitingForSignalingData[oakNumber].on('connect', function () {
addP2pConnectionToWtorrent(connectionsWaitingForSignalingData[oakNumber]);
connectionsWaitingForSignalingData[oakNumber] = undefined;
if (callback) {
callback();
}
});
connectionsWaitingForSignalingData[oakNumber].signal(signalingData);
};
function create_stream() {
var video_file;
var options = {};
var callback = function callback() {};
var returnTorrent = "";
var destroyTorrent = false;
// In order to enable that all but the callback parameter (i.e. the third parameter) of the create_stream method
// are optional, the arguments variable has to be read.
if (arguments[0].name || arguments[0].items || arguments[0].length || arguments[0].read) {
video_file = arguments[0];
if (typeof arguments[1] !== 'function') {
options = arguments[1];
callback = arguments[2];
if (arguments[3] === "Return torrent") {
returnTorrent = arguments[3];
destroyTorrent = arguments[4] || false;
} else {
returnTorrent = "No";
destroyTorrent = arguments[3];
}
} else {
callback = arguments[1];
if (arguments[2] === "Return torrent") {
returnTorrent = arguments[2];
destroyTorrent = arguments[3] || false;
} else {
returnTorrent = "No";
destroyTorrent = arguments[2];
}
}
} else {
options = arguments[0];
callback = arguments[1];
if (arguments[2] === "Return torrent") {
returnTorrent = arguments[2];
destroyTorrent = arguments[3] || false;
} else {
returnTorrent = "No";
destroyTorrent = arguments[2];
}
}
var streamTicket = options;
if (!streamTicket.path_to_file_on_web_server) {
streamTicket.path_to_file_on_web_server = "/" + video_file.name;
}
// The web_server_URL parameter gets parsed such that it can later easily be used for
// XML HTTP Requests (XHRs) commands of the Node.js http module.
if (streamTicket.web_server_URL === false) {
streamTicket.xhr_hostname = false;
} else if (streamTicket.web_server_URL === undefined) {
streamTicket.xhr_hostname = undefined;
} else if (streamTicket.web_server_URL) {
var xhr_hostname = "";
var xhr_port = -1;
var portNumberAsString = "";
if (streamTicket.web_server_URL.indexOf("]") === -1) {
// In this case, the URL does not contain a IPv6 address.
if (streamTicket.web_server_URL.indexOf("http://") === 0) {
xhr_hostname = streamTicket.web_server_URL.substring(7);
} else {
xhr_hostname = streamTicket.web_server_URL;
}
if (xhr_hostname.lastIndexOf(":") === -1) {
xhr_port = 80;
} else {
portNumberAsString = xhr_hostname.substring(xhr_hostname.lastIndexOf(":") + 1);
xhr_port = parseInt(portNumberAsString, 10);
xhr_hostname = xhr_hostname.substring(0, xhr_hostname.lastIndexOf(":"));
}
} else {
// In this case, the URL contains a IPv6 address.
if (streamTicket.web_server_URL.indexOf("http://") === 0) {
xhr_hostname = streamTicket.web_server_URL.substring(7);
} else {
xhr_hostname = streamTicket.web_server_URL;
}
var indexOfClosingBracket = xhr_hostname.lastIndexOf("]");
if (charAt(indexOfClosingBracket + 1) === ":") {
portNumberAsString = xhr_hostname.substring(indexOfClosingBracket + 2);
xhr_port = parseInt(portNumberAsString, 10);
} else {
xhr_port = 80;
}
}
streamTicket.xhr_hostname = xhr_hostname;
streamTicket.xhr_port = xhr_port;
}
webtorrentClient = new WebTorrent({ dht: false, tracker: true });
webtorrentClient.on('error', function (err) {
console.log("ERROR: " + err.message);
});
if (video_file) {
var seedingOptions = {
name: video_file.name + " - (Created by an OakStreaming client)"
};
// In contrast to the OakStreaming library, the WebTorrent library expects an array of arrays of
// WebTorrent trackers.
if (options.webTorrent_trackers) {
var myAnounceList = [];
for (var k = 0; k < options.webTorrent_trackers.length; k++) {
myAnounceList.push([options.webTorrent_trackers[k]]);
}
seedingOptions.announceList = myAnounceList;
} else {
if (options.webTorrent_trackers === undefined) {
// In this case, we use default tracking servers.
seedingOptions.announceList = [["wss://tracker.webtorrent.io"], ["wss://tracker.openwebtorrent.com"], ["wss://tracker.fastcast.nz"], ["wss://tracker.btorrent.xyz"]];
} else {
// In this case, no tracking server will be used and consequently the user of the library
// has to use the signaling1, signaling2 and signaling3 method to connect OakStreaming instances.
seedingOptions.announceList = [];
}
}
var self = this;
theTorrentSession = webtorrentClient.seed(video_file, seedingOptions, function onSeed(torrent) {
/* K42 Maybe I will need this later
var torrent_fileAsBlobURL = torrent.torrent_fileBlobURL;
var xhr = new XMLHttpRequest();
var XHROrMethodEndHappend = false;
xhr.open('GET', torrent_fileAsBlobURL, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
streamTicket.torrentAsBlob = this.response;
if(XHROrMethodEndHappend){
callback(streamTicket);
} else {
XHROrMethodEndHappend = true;
}
}
};
xhr.send();
*/
wtorrentFile = theTorrentSession.files[0];
streamTicket.torrent_file = torrent.torrentFile.toString('base64');
streamTicket.magnet_URI = torrent.magnet_URI;
streamTicket.infoHash = torrent.infoHash;
// If a large video files is seeded, WebTorrent creates several torrent.files entries for it.
SIZE_VIDEO_FILE = 0;
streamTicket.SIZE_VIDEO_FILE = 0;
for (var i = 0, length = torrent.files.length; i < length; i++) {
SIZE_VIDEO_FILE += torrent.files[i].length;
streamTicket.SIZE_VIDEO_FILE += torrent.files[i].length;
}
// var bufferTorrent = parseTorrent(streamTicket.parsedTorrent); K42
// If this OakStreaming instance is already connected to another peer, this function calls the callback
// function, which has been passed to it, immediately. Otherwise, the callback function gets called as soon as
// this OakStreaming instance connects to another peer.
self.forTesting_connectedToNewWtorrentPeer = function (callback) {
if (notificationsBecauseNewWire <= 0) {
notificationsBecauseNewWire--;
var callbackCalled = false;
torrent.on('wire', function (wire) {
if (!callbackCalled) {
callback();
callbackCalled = true;
}
});
} else {
notificationsBecauseNewWire--;
callback();
}
};
// This is necessary such that the forTesting_connectedToNewWtorrentPeer function knows how many peers
// are already connected to this OakStreaming instance.
torrent.on('wire', function (wire) {
notificationsBecauseNewWire++;
});
// For some Jasmine tests, it is appropriate that the torrentSession object gets destroyed immediately after
// the streamTicket has been created. The destruction of the torrentSession object stops the seeding.
if (returnTorrent === "Return torrent") {
if (destroyTorrent) {
notificationsBecauseNewWire = 0;
webtorrentClient.destroy();
} else {
callback(streamTicket, torrent);
}
} else {
callback(streamTicket);
}
});
theTorrentSession.on('error', function (err) {
console.log("ERROR: " + err.message);
});
// New peers can only be added to the swarm of torrentSession object, i.e. the set of peers that are used
// for video data exchange, when the infoHash of the torrentSession object has already been created.
if (theTorrentSession.infoHash) {
for (var j = 0; j < peersToAdd.length; j++) {
theTorrentSession.addPeer(peersToAdd[j][0]);
if (peersToAdd[j][1]) {
peersToAdd[j][1]();
}
peersToAdd.splice(j, 1);
j--;
}
} else {
theTorrentSession.on('infoHash', function () {
// Peers which used the offered methods to manually/explicitly connect to this OakStreaming instance
// before a torrent file has been loaded are added now to the swarm of the torrentSession object.
for (var j = 0; j < peersToAdd.length; j++) {
theTorrentSession.addPeer(peersToAdd[j][0]);
if (peersToAdd[j][1]) {
peersToAdd[j][1]();
}
peersToAdd.splice(j, 1);
j--;
}
});
theTorrentSession.on('metadata', function () {
// Peers which used the offered methods to manually connect to this OakStreaming instance
// before a torrent file was loaded are added now to the swarm of the torrentSession object.
for (var j = 0; j < peersToAdd.length; j++) {
theTorrentSession.addPeer(peersToAdd[j][0]);
if (peersToAdd[j][1]) {
peersToAdd[j][1]();
}
peersToAdd.splice(j, 1);
j--;
}
});
}
} else {
callback(streamTicket);
/* K42
if(XHROrMethodEndHappend){
callback(streamTicket);
} else {
XHROrMethodEndHappend = true;
}
*/
}
/* Nicht löschen!!!
function updateChart(){
if(theTorrentSession && wtorrentFile){
document.getElementById("WebTorrent-received").innerHTML = "wtorrentFile.length: " +
wtorrentFile.length + "\n torrent.uploaded: " + theTorrentSession.uploaded;
}
setTimeout(updateChart, 1000);
}
updateChart();
*/
}
// A function to start the video playback with a random time offset.
function waitStartPlayingOffset(streamTicket, callback, stopUploadingWhenVideoDownloaded) {
if (Date.now() - timeReceiptStreamInformationObject >= startPlayingOffset) {
timeLoadVideoMethodWasCalled = Date.now();
self.loadVideo(streamTicket, callback, stopUploadingWhenVideoDownloaded);
} else {
setTimeout(function () {
waitStartPlayingOffset(streamTicket, callback, stopUploadingWhenVideoDownloaded);
}, 10);
}
}
// In a Technical Evaluation, this method gets called instead of the receive_stream method.
function loadVideo_technical_evaluation(streamTicket, callback, stopUploadingWhenVideoDownloaded) {
timeReceiptStreamInformationObject = Date.now();
waitStartPlayingOffset(streamTicket, callback, stopUploadingWhenVideoDownloaded);
}
function receive_stream() {
/* This block of code is solely for conducting Technical Evaluations.
var timeLoadVideoMethodWasCalled = -42;
var timePlaybackWasStalled = 0;
var startUpTime = 0;
var timeTillTorrentOnDone = -42;
var startPlayingOffset = Math.floor(Math.random() * 10) + 1;
*/
// In order to enable that all but the streamTicket_object parameter (i.e. the first parameter) of the
// receive_stream method are optional, the arguments variable has to be read.
var streamTicket = arguments[0];
var htmlVideoTag = arguments[1];
var callback = function callback() {};
var stopUploadingWhenVideoDownloaded = false;
if (typeof arguments[2] === 'function') {
callback = arguments[2];
stopUploadingWhenVideoDownloaded = arguments[3];
} else {
callback = undefined;
stopUploadingWhenVideoDownloaded = arguments[2];
}
htmlVideoTag = document.getElementsByTagName('video')[0];
htmlVideoTag.addEventListener('error', function (err) {
console.log("ERROR: " + err.message);
});
/* This block of code is solely for conducting Technical Evaluations.
htmlVideoTag.onplay = function(){
console.log("event onplay is thrown");
play = true;
if(canplay){
startUpTime = Date.now() - timeLoadVideoMethodWasCalled;
timePlaybackWasStalled += startUpTime;
videoStartUpOver = true;
}
};
var userPausedVideo = false;
htmlVideoTag.pause = function(){
userPausedVideo = true;
};
htmlVideoTag.onwaiting = function() {
////console.log("Video is holded at " + (Date.now() - timeLoadVideoMethodWasCalled) +
" miliseconds after loadVideo has been called.");
lastTimeWhenVideoHolded = Date.now();
};
htmlVideoTag.onstalled = function() {
////console.log("Video is stalled at " + (Date.now() - timeLoadVideoMethodWasCalled) +
" miliseconds after loadVideo has been called.");
lastTimeWhenVideoHolded = Date.now();
};
htmlVideoTag.onplaying = function(){
if(playbackStopped){// && !userPausedVideo){
////console.log("Video is playing again after " + (Date.now() - lastTimeWhenVideoHolded) + " miliseconds.");
timePlaybackWasStalled += Date.now() - lastTimeWhenVideoHolded;
playbackStopped = false;
}
//userPausedVideo = false;
};
*/
// All these declared variables until 'var self = this' are intended to be constants.
var serverDeliverySelected = streamTicket.xhr_hostname !== false && (streamTicket.path_to_file_on_web_server || streamTicket.hash_value) ? true : false;
var wtorrentDeliverySelected = streamTicket.torrent_file ? true : false;
var XHR_HOSTNAME = streamTicket.xhr_hostname;
var XHR_PORT = streamTicket.xhr_port;
var PATH_TO_FILE = streamTicket.path_to_file_on_web_server;
var HASH_VALUE = streamTicket.hash_value;
var MAGNET_URI = streamTicket.magnet_URI;
if (wtorrentDeliverySelected) {
var TORRENT_FILE = Buffer.from(streamTicket.torrent_file, 'base64');
}
SIZE_VIDEO_FILE = streamTicket.SIZE_VIDEO_FILE; // in byte
var DOWNLOAD_FROM_P2P_TIME_RANGE = streamTicket.download_from_p2p_time_range || 20; // in seconds
var WTORRENT_REQUEST_SIZE = streamTicket.wtorrent_request_size || 6000000; // in byte
var DOWNLOAD_FROM_SERVER_TIME_RANGE = streamTicket.download_from_server_time_range || 3; // in seconds
var UPLOAD_LIMIT_MULTIPLIER = streamTicket.peer_upload_limit_multiplier || 2;
var UPLOAD_LIMIT_ADDEND = streamTicket.peer_upload_limit_addend || 3000000; // in byte
var XHR_REQUESTED_SIZE = streamTicket.XHR_request_size || 2000000; // in byte
var THRESHOLD_HAND_DATA_TO_MULTISTREAM = streamTicket.threshold_hand_data_to_multistream || 1000000; // in byte
var MAX_SIZE_ANSWERSTREAM = streamTicket.max_size_next_stream_for_multistream || 1999999; // in byte
var CHECK_IF_IN_SERVER_TIME_RANGE_INTERVAL = streamTicket.check_if_in_server_time_range_interval || 500; // in milliseconds
var CHECK_IF_IN_WTORRENT_TIME_RANGE_INTERVAL = streamTicket.check_if_in_wtorrent_time_range_interval || 2000; // in milliseconds
var CHECK_IF_ANSWERSTREAM_READY_INTERVAL = streamTicket.check_if_answerstream_ready_interval || 200; // in milliseconds
var UPDATE_CHART_INTERVAL = streamTicket.update_chart_interval || 1000; // in milliseconds
var CHOKE_IF_NECESSARY_INTERVAL = streamTicket.choke_if_necessary_interval || 300; // in milliseconds
var CHECK_IF_VIDEO_DOWNLOADED_INTERVAL = streamTicket.check_if_video_downloaded_interval || 500; // in milliseconds
// These variables are declared in this high scope in order to enable every function that is declared in
// receive_stream to access and manipulate these variables.
var self = this;
var endStreaming = false;
var neighbors = []; // This array contains P2P connections to other peers out of the WebTorrent network.
var videostreamRequestCounter = 0;
bytesReceivedFromServer = 0; // This variable gets only initialized not declared.
var videostreamRequestHandlers = [];
var inServerDownloadTimeRange = true; // inServerDownloadTimeRange === true means that there is less than
// DOWNLOAD_FROM_SERVER_TIME_RANGE seconds of video playback buffered and consequently XHRs will be
// conducted.
var playerHasBufferedVideo = false;
var videoDownloadedByWtorrent = false;
var bytesFromWtorrent = 0;
var bytesFromServer = 0;
var consoleCounter = 0; // This variable is only for debugging purposes.
// var first2000BytesOfVideo = null; Feature was too confusing to implement.
// var numberBytesInFirst2000BytesOfVideo = 0; Feature was too confusing to implement.
// var timeOfLastWtorrentRequest = 0; Not needed in this version
// These Node.js readable streams will be used to buffer received video data before it gets put into the
// source buffer object.
function SimpleReadableStream(options) {
readableStream.Readable.call(this, options);
}
util.inherits(SimpleReadableStream, readableStream.Readable);
SimpleReadableStream.prototype._read = function (size) {};
if (wtorrentDeliverySelected) {
webtorrentClient = new WebTorrent({ dht: false, tracker: true });
webtorrentClient.on('error', function (err) {
console.error("ERROR: " + err.message);
});
var webtorrentOptions = {};
theTorrentSession = webtorrentClient.add(TORRENT_FILE, webtorrentOptions, function (torrentSession) {
// From this point of time onwards, the WebTorrent instance will start downloading video data from the
// WebTorrent network. This downloading happens in the background and according to the rarest-peace-first
// strategy. The OakStreaming client downloads the video data as fast as possible.
// Sequential stream requests, for example created by calls to the WebTorrent function createReadStream, are
// prioritized over the before mentioned rarest-piece-first background downloading.
// A torrentSession object has many accessible properties and methods. One property of a
// torrentSession object is uploaded which returns the total number of bytes uploaded to
// other peers. One method of the torrentSession object is addPeer which enables to add an existing WebRTC
// connection directly to its (peer) swarm.
// Due to the fact that only one video can be received by an OakStreaming instance at the same time,
// at each moment the OakStreaming instance has at most one torrentSession running. The current torrentSession
// is saved in the theTorrentSession variable.
wtorrentFile = theTorrentSession.files[0];
theTorrentSession.on('error', function (err) {
console.log("ERROR: " + err.message);
});
// New peers can only be added to the swarm of torrentSession object, i.e. the set of peers that are used
// for video data exchange, when the infoHash of the torrentSession object has already been created.
if (theTorrentSession.infoHash) {
for (var j = 0; j < peersToAdd.length; j++) {
theTorrentSession.addPeer(peersToAdd[j][0]);
if (peersToAdd[j][1]) {
peersToAdd[j][1]();
}
peersToAdd.splice(j, 1);
j--;
}
} else {
theTorrentSession.on('infoHash', function () {
// Peers which used the offered methods to manually/explicitly connect to this OakStreaming instance
// before a torrent file has been loaded are added now to the swarm of the torrentSession object.
for (var j = 0; j < peersToAdd.length; j++) {
theTorrentSession.addPeer(peersToAdd[j][0]);
if (peersToAdd[j][1]) {
peersToAdd[j][1]();
}
peersToAdd.splice(j, 1);
j--;
}
});
theTorrentSession.on('metadata', function () {
// Peers which used the offered methods to manually connect to this OakStreaming instance
// before a torrent file was loaded are added now to the swarm of the torrentSession object.
for (var j = 0; j < peersToAdd.length; j++) {
theTorrentSession.addPeer(peersToAdd[j][0]);
if (peersToAdd[j][1]) {
peersToAdd[j][1]();
}
peersToAdd.splice(j, 1);
j--;
}
});
}
// Emitted as soon as the complete video file has been downloaded via the WebTorrent network.
theTorrentSession.on('done', function () {
videoDownloadedByWtorrent = true;
});
// If this OakStreaming instance is already connected to another peer, this function calls the callback
// function, which has been passed to it, immediately. Otherwise, the callback function gets called as soon as
// this OakStreaming instance connects to another peer.
self.forTesting_connectedToNewWtorrentPeer = function (callback) {
if (notificationsBecauseNewWire <= 0) {
notificationsBecauseNewWire--;
var callbackCalled = false;
theTorrentSession.on('wire', function (wire) {
if (!callbackCalled) {
callback();
callbackCalled = true;
}
});
} else {
notificationsBecauseNewWire--;
callback();
}
};
// This event listener gets called when a peer has been added to the swarm of this OakStreaming instance.
theTorrentSession.on('wire', function (wire) {
neighbors.push(wire);
notificationsBecauseNewWire++;
// This command activates the ut_pex extension for the communication with the new peer.
// The ut_pex extension enables to automatically establish WebRTC connections to the neighbors of
// ones neighbors.
wire.use(ut_pex());
wire.ut_pex.on('peer', function (peer) {
theTorrentSession.addPeer(peer);
// got a peer
// probably add it to peer connections queue
});
});
// For video playback, the client-side library videostream is used.
// This library requests video data from the OakStreaming client.
// Requests from the videostream library which happened before the webtorrentClient.add method has called
// this function are saved in the videostreamRequestHandlers array and are now worked off.
for (var i = 0, length = videostreamRequestHandlers.length; i < length; i++) {
var thisRequest = videostreamRequestHandlers[i];
// To answer a request from the videostream library, a Multistream
// (https://www.npmjs.com/package/multistream) is returned. This Multistream requests a so-called
// readableStream from the OakStreaming client as soon as its buffer has went dry.
// The callback of the last request from the Multistream is saved in the callbackOfMultistream variable.
// This callback should be called with the created readableStream which contains the next video data.
if (thisRequest.callbackOfMultistream !== null) {
/* Not needed in this version
if(htmlVideoTag.duration){
timeOfLastWtorrentRequest = htmlVideoTag.currentTime;
} else {
timeOfLastWtorrentRequest = 0;
}
*/
var endIndexRequest;
if (thisRequest.indexNextNeededByte + WTORRENT_REQUEST_SIZE > wtorrentFile.length - 1) {
endIndexRequest = wtorrentFile.length - 1;
} else {
endIndexRequest = thisRequest.indexNextNeededByte + WTORRENT_REQUEST_SIZE;
}
// The createReadStream method of the WebTorrent API conducts a sequential byte range request to the
// WebTorrent network.
thisRequest.wtorrentStream = wtorrentFile.createReadStream({ "start": thisRequest.indexNextNeededByte, "end": endIndexRequest });
/*
thisRequest.on('end', function(){
if(thisRequest.callbackOfMultistream !== null && thisRequest.indexNextNeededByte >
thisRequest.endSequentialWtorrentReq && thisRequest.indexNextNeededByte <
thisRequest.videoFileSize){
var endIndexRequest;
if(thisRequest.indexNextNeededByte + WTORRENT_REQUEST_SIZE >= wtorrentFile.length-1){
endIndexRequest = wtorrentFile.length-1;
} else {
endIndexRequest = thisRequest.indexNextNeededByte + WTORRENT_REQUEST_SIZE;
}
thisRequest.wtorrentStream = wtorrentFile.createReadStream({"start" : thisRequest.indexNextNeededByte,
"end" : endIndexRequest});
thisRequest.indexNextByteWtorrent = thisRequest.indexNextNeededByte;
thisRequest.wtorrentStream.unpipe();
thisRequest.wtorrentStream.pipe(thisRequest.collectorStreamForWtorrent);
}
});
*/
// Every videostreamRequestHandler has to save the byte index that it expects next from the WebTorrent
// network.
thisRequest.indexNextByteWtorrent = thisRequest.indexNextNeededByte;
thisRequest.endSequentialWtorrentReq = endIndexRequest;
// Data that is received from the sequential byte range request gets immediately pumped into a writeable
// stream called collectorStreamForWtorrent which processes the new data.
thisRequest.wtorrentStream.pipe(thisRequest.collectorStreamForWtorrent);
}
}
});
theTorrentSession.on('metadata', function () {
// This case is necessary because WebTorrents infoHash eventListener is not reliable.
// The metadata event listener gets called when all meta data about the torrent has been determined
// (including the info hash of the torrent).
for (var j = 0; j < peersToAdd.length; j++) {
theTorrentSession.addPeer(peersToAdd[j][0]);
if (peersToAdd[j][1]) {
peersToAdd[j][1]();
}
peersToAdd.splice(j, 1);
j--;
}
});
}
// The following line of code belongs to the "request first 2000 byte only once from server" feature
// The development of this feature has been canceled for now.
// first2000BytesOfVideo = new SimpleReadableStream({highWaterMark: 2000});
// This constructor will be used to create a file-like, seekable object that the videostream library queries for
// video data.
var FileLike = function FileLike(pathToFile) {
this.pathToFile = pathToFile;
};
// The videostream library will call createReadStream several times with different values for the start property
// of opts. The OakStreaming client has to return the byte range specified by the start and end property of opts.
FileLike.prototype.createReadStream = function (opts) {
if (opts.start >= SIZE_VIDEO_FILE) {
return new MultiStream(function (cb) {
cb(null, null);
});
}
inServerDownloadTimeRange = true;
var thisRequest = new VideostreamRequestHandler(++videostreamRequestCounter, opts.start, this);
// Every time I printed out the value of opts.end, it was NaN.
// I suppose that should be interpreted as "till the end of the file".
// In this case, the stream that this createReadStream method will return should, nevertheless, not buffer the
// hole video file in advance but instead retrieve and put out chunks of video data on-demand.
if (opts.end && !isNaN(opts.end)) {
thisRequest.xhrEndIndex = opts.end + 1;
} else {
if (SIZE_VIDEO_FILE !== 0) {
thisRequest.xhrEndIndex = SIZE_VIDEO_FILE;
}
}
// This writeable Node.js stream will process every data that is received from sequential WebTorrent streams.
thisRequest.CollectorStreamForWtorrent = function (highWaterMark) {
readableStream.Writable.call(this, highWaterMark);
};
util.inherits(thisRequest.CollectorStreamForWtorrent, readableStream.Writable);
thisRequest.CollectorStreamForWtorrent.prototype._write = function (chunk, encoding, done) {
if (thisRequest.indexNextNeededByte - thisRequest.indexNextByteWtorrent < chunk.length) {
bytesFromWtorrent += chunk.length - (thisRequest.indexNextNeededByte - thisRequest.indexNextByteWtorrent);
var streamHasMemoryLeft = thisRequest.nextAnswerstream.push(chunk.slice(thisRequest.indexNextNeededByte - thisRequest.indexNextByteWtorrent, chunk.length));
thisRequest.bytesInAnswerstream += chunk.length - (thisRequest.indexNextNeededByte - thisRequest.indexNextByteWtorrent);
thisRequest.indexNextNeededByte += chunk.length - (thisRequest.indexNextNeededByte - thisRequest.indexNextByteWtorrent);
if (streamHasMemoryLeft) {
if (thisRequest.callbackOfMultistream !== null && thisRequest.indexNextNeededByte >= thisRequest.xhrEndIndex) {
var theCallbackFunction = thisRequest.callbackOfMultistream;
thisRequest.callbackOfMultistream = null;
thisRequest.nextAnswerstream.push(null);
thisRequest.bytesInAnswerstream = 0;
var res = thisRequest.nextAnswerstream;
thisRequest.nextAnswerstream = new SimpleReadableStream({ highWaterMark: MAX_SIZE_ANSWERSTREAM });
theCallbackFunction(null, res);
} else {
checkIfAnswerstreamReady(thisRequest);
}
} else {
if (thisRequest.callbackOfMultistream === null) {
thisRequest.forNowNoDataNeeded = true;
} else {
var theCallbackFunction = thisRequest.callbackOfMultistream;
thisRequest.callbackOfMultistream = null;
thisRequest.nextAnswerstream.push(null);
thisRequest.bytesInAnswerstream = 0;
var res = thisRequest.nextAnswerstream;
thisRequest.nextAnswerstream = new SimpleReadableStream({ highWaterMark: MAX_SIZE_ANSWERSTREAM });
theCallbackFunction(null, res);
}
}
}
thisRequest.indexNextByteWtorrent += chunk.length;
done();
};
thisRequest.collectorStreamForWtorrent = new thisRequest.CollectorStreamForWtorrent(16);
videostreamRequestHandlers.push(thisRequest);
/* Not needed in current version of the OakStreaming library
if(htmlVideoTag.duration){
timeOfLastWtorrentRequest = htmlVideoTag.currentTime;
} else {
timeOfLastWtorrentRequest = 0;
}
*/
if (wtorrentFile) {
var endIndexRequest;
if (thisRequest.indexNextNeededByte + WTORRENT_REQUEST_SIZE >= wtorrentFile.length - 1) {
endIndexRequest = wtorrentFile.length - 1;
} else {
endIndexRequest = thisRequest.indexNextNeededByte + WTORRENT_REQUEST_SIZE;
}
// Creates a sequential byte range requests to the WebTorrent network.
thisRequest.wtorrentStream = wtorrentFile.createReadStream({ "start": thisRequest.indexNextNeededByte, "end": endIndexRequest });
thisRequest.endSequentialWtorrentReq = endIndexRequest;
thisRequest.indexNextByteWtorrent = thisRequest.indexNextNeededByte;
// Every byte that is received from the created sequential byte range request gets handed over to the
// collectorStreamForWtorrent stream.
thisRequest.wtorrentStream.pipe(thisRequest.collectorStreamForWtorrent);
}
/**
* @callback OakStreaming~callbackToMultistream
*/
/**
* This inline function is intended to be passed to the Multistream constructor. The streamFactory function
* requests data from the WebTorrent network and/or from a Web server. It returns, via the callback function,
* a Node.js readable stream of video data. The content of this stream does not exceed more than
* MAX_SIZE_ANSWERSTREAM bytes of video data. Moreover, the function returns the video data beginning from the
* byte index saved in the thisRequest.indexNextNeededByte variable.
* @private
* @param {OakStreaming~callbackToMultistream} cb - This callback function gets called with a Node.js readable
* stream containing the fetched video data.
*/
function streamFactory(cb) {
if (thisRequest.xhrEndIndex >= 0 && thisRequest.indexNextNeededByte >= thisRequest.xhrEndIndex) {
if (thisRequest.xhrRequest) {
thisRequest.xhrRequest.destroy();
thisRequest.xhrRequest = null;
}
return cb(null, null); // This tells the Multistream that no more data will be delivered to it.
}
thisRequest.callbackNumber++;
thisRequest.callbackOfMultistream = cb;
thisRequest.forNowNoDataNeeded = false;
/* Erstmal rausgenommen, da ich mich beim XHRHanlder part dazu irgendwie verhäddert habe
if(firstBytesOfVideo && (thisRequest.indexNextNeededByte < firstBytesOfVideo.length - 200) &&
thisRequest.videostreamRequestNumber < 5){ // Beim 10 mins big buck bunny video ist eben der erste
lange createReadStream (und einzige?) createReadStream Nummer 5
thisRequest.nextAnswerstream.push(firstBytesOfVideo.slice(thisRequest.indexNextNeededByte,
firstBytesOfVideo.length));
bytesFromServer += firstBytesOfVideo.length - thisRequest.indexNextNeededByte;
thisRequest.indexNextNeededByte += firstBytesOfVideo.length - thisRequest.indexNextNeededByte;
var theCallbackFunction = thisRequest.callbackOfMultistream;
thisRequest.callbackOfMultistream = null;
thisRequest.nextAnswerstream.push(null);
thisRequest.bytesInAnswerstream = 0;
var res = thisRequest.nextAnswerstream;
if(thisRequest.videostreamRequestNumber < 4){
thisRequest.nextAnswerstream = new SimpleReadableStream({highWaterMark: 2000});
} else {
thisRequest.nextAnswerstream = new SimpleReadableStream({highWaterMark: MAX_SIZE_ANSWERSTREAM});
}
////console.log("A CB has been answered with a part of firstBytesOfVideo for readstream number " +
thisRequest.videostreamRequestNumber + " with callback number " + thisRequest.callbackNumber);
theCallbackFunction(null, res);
return;
}
*/
if (!checkIfAnswerstreamReady(thisRequest)) {
// answerstream is nextAnswerstream
if (thisRequest.wtorrentStream) {
// thisRequest.wtorrentStream.resume(); 11.07.16 more a try
} else if (wtorrentFile) {
var endIndexRequest;
if (thisRequest.indexNextNeededByte + WTORRENT_REQUEST_SIZE - 1 >= wtorrentFile.length - 1) {
endIndexRequest = wtorrentFile.length - 1;
} else {
endIndexRequest = thisRequest.indexNextNeededByte + WTORRENT_REQUEST_SIZE - 1;
}
thisRequest.wtorrentStream = wtorrentFile.createReadStream({ "start": thisRequest.indexNextNeededByte, "end": endIndexRequest });
thisRequest.endSequentialWtorrentReq = endIndexRequest;
thisRequest.indexNextByteWtorrent = thisRequest.indexNextNeededByte;
thisRequest.wtorrentStream.pipe(thisRequest.collectorStreamForWtorrent);
}
if (serverDeliverySelected && inServerDownloadTimeRange && !thisRequest.xhrConducted) {
if (!wtorrentFile || !videoDownloadedByWtorrent) {
conductXhr(thisRequest);
}
}
}
}
// A Multistream gets created which will be returned as the answer to the request from the videostream library.
var multi = new MultiStream(streamFactory);
// The videostream library calls this deconstructor when it needs no more data from the multistream.
var deconstructorAlreadyCalled = false;
var destroy = multi.destroy;
multi.destroy = function () {
if (deconstructorAlreadyCalled) {
return;
}
deconstructorAlreadyCalled = true;
if (thisRequest.xhrRequest) {
thisRequest.xhrRequest.destroy();
}
var theCallback = thisRequest.callbackOfMultistream;
thisRequest.callbackOfMultistream = null;
thisRequest.forNowNoDataNeeded = true;
if (thisRequest.wtorrentStream) {
thisRequest.wtorrentStream.pause();
thisRequest.wtorrentStream.unpipe();
}
for (var i = 0; i < videostreamRequestHandlers.length; i++) {
if (videostreamRequestHandlers[i] === thisRequest) {
videostreamRequestHandlers.splice(i, 1);
}
}
// The program fills the nextAnswerstream stream even when no callbackOfMultistream is pending.
// Therefore, the call of the resume method, which empties the stream and thus frees the allocated memory,
// is necessary to avoid significant memory leaks.
thisRequest.nextAnswerstream.resume();
destroy.call(multi);
};
return multi;
};
// This function frequently checks whether less than DOWNLOAD_FROM_P2P_TIME_RANGE seconds of video data
// is buffered in advance. If this is the case, this function conducts a new sequential byte range request
// to the WebTorrent network.
function checkIfInP2pDownloadTimeRange() {
if (playerHasBufferedVideo) {
return;
}
/* Working version where only a minimal time limit is set when a new createReadStream to WebTorrent network is
conducted
if(htmlVideoTag.duration){
//////console.log("In if(htmlVideoTag.duration)");
if(theTorrentSession && (htmlVideoTag.currentTime - timeOfLastWtorrentRequest >=
MINIMAL_TIMESPAN_BEFORE_NEW_WEBTORRENT_REQUEST)){
for (var j = 0, length = videostreamRequestHandlers.length; j < length; j++) {
var thisRequest = videostreamRequestHandlers[j];
////console.log("createReadStream enlargement for request " + thisRequest.videostreamRequestNumber);
if(thisRequest.callbackOfMultistream !== null && thisRequest.indexNextNeededByte >
thisRequest.endSequentialWtorrentReq && thisRequest.indexNextNeededByte < SIZE_VIDEO_FILE){
timeOfLastWtorrentRequest = htmlVideoTag.currentTime;
var endIndexRequest;
if(thisRequest.indexNextNeededByte + WTORRENT_REQUEST_SIZE >= wtorrentFile.length-1){
endIndexRequest = wtorrentFile.length-1;
} else {
endIndexRequest = thisRequest.indexNextNeededByte + WTORRENT_REQUEST_SIZE;
}
////console.log("I set a new createReadstream for videostream request number " +
thisRequest.videostreamRequestNumber);
thisRequest.wtorrentStream.unpipe();
thisRequest.wtorrentStream = wtorrentFile.createReadStream({"start" : thisRequest.indexNextNeededByte,
"end" : endIndexRequest});
thisRequest.endSequentialWtorrentReq = endIndexRequest;
thisRequest.indexNextByteWtorrent = thisRequest.indexNextNeededByte;
thisRequest.collectorStreamForWtorrent = new thisRequest.CollectorStreamForWtorrent(16);
thisRequest.wtorrentStream.pipe(thisRequest.collectorStreamForWtorrent);
}
}
}
}
*/
var timeRanges = htmlVideoTag.buffered;
for (var i = 0, length = timeRanges.length; i < length; i++) {
if (htmlVideoTag.currentTime >= timeRanges.start(i) && htmlVideoTag.currentTime <= timeRanges.end(i) + 1) {
if (timeRanges.end(i) - htmlVideoTag.currentTime <= DOWNLOAD_FROM_P2P_TIME_RANGE) {
for (var j = 0, length2 = videostreamRequestHandlers.length; j < length2; j++) {
var thisRequest = videostreamRequestHandlers[j];
if (theTorrentSession && thisRequest.callbackOfMultistream !== null && thisRequest.indexNextNeededByte > thisRequest.endSequentialWtorrentReq && thisRequest.indexNextNeededByte < SIZE_VIDEO_FILE) {
var endIndexRequest;
if (thisRequest.indexNextNeededByte + WTORRENT_REQUEST_SIZE >= wtorrentFile.length - 1) {
endIndexRequest = wtorrentFile.length - 1;
} else {
endIndexRequest = thisRequest.indexNextNeededByte + WTORRENT_REQUEST_SIZE;
}
thisRequest.wtorrentStream.unpipe();
thisRequest.wtorrentStream = wtorrentFile.createReadStream({ "start": thisRequest.indexNextNeededByte, "end": endIndexRequest });
thisRequest.endSequentialWtorrentReq = endIndexRequest;
thisRequest.indexNextByteWtorrent = thisRequest.indexNextNeededByte;
thisRequest.collectorStreamForWtorrent = new thisRequest.CollectorStreamForWtorrent(16);
thisRequest.wtorrentStream.pipe(thisRequest.collectorStreamForWtorrent);
}
}
}
}
}
setTimeout(checkIfInP2pDownloadTimeRange, CHECK_IF_IN_WTORRENT_TIME_RANGE_INTERVAL);
}
// The final version of the library should not include this function. This function updates the statistics that
// are shown above the video.
/* Do not delete!
function updateChart(){
if(endStreaming){
return;
}
if(theTorrentSession && wtorrentFile){
document.getElementById("WebTorrent-received").innerHTML = "wtorrentFile.length: " + wtorrentFile.length +
"\n torrent.downloaded: " + theTorrentSession.downloaded + "\n torrent.received: " +
theTorrentSession.downloaded + "\n torrent.uploaded: " + theTorrentSession.uploaded +
"\n torrent.progress: " + theTorrentSession.progress + "\n Bytes received from server: " +
bytesReceivedFromServer + "\n Bytes taken from server delivery: " + bytesFromServer +
"\n Bytes taken from WebTorrent delivery: " + bytesFromWtorrent;
}
setTimeout(updateChart, UPDATE_CHART_INTERVAL);
}
*/
// This function checks for a given videostreamRequestHandler whether enough video data has been buffered to call
// the callbackOfMultistream function. If it is the case, callbackOfMultistream gets called together with the
// buffered data.
function checkIfAnswerstreamReady(thisRequest) {
if (thisRequest.videostreamRequestNumber < 4 && thisRequest.callbackOfMultistream && thisRequest.bytesInAnswerstream >= 2000 || thisRequest.callbackOfMultistream && (thisRequest.bytesInAnswerstream >= THRESHOLD_HAND_DATA_TO_MULTISTREAM || thisRequest.indexNextNeededByte >= SIZE_VIDEO_FILE)) {
var theCallbackFunction = thisRequest.callbackOfMultistream;
thisRequest.callbackOfMultistream = null;
thisRequest.nextAnswerstream.push(null);
thisRequest.bytesInAnswerstream = 0;
var res = thisRequest.nextAnswerstream;
thisRequest.nextAnswerstream = new SimpleReadableStream({ highWaterMark: MAX_SIZE_ANSWERSTREAM });
theCallbackFunction(null, res);
return true;
}
return false;
}
// This function frequently checks whether the video data upload should be throttled because the Peer Upload Limit
// is reached. If it should be throttled, then every neighbor gets choked which means no more data is send to
// other peers for approximately 800 milliseconds.
function chokeIfNecessary() {
if (stopUploadingWhenVideoDownloaded && videoDownloadedByWtorrent || theTorrentSession && theTorrentSession.uploaded >= theTorrentSession.downloaded * UPLOAD_LIMIT_MULTIPLIER + UPLOAD_LIMIT_ADDEND) {
for (var i = 0, length = neighbors.length; i < length; i++) {
neighbors[i].choke();
}
}
setTimeout(chokeIfNecessary, CHOKE_IF_NECESSARY_INTERVAL);
}
/**
* This constructor creates an object which serves as a container for all necessary information to handle the
* respective createReadStream call (which is a byte range request).
* @private
* @constructor
* @param {number} videostreamRequestNumber - The number of the videostream request, that is, the amount of times
* the createReadStream method of the FileLike object has been called.
* @param {object} indexFirstNeededByte - The index of the byte which is needed first from the video file.
* @param {object} theFileLikeObject - A reference to the OakStreaming instance.
*/
function VideostreamRequestHandler(videostreamRequestNumber, indexFirstNeededByte, theFileLikeObject) {
this.videostreamRequestNumber = videostreamRequestNumber;
this.indexNextNeededByte = indexFirstNeededByte || 0;
this.indexNextByteWtorrent = -42;
this.indexNextByteServer = -42;
this.callbackOfMultistream = null;
this.callbackNumber = 0;
this.wtorrentStream = null;
if (videostreamRequestNumber < 4) {
this.nextAnswerstream = new SimpleReadableStream({ highWaterMark: 2000 });
} else {
this.nextAnswerstream = new SimpleReadableStream({ highWaterMark: MAX_SIZE_ANSWERSTREAM });
}
this.bytesInAnswerstream = 0;
this.collectorStreamForWtorrent = null;
this.xhrConducted = false;
this.xhrEndIndex = -42;
this.theFileLikeObject = theFileLikeObject;
this.bytesFromWtorrent = 0;
this.bytesFromServer = 0;
this.forNowNoDataNeeded = false;
this.xhrRequest = null;
this.endSequentialWtorrentReq = -42;
this.xhrFilesize = -42;
}
// This function checks whether less than DOWNLOAD_FROM_SERVER_TIME_RANGE seconds of video playback are buffered
// in advance and sets the private property inServerDownloadTimeRange of the OakStreaming client accordingly.
// If the inServerDownloadTimeRange property has been set to true, this function may conduct XHRs.
function checkIfInServerDownloadTimeRange(justOnce) {
if (playerHasBufferedVideo) {
return;
}
if (htmlVideoTag.duration) {
var timeRanges = htmlVideoTag.buffered;
inServerDownloadTimeRange = true;
for (var i = 0, length = timeRanges.length; i < length; i++) {
if (htmlVideoTag.currentTime >= timeRanges.start(i) && htmlVideoTag.currentTime <= timeRanges.end(i) + 1) {
if (timeRanges.end(i) - htmlVideoTag.currentTime >= DOWNLOAD_FROM_SERVER_TIME_RANGE) {
inServerDownloadTimeRange = false;
}
}
}
if (serverDeliverySelected && inServerDownloadTimeRange) {
for (var j = 0, length = videostreamRequestHandlers.length; j < length; j++) {
if ((!wtorrentFile || !videoDownloadedByWtorrent) && videostreamRequestHandlers[j].callbackOfMultistream !== null && videostreamRequestHandlers[j].xhrConducted === false) {
conductXhr(videostreamRequestHandlers[j]);
}
}
}
}
if (!justOnce) {
setTimeout(checkIfInServerDownloadTimeRange, CHECK_IF_IN_SERVER_TIME_RANGE_INTERVAL);
}
}
// This function checks whether the video is completely downloaded.
function checkIfVideoDownloaded() {
if (playerHasBufferedVideo) {
return;
}
// This code block checks whether the video player has buffered the complete video.
if (htmlVideoTag.duration) {
var timeRanges = htmlVideoTag.buffered;
if (timeRanges.length >= 1) {
if (timeRanges.start(0) == 0 && timeRanges.end(0) == htmlVideoTag.duration) {
playerHasBufferedVideo = true;
if (callback) {
if (stopUploadingWhenVideoDownloaded) {
callback();
} else {
callback(theTorrentSession);
}
callback = null;
}
if (stopUploadingWhenVideoDownloaded) {
if (theTorrentSession) {
theTorrentSession.destroy();
theTorrentSession = null; // 30.09
}
if (webtorrentClient) {
webtorrentClient.destroy(); // 30.09
webtorrentClient = null; // 30.09
}
endStreaming = true;
return;
}
}
}
}
// This code block checks whether the created WebTorrent instance has buffered the complete video.
// If this is the case, no more video data has to be requested from the WebTorrent network
// and from the Web server. Video data that is buffered by the WebTorrent instance may not be loaded
// into the buffer of the video player yet.
if (theTorrentSession && theTorrentSession.progress === 1) {
// playerHasBufferedVideo = true; 12.10
videoDownloadedByWtorrent = true;
if (callback) {
if (stopUploadingWhenVideoDownloaded) {
callback();
} else {
callback(theTorrentSession);
}
callback = null;
}
if (stopUploadingWhenVideoDownloaded) {
endStreaming = true;
return;
}
}
setTimeout(checkIfVideoDownloaded, CHECK_IF_VIDEO_DOWNLOADED_INTERVAL);
}
// This function conducts a XHR for the VideostreamRequestHandler which is handed over to the function
// as its first and only parameter.
function conductXhr(thisRequest) {
if (thisRequest.callbackOfMultistream === null) {
return;
}
thisRequest.xhrConducted = true;
var reqStart = thisRequest.indexNextNeededByte;
var reqEnd = 0;
if (thisRequest.videostreamRequestNumber < 4) {
reqEnd = reqStart + 2000;
} else {
reqEnd = reqStart + XHR_REQUESTED_SIZE;
}
// The video file size (in byte) that the Web server stated in its latest XHR response is saved in
// the xhrFilesize variable. This block of program code reduces the value of the reqEnd
// variable if it would otherwise be greater than the xhrFilesize variable.
if (thisRequest.xhrFilesize > 0 && reqEnd > thisRequest.xhrFilesize) {
reqEnd = thisRequest.xhrFilesize;
} else if (thisRequest.xhrEndIndex >= 0 && reqEnd > thisRequest.xhrEndIndex) {
reqEnd = thisRequest.xhrEndIndex;
}
if (reqStart >= reqEnd) {
if (thisRequest.xhrRequest) {
thisRequest.xhrRequest.destroy();
thisRequest.xhrRequest = null;
}
thisRequest.xhrConducted = false;
if (thisRequest.callbackOfMultistream) {
return thisRequest.callbackOfMultistream(null, null);
} else {
return;
}
}
// This function gets called as soon as a new chunk of data from the Web server has been received.
// An answer to a XHR is usually divided in several chunks which each are several kilobyte in size.
var xhrDataHandler = function xhrDataHandler(chunk) {
bytesReceivedFromServer += chunk.length;
// thisRequest.indexNextByteServer += chunk.length; "buffer first 2000 bytes explicitly" feature
/* This is program code from the "buffer first 2000 bytes explicitly" feature to improve start-up time.
Unfortunately, implementing the feature got a bit too confusing for me which is why I froze the development
of this feature.
if(numberBytesInfirst2000BytesOfVideo < 2000 && thisRequest.indexNextNeededByte ==
numberBytesInfirst2000BytesOfVideo){
////console.log("Size of firstBytesOfVideo in bytes: " + chunk.length);
numberBytesInFirst2000BytesOfVideo += chunk.length; //<= (2000-numberBytesInFirst2000BytesOfVideo) ?
chunk.length : 2000;
first2000BytesOfVideo = Buffer.concat([first2000BytesOfVideo, chunk]); // chunk.slice(0,
2000-numberBytesInFirst2000BytesOfVideo)
}
if(thisRequest.callbackOfMultistream){
if(thisRequest.videostreamRequestNumber<5 && thisRequest.callbackNumber <5){
if(thisRequest.bytesInAnswerstream > 0){
thisRequest.nextAnswerstream.push(chunk);
thisRequest.indexNextNeededByte += chunk.length;
thisRequest.bytesFromServer += chunk.length;
var theCallbackFunction = thisRequest.callbackOfMultistream;
thisRequest.callbackOfMultistream = null;
thisRequest.nextAnswerstream.push(null);
thisRequest.bytesInAnswerstream = 0;
var res = thisRequest.nextAnswerstream;
if(thisRequest.videostreamRequestNumber <4){
thisRequest.nextAnswerstream = new SimpleReadableStream({highWaterMark: 2000});
} else {
thisRequest.nextAnswerstream = new SimpleReadableStream({highWaterMark: MAX_SIZE_ANSWERSTREAM});
}
theCallbackFunction(null, res);
} else {
var returnStream = new SimpleReadableStream(numberBytesInfirst2000BytesOfVideo -
thisRequest.indexNextNeededByte);
returnStream.push(first2000BytesOfVideo.slice(this.start, numberBytesInFirst2000BytesOfVideo);
returnStream.push(null);
bytesFromServer += numberBytesInfirst2000BytesOfVideo-thisRequest.indexNextNeededByte;
thisRequest.indexNextNeededByte += numberBytesInfirst2000BytesOfVideo;
var theCallbackFunction = thisRequest.callbackOfMultistream;
thisRequest.callbackOfMultistream = null;
theCallbackFunction(null, returnStream);
}
}
}
*/
if (thisRequest.forNowNoDataNeeded) {
thisRequest.indexNextByteServer += chunk.length;
return;
}
// This if clause checks whether the received chunk contains the the next needed byte.
// If this is the case, the part of the chunk which contains the desired video data
// gets put into the nextAnswerstream stream. When pushing data into this stream, it
// returns false if no additional data should be pushed into it.
if (thisRequest.indexNextNeededByte - thisRequest.indexNextByteServer < chunk.length) {
bytesFromServer += chunk.length - (thisRequest.indexNextNeededByte - thisRequest.indexNextByteServer);
thisRequest.bytesInAnswerstream += chunk.length - (thisRequest.indexNextNeededByte - thisRequest.indexNextByteServer);
var myBuffer = chunk.slice(thisRequest.indexNextNeededByte - thisRequest.indexNextByteServer, chunk.length);
var streamHasMemoryLeft = thisRequest.nextAnswerstream.push(myBuffer);
if (!streamHasMemoryLeft) {
// What happens next depends on whether the multistream currently expects data.
if (thisRequest.callbackOfMultistream !== null) {
var theCallbackFunction = thisRequest.callbackOfMultistream;
thisRequest.callbackOfMultistream = null;
thisRequest.nextAnswerstream.push(null);
thisRequest.bytesInAnswerstream = 0;
var res = thisRequest.nextAnswerstream;
thisRequest.nextAnswerstream = new SimpleReadableStream({ highWaterMark: MAX_SIZE_ANSWERSTREAM });
theCallbackFunction(null, res);
} else {
// In this case, we can not save additional video data for this videostream request until
// the respective multistream calls its streamFactory function again.
// Until this happens, for this videostream request neither from the Web server nor
// from the WebTorrent network additional video data is requested. As desired,
// the rarest-piece-selection background downloading nevertheless continues.
thisRequest.forNowNoDataNeeded = true;
}
} else {
if (thisRequest.indexNextNeededByte >= thisRequest.xhrEndIndex && thisRequest.callbackOfMultistream !== null) {
var theCallbackFunction = thisRequest.callbackOfMultistream;
thisRequest.callbackOfMultistream = null;
thisRequest.nextAnswerstream.push(null);
thisRequest.bytesInAnswerstream = 0;
var res = thisRequest.nextAnswerstream;
thisRequest.nextAnswerstream = new SimpleReadableStream({ highWaterMark: MAX_SIZE_ANSWERSTREAM });
theCallbackFunction(null, res);
}
}
thisRequest.indexNextNeededByte += chunk.length - (thisRequest.indexNextNeededByte - thisRequest.indexNextByteServer);
}
thisRequest.indexNextByteServer += chunk.length;
};
// This function gets called as soon as all chunks of the answer to the respective XHR have been received.
var xhrEnd = function xhrEnd() {
// Tests conducted in the curse of the bachelor thesis have indicated that the first three requests
// from the videostream library fetch meta data and hence target only a byte range of less than 2000 byte.
// As a result of this, it has been implemented that the first three created mutlistreams each only
// get filled with one single 2000 byte large stream.
// Therefore, the first four XHRs only request 2000 byte of data and the received 2000 byte get returned
// immediately to the multistream.
if (thisRequest.videostreamRequestNumber < 4 && thisRequest.callbackOfMultistream) {
var theCallbackFunction = thisRequest.callbackOfMultistream;
thisRequest.callbackOfMultistream = null;
thisRequest.nextAnswerstream.push(null);
thisRequest.bytesInAnswerstream = 0;
var res = thisRequest.nextAnswerstream;
if (thisRequest.videostreamRequestNumber < 3) {
thisRequest.nextAnswerstream = new SimpleReadableStream({ highWaterMark: 2000 });
} else {
thisRequest.nextAnswerstream = new SimpleReadableStream({ highWaterMark: MAX_SIZE_ANSWERSTREAM });
}
theCallbackFunction(null, res);
thisRequest.xhrConducted = false;
return;
}
/*
I have commented out this block of code in my attempt to solve the
"example_application.js:14013 Uncaught Error: Data too short" error.
if(thisRequest.bytesInAnswerstream > 0 && thisRequest.callbackOfMultistream !== null){
thisRequest.nextAnswerstream.push(null);
thisRequest.bytesInAnswerstream = 0;
var res = thisRequest.nextAnswerstream;
thisRequest.nextAnswerstream = new SimpleReadableStream({highWaterMark: MAX_SIZE_ANSWERSTREAM});
var theCallbackFunction = thisRequest.callbackOfMultistream;
thisRequest.callbackOfMultistream = null;
//console.log("xhrEnd: called CB with data out of nextAnswerstream from videostreamRequest number " +
thisRequest.videostreamRequestNumber);
theCallbackFunction(null, res);
}
*/
/*
Another way to solve the "example_application.js:14013 Uncaught Error: Data too short" error
if(!noMoreData){
if(thisRequest.indexNextNeededByte < SIZE_VIDEO_FILE && thisRequest.indexNextNeededByte <
thisRequest.xhrFilesize){
if(thisRequest.xhrEndIndex > 0 ){
if(thisRequest.indexNextNeededByte < thisRequest.xhrEndIndex){
conductXhr(thisRequest);
} else {
thisRequest.xhrConducted = false
}
} else {
conductXhr(thisRequest);
}
} else {
thisRequest.xhrConducted = false;
}
} else {
thisRequest.xhrConducted = false;
}
*/
thisRequest.xhrConducted = false;
// If appropriate, this function hands thisRequest.nextAnswerstream over to the multistream.
checkIfAnswerstreamReady(thisRequest);
// If appropriate, this function conducts a new XHR.
checkIfInServerDownloadTimeRange(true);
};
thisRequest.indexNextByteServer = reqStart;
var xhrOptionObject = {
path: thisRequest.theFileLikeObject.pathToFile,
headers: {
range: 'bytes=' + reqStart + '-' + (reqEnd - 1),
connection: 'keep-alive'
//protocol: 'http:'
//???? method: 'CONNECT',
}
};
if (XHR_HOSTNAME) {
xhrOptionObject.hostname = XHR_HOSTNAME;
xhrOptionObject.port = XHR_PORT;
}
thisRequest.xhrRequest = http.get(xhrOptionObject, function (res) {
var contentRange = res.headers['content-range'];
if (contentRange) {
// The part which is commented out had led to bugs. Fixing this has low priority.
// SIZE_VIDEO_FILE = parseInt(contentRange.split('/')[1], 10);
// if(thisRequest.xhrEndIndex === 0){
thisRequest.xhrFilesize = parseInt(contentRange.split('/')[1], 10);
// }
}
// Setting this kind of headers seems not to be necessary for CORS.
// res.setHeader('Access-Control-Allow-Headers', thisRequest.xhrRequest.header.origin);
if (res.statusCode && ('' + res.statusCode)[0] === "2") {
res.on('end', xhrEnd);
res.on('data', xhrDataHandler);
res.on('error', function (err) {
console.log("ERROR: " + err.message);
});
} else {
// A response from the server has been received but the server signals that it can not deliver the
// requested data.
thisRequest.xhrConducted = false;
}
});
thisRequest.xhrRequest.on('error', function (err) {
console.log("ERROR: " + err.message);
});
}
// This three functions will each be called in a different, specifiable frequent interval.
// Each of this three functions calls setTimeout to call itself in a frequent interval.
checkIfInP2pDownloadTimeRange();
chokeIfNecessary();
checkIfInServerDownloadTimeRange();
checkIfVideoDownloaded();
// updateChart(); Only for testing and debugging.
if (HASH_VALUE) {
Videostream(new FileLike(HASH_VALUE), htmlVideoTag);
} else {
Videostream(new FileLike(PATH_TO_FILE), htmlVideoTag);
}
}
// This function adds a simple-peer connection to the WebTorrent swarm of the OakStreaming instance.
// A simple-peer connection is a wrapper for a WebRTC connection.
function addP2pConnectionToWtorrent(simplePeerInstance, callback) {
if (theTorrentSession) {
if (theTorrentSession.infoHash) {
// If the infoHash property of a torrentSession object is not undefined, the addPeer method
// of the torrentSession object can be used to add simple-peer connections to the swarm
// of the WebTorrent instance.
theTorrentSession.addPeer(simplePeerInstance);
if (callback) {
callback();
}
} else {
// Because the infoHash property of the torrentSession object is undefined, the simple-peer
// connection will be saved, together with the callback function, in an array. As soon as the
// the infoHash property has been created by the WebTorrent instance, a callback function is called
// which adds all simple-peer connections in the peersToAdd array to the swarm and calls
// each corresponding callback function.
var pair = [];
pair.push(simplePeerInstance);
pair.push(callback);
peersToAdd.push(pair);
}
} else {
var pair = [];
pair.push(simplePeerInstance);
pair.push(callback);
peersToAdd.push(pair);
}
}
// Some method names of the OakStreaming library have changed during development.
// In order to increase the probability that applications which use the old method names still work,
// the current methods are also accessible via the old method names.
self.createSignalingData = self.signaling1;
self.createSignalingDataResponse = self.signaling2;
self.processSignalingResponse = self.signaling3;
self.streamVideo = self.create_stream;
self.loadVideo = self.receive_stream;
})();
}
}).call(this,require("buffer").Buffer)
},{"buffer":21,"http":34,"multistream":74,"readable-stream":112,"simple-peer":113,"ut_pex":119,"util":130,"videostream":132,"webtorrent":133}]},{},[1])
//# sourceMappingURL=example-application.js.map
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M4 10h12v2H4zm0-4h12v2H4zm0 8h8v2H4zm10 0v6l5-3z" />
, 'PlaylistPlaySharp');
|
import styles from "./index.module.scss";
import copy from "copy-to-clipboard";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faCheck,
faTrash,
faLink,
faPlay,
faTimes,
faEdit,
} from "@fortawesome/free-solid-svg-icons";
import Link from "next/link";
import { useEffect, useState } from "react";
import Button from "components/Button";
const QuizListItem = ({ title, _id, isPublic, stats, deleteQuiz, index }) => {
const [showConfirmButton, setShowConfirmButton] = useState(false);
const [isTooltipVisible, setIsTooltipVisible] = useState(false);
const [quizLink, setQuizLink] = useState("");
useEffect(() => {
setQuizLink(`${window.location.origin}/Quiz/${_id}`);
}, []);
const handleToggleConfirm = () => {
setShowConfirmButton(prev => !prev);
};
const handleCopyLink = () => {
copy(quizLink);
setIsTooltipVisible(true);
setTimeout(() => {
setIsTooltipVisible(false);
}, 2000);
};
return (
<div className={styles.container} key={_id}>
{/* quiz index */}
<div
className={[styles.tooltip, styles.tooltipBlue].join(" ")}
style={{ left: "-1%" }}
title="Quiz number"
>
{index}
</div>
{/* information if quiz is public */}
{isPublic && (
<div
className={[styles.tooltip, styles.tooltipYellow].join(" ")}
style={{ left: "8%" }}
title="This quiz is visible to other players"
>
Public
</div>
)}
{/* quiz name */}
<h3
className={[styles.tooltip, styles.title, styles.tooltipBlue].join(" ")}
title="Quiz name"
>
{title}
</h3>
{/* feedback after link is copied */}
{isTooltipVisible && (
<div
className={[styles.tooltip, styles.tooltipGreen].join(" ")}
style={{ right: "-1%" }}
>
<FontAwesomeIcon icon={faCheck} />
</div>
)}
{/* quiz stats - link, solved average result */}
<div className={styles.info}>
<p className={styles.text}>{quizLink}</p>
<p className={styles.text}>
Solved: <strong>{stats.solved}</strong> times
</p>
<p className={styles.text}>
Average result: <strong>{stats.average}%</strong>
</p>
</div>
{/* buttons container */}
<div className={styles.settings}>
<Link href={`/Quiz/${_id}`}>
<a>
<Button size="small" style="primary">
Play <FontAwesomeIcon icon={faPlay} />
</Button>
</a>
</Link>
<Link href={`/Dashboard/newquiz?id=${_id}`}>
<a>
<Button size="small">
Edit <FontAwesomeIcon icon={faEdit} />
</Button>
</a>
</Link>
<Button size="small" onClick={handleCopyLink}>
Copy link <FontAwesomeIcon icon={faLink} />
</Button>
{showConfirmButton ? (
<>
<Button
size="xsmall"
onClick={() => deleteQuiz(_id)}
style="confirm"
>
<FontAwesomeIcon icon={faCheck} /> Confirm
</Button>
<Button onClick={handleToggleConfirm} size="xsmall" style="danger">
<FontAwesomeIcon icon={faTimes} /> Cancel
</Button>
</>
) : (
<Button style="danger" size="small" onClick={handleToggleConfirm}>
Delete <FontAwesomeIcon icon={faTrash} />
</Button>
)}
</div>
</div>
);
};
export default QuizListItem;
|
require=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({"./lang/et":[function(require,module,exports){
module.exports = {
accepted: ":attribute tuleb aktsepteerida.",
active_url: ":attribute ei ole kehtiv URL.",
after: ":attribute peab olema kuupäev pärast :date.",
after_or_equal: ":attribute peab olema kuupäev pärast või samastuma :date.",
alpha: ":attribute võib sisaldada vaid tähemärke.",
alpha_dash: ":attribute võib sisaldada vaid tähti, numbreid ja kriipse.",
alpha_num: ":attribute võib sisaldada vaid tähti ja numbreid.",
attributes: {},
array: ":attribute peab olema massiiv.",
before: ":attribute peab olema kuupäev enne :date.",
before_or_equal: ":attribute peab olema kuupäev enne või samastuma :date.",
between: {
numeric: ":attribute peab olema :min ja :max vahel.",
file: ":attribute peab olema :min ja :max kilobaidi vahel.",
string: ":attribute peab olema :min ja :max tähemärgi vahel.",
array: ":attribute peab olema :min ja :max kirje vahel."
},
boolean: ":attribute väli peab olema tõene või väär.",
confirmed: ":attribute kinnitus ei vasta.",
date: ":attribute pole kehtiv kuupäev.",
date_format: ":attribute ei vasta formaadile :format.",
different: ":attribute ja :other peavad olema erinevad.",
digits: ":attribute peab olema :digits numbrit.",
digits_between: ":attribute peab olema :min ja :max numbri vahel.",
dimensions: ":attribute on valed pildi suurused.",
distinct: ":attribute väljal on topeltväärtus.",
email: ":attribute peab olema kehtiv e-posti aadress.",
exists: "Valitud :attribute on vigane.",
file: ":attribute peab olema fail.",
filled: ":attribute väli on nõutav.",
gt: {
numeric: "The :attribute must be greater than :value.",
file: "The :attribute must be greater than :value kilobytes.",
string: "The :attribute must be greater than :value characters.",
array: "The :attribute must have more than :value items."
},
gte: {
numeric: "The :attribute must be greater than or equal :value.",
file: "The :attribute must be greater than or equal :value kilobytes.",
string: "The :attribute must be greater than or equal :value characters.",
array: "The :attribute must have :value items or more."
},
hex: "The :attribute field should have hexadecimal format",
image: ":attribute peab olema pilt.",
in: "Valitud :attribute on vigane.",
in_array: ":attribute väli ei eksisteeri :other sees.",
integer: ":attribute peab olema täisarv.",
ip: ":attribute peab olema kehtiv IP aadress.",
ipv4: ":attribute peab olema kehtiv IPv4 aadress.",
ipv6: ":attribute peab olema kehtiv IPv6 aadress.",
json: ":attribute peab olema kehtiv JSON string.",
lt: {
numeric: "The :attribute must be less than :value.",
file: "The :attribute must be less than :value kilobytes.",
string: "The :attribute must be less than :value characters.",
array: "The :attribute must have less than :value items."
},
lte: {
numeric: "The :attribute must be less than or equal :value.",
file: "The :attribute must be less than or equal :value kilobytes.",
string: "The :attribute must be less than or equal :value characters.",
array: "The :attribute must not have more than :value items."
},
max: {
numeric: ":attribute ei tohi olla suurem kui :max.",
file: ":attribute ei tohi olla suurem kui :max kilobaiti.",
string: ":attribute ei tohi olla suurem kui :max tähemärki.",
array: ":attribute ei tohi sisaldada rohkem kui :max kirjet."
},
mimes: ":attribute peab olema :values tüüpi.",
mimetypes: ":attribute peab olema :values tüüpi.",
min: {
numeric: ":attribute peab olema vähemalt :min.",
file: ":attribute peab olema vähemalt :min kilobaiti.",
string: ":attribute peab olema vähemalt :min tähemärki.",
array: ":attribute peab olema vähemalt :min kirjet."
},
not_in: "Valitud :attribute on vigane.",
not_regex: "The :attribute format is invalid.",
numeric: ":attribute peab olema number.",
present: ":attribute väli peab olema esindatud.",
regex: ":attribute vorming on vigane.",
required: ":attribute väli on nõutud.",
required_if: ":attribute väli on nõutud, kui :other on :value.",
required_unless: ":attribute väli on nõutud, välja arvatud, kui :other on :values.",
required_with: ":attribute väli on nõutud, kui :values on esindatud.",
required_with_all: ":attribute väli on nõutud, kui :values on esindatud.",
required_without: ":attribute väli on nõutud, kui :values ei ole esindatud.",
required_without_all: ":attribute väli on nõutud, kui ükski :values pole esindatud.",
same: ":attribute ja :other peavad sobima.",
size: {
numeric: ":attribute peab olema :size.",
file: ":attribute peab olema :size kilobaiti.",
string: ":attribute peab olema :size tähemärki.",
array: ":attribute peab sisaldama :size kirjet."
},
string: ":attribute peab olema string.",
timezone: ":attribute peab olema kehtiv tsoon.",
unique: ":attribute on juba hõivatud.",
uploaded: ":attribute ei õnnestunud laadida.",
url: ":attribute vorming on vigane."
};
},{}]},{},[]);
|
import {expect} from 'chai'
import {shallow} from 'enzyme'
import React from 'react'
import ConfigView from '../../app/scripts/views/config'
describe('ConfigView', () => {
it('renders the given config', () => {
const config = {a: true, b: {c: 'hello'}}
const el = shallow(<ConfigView config={config}/>)
expect(el.find('textarea')).to.have.prop('value', JSON.stringify(config, null, 2))
})
})
|
/*!
localForage -- Offline Storage, Improved
Version 1.7.3
https://localforage.github.io/localForage
(c) 2013-2017 Mozilla, Apache License 2.0
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.localforage = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw (f.code="MODULE_NOT_FOUND", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function getIDB() {
/* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */
try {
if (typeof indexedDB !== 'undefined') {
return indexedDB;
}
if (typeof webkitIndexedDB !== 'undefined') {
return webkitIndexedDB;
}
if (typeof mozIndexedDB !== 'undefined') {
return mozIndexedDB;
}
if (typeof OIndexedDB !== 'undefined') {
return OIndexedDB;
}
if (typeof msIndexedDB !== 'undefined') {
return msIndexedDB;
}
} catch (e) {
return;
}
}
var idb = getIDB();
function isIndexedDBValid() {
try {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
if (!idb || !idb.open) {
return false;
}
// We mimic PouchDB here;
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;
// Safari <10.1 does not meet our requirements for IDB support
// (see: https://github.com/pouchdb/pouchdb/issues/5572).
// Safari 10.1 shipped with fetch, we can use that to detect it.
// Note: this creates issues with `window.fetch` polyfills and
// overrides; see:
// https://github.com/localForage/localForage/issues/856
return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&
// some outdated implementations of IDB that appear on Samsung
// and HTC Android devices <4.4 are missing IDBKeyRange
// See: https://github.com/mozilla/localForage/issues/128
// See: https://github.com/mozilla/localForage/issues/272
typeof IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
}
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function createBlob(parts, properties) {
/* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;
var builder = new Builder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// This is CommonJS because lie is an external dependency, so Rollup
// can just ignore it.
if (typeof Promise === 'undefined') {
// In the "nopromises" build this will just throw if you don't have
// a global promise object, but it would throw anyway later.
_dereq_('lie/polyfill');
}
var Promise$1 = Promise;
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
function executeTwoCallbacks(promise, callback, errorCallback) {
if (typeof callback === 'function') {
promise.then(callback);
}
if (typeof errorCallback === 'function') {
promise["catch"](errorCallback);
}
}
function normalizeKey(key) {
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
return key;
}
function getCallback() {
if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
return arguments[arguments.length - 1];
}
}
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
var supportsBlobs = void 0;
var dbContexts = {};
var toString = Object.prototype.toString;
// Transaction Modes
var READ_ONLY = 'readonly';
var READ_WRITE = 'readwrite';
// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
//
// Blobs are not supported in all versions of IndexedDB, notably
// Chrome <37 and Android <5. In those versions, storing a blob will throw.
//
// Various other blob bugs exist in Chrome v37-42 (inclusive).
// Detecting them is expensive and confusing to users, and Chrome 37-42
// is at very low usage worldwide, so we do a hacky userAgent check instead.
//
// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
// Code borrowed from PouchDB. See:
// https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js
//
function _checkBlobSupportWithoutCaching(idb) {
return new Promise$1(function (resolve) {
var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
var blob = createBlob(['']);
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.onabort = function (e) {
// If the transaction aborts now its due to not being able to
// write to the database, likely due to the disk being full
e.preventDefault();
e.stopPropagation();
resolve(false);
};
txn.oncomplete = function () {
var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
var matchedEdge = navigator.userAgent.match(/Edge\//);
// MS Edge pretends to be Chrome 42:
// https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
};
})["catch"](function () {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === 'boolean') {
return Promise$1.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function (value) {
supportsBlobs = value;
return supportsBlobs;
});
}
function _deferReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Create a deferred object representing the current database operation.
var deferredOperation = {};
deferredOperation.promise = new Promise$1(function (resolve, reject) {
deferredOperation.resolve = resolve;
deferredOperation.reject = reject;
});
// Enqueue the deferred operation.
dbContext.deferredOperations.push(deferredOperation);
// Chain its promise to the database readiness.
if (!dbContext.dbReady) {
dbContext.dbReady = deferredOperation.promise;
} else {
dbContext.dbReady = dbContext.dbReady.then(function () {
return deferredOperation.promise;
});
}
}
function _advanceReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Dequeue a deferred operation.
var deferredOperation = dbContext.deferredOperations.pop();
// Resolve its promise (which is part of the database readiness
// chain of promises).
if (deferredOperation) {
deferredOperation.resolve();
return deferredOperation.promise;
}
}
function _rejectReadiness(dbInfo, err) {
var dbContext = dbContexts[dbInfo.name];
// Dequeue a deferred operation.
var deferredOperation = dbContext.deferredOperations.pop();
// Reject its promise (which is part of the database readiness
// chain of promises).
if (deferredOperation) {
deferredOperation.reject(err);
return deferredOperation.promise;
}
}
function _getConnection(dbInfo, upgradeNeeded) {
return new Promise$1(function (resolve, reject) {
dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
if (dbInfo.db) {
if (upgradeNeeded) {
_deferReadiness(dbInfo);
dbInfo.db.close();
} else {
return resolve(dbInfo.db);
}
}
var dbArgs = [dbInfo.name];
if (upgradeNeeded) {
dbArgs.push(dbInfo.version);
}
var openreq = idb.open.apply(idb, dbArgs);
if (upgradeNeeded) {
openreq.onupgradeneeded = function (e) {
var db = openreq.result;
try {
db.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// Added when support for blob shims was added
db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
} catch (ex) {
if (ex.name === 'ConstraintError') {
console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
} else {
throw ex;
}
}
};
}
openreq.onerror = function (e) {
e.preventDefault();
reject(openreq.error);
};
openreq.onsuccess = function () {
resolve(openreq.result);
_advanceReadiness(dbInfo);
};
});
}
function _getOriginalConnection(dbInfo) {
return _getConnection(dbInfo, false);
}
function _getUpgradedConnection(dbInfo) {
return _getConnection(dbInfo, true);
}
function _isUpgradeNeeded(dbInfo, defaultVersion) {
if (!dbInfo.db) {
return true;
}
var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
var isDowngrade = dbInfo.version < dbInfo.db.version;
var isUpgrade = dbInfo.version > dbInfo.db.version;
if (isDowngrade) {
// If the version is not the default one
// then warn for impossible downgrade.
if (dbInfo.version !== defaultVersion) {
console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
}
// Align the versions to prevent errors.
dbInfo.version = dbInfo.db.version;
}
if (isUpgrade || isNewStore) {
// If the store is new then increment the version (if needed).
// This will trigger an "upgradeneeded" event which is required
// for creating a store.
if (isNewStore) {
var incVersion = dbInfo.db.version + 1;
if (incVersion > dbInfo.version) {
dbInfo.version = incVersion;
}
}
return true;
}
return false;
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new Promise$1(function (resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function (e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
}
// decode an encoded blob
function _decodeBlob(encodedBlob) {
var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
return createBlob([arrayBuff], { type: encodedBlob.type });
}
// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
// Specialize the default `ready()` function by making it dependent
// on the current database operations. Thus, the driver will be actually
// ready when it's been initialized (default) *and* there are no pending
// operations on the database (initiated by some other instances).
function _fullyReady(callback) {
var self = this;
var promise = self._initReady().then(function () {
var dbContext = dbContexts[self._dbInfo.name];
if (dbContext && dbContext.dbReady) {
return dbContext.dbReady;
}
});
executeTwoCallbacks(promise, callback, callback);
return promise;
}
// Try to establish a new db connection to replace the
// current one which is broken (i.e. experiencing
// InvalidStateError while creating a transaction).
function _tryReconnect(dbInfo) {
_deferReadiness(dbInfo);
var dbContext = dbContexts[dbInfo.name];
var forages = dbContext.forages;
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
if (forage._dbInfo.db) {
forage._dbInfo.db.close();
forage._dbInfo.db = null;
}
}
dbInfo.db = null;
return _getOriginalConnection(dbInfo).then(function (db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
}).then(function (db) {
// store the latest db reference
// in case the db was upgraded
dbInfo.db = dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
forages[i]._dbInfo.db = db;
}
})["catch"](function (err) {
_rejectReadiness(dbInfo, err);
throw err;
});
}
// FF doesn't like Promises (micro-tasks) and IDDB store operations,
// so we have to do it with callbacks
function createTransaction(dbInfo, mode, callback, retries) {
if (retries === undefined) {
retries = 1;
}
try {
var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
callback(null, tx);
} catch (err) {
if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {
return Promise$1.resolve().then(function () {
if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
// increase the db version, to create the new ObjectStore
if (dbInfo.db) {
dbInfo.version = dbInfo.db.version + 1;
}
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
}).then(function () {
return _tryReconnect(dbInfo).then(function () {
createTransaction(dbInfo, mode, callback, retries - 1);
});
})["catch"](callback);
}
callback(err);
}
}
function createDbContext() {
return {
// Running localForages sharing a database.
forages: [],
// Shared database.
db: null,
// Database readiness (promise).
dbReady: null,
// Deferred operations on the database.
deferredOperations: []
};
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
// Get the current context of the database;
var dbContext = dbContexts[dbInfo.name];
// ...or create a new context.
if (!dbContext) {
dbContext = createDbContext();
// Register the new context in the global container.
dbContexts[dbInfo.name] = dbContext;
}
// Register itself as a running localForage in the current context.
dbContext.forages.push(self);
// Replace the default `ready()` function with the specialized one.
if (!self._initReady) {
self._initReady = self.ready;
self.ready = _fullyReady;
}
// Create an array of initialization states of the related localForages.
var initPromises = [];
function ignoreErrors() {
// Don't handle errors here,
// just makes sure related localForages aren't pending.
return Promise$1.resolve();
}
for (var j = 0; j < dbContext.forages.length; j++) {
var forage = dbContext.forages[j];
if (forage !== self) {
// Don't wait for itself...
initPromises.push(forage._initReady()["catch"](ignoreErrors));
}
}
// Take a snapshot of the related localForages.
var forages = dbContext.forages.slice(0);
// Initialize the connection process only when
// all the related localForages aren't pending.
return Promise$1.all(initPromises).then(function () {
dbInfo.db = dbContext.db;
// Get the connection or open a new one without upgrade.
return _getOriginalConnection(dbInfo);
}).then(function (db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
}).then(function (db) {
dbInfo.db = dbContext.db = db;
self._dbInfo = dbInfo;
// Share the final connection amongst related localForages.
for (var k = 0; k < forages.length; k++) {
var forage = forages[k];
if (forage !== self) {
// Self is already up-to-date.
forage._dbInfo.db = dbInfo.db;
forage._dbInfo.version = dbInfo.version;
}
}
});
}
function getItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function () {
var value = req.result;
if (value === undefined) {
value = null;
}
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
resolve(value);
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function () {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
var result = iterator(value, cursor.key, iterationNumber++);
// when the iterator callback retuns any
// (non-`undefined`) value, then we stop
// the iteration immediately
if (result !== void 0) {
resolve(result);
} else {
cursor["continue"]();
}
} else {
resolve();
}
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
var dbInfo;
self.ready().then(function () {
dbInfo = self._dbInfo;
if (toString.call(value) === '[object Blob]') {
return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
if (blobSupport) {
return value;
}
return _encodeBlob(value);
});
}
return value;
}).then(function (value) {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var req = store.put(value, key);
transaction.oncomplete = function () {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `.delete()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store["delete"](key);
transaction.oncomplete = function () {
resolve();
};
transaction.onerror = function () {
reject(req.error);
};
// The request will be also be aborted if we've exceeded our storage
// space.
transaction.onabort = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function () {
resolve();
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.count();
req.onsuccess = function () {
resolve(req.result);
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var advanced = false;
var req = store.openCursor();
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.openCursor();
var keys = [];
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor["continue"]();
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function dropInstance(options, callback) {
callback = getCallback.apply(this, arguments);
var currentConfig = this.config();
options = typeof options !== 'function' && options || {};
if (!options.name) {
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = Promise$1.reject('Invalid arguments');
} else {
var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;
var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
forages[i]._dbInfo.db = db;
}
return db;
});
if (!options.storeName) {
promise = dbPromise.then(function (db) {
_deferReadiness(options);
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
db.close();
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
forage._dbInfo.db = null;
}
var dropDBPromise = new Promise$1(function (resolve, reject) {
var req = idb.deleteDatabase(options.name);
req.onerror = req.onblocked = function (err) {
var db = req.result;
if (db) {
db.close();
}
reject(err);
};
req.onsuccess = function () {
var db = req.result;
if (db) {
db.close();
}
resolve(db);
};
});
return dropDBPromise.then(function (db) {
dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
var _forage = forages[i];
_advanceReadiness(_forage._dbInfo);
}
})["catch"](function (err) {
(_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
throw err;
});
});
} else {
promise = dbPromise.then(function (db) {
if (!db.objectStoreNames.contains(options.storeName)) {
return;
}
var newVersion = db.version + 1;
_deferReadiness(options);
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
db.close();
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
forage._dbInfo.db = null;
forage._dbInfo.version = newVersion;
}
var dropObjectPromise = new Promise$1(function (resolve, reject) {
var req = idb.open(options.name, newVersion);
req.onerror = function (err) {
var db = req.result;
db.close();
reject(err);
};
req.onupgradeneeded = function () {
var db = req.result;
db.deleteObjectStore(options.storeName);
};
req.onsuccess = function () {
var db = req.result;
db.close();
resolve(db);
};
});
return dropObjectPromise.then(function (db) {
dbContext.db = db;
for (var j = 0; j < forages.length; j++) {
var _forage2 = forages[j];
_forage2._dbInfo.db = db;
_advanceReadiness(_forage2._dbInfo);
}
})["catch"](function (err) {
(_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
throw err;
});
});
}
}
executeCallback(promise, callback);
return promise;
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
_support: isIndexedDBValid(),
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys,
dropInstance: dropInstance
};
function isWebSQLValid() {
return typeof openDatabase === 'function';
}
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
var toString$1 = Object.prototype.toString;
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i += 4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
/*jslint bitwise: true */
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if (bytes.length % 3 === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
var valueType = '';
if (value) {
valueType = toString$1.call(value);
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueType === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueType === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueType === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueType === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueType === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueType === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueType === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueType === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueType === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueType === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function () {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ", value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return createBlob([buffer], { type: blobType });
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
function createDbTable(t, dbInfo, callback, errorCallback) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage$1(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
}
}
var dbInfoPromise = new Promise$1(function (resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
} catch (e) {
return reject(e);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function (t) {
createDbTable(t, dbInfo, function () {
self._dbInfo = dbInfo;
resolve();
}, function (t, error) {
reject(error);
});
}, reject);
});
dbInfo.serializer = localforageSerializer;
return dbInfoPromise;
}
function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {
t.executeSql(sqlStatement, args, callback, function (t, error) {
if (error.code === error.SYNTAX_ERR) {
t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name = ?", [dbInfo.storeName], function (t, results) {
if (!results.rows.length) {
// if the table is missing (was deleted)
// re-create it table and retry
createDbTable(t, dbInfo, function () {
t.executeSql(sqlStatement, args, callback, errorCallback);
}, errorCallback);
} else {
errorCallback(t, error);
}
}, errorCallback);
} else {
errorCallback(t, error);
}
}, errorCallback);
}
function getItem$1(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {
var result = results.rows.length ? results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
resolve(result);
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate$1(iterator, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void 0) {
resolve(result);
return;
}
}
resolve();
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function _setItem(key, value, callback, retriesLeft) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {
resolve(originalValue);
}, function (t, error) {
reject(error);
});
}, function (sqlError) {
// The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// Try to re-run the transaction.
if (retriesLeft > 0) {
resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));
return;
}
reject(sqlError);
}
});
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem$1(key, value, callback) {
return _setItem.apply(this, [key, value, callback, 1]);
}
function removeItem$1(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear$1(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length$1(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
// Ahhh, SQL makes this one soooooo easy.
tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key$1(n, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {
var result = results.rows.length ? results.rows.item(0).key : null;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys$1(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// https://www.w3.org/TR/webdatabase/#databases
// > There is no way to enumerate or delete the databases available for an origin from this API.
function getAllStoreNames(db) {
return new Promise$1(function (resolve, reject) {
db.transaction(function (t) {
t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function (t, results) {
var storeNames = [];
for (var i = 0; i < results.rows.length; i++) {
storeNames.push(results.rows.item(i).name);
}
resolve({
db: db,
storeNames: storeNames
});
}, function (t, error) {
reject(error);
});
}, function (sqlError) {
reject(sqlError);
});
});
}
function dropInstance$1(options, callback) {
callback = getCallback.apply(this, arguments);
var currentConfig = this.config();
options = typeof options !== 'function' && options || {};
if (!options.name) {
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = Promise$1.reject('Invalid arguments');
} else {
promise = new Promise$1(function (resolve) {
var db;
if (options.name === currentConfig.name) {
// use the db reference of the current instance
db = self._dbInfo.db;
} else {
db = openDatabase(options.name, '', '', 0);
}
if (!options.storeName) {
// drop all database tables
resolve(getAllStoreNames(db));
} else {
resolve({
db: db,
storeNames: [options.storeName]
});
}
}).then(function (operationInfo) {
return new Promise$1(function (resolve, reject) {
operationInfo.db.transaction(function (t) {
function dropTable(storeName) {
return new Promise$1(function (resolve, reject) {
t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
}
var operations = [];
for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {
operations.push(dropTable(operationInfo.storeNames[i]));
}
Promise$1.all(operations).then(function () {
resolve();
})["catch"](function (e) {
reject(e);
});
}, function (sqlError) {
reject(sqlError);
});
});
});
}
executeCallback(promise, callback);
return promise;
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage$1,
_support: isWebSQLValid(),
iterate: iterate$1,
getItem: getItem$1,
setItem: setItem$1,
removeItem: removeItem$1,
clear: clear$1,
length: length$1,
key: key$1,
keys: keys$1,
dropInstance: dropInstance$1
};
function isLocalStorageValid() {
try {
return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&
// in IE8 typeof localStorage.setItem === 'object'
!!localStorage.setItem;
} catch (e) {
return false;
}
}
function _getKeyPrefix(options, defaultConfig) {
var keyPrefix = options.name + '/';
if (options.storeName !== defaultConfig.storeName) {
keyPrefix += options.storeName + '/';
}
return keyPrefix;
}
// Check if localStorage throws when saving an item
function checkIfLocalStorageThrows() {
var localStorageTestKey = '_localforage_support_test';
try {
localStorage.setItem(localStorageTestKey, true);
localStorage.removeItem(localStorageTestKey);
return false;
} catch (e) {
return true;
}
}
// Check if localStorage is usable and allows to save an item
// This method checks if localStorage is usable in Safari Private Browsing
// mode, or in any other case where the available quota for localStorage
// is 0 and there wasn't any saved items yet.
function _isLocalStorageUsable() {
return !checkIfLocalStorageThrows() || localStorage.length > 0;
}
// Config the localStorage backend, using options set in the config.
function _initStorage$2(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);
if (!_isLocalStorageUsable()) {
return Promise$1.reject();
}
self._dbInfo = dbInfo;
dbInfo.serializer = localforageSerializer;
return Promise$1.resolve();
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear$2(callback) {
var self = this;
var promise = self.ready().then(function () {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem$2(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate$2(iterator, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var keyPrefix = dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
// We use a dedicated iterator instead of the `i` variable below
// so other keys we fetch in localStorage aren't counted in
// the `iterationNumber` argument passed to the `iterate()`
// callback.
//
// See: github.com/mozilla/localForage/pull/435#discussion_r38061530
var iterationNumber = 1;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) !== 0) {
continue;
}
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = dbInfo.serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
if (value !== void 0) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key$2(n, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys$2(callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
var itemKey = localStorage.key(i);
if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
keys.push(itemKey.substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length$2(callback) {
var self = this;
var promise = self.keys().then(function (keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem$2(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem$2(key, value, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise$1(function (resolve, reject) {
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
try {
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function dropInstance$2(options, callback) {
callback = getCallback.apply(this, arguments);
options = typeof options !== 'function' && options || {};
if (!options.name) {
var currentConfig = this.config();
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = Promise$1.reject('Invalid arguments');
} else {
promise = new Promise$1(function (resolve) {
if (!options.storeName) {
resolve(options.name + '/');
} else {
resolve(_getKeyPrefix(options, self._defaultConfig));
}
}).then(function (keyPrefix) {
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
}
executeCallback(promise, callback);
return promise;
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage$2,
_support: isLocalStorageValid(),
iterate: iterate$2,
getItem: getItem$2,
setItem: setItem$2,
removeItem: removeItem$2,
clear: clear$2,
length: length$2,
key: key$2,
keys: keys$2,
dropInstance: dropInstance$2
};
var sameValue = function sameValue(x, y) {
return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);
};
var includes = function includes(array, searchElement) {
var len = array.length;
var i = 0;
while (i < len) {
if (sameValue(array[i], searchElement)) {
return true;
}
i++;
}
return false;
};
var isArray = Array.isArray || function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
// Drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var DefinedDrivers = {};
var DriverSupport = {};
var DefaultDrivers = {
INDEXEDDB: asyncStorage,
WEBSQL: webSQLStorage,
LOCALSTORAGE: localStorageWrapper
};
var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];
var OptionalDriverMethods = ['dropInstance'];
var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);
var DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function () {
var _args = arguments;
return localForageInstance.ready().then(function () {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var _key in arg) {
if (arg.hasOwnProperty(_key)) {
if (isArray(arg[_key])) {
arguments[0][_key] = arg[_key].slice();
} else {
arguments[0][_key] = arg[_key];
}
}
}
}
}
return arguments[0];
}
var LocalForage = function () {
function LocalForage(options) {
_classCallCheck(this, LocalForage);
for (var driverTypeKey in DefaultDrivers) {
if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
var driver = DefaultDrivers[driverTypeKey];
var driverName = driver._driver;
this[driverTypeKey] = driverName;
if (!DefinedDrivers[driverName]) {
// we don't need to wait for the promise,
// since the default drivers can be defined
// in a blocking manner
this.defineDriver(driver);
}
}
}
this._defaultConfig = extend({}, DefaultConfig);
this._config = extend({}, this._defaultConfig, options);
this._driverSet = null;
this._initDriver = null;
this._ready = false;
this._dbInfo = null;
this._wrapLibraryMethodsWithReady();
this.setDriver(this._config.driver)["catch"](function () {});
}
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function config(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " + 'has been used.');
}
for (var i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
if (i === 'version' && typeof options[i] !== 'number') {
return new Error('Database version must be a number.');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
return this.setDriver(this._config.driver);
}
return true;
} else if (typeof options === 'string') {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
var promise = new Promise$1(function (resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
var driverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0, len = driverMethods.length; i < len; i++) {
var driverMethodName = driverMethods[i];
// when the property is there,
// it should be a method even when optional
var isRequired = !includes(OptionalDriverMethods, driverMethodName);
if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {
reject(complianceError);
return;
}
}
var configureMissingMethods = function configureMissingMethods() {
var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {
return function () {
var error = new Error('Method ' + methodName + ' is not implemented by the current driver');
var promise = Promise$1.reject(error);
executeCallback(promise, arguments[arguments.length - 1]);
return promise;
};
};
for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {
var optionalDriverMethod = OptionalDriverMethods[_i];
if (!driverObject[optionalDriverMethod]) {
driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);
}
}
};
configureMissingMethods();
var setDriverSupport = function setDriverSupport(support) {
if (DefinedDrivers[driverName]) {
console.info('Redefining LocalForage driver: ' + driverName);
}
DefinedDrivers[driverName] = driverObject;
DriverSupport[driverName] = support;
// don't use a then, so that we can define
// drivers that have simple _support methods
// in a blocking manner
resolve();
};
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
driverObject._support().then(setDriverSupport, reject);
} else {
setDriverSupport(!!driverObject._support);
}
} else {
setDriverSupport(true);
}
} catch (e) {
reject(e);
}
});
executeTwoCallbacks(promise, callback, errorCallback);
return promise;
};
LocalForage.prototype.driver = function driver() {
return this._driver || null;
};
LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));
executeTwoCallbacks(getDriverPromise, callback, errorCallback);
return getDriverPromise;
};
LocalForage.prototype.getSerializer = function getSerializer(callback) {
var serializerPromise = Promise$1.resolve(localforageSerializer);
executeTwoCallbacks(serializerPromise, callback);
return serializerPromise;
};
LocalForage.prototype.ready = function ready(callback) {
var self = this;
var promise = self._driverSet.then(function () {
if (self._ready === null) {
self._ready = self._initDriver();
}
return self._ready;
});
executeTwoCallbacks(promise, callback, callback);
return promise;
};
LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
var self = this;
if (!isArray(drivers)) {
drivers = [drivers];
}
var supportedDrivers = this._getSupportedDrivers(drivers);
function setDriverToConfig() {
self._config.driver = self.driver();
}
function extendSelfWithDriver(driver) {
self._extend(driver);
setDriverToConfig();
self._ready = self._initStorage(self._config);
return self._ready;
}
function initDriver(supportedDrivers) {
return function () {
var currentDriverIndex = 0;
function driverPromiseLoop() {
while (currentDriverIndex < supportedDrivers.length) {
var driverName = supportedDrivers[currentDriverIndex];
currentDriverIndex++;
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop);
}
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise$1.reject(error);
return self._driverSet;
}
return driverPromiseLoop();
};
}
// There might be a driver initialization in progress
// so wait for it to finish in order to avoid a possible
// race condition to set _dbInfo
var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () {
return Promise$1.resolve();
}) : Promise$1.resolve();
this._driverSet = oldDriverSetDone.then(function () {
var driverName = supportedDrivers[0];
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(function (driver) {
self._driver = driver._driver;
setDriverToConfig();
self._wrapLibraryMethodsWithReady();
self._initDriver = initDriver(supportedDrivers);
});
})["catch"](function () {
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise$1.reject(error);
return self._driverSet;
});
executeTwoCallbacks(this._driverSet, callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function supports(driverName) {
return !!DriverSupport[driverName];
};
LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
var supportedDrivers = [];
for (var i = 0, len = drivers.length; i < len; i++) {
var driverName = drivers[i];
if (this.supports(driverName)) {
supportedDrivers.push(driverName);
}
}
return supportedDrivers;
};
LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0, len = LibraryMethods.length; i < len; i++) {
callWhenReady(this, LibraryMethods[i]);
}
};
LocalForage.prototype.createInstance = function createInstance(options) {
return new LocalForage(options);
};
return LocalForage;
}();
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
var localforage_js = new LocalForage();
module.exports = localforage_js;
},{"undefined":undefined}]},{},[1])(1)
});
|
// @flow
import * as N from "../types";
import { types as tt, type TokenType } from "../tokenizer/types";
import ExpressionParser from "./expression";
import { Errors } from "./location";
import {
isIdentifierChar,
isIdentifierStart,
keywordRelationalOperator,
} from "../util/identifier";
import { lineBreak } from "../util/whitespace";
import * as charCodes from "charcodes";
import {
BIND_CLASS,
BIND_LEXICAL,
BIND_VAR,
BIND_FUNCTION,
SCOPE_CLASS,
SCOPE_FUNCTION,
SCOPE_OTHER,
SCOPE_SIMPLE_CATCH,
SCOPE_SUPER,
CLASS_ELEMENT_OTHER,
CLASS_ELEMENT_INSTANCE_GETTER,
CLASS_ELEMENT_INSTANCE_SETTER,
CLASS_ELEMENT_STATIC_GETTER,
CLASS_ELEMENT_STATIC_SETTER,
type BindingTypes,
} from "../util/scopeflags";
import { ExpressionErrors } from "./util";
import { PARAM, functionFlags } from "../util/production-parameter";
const loopLabel = { kind: "loop" },
switchLabel = { kind: "switch" };
const FUNC_NO_FLAGS = 0b000,
FUNC_STATEMENT = 0b001,
FUNC_HANGING_STATEMENT = 0b010,
FUNC_NULLABLE_ID = 0b100;
export default class StatementParser extends ExpressionParser {
// ### Statement parsing
// Parse a program. Initializes the parser, reads any number of
// statements, and wraps them in a Program node. Optionally takes a
// `program` argument. If present, the statements will be appended
// to its body instead of creating a new node.
parseTopLevel(file: N.File, program: N.Program): N.File {
program.sourceType = this.options.sourceType;
program.interpreter = this.parseInterpreterDirective();
this.parseBlockBody(program, true, true, tt.eof);
if (
this.inModule &&
!this.options.allowUndeclaredExports &&
this.scope.undefinedExports.size > 0
) {
for (const [name] of Array.from(this.scope.undefinedExports)) {
const pos = this.scope.undefinedExports.get(name);
// $FlowIssue
this.raise(pos, Errors.ModuleExportUndefined, name);
}
}
file.program = this.finishNode(program, "Program");
file.comments = this.state.comments;
if (this.options.tokens) file.tokens = this.tokens;
return this.finishNode(file, "File");
}
// TODO
stmtToDirective(stmt: N.Statement): N.Directive {
const expr = stmt.expression;
const directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
const directive = this.startNodeAt(stmt.start, stmt.loc.start);
const raw = this.input.slice(expr.start, expr.end);
const val = (directiveLiteral.value = raw.slice(1, -1)); // remove quotes
this.addExtra(directiveLiteral, "raw", raw);
this.addExtra(directiveLiteral, "rawValue", val);
directive.value = this.finishNodeAt(
directiveLiteral,
"DirectiveLiteral",
expr.end,
expr.loc.end,
);
return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
}
parseInterpreterDirective(): N.InterpreterDirective | null {
if (!this.match(tt.interpreterDirective)) {
return null;
}
const node = this.startNode();
node.value = this.state.value;
this.next();
return this.finishNode(node, "InterpreterDirective");
}
isLet(context: ?string): boolean {
if (!this.isContextual("let")) {
return false;
}
const next = this.nextTokenStart();
const nextCh = this.input.charCodeAt(next);
// For ambiguous cases, determine if a LexicalDeclaration (or only a
// Statement) is allowed here. If context is not empty then only a Statement
// is allowed. However, `let [` is an explicit negative lookahead for
// ExpressionStatement, so special-case it first.
if (nextCh === charCodes.leftSquareBracket) return true;
if (context) return false;
if (nextCh === charCodes.leftCurlyBrace) return true;
if (isIdentifierStart(nextCh)) {
let pos = next + 1;
while (isIdentifierChar(this.input.charCodeAt(pos))) {
++pos;
}
const ident = this.input.slice(next, pos);
if (!keywordRelationalOperator.test(ident)) return true;
}
return false;
}
// Parse a single statement.
//
// If expecting a statement and finding a slash operator, parse a
// regular expression literal. This is to handle cases like
// `if (foo) /blah/.exec(foo)`, where looking at the previous token
// does not help.
parseStatement(context: ?string, topLevel?: boolean): N.Statement {
if (this.match(tt.at)) {
this.parseDecorators(true);
}
return this.parseStatementContent(context, topLevel);
}
parseStatementContent(context: ?string, topLevel: ?boolean): N.Statement {
let starttype = this.state.type;
const node = this.startNode();
let kind;
if (this.isLet(context)) {
starttype = tt._var;
kind = "let";
}
// Most types of statements are recognized by the keyword they
// start with. Many are trivial to parse, some require a bit of
// complexity.
switch (starttype) {
case tt._break:
case tt._continue:
// $FlowFixMe
return this.parseBreakContinueStatement(node, starttype.keyword);
case tt._debugger:
return this.parseDebuggerStatement(node);
case tt._do:
return this.parseDoStatement(node);
case tt._for:
return this.parseForStatement(node);
case tt._function:
if (this.lookaheadCharCode() === charCodes.dot) break;
if (context) {
if (this.state.strict) {
this.raise(this.state.start, Errors.StrictFunction);
} else if (context !== "if" && context !== "label") {
this.raise(this.state.start, Errors.SloppyFunction);
}
}
return this.parseFunctionStatement(node, false, !context);
case tt._class:
if (context) this.unexpected();
return this.parseClass(node, true);
case tt._if:
return this.parseIfStatement(node);
case tt._return:
return this.parseReturnStatement(node);
case tt._switch:
return this.parseSwitchStatement(node);
case tt._throw:
return this.parseThrowStatement(node);
case tt._try:
return this.parseTryStatement(node);
case tt._const:
case tt._var:
kind = kind || this.state.value;
if (context && kind !== "var") {
this.raise(this.state.start, Errors.UnexpectedLexicalDeclaration);
}
return this.parseVarStatement(node, kind);
case tt._while:
return this.parseWhileStatement(node);
case tt._with:
return this.parseWithStatement(node);
case tt.braceL:
return this.parseBlock();
case tt.semi:
return this.parseEmptyStatement(node);
case tt._export:
case tt._import: {
const nextTokenCharCode = this.lookaheadCharCode();
if (
nextTokenCharCode === charCodes.leftParenthesis ||
nextTokenCharCode === charCodes.dot
) {
break;
}
if (!this.options.allowImportExportEverywhere && !topLevel) {
this.raise(this.state.start, Errors.UnexpectedImportExport);
}
this.next();
let result;
if (starttype === tt._import) {
result = this.parseImport(node);
if (
result.type === "ImportDeclaration" &&
(!result.importKind || result.importKind === "value")
) {
this.sawUnambiguousESM = true;
}
} else {
result = this.parseExport(node);
if (
(result.type === "ExportNamedDeclaration" &&
(!result.exportKind || result.exportKind === "value")) ||
(result.type === "ExportAllDeclaration" &&
(!result.exportKind || result.exportKind === "value")) ||
result.type === "ExportDefaultDeclaration"
) {
this.sawUnambiguousESM = true;
}
}
this.assertModuleNodeAllowed(node);
return result;
}
default: {
if (this.isAsyncFunction()) {
if (context) {
this.raise(
this.state.start,
Errors.AsyncFunctionInSingleStatementContext,
);
}
this.next();
return this.parseFunctionStatement(node, true, !context);
}
}
}
// If the statement does not start with a statement keyword or a
// brace, it's an ExpressionStatement or LabeledStatement. We
// simply start parsing an expression, and afterwards, if the
// next token is a colon and the expression was a simple
// Identifier node, we switch to interpreting it as a label.
const maybeName = this.state.value;
const expr = this.parseExpression();
if (
starttype === tt.name &&
expr.type === "Identifier" &&
this.eat(tt.colon)
) {
return this.parseLabeledStatement(node, maybeName, expr, context);
} else {
return this.parseExpressionStatement(node, expr);
}
}
assertModuleNodeAllowed(node: N.Node): void {
if (!this.options.allowImportExportEverywhere && !this.inModule) {
this.raiseWithData(
node.start,
{
code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED",
},
Errors.ImportOutsideModule,
);
}
}
takeDecorators(node: N.HasDecorators): void {
const decorators = this.state.decoratorStack[
this.state.decoratorStack.length - 1
];
if (decorators.length) {
node.decorators = decorators;
this.resetStartLocationFromNode(node, decorators[0]);
this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
}
}
canHaveLeadingDecorator(): boolean {
return this.match(tt._class);
}
parseDecorators(allowExport?: boolean): void {
const currentContextDecorators = this.state.decoratorStack[
this.state.decoratorStack.length - 1
];
while (this.match(tt.at)) {
const decorator = this.parseDecorator();
currentContextDecorators.push(decorator);
}
if (this.match(tt._export)) {
if (!allowExport) {
this.unexpected();
}
if (
this.hasPlugin("decorators") &&
!this.getPluginOption("decorators", "decoratorsBeforeExport")
) {
this.raise(this.state.start, Errors.DecoratorExportClass);
}
} else if (!this.canHaveLeadingDecorator()) {
throw this.raise(this.state.start, Errors.UnexpectedLeadingDecorator);
}
}
parseDecorator(): N.Decorator {
this.expectOnePlugin(["decorators-legacy", "decorators"]);
const node = this.startNode();
this.next();
if (this.hasPlugin("decorators")) {
// Every time a decorator class expression is evaluated, a new empty array is pushed onto the stack
// So that the decorators of any nested class expressions will be dealt with separately
this.state.decoratorStack.push([]);
const startPos = this.state.start;
const startLoc = this.state.startLoc;
let expr: N.Expression;
if (this.eat(tt.parenL)) {
expr = this.parseExpression();
this.expect(tt.parenR);
} else {
expr = this.parseIdentifier(false);
while (this.eat(tt.dot)) {
const node = this.startNodeAt(startPos, startLoc);
node.object = expr;
node.property = this.parseIdentifier(true);
node.computed = false;
expr = this.finishNode(node, "MemberExpression");
}
}
node.expression = this.parseMaybeDecoratorArguments(expr);
this.state.decoratorStack.pop();
} else {
node.expression = this.parseExprSubscripts();
}
return this.finishNode(node, "Decorator");
}
parseMaybeDecoratorArguments(expr: N.Expression): N.Expression {
if (this.eat(tt.parenL)) {
const node = this.startNodeAtNode(expr);
node.callee = expr;
node.arguments = this.parseCallExpressionArguments(tt.parenR, false);
this.toReferencedList(node.arguments);
return this.finishNode(node, "CallExpression");
}
return expr;
}
parseBreakContinueStatement(
node: N.BreakStatement | N.ContinueStatement,
keyword: string,
): N.BreakStatement | N.ContinueStatement {
const isBreak = keyword === "break";
this.next();
if (this.isLineTerminator()) {
node.label = null;
} else {
node.label = this.parseIdentifier();
this.semicolon();
}
this.verifyBreakContinue(node, keyword);
return this.finishNode(
node,
isBreak ? "BreakStatement" : "ContinueStatement",
);
}
verifyBreakContinue(
node: N.BreakStatement | N.ContinueStatement,
keyword: string,
) {
const isBreak = keyword === "break";
let i;
for (i = 0; i < this.state.labels.length; ++i) {
const lab = this.state.labels[i];
if (node.label == null || lab.name === node.label.name) {
if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
if (node.label && isBreak) break;
}
}
if (i === this.state.labels.length) {
this.raise(node.start, Errors.IllegalBreakContinue, keyword);
}
}
parseDebuggerStatement(node: N.DebuggerStatement): N.DebuggerStatement {
this.next();
this.semicolon();
return this.finishNode(node, "DebuggerStatement");
}
parseHeaderExpression(): N.Expression {
this.expect(tt.parenL);
const val = this.parseExpression();
this.expect(tt.parenR);
return val;
}
parseDoStatement(node: N.DoWhileStatement): N.DoWhileStatement {
this.next();
this.state.labels.push(loopLabel);
node.body =
// For the smartPipelines plugin: Disable topic references from outer
// contexts within the loop body. They are permitted in test expressions,
// outside of the loop body.
this.withTopicForbiddingContext(() =>
// Parse the loop body's body.
this.parseStatement("do"),
);
this.state.labels.pop();
this.expect(tt._while);
node.test = this.parseHeaderExpression();
this.eat(tt.semi);
return this.finishNode(node, "DoWhileStatement");
}
// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
// loop is non-trivial. Basically, we have to parse the init `var`
// statement or expression, disallowing the `in` operator (see
// the second parameter to `parseExpression`), and then check
// whether the next token is `in` or `of`. When there is no init
// part (semicolon immediately after the opening parenthesis), it
// is a regular `for` loop.
parseForStatement(node: N.Node): N.ForLike {
this.next();
this.state.labels.push(loopLabel);
let awaitAt = -1;
if (this.isAwaitAllowed() && this.eatContextual("await")) {
awaitAt = this.state.lastTokStart;
}
this.scope.enter(SCOPE_OTHER);
this.expect(tt.parenL);
if (this.match(tt.semi)) {
if (awaitAt > -1) {
this.unexpected(awaitAt);
}
return this.parseFor(node, null);
}
const isLet = this.isLet();
if (this.match(tt._var) || this.match(tt._const) || isLet) {
const init = this.startNode();
const kind = isLet ? "let" : this.state.value;
this.next();
this.parseVar(init, true, kind);
this.finishNode(init, "VariableDeclaration");
if (
(this.match(tt._in) || this.isContextual("of")) &&
init.declarations.length === 1
) {
return this.parseForIn(node, init, awaitAt);
}
if (awaitAt > -1) {
this.unexpected(awaitAt);
}
return this.parseFor(node, init);
}
const refExpressionErrors = new ExpressionErrors();
const init = this.parseExpression(true, refExpressionErrors);
if (this.match(tt._in) || this.isContextual("of")) {
this.toAssignable(init);
const description = this.isContextual("of")
? "for-of statement"
: "for-in statement";
this.checkLVal(init, undefined, undefined, description);
return this.parseForIn(node, init, awaitAt);
} else {
this.checkExpressionErrors(refExpressionErrors, true);
}
if (awaitAt > -1) {
this.unexpected(awaitAt);
}
return this.parseFor(node, init);
}
parseFunctionStatement(
node: N.FunctionDeclaration,
isAsync?: boolean,
declarationPosition?: boolean,
): N.FunctionDeclaration {
this.next();
return this.parseFunction(
node,
FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT),
isAsync,
);
}
parseIfStatement(node: N.IfStatement): N.IfStatement {
this.next();
node.test = this.parseHeaderExpression();
node.consequent = this.parseStatement("if");
node.alternate = this.eat(tt._else) ? this.parseStatement("if") : null;
return this.finishNode(node, "IfStatement");
}
parseReturnStatement(node: N.ReturnStatement): N.ReturnStatement {
if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
this.raise(this.state.start, Errors.IllegalReturn);
}
this.next();
// In `return` (and `break`/`continue`), the keywords with
// optional arguments, we eagerly look for a semicolon or the
// possibility to insert one.
if (this.isLineTerminator()) {
node.argument = null;
} else {
node.argument = this.parseExpression();
this.semicolon();
}
return this.finishNode(node, "ReturnStatement");
}
parseSwitchStatement(node: N.SwitchStatement): N.SwitchStatement {
this.next();
node.discriminant = this.parseHeaderExpression();
const cases = (node.cases = []);
this.expect(tt.braceL);
this.state.labels.push(switchLabel);
this.scope.enter(SCOPE_OTHER);
// Statements under must be grouped (by label) in SwitchCase
// nodes. `cur` is used to keep the node that we are currently
// adding statements to.
let cur;
for (let sawDefault; !this.match(tt.braceR); ) {
if (this.match(tt._case) || this.match(tt._default)) {
const isCase = this.match(tt._case);
if (cur) this.finishNode(cur, "SwitchCase");
cases.push((cur = this.startNode()));
cur.consequent = [];
this.next();
if (isCase) {
cur.test = this.parseExpression();
} else {
if (sawDefault) {
this.raise(
this.state.lastTokStart,
Errors.MultipleDefaultsInSwitch,
);
}
sawDefault = true;
cur.test = null;
}
this.expect(tt.colon);
} else {
if (cur) {
cur.consequent.push(this.parseStatement(null));
} else {
this.unexpected();
}
}
}
this.scope.exit();
if (cur) this.finishNode(cur, "SwitchCase");
this.next(); // Closing brace
this.state.labels.pop();
return this.finishNode(node, "SwitchStatement");
}
parseThrowStatement(node: N.ThrowStatement): N.ThrowStatement {
this.next();
if (
lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))
) {
this.raise(this.state.lastTokEnd, Errors.NewlineAfterThrow);
}
node.argument = this.parseExpression();
this.semicolon();
return this.finishNode(node, "ThrowStatement");
}
parseTryStatement(node: N.TryStatement): N.TryStatement {
this.next();
node.block = this.parseBlock();
node.handler = null;
if (this.match(tt._catch)) {
const clause = this.startNode();
this.next();
if (this.match(tt.parenL)) {
this.expect(tt.parenL);
clause.param = this.parseBindingAtom();
const simple = clause.param.type === "Identifier";
this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
this.checkLVal(clause.param, BIND_LEXICAL, null, "catch clause");
this.expect(tt.parenR);
} else {
clause.param = null;
this.scope.enter(SCOPE_OTHER);
}
clause.body =
// For the smartPipelines plugin: Disable topic references from outer
// contexts within the function body. They are permitted in function
// default-parameter expressions, which are part of the outer context,
// outside of the function body.
this.withTopicForbiddingContext(() =>
// Parse the catch clause's body.
this.parseBlock(false, false),
);
this.scope.exit();
node.handler = this.finishNode(clause, "CatchClause");
}
node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null;
if (!node.handler && !node.finalizer) {
this.raise(node.start, Errors.NoCatchOrFinally);
}
return this.finishNode(node, "TryStatement");
}
parseVarStatement(
node: N.VariableDeclaration,
kind: "var" | "let" | "const",
): N.VariableDeclaration {
this.next();
this.parseVar(node, false, kind);
this.semicolon();
return this.finishNode(node, "VariableDeclaration");
}
parseWhileStatement(node: N.WhileStatement): N.WhileStatement {
this.next();
node.test = this.parseHeaderExpression();
this.state.labels.push(loopLabel);
node.body =
// For the smartPipelines plugin:
// Disable topic references from outer contexts within the loop body.
// They are permitted in test expressions, outside of the loop body.
this.withTopicForbiddingContext(() =>
// Parse loop body.
this.parseStatement("while"),
);
this.state.labels.pop();
return this.finishNode(node, "WhileStatement");
}
parseWithStatement(node: N.WithStatement): N.WithStatement {
if (this.state.strict) {
this.raise(this.state.start, Errors.StrictWith);
}
this.next();
node.object = this.parseHeaderExpression();
node.body =
// For the smartPipelines plugin:
// Disable topic references from outer contexts within the function body.
// They are permitted in function default-parameter expressions, which are
// part of the outer context, outside of the function body.
this.withTopicForbiddingContext(() =>
// Parse the statement body.
this.parseStatement("with"),
);
return this.finishNode(node, "WithStatement");
}
parseEmptyStatement(node: N.EmptyStatement): N.EmptyStatement {
this.next();
return this.finishNode(node, "EmptyStatement");
}
parseLabeledStatement(
node: N.LabeledStatement,
maybeName: string,
expr: N.Identifier,
context: ?string,
): N.LabeledStatement {
for (const label of this.state.labels) {
if (label.name === maybeName) {
this.raise(expr.start, Errors.LabelRedeclaration, maybeName);
}
}
const kind = this.state.type.isLoop
? "loop"
: this.match(tt._switch)
? "switch"
: null;
for (let i = this.state.labels.length - 1; i >= 0; i--) {
const label = this.state.labels[i];
if (label.statementStart === node.start) {
label.statementStart = this.state.start;
label.kind = kind;
} else {
break;
}
}
this.state.labels.push({
name: maybeName,
kind: kind,
statementStart: this.state.start,
});
node.body = this.parseStatement(
context
? context.indexOf("label") === -1
? context + "label"
: context
: "label",
);
this.state.labels.pop();
node.label = expr;
return this.finishNode(node, "LabeledStatement");
}
parseExpressionStatement(
node: N.ExpressionStatement,
expr: N.Expression,
): N.Statement {
node.expression = expr;
this.semicolon();
return this.finishNode(node, "ExpressionStatement");
}
// Parse a semicolon-enclosed block of statements, handling `"use
// strict"` declarations when `allowStrict` is true (used for
// function bodies).
parseBlock(
allowDirectives?: boolean = false,
createNewLexicalScope?: boolean = true,
afterBlockParse?: (hasStrictModeDirective: boolean) => void,
): N.BlockStatement {
const node = this.startNode();
this.expect(tt.braceL);
if (createNewLexicalScope) {
this.scope.enter(SCOPE_OTHER);
}
this.parseBlockBody(
node,
allowDirectives,
false,
tt.braceR,
afterBlockParse,
);
if (createNewLexicalScope) {
this.scope.exit();
}
return this.finishNode(node, "BlockStatement");
}
isValidDirective(stmt: N.Statement): boolean {
return (
stmt.type === "ExpressionStatement" &&
stmt.expression.type === "StringLiteral" &&
!stmt.expression.extra.parenthesized
);
}
parseBlockBody(
node: N.BlockStatementLike,
allowDirectives: ?boolean,
topLevel: boolean,
end: TokenType,
afterBlockParse?: (hasStrictModeDirective: boolean) => void,
): void {
const body = (node.body = []);
const directives = (node.directives = []);
this.parseBlockOrModuleBlockBody(
body,
allowDirectives ? directives : undefined,
topLevel,
end,
afterBlockParse,
);
}
// Undefined directives means that directives are not allowed.
parseBlockOrModuleBlockBody(
body: N.Statement[],
directives: ?(N.Directive[]),
topLevel: boolean,
end: TokenType,
afterBlockParse?: (hasStrictModeDirective: boolean) => void,
): void {
const octalPositions = [];
let parsedNonDirective = false;
let oldStrict = null;
while (!this.eat(end)) {
// Track octal literals that occur before a "use strict" directive.
if (!parsedNonDirective && this.state.octalPositions.length) {
octalPositions.push(...this.state.octalPositions);
}
const stmt = this.parseStatement(null, topLevel);
if (directives && !parsedNonDirective && this.isValidDirective(stmt)) {
const directive = this.stmtToDirective(stmt);
directives.push(directive);
if (oldStrict === null && directive.value.value === "use strict") {
oldStrict = this.state.strict;
this.setStrict(true);
}
continue;
}
parsedNonDirective = true;
body.push(stmt);
}
// Throw an error for any octal literals found before a
// "use strict" directive. Strict mode will be set at parse
// time for any literals that occur after the directive.
if (this.state.strict && octalPositions.length) {
for (const pos of octalPositions) {
this.raise(pos, Errors.StrictOctalLiteral);
}
}
if (afterBlockParse) {
afterBlockParse.call(
this,
/* hasStrictModeDirective */ oldStrict !== null,
);
}
if (oldStrict === false) {
this.setStrict(false);
}
}
// Parse a regular `for` loop. The disambiguation code in
// `parseStatement` will already have parsed the init statement or
// expression.
parseFor(
node: N.ForStatement,
init: ?(N.VariableDeclaration | N.Expression),
): N.ForStatement {
node.init = init;
this.expect(tt.semi);
node.test = this.match(tt.semi) ? null : this.parseExpression();
this.expect(tt.semi);
node.update = this.match(tt.parenR) ? null : this.parseExpression();
this.expect(tt.parenR);
node.body =
// For the smartPipelines plugin: Disable topic references from outer
// contexts within the loop body. They are permitted in test expressions,
// outside of the loop body.
this.withTopicForbiddingContext(() =>
// Parse the loop body.
this.parseStatement("for"),
);
this.scope.exit();
this.state.labels.pop();
return this.finishNode(node, "ForStatement");
}
// Parse a `for`/`in` and `for`/`of` loop, which are almost
// same from parser's perspective.
parseForIn(
node: N.ForInOf,
init: N.VariableDeclaration | N.AssignmentPattern,
awaitAt: number,
): N.ForInOf {
const isForIn = this.match(tt._in);
this.next();
if (isForIn) {
if (awaitAt > -1) this.unexpected(awaitAt);
} else {
node.await = awaitAt > -1;
}
if (
init.type === "VariableDeclaration" &&
init.declarations[0].init != null &&
(!isForIn ||
this.state.strict ||
init.kind !== "var" ||
init.declarations[0].id.type !== "Identifier")
) {
this.raise(
init.start,
Errors.ForInOfLoopInitializer,
isForIn ? "for-in" : "for-of",
);
} else if (init.type === "AssignmentPattern") {
this.raise(init.start, Errors.InvalidLhs, "for-loop");
}
node.left = init;
node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
this.expect(tt.parenR);
node.body =
// For the smartPipelines plugin:
// Disable topic references from outer contexts within the loop body.
// They are permitted in test expressions, outside of the loop body.
this.withTopicForbiddingContext(() =>
// Parse loop body.
this.parseStatement("for"),
);
this.scope.exit();
this.state.labels.pop();
return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
}
// Parse a list of variable declarations.
parseVar(
node: N.VariableDeclaration,
isFor: boolean,
kind: "var" | "let" | "const",
): N.VariableDeclaration {
const declarations = (node.declarations = []);
const isTypescript = this.hasPlugin("typescript");
node.kind = kind;
for (;;) {
const decl = this.startNode();
this.parseVarId(decl, kind);
if (this.eat(tt.eq)) {
decl.init = this.parseMaybeAssign(isFor);
} else {
if (
kind === "const" &&
!(this.match(tt._in) || this.isContextual("of"))
) {
// `const` with no initializer is allowed in TypeScript.
// It could be a declaration like `const x: number;`.
if (!isTypescript) {
this.unexpected();
}
} else if (
decl.id.type !== "Identifier" &&
!(isFor && (this.match(tt._in) || this.isContextual("of")))
) {
this.raise(
this.state.lastTokEnd,
Errors.DeclarationMissingInitializer,
"Complex binding patterns",
);
}
decl.init = null;
}
declarations.push(this.finishNode(decl, "VariableDeclarator"));
if (!this.eat(tt.comma)) break;
}
return node;
}
parseVarId(decl: N.VariableDeclarator, kind: "var" | "let" | "const"): void {
decl.id = this.parseBindingAtom();
this.checkLVal(
decl.id,
kind === "var" ? BIND_VAR : BIND_LEXICAL,
undefined,
"variable declaration",
kind !== "var",
);
}
// Parse a function declaration or literal (depending on the
// `isStatement` parameter).
parseFunction<T: N.NormalFunction>(
node: T,
statement?: number = FUNC_NO_FLAGS,
isAsync?: boolean = false,
): T {
const isStatement = statement & FUNC_STATEMENT;
const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
this.initFunction(node, isAsync);
if (this.match(tt.star) && isHangingStatement) {
this.raise(this.state.start, Errors.GeneratorInSingleStatementContext);
}
node.generator = this.eat(tt.star);
if (isStatement) {
node.id = this.parseFunctionId(requireId);
}
const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
const oldYieldPos = this.state.yieldPos;
const oldAwaitPos = this.state.awaitPos;
this.state.maybeInArrowParameters = false;
this.state.yieldPos = -1;
this.state.awaitPos = -1;
this.scope.enter(SCOPE_FUNCTION);
this.prodParam.enter(functionFlags(isAsync, node.generator));
if (!isStatement) {
node.id = this.parseFunctionId();
}
this.parseFunctionParams(node);
// For the smartPipelines plugin: Disable topic references from outer
// contexts within the function body. They are permitted in test
// expressions, outside of the function body.
this.withTopicForbiddingContext(() => {
// Parse the function body.
this.parseFunctionBodyAndFinish(
node,
isStatement ? "FunctionDeclaration" : "FunctionExpression",
);
});
this.prodParam.exit();
this.scope.exit();
if (isStatement && !isHangingStatement) {
// We need to register this _after_ parsing the function body
// because of TypeScript body-less function declarations,
// which shouldn't be added to the scope.
this.registerFunctionStatementId(node);
}
this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
this.state.yieldPos = oldYieldPos;
this.state.awaitPos = oldAwaitPos;
return node;
}
parseFunctionId(requireId?: boolean): ?N.Identifier {
return requireId || this.match(tt.name) ? this.parseIdentifier() : null;
}
parseFunctionParams(node: N.Function, allowModifiers?: boolean): void {
const oldInParameters = this.state.inParameters;
this.state.inParameters = true;
this.expect(tt.parenL);
node.params = this.parseBindingList(
tt.parenR,
charCodes.rightParenthesis,
/* allowEmpty */ false,
allowModifiers,
);
this.state.inParameters = oldInParameters;
this.checkYieldAwaitInDefaultParams();
}
registerFunctionStatementId(node: N.Function): void {
if (!node.id) return;
// If it is a regular function declaration in sloppy mode, then it is
// subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
// mode depends on properties of the current scope (see
// treatFunctionsAsVar).
this.scope.declareName(
node.id.name,
this.state.strict || node.generator || node.async
? this.scope.treatFunctionsAsVar
? BIND_VAR
: BIND_LEXICAL
: BIND_FUNCTION,
node.id.start,
);
}
// Parse a class declaration or literal (depending on the
// `isStatement` parameter).
parseClass<T: N.Class>(
node: T,
isStatement: /* T === ClassDeclaration */ boolean,
optionalId?: boolean,
): T {
this.next();
this.takeDecorators(node);
// A class definition is always strict mode code.
const oldStrict = this.state.strict;
this.state.strict = true;
this.parseClassId(node, isStatement, optionalId);
this.parseClassSuper(node);
node.body = this.parseClassBody(!!node.superClass);
this.state.strict = oldStrict;
return this.finishNode(
node,
isStatement ? "ClassDeclaration" : "ClassExpression",
);
}
isClassProperty(): boolean {
return this.match(tt.eq) || this.match(tt.semi) || this.match(tt.braceR);
}
isClassMethod(): boolean {
return this.match(tt.parenL);
}
isNonstaticConstructor(method: N.ClassMethod | N.ClassProperty): boolean {
return (
!method.computed &&
!method.static &&
(method.key.name === "constructor" || // Identifier
method.key.value === "constructor") // String literal
);
}
parseClassBody(constructorAllowsSuper: boolean): N.ClassBody {
this.classScope.enter();
const state = { hadConstructor: false };
let decorators: N.Decorator[] = [];
const classBody: N.ClassBody = this.startNode();
classBody.body = [];
this.expect(tt.braceL);
// For the smartPipelines plugin: Disable topic references from outer
// contexts within the class body. They are permitted in test expressions,
// outside of the class body.
this.withTopicForbiddingContext(() => {
while (!this.eat(tt.braceR)) {
if (this.eat(tt.semi)) {
if (decorators.length > 0) {
throw this.raise(this.state.lastTokEnd, Errors.DecoratorSemicolon);
}
continue;
}
if (this.match(tt.at)) {
decorators.push(this.parseDecorator());
continue;
}
const member = this.startNode();
// steal the decorators if there are any
if (decorators.length) {
member.decorators = decorators;
this.resetStartLocationFromNode(member, decorators[0]);
decorators = [];
}
this.parseClassMember(classBody, member, state, constructorAllowsSuper);
if (
member.kind === "constructor" &&
member.decorators &&
member.decorators.length > 0
) {
this.raise(member.start, Errors.DecoratorConstructor);
}
}
});
if (decorators.length) {
throw this.raise(this.state.start, Errors.TrailingDecorator);
}
this.classScope.exit();
return this.finishNode(classBody, "ClassBody");
}
// returns true if the current identifier is a method/field name,
// false if it is a modifier
parseClassMemberFromModifier(
classBody: N.ClassBody,
member: N.ClassMember,
): boolean {
const containsEsc = this.state.containsEsc;
const key = this.parseIdentifier(true); // eats the modifier
if (this.isClassMethod()) {
const method: N.ClassMethod = (member: any);
// a method named like the modifier
method.kind = "method";
method.computed = false;
method.key = key;
method.static = false;
this.pushClassMethod(
classBody,
method,
false,
false,
/* isConstructor */ false,
false,
);
return true;
} else if (this.isClassProperty()) {
const prop: N.ClassProperty = (member: any);
// a property named like the modifier
prop.computed = false;
prop.key = key;
prop.static = false;
classBody.body.push(this.parseClassProperty(prop));
return true;
} else if (containsEsc) {
throw this.unexpected();
}
return false;
}
parseClassMember(
classBody: N.ClassBody,
member: N.ClassMember,
state: { hadConstructor: boolean },
constructorAllowsSuper: boolean,
): void {
const isStatic = this.isContextual("static");
if (isStatic && this.parseClassMemberFromModifier(classBody, member)) {
// a class element named 'static'
return;
}
this.parseClassMemberWithIsStatic(
classBody,
member,
state,
isStatic,
constructorAllowsSuper,
);
}
parseClassMemberWithIsStatic(
classBody: N.ClassBody,
member: N.ClassMember,
state: { hadConstructor: boolean },
isStatic: boolean,
constructorAllowsSuper: boolean,
) {
const publicMethod: $FlowSubtype<N.ClassMethod> = member;
const privateMethod: $FlowSubtype<N.ClassPrivateMethod> = member;
const publicProp: $FlowSubtype<N.ClassMethod> = member;
const privateProp: $FlowSubtype<N.ClassPrivateMethod> = member;
const method: typeof publicMethod | typeof privateMethod = publicMethod;
const publicMember: typeof publicMethod | typeof publicProp = publicMethod;
member.static = isStatic;
if (this.eat(tt.star)) {
// a generator
method.kind = "method";
this.parseClassPropertyName(method);
if (method.key.type === "PrivateName") {
// Private generator method
this.pushClassPrivateMethod(classBody, privateMethod, true, false);
return;
}
if (this.isNonstaticConstructor(publicMethod)) {
this.raise(publicMethod.key.start, Errors.ConstructorIsGenerator);
}
this.pushClassMethod(
classBody,
publicMethod,
true,
false,
/* isConstructor */ false,
false,
);
return;
}
const containsEsc = this.state.containsEsc;
const key = this.parseClassPropertyName(member);
const isPrivate = key.type === "PrivateName";
// Check the key is not a computed expression or string literal.
const isSimple = key.type === "Identifier";
const maybeQuestionTokenStart = this.state.start;
this.parsePostMemberNameModifiers(publicMember);
if (this.isClassMethod()) {
method.kind = "method";
if (isPrivate) {
this.pushClassPrivateMethod(classBody, privateMethod, false, false);
return;
}
// a normal method
const isConstructor = this.isNonstaticConstructor(publicMethod);
let allowsDirectSuper = false;
if (isConstructor) {
publicMethod.kind = "constructor";
// TypeScript allows multiple overloaded constructor declarations.
if (state.hadConstructor && !this.hasPlugin("typescript")) {
this.raise(key.start, Errors.DuplicateConstructor);
}
state.hadConstructor = true;
allowsDirectSuper = constructorAllowsSuper;
}
this.pushClassMethod(
classBody,
publicMethod,
false,
false,
isConstructor,
allowsDirectSuper,
);
} else if (this.isClassProperty()) {
if (isPrivate) {
this.pushClassPrivateProperty(classBody, privateProp);
} else {
this.pushClassProperty(classBody, publicProp);
}
} else if (
isSimple &&
key.name === "async" &&
!containsEsc &&
!this.isLineTerminator()
) {
// an async method
const isGenerator = this.eat(tt.star);
if (publicMember.optional) {
this.unexpected(maybeQuestionTokenStart);
}
method.kind = "method";
// The so-called parsed name would have been "async": get the real name.
this.parseClassPropertyName(method);
this.parsePostMemberNameModifiers(publicMember);
if (method.key.type === "PrivateName") {
// private async method
this.pushClassPrivateMethod(
classBody,
privateMethod,
isGenerator,
true,
);
} else {
if (this.isNonstaticConstructor(publicMethod)) {
this.raise(publicMethod.key.start, Errors.ConstructorIsAsync);
}
this.pushClassMethod(
classBody,
publicMethod,
isGenerator,
true,
/* isConstructor */ false,
false,
);
}
} else if (
isSimple &&
(key.name === "get" || key.name === "set") &&
!containsEsc &&
!(this.match(tt.star) && this.isLineTerminator())
) {
// `get\n*` is an uninitialized property named 'get' followed by a generator.
// a getter or setter
method.kind = key.name;
// The so-called parsed name would have been "get/set": get the real name.
this.parseClassPropertyName(publicMethod);
if (method.key.type === "PrivateName") {
// private getter/setter
this.pushClassPrivateMethod(classBody, privateMethod, false, false);
} else {
if (this.isNonstaticConstructor(publicMethod)) {
this.raise(publicMethod.key.start, Errors.ConstructorIsAccessor);
}
this.pushClassMethod(
classBody,
publicMethod,
false,
false,
/* isConstructor */ false,
false,
);
}
this.checkGetterSetterParams(publicMethod);
} else if (this.isLineTerminator()) {
// an uninitialized class property (due to ASI, since we don't otherwise recognize the next token)
if (isPrivate) {
this.pushClassPrivateProperty(classBody, privateProp);
} else {
this.pushClassProperty(classBody, publicProp);
}
} else {
this.unexpected();
}
}
parseClassPropertyName(member: N.ClassMember): N.Expression | N.Identifier {
const key = this.parsePropertyName(member, /* isPrivateNameAllowed */ true);
if (
!member.computed &&
member.static &&
((key: $FlowSubtype<N.Identifier>).name === "prototype" ||
(key: $FlowSubtype<N.StringLiteral>).value === "prototype")
) {
this.raise(key.start, Errors.StaticPrototype);
}
if (key.type === "PrivateName" && key.id.name === "constructor") {
this.raise(key.start, Errors.ConstructorClassPrivateField);
}
return key;
}
pushClassProperty(classBody: N.ClassBody, prop: N.ClassProperty) {
if (
!prop.computed &&
(prop.key.name === "constructor" || prop.key.value === "constructor")
) {
// Non-computed field, which is either an identifier named "constructor"
// or a string literal named "constructor"
this.raise(prop.key.start, Errors.ConstructorClassField);
}
classBody.body.push(this.parseClassProperty(prop));
}
pushClassPrivateProperty(
classBody: N.ClassBody,
prop: N.ClassPrivateProperty,
) {
this.expectPlugin("classPrivateProperties", prop.key.start);
const node = this.parseClassPrivateProperty(prop);
classBody.body.push(node);
this.classScope.declarePrivateName(
node.key.id.name,
CLASS_ELEMENT_OTHER,
node.key.start,
);
}
pushClassMethod(
classBody: N.ClassBody,
method: N.ClassMethod,
isGenerator: boolean,
isAsync: boolean,
isConstructor: boolean,
allowsDirectSuper: boolean,
): void {
classBody.body.push(
this.parseMethod(
method,
isGenerator,
isAsync,
isConstructor,
allowsDirectSuper,
"ClassMethod",
true,
),
);
}
pushClassPrivateMethod(
classBody: N.ClassBody,
method: N.ClassPrivateMethod,
isGenerator: boolean,
isAsync: boolean,
): void {
this.expectPlugin("classPrivateMethods", method.key.start);
const node = this.parseMethod(
method,
isGenerator,
isAsync,
/* isConstructor */ false,
false,
"ClassPrivateMethod",
true,
);
classBody.body.push(node);
const kind =
node.kind === "get"
? node.static
? CLASS_ELEMENT_STATIC_GETTER
: CLASS_ELEMENT_INSTANCE_GETTER
: node.kind === "set"
? node.static
? CLASS_ELEMENT_STATIC_SETTER
: CLASS_ELEMENT_INSTANCE_SETTER
: CLASS_ELEMENT_OTHER;
this.classScope.declarePrivateName(node.key.id.name, kind, node.key.start);
}
// Overridden in typescript.js
parsePostMemberNameModifiers(
// eslint-disable-next-line no-unused-vars
methodOrProp: N.ClassMethod | N.ClassProperty,
): void {}
// Overridden in typescript.js
parseAccessModifier(): ?N.Accessibility {
return undefined;
}
parseClassPrivateProperty(
node: N.ClassPrivateProperty,
): N.ClassPrivateProperty {
this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
// [In] production parameter is tracked in parseMaybeAssign
this.prodParam.enter(PARAM);
node.value = this.eat(tt.eq) ? this.parseMaybeAssign() : null;
this.semicolon();
this.prodParam.exit();
this.scope.exit();
return this.finishNode(node, "ClassPrivateProperty");
}
parseClassProperty(node: N.ClassProperty): N.ClassProperty {
if (!node.typeAnnotation) {
this.expectPlugin("classProperties");
}
this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
// [In] production parameter is tracked in parseMaybeAssign
this.prodParam.enter(PARAM);
if (this.match(tt.eq)) {
this.expectPlugin("classProperties");
this.next();
node.value = this.parseMaybeAssign();
} else {
node.value = null;
}
this.semicolon();
this.prodParam.exit();
this.scope.exit();
return this.finishNode(node, "ClassProperty");
}
parseClassId(
node: N.Class,
isStatement: boolean,
optionalId: ?boolean,
bindingType: BindingTypes = BIND_CLASS,
): void {
if (this.match(tt.name)) {
node.id = this.parseIdentifier();
if (isStatement) {
this.checkLVal(node.id, bindingType, undefined, "class name");
}
} else {
if (optionalId || !isStatement) {
node.id = null;
} else {
this.unexpected(null, Errors.MissingClassName);
}
}
}
parseClassSuper(node: N.Class): void {
node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null;
}
// Parses module export declaration.
parseExport(node: N.Node): N.AnyExport {
const hasDefault = this.maybeParseExportDefaultSpecifier(node);
const parseAfterDefault = !hasDefault || this.eat(tt.comma);
const hasStar = parseAfterDefault && this.eatExportStar(node);
const hasNamespace =
hasStar && this.maybeParseExportNamespaceSpecifier(node);
const parseAfterNamespace =
parseAfterDefault && (!hasNamespace || this.eat(tt.comma));
const isFromRequired = hasDefault || hasStar;
if (hasStar && !hasNamespace) {
if (hasDefault) this.unexpected();
this.parseExportFrom(node, true);
return this.finishNode(node, "ExportAllDeclaration");
}
const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
if (
(hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers) ||
(hasNamespace && parseAfterNamespace && !hasSpecifiers)
) {
throw this.unexpected(null, tt.braceL);
}
let hasDeclaration;
if (isFromRequired || hasSpecifiers) {
hasDeclaration = false;
this.parseExportFrom(node, isFromRequired);
} else {
hasDeclaration = this.maybeParseExportDeclaration(node);
}
if (isFromRequired || hasSpecifiers || hasDeclaration) {
this.checkExport(node, true, false, !!node.source);
return this.finishNode(node, "ExportNamedDeclaration");
}
if (this.eat(tt._default)) {
// export default ...
node.declaration = this.parseExportDefaultExpression();
this.checkExport(node, true, true);
return this.finishNode(node, "ExportDefaultDeclaration");
}
throw this.unexpected(null, tt.braceL);
}
// eslint-disable-next-line no-unused-vars
eatExportStar(node: N.Node): boolean {
return this.eat(tt.star);
}
maybeParseExportDefaultSpecifier(node: N.Node): boolean {
if (this.isExportDefaultSpecifier()) {
// export defaultObj ...
this.expectPlugin("exportDefaultFrom");
const specifier = this.startNode();
specifier.exported = this.parseIdentifier(true);
node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
return true;
}
return false;
}
maybeParseExportNamespaceSpecifier(node: N.Node): boolean {
if (this.isContextual("as")) {
if (!node.specifiers) node.specifiers = [];
const specifier = this.startNodeAt(
this.state.lastTokStart,
this.state.lastTokStartLoc,
);
this.next();
specifier.exported = this.parseIdentifier(true);
node.specifiers.push(
this.finishNode(specifier, "ExportNamespaceSpecifier"),
);
return true;
}
return false;
}
maybeParseExportNamedSpecifiers(node: N.Node): boolean {
if (this.match(tt.braceL)) {
if (!node.specifiers) node.specifiers = [];
node.specifiers.push(...this.parseExportSpecifiers());
node.source = null;
node.declaration = null;
return true;
}
return false;
}
maybeParseExportDeclaration(node: N.Node): boolean {
if (this.shouldParseExportDeclaration()) {
if (this.isContextual("async")) {
const next = this.nextTokenStart();
// export async;
if (!this.isUnparsedContextual(next, "function")) {
this.unexpected(next, tt._function);
}
}
node.specifiers = [];
node.source = null;
node.declaration = this.parseExportDeclaration(node);
return true;
}
return false;
}
isAsyncFunction(): boolean {
if (!this.isContextual("async")) return false;
const next = this.nextTokenStart();
return (
!lineBreak.test(this.input.slice(this.state.pos, next)) &&
this.isUnparsedContextual(next, "function")
);
}
parseExportDefaultExpression(): N.Expression | N.Declaration {
const expr = this.startNode();
const isAsync = this.isAsyncFunction();
if (this.match(tt._function) || isAsync) {
this.next();
if (isAsync) {
this.next();
}
return this.parseFunction(
expr,
FUNC_STATEMENT | FUNC_NULLABLE_ID,
isAsync,
);
} else if (this.match(tt._class)) {
return this.parseClass(expr, true, true);
} else if (this.match(tt.at)) {
if (
this.hasPlugin("decorators") &&
this.getPluginOption("decorators", "decoratorsBeforeExport")
) {
this.raise(this.state.start, Errors.DecoratorBeforeExport);
}
this.parseDecorators(false);
return this.parseClass(expr, true, true);
} else if (this.match(tt._const) || this.match(tt._var) || this.isLet()) {
throw this.raise(this.state.start, Errors.UnsupportedDefaultExport);
} else {
const res = this.parseMaybeAssign();
this.semicolon();
return res;
}
}
// eslint-disable-next-line no-unused-vars
parseExportDeclaration(node: N.ExportNamedDeclaration): ?N.Declaration {
return this.parseStatement(null);
}
isExportDefaultSpecifier(): boolean {
if (this.match(tt.name)) {
return this.state.value !== "async" && this.state.value !== "let";
}
if (!this.match(tt._default)) {
return false;
}
const next = this.nextTokenStart();
return (
this.input.charCodeAt(next) === charCodes.comma ||
this.isUnparsedContextual(next, "from")
);
}
parseExportFrom(node: N.ExportNamedDeclaration, expect?: boolean): void {
if (this.eatContextual("from")) {
node.source = this.parseImportSource();
this.checkExport(node);
} else {
if (expect) {
this.unexpected();
} else {
node.source = null;
}
}
this.semicolon();
}
shouldParseExportDeclaration(): boolean {
if (this.match(tt.at)) {
this.expectOnePlugin(["decorators", "decorators-legacy"]);
if (this.hasPlugin("decorators")) {
if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
this.unexpected(this.state.start, Errors.DecoratorBeforeExport);
} else {
return true;
}
}
}
return (
this.state.type.keyword === "var" ||
this.state.type.keyword === "const" ||
this.state.type.keyword === "function" ||
this.state.type.keyword === "class" ||
this.isLet() ||
this.isAsyncFunction()
);
}
checkExport(
node: N.ExportNamedDeclaration,
checkNames?: boolean,
isDefault?: boolean,
isFrom?: boolean,
): void {
if (checkNames) {
// Check for duplicate exports
if (isDefault) {
// Default exports
this.checkDuplicateExports(node, "default");
} else if (node.specifiers && node.specifiers.length) {
// Named exports
for (const specifier of node.specifiers) {
this.checkDuplicateExports(specifier, specifier.exported.name);
// $FlowIgnore
if (!isFrom && specifier.local) {
// check for keywords used as local names
this.checkReservedWord(
specifier.local.name,
specifier.local.start,
true,
false,
);
// check if export is defined
// $FlowIgnore
this.scope.checkLocalExport(specifier.local);
}
}
} else if (node.declaration) {
// Exported declarations
if (
node.declaration.type === "FunctionDeclaration" ||
node.declaration.type === "ClassDeclaration"
) {
const id = node.declaration.id;
if (!id) throw new Error("Assertion failure");
this.checkDuplicateExports(node, id.name);
} else if (node.declaration.type === "VariableDeclaration") {
for (const declaration of node.declaration.declarations) {
this.checkDeclaration(declaration.id);
}
}
}
}
const currentContextDecorators = this.state.decoratorStack[
this.state.decoratorStack.length - 1
];
if (currentContextDecorators.length) {
const isClass =
node.declaration &&
(node.declaration.type === "ClassDeclaration" ||
node.declaration.type === "ClassExpression");
if (!node.declaration || !isClass) {
throw this.raise(node.start, Errors.UnsupportedDecoratorExport);
}
this.takeDecorators(node.declaration);
}
}
checkDeclaration(node: N.Pattern | N.ObjectProperty): void {
if (node.type === "Identifier") {
this.checkDuplicateExports(node, node.name);
} else if (node.type === "ObjectPattern") {
for (const prop of node.properties) {
this.checkDeclaration(prop);
}
} else if (node.type === "ArrayPattern") {
for (const elem of node.elements) {
if (elem) {
this.checkDeclaration(elem);
}
}
} else if (node.type === "ObjectProperty") {
this.checkDeclaration(node.value);
} else if (node.type === "RestElement") {
this.checkDeclaration(node.argument);
} else if (node.type === "AssignmentPattern") {
this.checkDeclaration(node.left);
}
}
checkDuplicateExports(
node:
| N.Identifier
| N.ExportNamedDeclaration
| N.ExportSpecifier
| N.ExportDefaultSpecifier,
name: string,
): void {
if (this.state.exportedIdentifiers.indexOf(name) > -1) {
this.raise(
node.start,
name === "default"
? Errors.DuplicateDefaultExport
: Errors.DuplicateExport,
name,
);
}
this.state.exportedIdentifiers.push(name);
}
// Parses a comma-separated list of module exports.
parseExportSpecifiers(): Array<N.ExportSpecifier> {
const nodes = [];
let first = true;
// export { x, y as z } [from '...']
this.expect(tt.braceL);
while (!this.eat(tt.braceR)) {
if (first) {
first = false;
} else {
this.expect(tt.comma);
if (this.eat(tt.braceR)) break;
}
const node = this.startNode();
node.local = this.parseIdentifier(true);
node.exported = this.eatContextual("as")
? this.parseIdentifier(true)
: node.local.__clone();
nodes.push(this.finishNode(node, "ExportSpecifier"));
}
return nodes;
}
// Parses import declaration.
parseImport(node: N.Node): N.AnyImport {
// import '...'
node.specifiers = [];
if (!this.match(tt.string)) {
const hasDefault = this.maybeParseDefaultImportSpecifier(node);
const parseNext = !hasDefault || this.eat(tt.comma);
const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
this.expectContextual("from");
}
node.source = this.parseImportSource();
this.semicolon();
return this.finishNode(node, "ImportDeclaration");
}
parseImportSource(): N.StringLiteral {
if (!this.match(tt.string)) this.unexpected();
return this.parseExprAtom();
}
// eslint-disable-next-line no-unused-vars
shouldParseDefaultImport(node: N.ImportDeclaration): boolean {
return this.match(tt.name);
}
parseImportSpecifierLocal(
node: N.ImportDeclaration,
specifier: N.Node,
type: string,
contextDescription: string,
): void {
specifier.local = this.parseIdentifier();
this.checkLVal(
specifier.local,
BIND_LEXICAL,
undefined,
contextDescription,
);
node.specifiers.push(this.finishNode(specifier, type));
}
maybeParseDefaultImportSpecifier(node: N.ImportDeclaration): boolean {
if (this.shouldParseDefaultImport(node)) {
// import defaultObj, { x, y as z } from '...'
this.parseImportSpecifierLocal(
node,
this.startNode(),
"ImportDefaultSpecifier",
"default import specifier",
);
return true;
}
return false;
}
maybeParseStarImportSpecifier(node: N.ImportDeclaration): boolean {
if (this.match(tt.star)) {
const specifier = this.startNode();
this.next();
this.expectContextual("as");
this.parseImportSpecifierLocal(
node,
specifier,
"ImportNamespaceSpecifier",
"import namespace specifier",
);
return true;
}
return false;
}
parseNamedImportSpecifiers(node: N.ImportDeclaration) {
let first = true;
this.expect(tt.braceL);
while (!this.eat(tt.braceR)) {
if (first) {
first = false;
} else {
// Detect an attempt to deep destructure
if (this.eat(tt.colon)) {
throw this.raise(this.state.start, Errors.DestructureNamedImport);
}
this.expect(tt.comma);
if (this.eat(tt.braceR)) break;
}
this.parseImportSpecifier(node);
}
}
parseImportSpecifier(node: N.ImportDeclaration): void {
const specifier = this.startNode();
specifier.imported = this.parseIdentifier(true);
if (this.eatContextual("as")) {
specifier.local = this.parseIdentifier();
} else {
this.checkReservedWord(
specifier.imported.name,
specifier.start,
true,
true,
);
specifier.local = specifier.imported.__clone();
}
this.checkLVal(
specifier.local,
BIND_LEXICAL,
undefined,
"import specifier",
);
node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
}
}
|
import React, { useEffect } from "react";
import { Switch, Route, useLocation } from "react-router-dom";
import Home from "./pages/Home";
const Routes = (props) => {
return <Switch>
<Route exact path="/">
<Home
isLoading={props.isLoading}
dayChange={props.dayChange}
total={props.total}
tested={props.tested}
statewise={props.statewise}
statewiseTestingData = {props.statewiseTestingData}
isMobile={props.isMobile}
ageGroup={props.ageGroup}
nationality={props.nationality}
gender={props.gender}
theme={props.theme}
hospitalizationStatus={props.hospitalizationStatus}
></Home>
</Route>
</Switch>
}
export default Routes;
|
/*
* AboutPage Messages
*
* This contains all the text for the AboutPage component.
*/
import { defineMessages } from 'react-intl';
export default defineMessages({
header: {
id: 'app.containers.AboutPage.header',
defaultMessage: 'This is AboutPage container !',
},
});
|
import { Observable } from "rxjs";
import { log } from "@ledgerhq/logs";
export const monitorCharacteristic = characteristic => Observable.create(o => {
log("ble-verbose", "start monitor " + characteristic.uuid);
function onCharacteristicValueChanged(event) {
const characteristic = event.target;
if (characteristic.value) {
o.next(Buffer.from(characteristic.value.buffer));
}
}
characteristic.startNotifications().then(() => {
characteristic.addEventListener("characteristicvaluechanged", onCharacteristicValueChanged);
});
return () => {
log("ble-verbose", "end monitor " + characteristic.uuid);
characteristic.stopNotifications();
};
});
//# sourceMappingURL=monitorCharacteristic.js.map
|
import axios from 'axios';
export default class LabelServices {
getLabels() {
var auth = "Bearer ".concat(localStorage.getItem('token'))
return axios.get('/api/getAllLabel', { headers: { Authorization: auth } })
.then((response) => {
return response;
}
)
.catch((error) => {
return error;
});
}
createNewLabel(labelName) {
var auth = "Bearer ".concat(localStorage.getItem('token'))
return axios.post('/api/createLabel', labelName, { headers: { Authorization: auth } })
.then((response) => {
return response;
})
.catch((error) => {
return error;
})
}
removeLabel(labelId){
var auth = "Bearer ".concat(localStorage.getItem('token'))
return axios.post('/api/removeLabel', labelId, { headers: { Authorization: auth } })
.then((response) => {
return response;
})
.catch((error) => {
return error;
})
}
updateLabel(labelData){
var auth = "Bearer ".concat(localStorage.getItem('token'))
return axios.post('/api/updateLabel', labelData, { headers: { Authorization: auth } })
.then((response) => {
return response;
})
.catch((error) => {
return error;
})
}
addLabelOnNote(labelData) {
var auth = "Bearer ".concat(localStorage.getItem('token'))
return axios.post('/api/addLabelOnNote', labelData, { headers: { Authorization: auth } })
.then((response) => {
return response;
})
.catch((error) => {
return error;
})
}
deleteLabelFromNote(labelData){
var auth = "Bearer ".concat(localStorage.getItem('token'))
return axios.post('/api/removeLabelFromNote', labelData, { headers: { Authorization: auth } })
.then((response) => {
return response;
})
.catch((error) => {
return error;
})
}
}
|
import {combineReducers} from "redux-immutable";
import userReducer from "./users";
function configureReducer() {
return combineReducers({
users: userReducer
});
}
export default configureReducer;
|
import React from 'react';
import { View } from 'react-native';
const CardContent = (props) => {
return (
<View style={styles.containerStyle}>
{props.children}
</View>
);
};
const styles = {
containerStyle: {
padding: 5,
justifyContent: 'flex-start',
flexDirection: 'row',
borderColor: '#ddd',
position: 'relative',
flex: 1
}
};
export { CardContent };
|
class WT_G3x5_TSCNavigraphLink extends WT_G3x5_TSCPopUpElement {
/**
* @param {WT_NavigraphAPI} navigraphAPI
*/
constructor(navigraphAPI) {
super();
this._navigraphAPI = navigraphAPI;
this._isReady = false;
this._accountLinkData = null;
}
/**
* @readonly
* @type {WT_G3x5_TSCNavigraphLinkHTMLElement}
*/
get htmlElement() {
return this._htmlElement;
}
_createHTMLElement() {
return new WT_G3x5_TSCNavigraphLinkHTMLElement();
}
_initButtonListener() {
this.htmlElement.addExecuteButtonListener(this._onExecuteButtonPressed.bind(this));
}
async _initFromHTMLElement() {
await WT_Wait.awaitCallback(() => this.htmlElement.isInitialized);
this._initButtonListener();
this._isReady = true;
if (this.isActive) {
this._prepareAccountLink();
}
}
onInit() {
this._htmlElement = this._createHTMLElement();
this.popUpWindow.appendChild(this.htmlElement);
this._initFromHTMLElement();
}
async _executeAccountLink() {
this.htmlElement.setState(WT_G3x5_TSCNavigraphLink.State.EXECUTE);
let success = await this._navigraphAPI.executeAccountLink(this._accountLinkData.pkce, this._accountLinkData.deviceCode);
if (success) {
this.htmlElement.setState(WT_G3x5_TSCNavigraphLink.State.EXECUTE_SUCCESS);
} else {
this.htmlElement.setState(WT_G3x5_TSCNavigraphLink.State.EXECUTE_FAIL);
}
}
_onExecuteButtonPressed(button) {
if (!this._accountLinkData) {
return;
}
this._executeAccountLink();
}
_openBrowser(url) {
OpenBrowser(url);
}
async _prepareAccountLink() {
this.htmlElement.setState(WT_G3x5_TSCNavigraphLink.State.PREPARE);
this._accountLinkData = await this._navigraphAPI.prepareAccountLink();
if (this._accountLinkData) {
this.htmlElement.setURI(this._accountLinkData.uri);
this.htmlElement.setState(WT_G3x5_TSCNavigraphLink.State.PREPARE_SUCCESS);
this._openBrowser(this._accountLinkData.uri);
} else {
this.htmlElement.setURI("");
this.htmlElement.setState(WT_G3x5_TSCNavigraphLink.State.PREPARE_FAIL);
}
}
onEnter() {
super.onEnter();
if (this._isReady) {
this._prepareAccountLink();
}
}
_reset() {
this._accountLinkData = null;
this.htmlElement.setURI("");
this.htmlElement.setState(WT_G3x5_TSCNavigraphLink.State.NONE);
}
onExit() {
super.onExit();
this._reset();
}
}
/**
* @enum {Number}
*/
WT_G3x5_TSCNavigraphLink.State = {
NONE: 0,
PREPARE: 1,
PREPARE_FAIL: 2,
PREPARE_SUCCESS: 3,
EXECUTE: 4,
EXECUTE_FAIL: 5,
EXECUTE_SUCCESS: 6
};
class WT_G3x5_TSCNavigraphLinkHTMLElement extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: "open"});
this.shadowRoot.appendChild(this._getTemplate().content.cloneNode(true));
this._isInit = false;
this._isOpen = false;
}
_getTemplate() {
return WT_G3x5_TSCNavigraphLinkHTMLElement.TEMPLATE;
}
/**
* @readonly
* @type {Boolean}
*/
get isInitialized() {
return this._isInit;
}
async _defineChildren() {
this._wrapper = this.shadowRoot.querySelector(`#wrapper`);
this._uri = this.shadowRoot.querySelector(`#uri`);
this._executeButton = await WT_CustomElementSelector.select(this.shadowRoot, `#execute`, WT_TSCLabeledButton);
}
async _connectedCallbackHelper() {
await this._defineChildren();
this._isInit = true;
}
connectedCallback() {
this._connectedCallbackHelper();
}
addExecuteButtonListener(listener) {
this._executeButton.addButtonListener(listener);
}
removeExecuteButtonListener(listener) {
this._executeButton.removeButtonListener(listener);
}
setURI(uri) {
this._uri.innerHTML = uri.split("//").map(part => part.replace(/([/~,\-_?#%])/giu, "<wbr>$1")).join("//<wbr>");
}
setState(state) {
this._wrapper.setAttribute("state", WT_G3x5_TSCNavigraphLinkHTMLElement.STATE_ATTRIBUTES[state]);
switch (state) {
case WT_G3x5_TSCNavigraphLink.State.PREPARE_SUCCESS:
case WT_G3x5_TSCNavigraphLink.State.EXECUTE_FAIL:
this._executeButton.enabled = "true";
break;
default:
this._executeButton.enabled = "false";
}
}
}
WT_G3x5_TSCNavigraphLinkHTMLElement.STATE_ATTRIBUTES = [
"none",
"prepare",
"preparefail",
"preparesuccess",
"execute",
"executefail",
"executesuccess"
];
WT_G3x5_TSCNavigraphLinkHTMLElement.NAME = "wt-tsc-navigraphlink";
WT_G3x5_TSCNavigraphLinkHTMLElement.TEMPLATE = document.createElement("template");
WT_G3x5_TSCNavigraphLinkHTMLElement.TEMPLATE.innerHTML = `
<style>
:host {
display: block;
border-radius: 5px;
background: linear-gradient(#1f3445, black 25px);
background-color: black;
border: 3px solid var(--wt-g3x5-bordergray);
}
#wrapper {
position: absolute;
left: var(--navigraphlink-padding-left, 0.5em);
top: var(--navigraphlink-padding-top, 0.5em);
width: calc(100% - var(--navigraphlink-padding-left, 0.5em) - var(--navigraphlink-padding-right, 0.5em));
height: calc(100% - var(--navigraphlink-padding-top, 0.5em) - var(--navigraphlink-padding-bottom, 0.5em));
color: white;
}
.text {
display: none;
position: absolute;
left: 0%;
top: 50%;
width: 100%;
transform: translateY(-50%);
text-align: center;
}
#linkpreparetext {
position: absolute;
left: 0%;
top: 0%;
width: 100%;
height: calc((100% - var(--navigraphlink-executebutton-height, 2em)) / 2);
}
#wrapper[state="prepare"] #linkpreparewait {
display: block;
}
#wrapper[state="preparefail"] #linkpreparefail {
display: block;
}
#wrapper[state="preparesuccess"] #urimessage {
display: block;
}
#linkexecutetext {
position: absolute;
left: 0%;
top: calc((100% - var(--navigraphlink-executebutton-height, 2em)) / 2);
width: 100%;
height: calc((100% - var(--navigraphlink-executebutton-height, 2em)) / 2);
}
#wrapper[state="preparesuccess"] #linkexecuteinstructions {
display: block;
}
#wrapper[state="execute"] #linkexecutewait,
#wrapper[state="execute"] #urimessage {
display: block;
}
#wrapper[state="executefail"] #linkexecutefail,
#wrapper[state="executefail"] #urimessage {
display: block;
}
#wrapper[state="executesuccess"] #linkexecutesuccess {
display: block;
}
#execute {
position: absolute;
left: 50%;
bottom: 0%;
width: var(--navigraphlink-executebutton-width, 50%);
height: var(--navigraphlink-executebutton-height, 2em);
transform: translateX(-50%);
font-size: 1.25em;
}
</style>
<div id="wrapper">
<div id="linkpreparetext">
<div id="linkpreparewait" class="text">Fetching pre-authorization data. Please wait...</div>
<div id="linkpreparefail" class="text">An error has occurred.<br>Please close and re-open this window to try again.</div>
<div id="urimessage" class="text">If a browser window doesn't automatically open in the next few seconds, please go to the following URL to login to Navigraph:<br><span id="uri"></span></div>
</div>
<div id="linkexecutetext">
<div id="linkexecuteinstructions" class="text">After logging in to Navigraph and authorizing account access, click the button below to link your account.</div>
<div id="linkexecutewait" class="text">Attempting to link account. Please wait...</div>
<div id="linkexecutefail" class="text">The account linking process has timed out without success.</div>
<div id="linkexecutesuccess" class="text">Account successfully linked.</div>
</div>
<wt-tsc-button-label id="execute" labeltext="Link Account" enabled="false"></wt-tsc-button-label>
</div>
`;
customElements.define(WT_G3x5_TSCNavigraphLinkHTMLElement.NAME, WT_G3x5_TSCNavigraphLinkHTMLElement);
|
import { useReducer } from 'react';
import { useRecoilValue } from 'recoil';
import { Grid, IconButton } from '@material-ui/core';
import { Add, Remove } from '@material-ui/icons';
import { makeStyles } from '@material-ui/styles';
import { layerIdsState } from '../state';
import LayerController from './LayerController';
const useStyles = makeStyles({
root: {
zIndex: 1,
position: 'absolute',
backgroundColor: 'rgba(0, 0, 0, 0.7)',
borderRadius: '5px',
left: '5px',
top: '5px',
},
scroll: {
maxHeight: 500,
overflowX: 'hidden',
overflowY: 'scroll',
'&::-webkit-scrollbar': {
display: 'none',
background: 'transparent',
},
scrollbarWidth: 'none',
flexDirection: 'column',
},
});
function Menu() {
const layerIds = useRecoilValue(layerIdsState);
const [hidden, toggle] = useReducer((v) => !v, false);
const classes = useStyles();
return (
<div className={classes.root} style={{ padding: `0px 5px ${hidden ? 0 : 5}px 5px` }}>
<Grid container direction="column" alignItems="flex-start">
<IconButton
style={{
backgroundColor: 'transparent',
padding: 0,
}}
onClick={toggle}
>
{hidden ? <Add /> : <Remove />}
</IconButton>
<div className={classes.scroll} style={{ display: hidden ? 'none' : 'flex' }}>
{layerIds.map((id) => (
<LayerController id={id} key={id} />
))}
</div>
</Grid>
</div>
);
}
export default Menu;
|
// @flow
import { type ElementConfig } from 'react';
import SelectBase from './Select';
import manageState from './stateManager';
export default manageState<ElementConfig<typeof SelectBase>>(SelectBase);
export { mergeStyles } from './styles';
export { defaultTheme } from './theme';
export { createFilter } from './filters';
export { components } from './components';
|
/*====================================================================
*
* This file is used to setup all the necessary tools the other scripts need.
*
=====================================================================*/
// Setup Angular
window.yachtApp = angular.module('yachtApp', []);
//Setup Canvas "stuff"
//========================
window.currUser = "";
window.cursorStates = {};
window.drawing = false;
window.mousePos = { x:0, y:0 };
window.lastPos = mousePos;
// Mouse Layer
window.mouseCanvas = document.getElementById("mouse-canvas");
window.mouseCtx = mouseCanvas.getContext("2d");
// Drawing Layer
window.collabCanvas = document.getElementById("collab-canvas");
window.ctx = collabCanvas.getContext("2d");
window.drawColor = "#000000";
ctx.strokeStyle = drawColor;
ctx.lineWidth = 2;
|
'use strict'
/**
* Numbers of milliseconds in a day
*/
exports.dayMs = 24 * 60 * 60 * 1000
|
// @flow
import { observer, inject } from "mobx-react";
import {
ArchiveIcon,
EditIcon,
GoToIcon,
MoreIcon,
PadlockIcon,
ShapesIcon,
TrashIcon,
} from "outline-icons";
import * as React from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import CollectionsStore from "stores/CollectionsStore";
import Document from "models/Document";
import CollectionIcon from "components/CollectionIcon";
import Flex from "components/Flex";
import BreadcrumbMenu from "./BreadcrumbMenu";
import { collectionUrl } from "utils/routeHelpers";
type Props = {
document: Document,
collections: CollectionsStore,
onlyText: boolean,
};
function Icon({ document }) {
if (document.isDeleted) {
return (
<>
<CollectionName to="/trash">
<TrashIcon color="currentColor" />
<span>Trash</span>
</CollectionName>
<Slash />
</>
);
}
if (document.isArchived) {
return (
<>
<CollectionName to="/archive">
<ArchiveIcon color="currentColor" />
<span>Archive</span>
</CollectionName>
<Slash />
</>
);
}
if (document.isDraft) {
return (
<>
<CollectionName to="/drafts">
<EditIcon color="currentColor" />
<span>Drafts</span>
</CollectionName>
<Slash />
</>
);
}
if (document.isTemplate) {
return (
<>
<CollectionName to="/templates">
<ShapesIcon color="currentColor" />
<span>Templates</span>
</CollectionName>
<Slash />
</>
);
}
return null;
}
const Breadcrumb = observer(({ document, collections, onlyText }: Props) => {
let collection = collections.get(document.collectionId);
if (!collection) {
if (!document.deletedAt) return <div />;
collection = {
id: document.collectionId,
name: "Deleted Collection",
color: "currentColor",
};
}
const path = collection.pathToDocument
? collection.pathToDocument(document).slice(0, -1)
: [];
if (onlyText === true) {
return (
<>
{collection.private && (
<>
<SmallPadlockIcon color="currentColor" size={16} />{" "}
</>
)}
{collection.name}
{path.map((n) => (
<React.Fragment key={n.id}>
<SmallSlash />
{n.title}
</React.Fragment>
))}
</>
);
}
const isNestedDocument = path.length > 1;
const lastPath = path.length ? path[path.length - 1] : undefined;
const menuPath = isNestedDocument ? path.slice(0, -1) : [];
return (
<Wrapper justify="flex-start" align="center">
<Icon document={document} />
<CollectionName to={collectionUrl(collection.id)}>
<CollectionIcon collection={collection} expanded />
<span>{collection.name}</span>
</CollectionName>
{isNestedDocument && (
<>
<Slash /> <BreadcrumbMenu label={<Overflow />} path={menuPath} />
</>
)}
{lastPath && (
<>
<Slash />{" "}
<Crumb to={lastPath.url} title={lastPath.title}>
{lastPath.title}
</Crumb>
</>
)}
</Wrapper>
);
});
const Wrapper = styled(Flex)`
display: none;
${breakpoint("tablet")`
display: flex;
`};
`;
const SmallPadlockIcon = styled(PadlockIcon)`
display: inline-block;
vertical-align: sub;
`;
const SmallSlash = styled(GoToIcon)`
width: 15px;
height: 10px;
flex-shrink: 0;
opacity: 0.25;
`;
export const Slash = styled(GoToIcon)`
flex-shrink: 0;
fill: ${(props) => props.theme.divider};
`;
const Overflow = styled(MoreIcon)`
flex-shrink: 0;
transition: opacity 100ms ease-in-out;
fill: ${(props) => props.theme.divider};
&:active,
&:hover {
fill: ${(props) => props.theme.text};
}
`;
const Crumb = styled(Link)`
color: ${(props) => props.theme.text};
font-size: 15px;
height: 24px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
&:hover {
text-decoration: underline;
}
`;
const CollectionName = styled(Link)`
display: flex;
flex-shrink: 0;
color: ${(props) => props.theme.text};
font-size: 15px;
font-weight: 500;
white-space: nowrap;
overflow: hidden;
`;
export default inject("collections")(Breadcrumb);
|
"use strict";
angular
.module("app")
.factory("mainService", mainService);
mainService.$inject = ['$http'];
function mainService($http) {
var service = {
getAllPlaces: getAllPlaces
};
return service;
function getAllPlaces() {
return $http.get("app/data.json");
}
}
|
// @flow
import React, { Component } from 'react';
import { translate } from 'react-i18next';
import { Container, Dropdown, Form, Input, Message, Segment, Header, Divider } from 'semantic-ui-react';
import GlobalFormFieldMemo from '../../../../Global/Form/Field/Memo';
import GlobalFormFieldGeneric from '../../../../Global/Form/Field/Generic';
import FormMessageError from '../../../../Global/Form/Message/Error';
class WalletPanelFormBuyFiatAmount extends Component<Props> {
onSubmit = () => this.props.onSubmit()
render() {
const {
cusdSymbol,
error,
globals,
isValid,
onChange,
onChangeFast,
rates,
settings,
shouldShowKYCWarning,
t,
values
} = this.props;
const contactDetails = globals.exchangecontact && globals.exchangecontact.details;
const currencies = [
{ key: 'usd', value: 'usd', text: 'US Dollar' },
{ key: 'eur', value: 'eur', text: 'Euro' },
{ key: 'gbp', value: 'gbp', text: 'Great Britain Pound' }
];
const tokens = [];
tokens.push({key: 'tlos',value: 'tlos',text: 'Telos'});
if (contactDetails && contactDetails.kycStatusStablecoin == true) {
tokens.push({
key: cusdSymbol,
value: cusdSymbol,
text: cusdSymbol.toUpperCase()
});
}
tokens.push({key: 'btc',value: 'btc',text: 'Bitcoin'});
tokens.push({key: 'eos',value: 'eos',text: 'EOS'});
return (
<Form onSubmit={this.onSubmit}>
<Header>
{t('wallet_buytoken_request_step_1_header', {tokenSymbol:values.token.toUpperCase()})}
<Header.Subheader>
{t('wallet_buytoken_request_step_1_subheader', {tokenSymbol:values.token.toUpperCase()})}
</Header.Subheader>
</Header>
<Segment basic color='green'>
<p><strong>Token</strong></p>
<Dropdown
defaultValue={values.token}
name="token"
onChange={onChange}
options={tokens}
style={{ marginBottom:"20px" }}
/>
<Form.Field
autoFocus
style={{ float:"left" }}
control={Input}
fluid
icon={values.currency}
label={t('wallet_buytoken_request_amount')}
name="amount"
onChange={onChange}
defaultValue={values.amount || ''}
width="5"
/>
<Dropdown
style={{ float:"left", marginLeft: "15px" }}
name="currency"
onChange={onChange}
options={currencies}
defaultValue='usd'
/>
<GlobalFormFieldMemo
value={values.memo || ''}
icon="note"
label={t('wallet_buytoken_request_memo')}
name="memo"
onChange={onChangeFast}
/>
</Segment>
<Message style={{marginLeft:"15px",marginRight:"15px"}} info size="small">
Minimum purchase of 5.00 {values.currency.toUpperCase()} required
</Message>
{(shouldShowKYCWarning)
? (
<Message
content={t('wallet_buytoken_request_kyc_warning', {limit:values.limit,currency:values.currency.toUpperCase()})}
icon="info circle"
info
/>
) : ''}
<Container textAlign="right">
<Form.Button
color="blue"
content={t('next')}
loading={!isValid && values.amount >= 5}
disabled={!isValid || !rates || rates.txFee == 0}
style={{marginRight:"15px"}}
/>
</Container>
</Form>
);
}
}
export default translate('wallet')(WalletPanelFormBuyFiatAmount);
|
/**
* Copyright 2018-present Facebook.
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* @format
*/
import type {Logger} from '../fb-interfaces/Logger';
import Server from '../server';
import {promisify} from 'util';
const fs = require('fs');
import {
openssl,
isInstalled as opensslInstalled,
} from './openssl-wrapper-with-promises';
const path = require('path');
const tmp = require('tmp');
const tmpFile = promisify(tmp.file);
const tmpDir = promisify(tmp.dir);
import iosUtil from '../fb-stubs/iOSContainerUtility';
import {reportPlatformFailures} from './metrics';
import {getAdbClient} from './adbClient';
import * as androidUtil from './androidContainerUtility';
// Desktop file paths
const os = require('os');
const caKey = getFilePath('ca.key');
const caCert = getFilePath('ca.crt');
const serverKey = getFilePath('server.key');
const serverCsr = getFilePath('server.csr');
const serverSrl = getFilePath('server.srl');
const serverCert = getFilePath('server.crt');
// Device file paths
const csrFileName = 'app.csr';
const deviceCAcertFile = 'sonarCA.crt';
const deviceClientCertFile = 'device.crt';
const caSubject = '/C=US/ST=CA/L=Menlo Park/O=Sonar/CN=SonarCA';
const serverSubject = '/C=US/ST=CA/L=Menlo Park/O=Sonar/CN=localhost';
const minCertExpiryWindowSeconds = 24 * 60 * 60;
const allowedAppNameRegex = /^[a-zA-Z0-9._\-]+$/;
const logTag = 'CertificateProvider';
/*
* RFC2253 specifies the unamiguous x509 subject format.
* However, even when specifying this, different openssl implementations
* wrap it differently, e.g "subject=X" vs "subject= X".
*/
const x509SubjectCNRegex = /[=,]\s*CN=([^,]*)(,.*)?$/;
export type SecureServerConfig = {|
key: Buffer,
cert: Buffer,
ca: Buffer,
requestCert: boolean,
rejectUnauthorized: boolean,
|};
/*
* This class is responsible for generating and deploying server and client
* certificates to allow for secure communication between Flipper and apps.
* It takes a Certificate Signing Request which was generated by the app,
* using the app's public/private keypair.
* With this CSR it uses the Flipper CA to sign a client certificate which it
* deploys securely to the app.
* It also deploys the Flipper CA cert to the app.
* The app can trust a server if and only if it has a certificate signed by the
* Flipper CA.
*/
export default class CertificateProvider {
logger: Logger;
adb: Promise<any>;
certificateSetup: Promise<void>;
server: Server;
constructor(server: Server, logger: Logger) {
this.logger = logger;
this.adb = getAdbClient();
this.certificateSetup = reportPlatformFailures(
this.ensureServerCertExists(),
'ensureServerCertExists',
);
this.server = server;
}
processCertificateSigningRequest(
unsanitizedCsr: string,
os: string,
appDirectory: string,
): Promise<{|deviceId: string|}> {
const csr = this.santitizeString(unsanitizedCsr);
if (csr === '') {
return Promise.reject(new Error(`Received empty CSR from ${os} device`));
}
this.ensureOpenSSLIsAvailable();
return this.certificateSetup
.then(_ => this.getCACertificate())
.then(caCert =>
this.deployFileToMobileApp(
appDirectory,
deviceCAcertFile,
caCert,
csr,
os,
),
)
.then(_ => this.generateClientCertificate(csr))
.then(clientCert =>
this.deployFileToMobileApp(
appDirectory,
deviceClientCertFile,
clientCert,
csr,
os,
),
)
.then(_ => this.extractAppNameFromCSR(csr))
.then(appName => this.getTargetDeviceId(os, appName, appDirectory, csr))
.then(deviceId => {
return {
deviceId,
};
});
}
getTargetDeviceId(
os: string,
appName: string,
appDirectory: string,
csr: string,
): Promise<string> {
if (os === 'Android') {
return this.getTargetAndroidDeviceId(appName, appDirectory, csr);
} else if (os === 'iOS') {
return this.getTargetiOSDeviceId(appName, appDirectory, csr);
}
return Promise.resolve('unknown');
}
ensureOpenSSLIsAvailable(): void {
if (!opensslInstalled()) {
const e = Error(
"It looks like you don't have OpenSSL installed. Please install it to continue.",
);
this.server.emit('error', e);
}
}
getCACertificate(): Promise<string> {
return new Promise((resolve, reject) => {
fs.readFile(caCert, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data.toString());
}
});
});
}
generateClientCertificate(csr: string): Promise<string> {
console.debug('Creating new client cert', logTag);
return this.writeToTempFile(csr).then(path => {
return openssl('x509', {
req: true,
in: path,
CA: caCert,
CAkey: caKey,
CAcreateserial: true,
CAserial: serverSrl,
});
});
}
getRelativePathInAppContainer(absolutePath: string) {
const matches = /Application\/[^/]+\/(.*)/.exec(absolutePath);
if (matches && matches.length === 2) {
return matches[1];
}
throw new Error("Path didn't match expected pattern: " + absolutePath);
}
deployFileToMobileApp(
destination: string,
filename: string,
contents: string,
csr: string,
os: string,
): Promise<void> {
const appNamePromise = this.extractAppNameFromCSR(csr);
if (os === 'Android') {
const deviceIdPromise = appNamePromise.then(app =>
this.getTargetAndroidDeviceId(app, destination, csr),
);
return Promise.all([deviceIdPromise, appNamePromise]).then(
([deviceId, appName]) =>
androidUtil.push(deviceId, appName, destination + filename, contents),
);
}
if (os === 'iOS' || os === 'windows') {
return promisify(fs.writeFile)(destination + filename, contents).catch(
err => {
if (os === 'iOS') {
// Writing directly to FS failed. It's probably a physical device.
const relativePathInsideApp = this.getRelativePathInAppContainer(
destination,
);
return appNamePromise
.then(appName =>
this.getTargetiOSDeviceId(appName, destination, csr),
)
.then(udid => {
return appNamePromise.then(appName =>
this.pushFileToiOSDevice(
udid,
appName,
relativePathInsideApp,
filename,
contents,
),
);
});
}
throw new Error(
`Invalid appDirectory recieved from ${os} device: ${destination}: ` +
err.toString(),
);
},
);
}
return Promise.reject(new Error(`Unsupported device os: ${os}`));
}
pushFileToiOSDevice(
udid: string,
bundleId: string,
destination: string,
filename: string,
contents: string,
): Promise<void> {
return tmpDir({unsafeCleanup: true}).then(dir => {
const filePath = path.resolve(dir, filename);
promisify(fs.writeFile)(filePath, contents).then(() =>
iosUtil.push(udid, filePath, bundleId, destination),
);
});
}
getTargetAndroidDeviceId(
appName: string,
deviceCsrFilePath: string,
csr: string,
): Promise<string> {
return this.adb
.then(client => client.listDevices())
.then((devices: Array<{id: string}>) => {
if (devices.length === 0) {
throw new Error('No Android devices found');
}
const deviceMatchList = devices.map(device =>
this.androidDeviceHasMatchingCSR(
deviceCsrFilePath,
device.id,
appName,
csr,
)
.then(isMatch => {
return {id: device.id, isMatch, error: null};
})
.catch(e => {
console.error(
`Unable to check for matching CSR in ${device.id}:${appName}`,
logTag,
);
return {id: device.id, isMatch: false, error: e};
}),
);
return Promise.all(deviceMatchList).then(devices => {
const matchingIds = devices.filter(m => m.isMatch).map(m => m.id);
if (matchingIds.length == 0) {
const erroredDevice = devices.find(d => d.error);
if (erroredDevice) {
throw erroredDevice.error;
}
throw new Error(`No matching device found for app: ${appName}`);
}
if (matchingIds.length > 1) {
console.error(
new Error('More than one matching device found for CSR'),
csr,
);
}
return matchingIds[0];
});
});
}
getTargetiOSDeviceId(
appName: string,
deviceCsrFilePath: string,
csr: string,
): Promise<string> {
const matches = /\/Devices\/([^/]+)\//.exec(deviceCsrFilePath);
if (matches && matches.length == 2) {
// It's a simulator, the deviceId is in the filepath.
return Promise.resolve(matches[1]);
}
return iosUtil.targets().then(targets => {
if (targets.length === 0) {
throw new Error('No iOS devices found');
}
const deviceMatchList = targets.map(target =>
this.iOSDeviceHasMatchingCSR(
deviceCsrFilePath,
target.udid,
appName,
csr,
).then(isMatch => {
return {id: target.udid, isMatch};
}),
);
return Promise.all(deviceMatchList).then(devices => {
const matchingIds = devices.filter(m => m.isMatch).map(m => m.id);
if (matchingIds.length == 0) {
throw new Error(`No matching device found for app: ${appName}`);
}
return matchingIds[0];
});
});
}
androidDeviceHasMatchingCSR(
directory: string,
deviceId: string,
processName: string,
csr: string,
): Promise<boolean> {
return androidUtil
.pull(deviceId, processName, directory + csrFileName)
.then(deviceCsr => {
return this.santitizeString(deviceCsr.toString()) === csr;
});
}
iOSDeviceHasMatchingCSR(
directory: string,
deviceId: string,
bundleId: string,
csr: string,
): Promise<boolean> {
const originalFile = this.getRelativePathInAppContainer(
path.resolve(directory, csrFileName),
);
return tmpDir({unsafeCleanup: true})
.then(dir => {
return iosUtil
.pull(deviceId, originalFile, bundleId, dir)
.then(() => dir);
})
.then(dir => {
return promisify(fs.readdir)(dir)
.then(items => {
if (items.length > 1) {
throw new Error('Conflict in temp dir');
}
if (items.length === 0) {
throw new Error('Failed to pull CSR from device');
}
return items[0];
})
.then(fileName => {
const copiedFile = path.resolve(dir, fileName);
return promisify(fs.readFile)(copiedFile).then(data =>
this.santitizeString(data.toString()),
);
});
})
.then(csrFromDevice => csrFromDevice === csr);
}
santitizeString(csrString: string): string {
return csrString.replace(/\r/g, '').trim();
}
extractAppNameFromCSR(csr: string): Promise<string> {
return this.writeToTempFile(csr)
.then(path =>
openssl('req', {
in: path,
noout: true,
subject: true,
nameopt: true,
RFC2253: false,
}).then(subject => {
return [path, subject];
}),
)
.then(([path, subject]) => {
return new Promise(function(resolve, reject) {
fs.unlink(path, err => {
if (err) {
reject(err);
} else {
resolve(subject);
}
});
});
})
.then(subject => {
const matches = subject.trim().match(x509SubjectCNRegex);
if (!matches || matches.length < 2) {
throw new Error(`Cannot extract CN from ${subject}`);
}
return matches[1];
})
.then(appName => {
if (!appName.match(allowedAppNameRegex)) {
throw new Error(
`Disallowed app name in CSR: ${appName}. Only alphanumeric characters and '.' allowed.`,
);
}
return appName;
});
}
loadSecureServerConfig(): Promise<SecureServerConfig> {
return this.certificateSetup.then(() => {
return {
key: fs.readFileSync(serverKey),
cert: fs.readFileSync(serverCert),
ca: fs.readFileSync(caCert),
requestCert: true,
rejectUnauthorized: true, // can be false if necessary as we don't strictly need to verify the client
};
});
}
ensureCertificateAuthorityExists(): Promise<void> {
if (!fs.existsSync(caKey)) {
return this.generateCertificateAuthority();
}
return this.checkCertIsValid(caCert).catch(e =>
this.generateCertificateAuthority(),
);
}
checkCertIsValid(filename: string): Promise<void> {
if (!fs.existsSync(filename)) {
return Promise.reject();
}
// openssl checkend is a nice feature but it only checks for certificates
// expiring in the future, not those that have already expired.
// So we need a separate check for certificates that have already expired
// but since this involves parsing date outputs from openssl, which is less
// reliable, keeping both checks for safety.
return openssl('x509', {
checkend: minCertExpiryWindowSeconds,
in: filename,
})
.then(output => undefined)
.catch(e => {
console.warn(`Certificate will expire soon: ${filename}`, logTag);
throw e;
})
.then(_ =>
openssl('x509', {
enddate: true,
in: filename,
noout: true,
}),
)
.then(endDateOutput => {
const dateString = endDateOutput
.trim()
.split('=')[1]
.trim();
const expiryDate = Date.parse(dateString);
if (isNaN(expiryDate)) {
console.error(
'Unable to parse certificate expiry date: ' + endDateOutput,
);
throw new Error(
'Cannot parse certificate expiry date. Assuming it has expired.',
);
}
if (expiryDate <= Date.now() + minCertExpiryWindowSeconds * 1000) {
throw new Error('Certificate has expired or will expire soon.');
}
});
}
verifyServerCertWasIssuedByCA() {
const options = {CAfile: caCert};
options[serverCert] = false;
return openssl('verify', options).then(output => {
const verified = output.match(/[^:]+: OK/);
if (!verified) {
// This should never happen, but if it does, we need to notice so we can
// generate a valid one, or no clients will trust our server.
throw new Error('Current server cert was not issued by current CA');
}
});
}
generateCertificateAuthority(): Promise<void> {
if (!fs.existsSync(getFilePath(''))) {
fs.mkdirSync(getFilePath(''));
}
console.log('Generating new CA', logTag);
return openssl('genrsa', {out: caKey, '2048': false})
.then(_ =>
openssl('req', {
new: true,
x509: true,
subj: caSubject,
key: caKey,
out: caCert,
}),
)
.then(_ => undefined);
}
ensureServerCertExists(): Promise<void> {
if (
!(
fs.existsSync(serverKey) &&
fs.existsSync(serverCert) &&
fs.existsSync(caCert)
)
) {
return this.generateServerCertificate();
}
return this.checkCertIsValid(serverCert)
.then(_ => this.verifyServerCertWasIssuedByCA())
.catch(e => this.generateServerCertificate());
}
generateServerCertificate(): Promise<void> {
return this.ensureCertificateAuthorityExists()
.then(_ => {
console.warn('Creating new server cert', logTag);
})
.then(_ => openssl('genrsa', {out: serverKey, '2048': false}))
.then(_ =>
openssl('req', {
new: true,
key: serverKey,
out: serverCsr,
subj: serverSubject,
}),
)
.then(_ =>
openssl('x509', {
req: true,
in: serverCsr,
CA: caCert,
CAkey: caKey,
CAcreateserial: true,
CAserial: serverSrl,
out: serverCert,
}),
)
.then(_ => undefined);
}
writeToTempFile(content: string): Promise<string> {
return tmpFile().then((path, fd, cleanupCallback) =>
promisify(fs.writeFile)(path, content).then(_ => path),
);
}
}
function getFilePath(fileName: string): string {
return path.resolve(os.homedir(), '.flipper', 'certs', fileName);
}
|
!function(t){function e(a){if(i[a])return i[a].exports;var s=i[a]={exports:{},id:a,loaded:!1};return t[a].call(s.exports,s,s.exports,e),s.loaded=!0,s.exports}var i={};return e.m=t,e.c=i,e.p="",e(0)}([function(t,e){if("undefined"==typeof AFRAME)throw new Error("Component attempted to register before AFRAME was available.");var i="Double-click outside player to hide or show it.",a="Look+click on play or bar. Space bar and arrows also work.";AFRAME.registerComponent("video-controls",{schema:{src:{type:"string"},size:{type:"number","default":1},distance:{type:"number","default":2},backgroundColor:{"default":"black"},barColor:{"default":"red"},textColor:{"default":"yellow"},infoTextBottom:{"default":i},infoTextTop:{"default":a},infoTextFont:{"default":"35px Helvetica Neue"},statusTextFont:{"default":"30px Helvetica Neue"},timeTextFont:{"default":"70px Helvetica Neue"}},position_time_from_steps:function(){var t=this.current_step/this.bar_steps;this.video_el.readyState>0&&(this.video_el.currentTime=t*this.video_el.duration)},position_control_from_camera:function(){var t=this,e=t.el.sceneEl.camera;if(e){var i=e.el.getAttribute("rotation"),a=i.y;t.y_position=e.position.y+1.6,t.x_position=-t.data.distance*Math.sin(a*Math.PI/180),t.z_position=-t.data.distance*Math.cos(a*Math.PI/180),t.el.setAttribute("position",[t.x_position,t.y_position,t.z_position].join(" ")),this.el.object3D.lookAt(new THREE.Vector3(e.position.x,e.position.y+1.6,e.position.z))}},init:function(){var t=this;this.bar_steps=10,this.current_step=0,this.el.setAttribute("visible",!0),this.video_selector=this.data.src,this.video_el=document.querySelector(this.video_selector),t.play_image_src=document.getElementById("video-play-image")?"#video-play-image":"https://res.cloudinary.com/dxbh0pppv/image/upload/c_scale,h_512,q_10/v1471016296/play_wvmogo.png",t.pause_image_src=document.getElementById("video-pause-image")?"#video-pause-image":"https://res.cloudinary.com/dxbh0pppv/image/upload/c_scale,h_512,q_25/v1471016296/pause_ndega5.png",this.play_image=document.createElement("a-image"),this.video_el.paused?this.play_image.setAttribute("src",t.play_image_src):this.play_image.setAttribute("src",t.pause_image_src),this.video_el.addEventListener("ended",function(){t.play_image.setAttribute("src",t.play_image_src)}),this.video_el.addEventListener("pause",function(){t.play_image.setAttribute("src",t.play_image_src)}),this.video_el.addEventListener("playing",function(){t.play_image.setAttribute("src",t.pause_image_src)}),this.bar_canvas=document.createElement("canvas"),this.bar_canvas.setAttribute("id","video_player_canvas"),this.bar_canvas.width=1024,this.bar_canvas.height=256,this.bar_canvas.style.display="none",this.context=this.bar_canvas.getContext("2d"),this.texture=new THREE.Texture(this.bar_canvas),this.play_image.addEventListener("click",function(e){t.video_el.paused?(this.setAttribute("src",t.pause_image_src),t.video_el.play()):(this.setAttribute("src",t.play_image_src),t.video_el.pause()),e.stopPropagation(),e.preventDefault()}),window.addEventListener("keyup",function(e){switch(e.keyCode){case 32:t.play_image.dispatchEvent(new Event("click"));break;case 37:t.current_step=0,t.position_time_from_steps();break;case 39:t.current_step=t.bar_steps,t.position_time_from_steps();break;case 38:t.current_step=t.current_step<t.bar_steps?t.current_step+1:t.current_step,t.position_time_from_steps();break;case 40:t.current_step=t.current_step>0?t.current_step-1:t.current_step,t.position_time_from_steps()}},!1),this.bar=document.createElement("a-plane"),this.bar.setAttribute("color","#000"),this.bar.addEventListener("click",function(e){var i=document.querySelector("a-cursor").components.raycaster.raycaster.intersectObject(this.object3D,!0)[0].point,a=this.object3D.worldToLocal(i).x,s=a/t.data.size+.5;t.current_step=Math.round(s*t.bar_steps),t.video_el.readyState>0&&(t.video_el.currentTime=s*t.video_el.duration),e.stopPropagation(),e.preventDefault()}),this.el.appendChild(this.bar_canvas),this.el.appendChild(this.play_image),this.el.appendChild(this.bar),this.el.sceneEl.addEventListener("loaded",function(){t.position_control_from_camera(),this.addEventListener("dblclick",function(){var e=document.querySelector("a-cursor").components.raycaster.raycaster;0==e.intersectObject(t.el.object3D,!0).length&&(t.el.getAttribute("visible")?t.el.setAttribute("visible",!1):(t.el.setAttribute("visible",!0),t.position_control_from_camera()))})})},update:function(t){this.position_control_from_camera(),this.bar.setAttribute("height",this.data.size/4),this.bar.setAttribute("width",this.data.size),this.bar.setAttribute("position","0.0 0.0 0"),this.play_image.setAttribute("height",this.data.size/4),this.play_image.setAttribute("width",this.data.size/4),this.play_image.setAttribute("position",-this.data.size/2*1.4+" 0 0")},remove:function(){},tick:function(t){if("undefined"==typeof this.last_time||t-this.last_time>250){if(this.video_el.readyState>0){var e=Math.floor(this.video_el.currentTime/60),i=Math.floor(this.video_el.currentTime%60);e=e<10?"0"+e:e,i=i<10?"0"+i:i;var a=Math.floor(this.video_el.duration/60),s=Math.floor(this.video_el.duration%60);a=a<10?"0"+a:a,s=s<10?"0"+s:s;var r=e+":"+i+" / "+a+":"+s,o=this.bar_canvas.width/this.video_el.duration;if(this.video_el.buffered.length>0){this.current_step=Math.round(this.video_el.currentTime/this.video_el.duration*this.bar_steps);var n=this.context;if(n.fillStyle=this.data.backgroundColor,n.fillRect(0,0,this.bar_canvas.width,this.bar_canvas.height),n.font=this.data.timeTextFont,n.fillStyle="white",n.textAlign="center",n.fillText(r,this.bar_canvas.width/2,.65*this.bar_canvas.height),this.video_el.seeking)n.font=this.data.statusTextFont,n.fillStyle=this.data.textColor,n.textAlign="end",n.fillText("Seeking",.95*this.bar_canvas.width,.6*this.bar_canvas.height);else{var l=this.video_el.buffered.end(this.video_el.buffered.length-1)/this.video_el.duration*100;n.font=this.data.statusTextFont,n.fillStyle=this.data.textColor,n.textAlign="end",n.fillText(l.toFixed(0)+"% loaded",.95*this.bar_canvas.width,.6*this.bar_canvas.height)}n.fillStyle=this.data.textColor,n.font=this.data.infoTextFont,n.textAlign="center",n.fillText(this.data.infoTextTop,this.bar_canvas.width/2,.8*this.bar_canvas.height),n.fillText(this.data.infoTextBottom,this.bar_canvas.width/2,.95*this.bar_canvas.height);for(var c=0;c<this.video_el.buffered.length;c++){var d=this.video_el.buffered.start(c)*o,h=this.video_el.buffered.end(c)*o,_=h-d;n.fillStyle="grey",n.fillRect(d,0,_,this.bar_canvas.height/3)}n.fillStyle=this.data.barColor,n.fillRect(0,0,this.video_el.currentTime/this.video_el.duration*this.bar_canvas.width,this.bar_canvas.height/3)}this.bar.object3D.children.length>0&&(null===this.bar.object3D.children[0].material.map&&(this.bar.object3D.children[0].material=new THREE.MeshBasicMaterial,this.bar.object3D.children[0].material.map=this.texture),this.texture.needsUpdate=!0)}this.last_time=t}},pause:function(){},play:function(){}})}]);
|
define(["exports","require"],function(_exports,_require){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.cellBehaviors=_exports.displayBehaviors=void 0,_require=babelHelpers.interopRequireWildcard(_require);_exports.displayBehaviors=function(SuperClass){return class extends SuperClass{static get properties(){let props={bordered:{type:Boolean,value:!1,reflectToAttribute:!0,notify:!0},caption:{type:String,value:null,notify:!0},columnHeader:{type:Boolean,value:!1,reflectToAttribute:!0,notify:!0},csvData:{type:String,value:""},condensed:{type:Boolean,value:!1,reflectToAttribute:!0,notify:!0},data:{type:Array,value:[],notify:!0,observer:"_dataChanged"},dataCsv:{type:String},filter:{type:Boolean,value:!1,reflectToAttribute:!0,notify:!0},footer:{type:Boolean,value:!1,reflectToAttribute:!0,notify:!0},rowHeader:{type:Boolean,value:!1,reflectToAttribute:!0,notify:!0},responsive:{type:Boolean,value:!1,reflectToAttribute:!0,notify:!0},sort:{type:Boolean,value:!1,reflectToAttribute:!0,notify:!0},striped:{type:Boolean,value:!1,reflectToAttribute:!0,notify:!0},thead:{type:Array,computed:"_getThead(data,columnHeader)"},tbody:{type:Array,computed:"_getTbody(data,columnHeader,footer)"},tfoot:{type:Array,computed:"_getTfoot(data,footer)"}};return super.properties&&(props=Object.assign(props,super.properties)),props}constructor(){super(),new Promise((res,rej)=>_require.default(["../../../@polymer/iron-ajax/iron-ajax.js"],res,rej))}CSVtoArray(text){let l,p="",row=[""],ret=[row],i=0,r=0,s=!0;for(l in text)'"'===(l=text[l])?(s&&l===p&&(row[i]+=l),s=!s):","===l&&s?l=row[++i]="":"\n"===l&&s?("\r"===p&&(row[i]=row[i].slice(0,-1)),row=ret[++r]=[l=""],i=0):row[i]+=l,p=l;return ret}getTableCSV(){return this.data.map(row=>row.map(cell=>(cell=this._replaceBlankCell(cell),this._isNumeric(cell)?cell.replace(/,/g,""):`"${cell}"`)).join(",")).join("\n")}getTableHTML(){let getTR=(tr,open="td",close="td")=>{let th=this.rowHeader?tr.slice(0,1):[],td=this.rowHeader?tr.slice(1):tr;return`\n\t\t<tr>${th.map(cell=>`\n\t\t\t<th scope="row">${this._replaceBlankCell(cell)}</th>`).join("")}${td.map(cell=>`\n\t\t\t<${open}>${this._replaceBlankCell(cell)}</${close}>`).join("")}\n\t\t</tr>`},headers=this.thead.map(tr=>getTR(tr,'th scope="col"',"th")),body=this.tbody.map(tr=>getTR(tr)),footer=this.tfoot.map(tr=>getTR(tr));return["<table>",""!==this.caption?`\n\t<caption>\n\t\t${this.caption}\n\t</caption>`:"",headers.length>0?`\n\t<thead>${headers.join("")}\n\t</thead>`:"",body.length>0?`\n\t<tbody>${body.join("")}\n\t</tbody>`:"",footer.length>0?`\n\t<tfoot>${footer.join("")}\n\t</tfoot>`:"","\n</table>"].join("")}getTableProperties(){return{bordered:this.hideBordered?null:this.bordered,caption:this.caption,columnHeader:this.columnHeader,condensed:this.hideCondensed?null:this.condensed,data:this.data,filter:this.hideFilter?null:this.filter,footer:this.footer,rowHeader:this.rowHeader,responsive:this.hideResponsive?null:this.responsive,sort:this.hideSort?null:this.sort,striped:this.hideStriped?null:this.striped,summary:this.summary}}importHTML(table){let data=[].slice.call(table.querySelectorAll("tr")).map(row=>[].slice.call(row.querySelectorAll("th,td")).map(cell=>"string"==typeof cell.innerHTML?cell.innerHTML.trim():cell.innerHTML));data.length>0&&data[0].length>0&&this.set("data",data),this.columnHeader=this.columnHeader||table.querySelectorAll("thead").length>0,this.rowHeader=this.rowHeader||table.querySelectorAll("tbody th").length>0,this.footer=this.footer||table.querySelectorAll("tfoot").length>0,this.caption=null!==this.caption?this.caption:table.querySelectorAll("caption").length>0?table.querySelector("caption").innerHTML.trim():null}_loadExternalData(e){let data=this.CSVtoArray(this.csvData);data.length>0&&data[0].length>0&&this.set("data",data)}_getTbody(data,columnHeader,footer){if(null!=data&&data.length>0&&data[0].length>0){let ch=columnHeader?1:0,ft=footer?data.length-1:data.length;return data.slice(ch,ft)}}_getTfoot(data,footer){return data.length>0&&data[0].length>0&&footer?data.slice(data.length-1):[]}_getThead(data,columnHeader){return data.length>0&&data[0].length>0&&columnHeader?data.slice(0,1):[]}_replaceBlankCell(cell){return""===String(cell).trim()?"-":cell}_isNumeric(cell){return null!==cell&&!isNaN(cell.trim().replace(/\$/g,""))}}};_exports.cellBehaviors=function(SuperClass){return class extends SuperClass{_getLabel(index,row){if(row)return index+1;{let numerals="ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),results=this._getLetter(index).split("-").reverse(),label="";for(let i=0;i<results.length;i++)""!==results[i]&&(label+=numerals[results[i]]);return label}}_getLetter(index){let place=Math.floor(index/26),letters="";return letters+=index-26*place+"-",place>0&&place<26?letters+=place-1+"-":place>=26&&(letters+=this._getLetter(place-1)),letters}}}});
|
// @remove-on-eject-begin
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// @remove-on-eject-end
'use strict';
const fs = require('fs');
const isWsl = require('is-wsl');
const path = require('path');
const webpack = require('webpack');
const resolve = require('resolve');
const PnpWebpackPlugin = require('pnp-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const safePostCssParser = require('postcss-safe-parser');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
const paths = require('./paths');
const modules = require('./modules');
const getClientEnvironment = require('./env');
const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
const ForkTsCheckerWebpackPlugin = require('react-dev-utils/ForkTsCheckerWebpackPlugin');
const typescriptFormatter = require('react-dev-utils/typescriptFormatter');
// @remove-on-eject-begin
const getCacheIdentifier = require('react-dev-utils/getCacheIdentifier');
// @remove-on-eject-end
const postcssNormalize = require('postcss-normalize');
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
// Some apps do not need the benefits of saving a web request, so not inlining the chunk
// makes for a smoother build process.
const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
// Check if TypeScript is setup
const useTypeScript = fs.existsSync(paths.appTsConfig);
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
// This is the production and development configuration.
// It is focused on developer experience, fast rebuilds, and a minimal bundle.
module.exports = function(webpackEnv) {
const isEnvDevelopment = webpackEnv === 'development';
const isEnvProduction = webpackEnv === 'production';
// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
// In development, we always serve from the root. This makes config easier.
const publicPath = isEnvProduction
? paths.servedPath
: isEnvDevelopment && '/';
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
const publicUrl = isEnvProduction
? publicPath.slice(0, -1)
: isEnvDevelopment && '';
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// common function to get style loaders
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
loader: MiniCssExtractPlugin.loader,
options: shouldUseRelativeAssetPaths ? { publicPath: '../../' } : {},
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
}),
// Adds PostCSS Normalize as the reset css with default options,
// so that it honors browserslist config in package.json
// which in turn let's users customize the target behavior as per their needs.
postcssNormalize(),
],
sourceMap: isEnvProduction && shouldUseSourceMap,
},
},
].filter(Boolean);
if (preProcessor) {
loaders.push({
loader: require.resolve(preProcessor),
options: {
sourceMap: isEnvProduction && shouldUseSourceMap,
},
});
}
return loaders;
};
return {
mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
// Stop compilation early in production
bail: isEnvProduction,
devtool: isEnvProduction
? shouldUseSourceMap
? 'source-map'
: false
: isEnvDevelopment && 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
entry: [
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
isEnvDevelopment &&
require.resolve('react-dev-utils/webpackHotDevClient'),
// Finally, this is your app's code:
paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
].filter(Boolean),
output: {
// The build folder.
path: isEnvProduction ? paths.appBuild : undefined,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: isEnvDevelopment,
// There will be one main bundle, and one file per asynchronous chunk.
// In development, it does not produce real files.
filename: isEnvProduction
? 'static/js/[name].[contenthash:8].js'
: isEnvDevelopment && 'static/js/bundle.js',
// TODO: remove this when upgrading to webpack 5
futureEmitAssets: true,
// There are also additional JS chunk files if you use code splitting.
chunkFilename: isEnvProduction
? 'static/js/[name].[contenthash:8].chunk.js'
: isEnvDevelopment && 'static/js/[name].chunk.js',
// We inferred the "public path" (such as / or /my-project) from homepage.
// We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: isEnvProduction
? info =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/')
: isEnvDevelopment &&
(info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')),
},
optimization: {
minimize: isEnvProduction,
minimizer: [
// This is only used in production mode
new TerserPlugin({
terserOptions: {
parse: {
// we want terser to parse ecma 8 code. However, we don't want it
// to apply any minfication steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the 'compress' and 'output'
// sections only apply transformations that are ecma 5 safe
// https://github.com/facebook/create-react-app/pull/4234
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebook/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
// Disabled because of an issue with Terser breaking valid code:
// https://github.com/facebook/create-react-app/issues/5250
// Pending futher investigation:
// https://github.com/terser-js/terser/issues/120
inline: 2,
},
mangle: {
safari10: true,
},
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebook/create-react-app/issues/2488
ascii_only: true,
},
},
// Use multi-process parallel running to improve the build speed
// Default number of concurrent runs: os.cpus().length - 1
// Disabled on WSL (Windows Subsystem for Linux) due to an issue with Terser
// https://github.com/webpack-contrib/terser-webpack-plugin/issues/21
parallel: !isWsl,
// Enable file caching
cache: true,
sourceMap: shouldUseSourceMap,
}),
// This is only used in production mode
new OptimizeCSSAssetsPlugin({
cssProcessorOptions: {
parser: safePostCssParser,
map: shouldUseSourceMap
? {
// `inline: false` forces the sourcemap to be output into a
// separate file
inline: false,
// `annotation: true` appends the sourceMappingURL to the end of
// the css file, helping the browser find the sourcemap
annotation: true,
}
: false,
},
}),
],
// Automatically split vendor and commons
// https://twitter.com/wSokra/status/969633336732905474
// https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366
splitChunks: {
chunks: 'all',
name: false,
},
// Keep the runtime chunk separated to enable long term caching
// https://twitter.com/wSokra/status/969679223278505985
runtimeChunk: true,
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebook/create-react-app/issues/253
modules: [paths.appNodeModules, 'node_modules'].concat(
modules.additionalModulePaths || []
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebook/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: paths.moduleFileExtensions
.map(ext => `.${ext}`)
.filter(ext => useTypeScript || !ext.includes('ts')),
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
},
plugins: [
// Adds support for installing with Plug'n'Play, leading to faster installs and adding
// guards against forgotten dependencies and such.
PnpWebpackPlugin,
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
resolveLoader: {
plugins: [
// Also related to Plug'n'Play, but this time it tells Webpack to load its loaders
// from the current package.
PnpWebpackPlugin.moduleLoader(module),
],
},
module: {
strictExportPresence: true,
rules: [
// Disable require.ensure as it's not a standard language feature.
{ parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
enforce: 'pre',
use: [
{
options: {
formatter: require.resolve('react-dev-utils/eslintFormatter'),
eslintPath: require.resolve('eslint'),
// @remove-on-eject-begin
baseConfig: {
extends: [require.resolve('eslint-config-react-app')],
},
ignore: false,
useEslintrc: false,
// @remove-on-eject-end
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process application JS with Babel.
// The preset includes JSX, Flow, TypeScript, and some ESnext features.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve(
'babel-preset-react-app/webpack-overrides'
),
// @remove-on-eject-begin
babelrc: false,
configFile: false,
presets: [require.resolve('babel-preset-react-app')],
// Make sure we have a unique cache identifier, erring on the
// side of caution.
// We remove this when the user ejects because the default
// is sane and uses Babel options. Instead of options, we use
// the react-scripts and babel-preset-react-app versions.
cacheIdentifier: getCacheIdentifier(
isEnvProduction
? 'production'
: isEnvDevelopment && 'development',
[
'babel-plugin-named-asset-import',
'babel-preset-react-app',
'react-dev-utils',
'react-scripts',
]
),
// @remove-on-eject-end
plugins: [
[
require.resolve('babel-plugin-named-asset-import'),
{
loaderMap: {
svg: {
ReactComponent: '@svgr/webpack?-svgo,+ref![path]',
},
},
},
],
],
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
cacheCompression: isEnvProduction,
compact: isEnvProduction,
},
},
// Process any JS outside of the app with Babel.
// Unlike the application JS, we only compile the standard ES features.
{
test: /\.(js|mjs)$/,
exclude: /@babel(?:\/|\\{1,2})runtime/,
loader: require.resolve('babel-loader'),
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true },
],
],
cacheDirectory: true,
cacheCompression: isEnvProduction,
// @remove-on-eject-begin
cacheIdentifier: getCacheIdentifier(
isEnvProduction
? 'production'
: isEnvDevelopment && 'development',
[
'babel-plugin-named-asset-import',
'babel-preset-react-app',
'react-dev-utils',
'react-scripts',
]
),
// @remove-on-eject-end
// If an error happens in a package, it's possible to be
// because it was compiled. Thus, we don't want the browser
// debugger to show the original code. Instead, the code
// being evaluated would be much more helpful.
sourceMaps: false,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use MiniCSSExtractPlugin to extract that CSS
// to a file, but in development "style" loader enables hot editing
// of CSS.
// By default we support CSS Modules with the extension .module.css
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
}),
},
// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
},
'sass-loader'
),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
},
'sass-loader'
),
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
loader: require.resolve('file-loader'),
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise be processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
],
},
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
template: paths.appHtml,
},
isEnvProduction
? {
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}
: undefined
)
),
// Inlines the webpack runtime script. This script is too small to warrant
// a network request.
isEnvProduction &&
shouldInlineRuntimeChunk &&
new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime~.+[.]js/]),
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In production, it will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
// In development, this will be an empty string.
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
// This gives some necessary context to module not found errors, such as
// the requesting resource.
new ModuleNotFoundPlugin(paths.appPath),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV is set to production
// during a production build.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
isEnvDevelopment && new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebook/create-react-app/issues/240
isEnvDevelopment && new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebook/create-react-app/issues/186
isEnvDevelopment &&
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
isEnvProduction &&
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'static/css/[name].[contenthash:8].css',
chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
}),
// Generate a manifest file which contains a mapping of all asset filenames
// to their corresponding output file so that tools can pick it up without
// having to parse `index.html`.
new ManifestPlugin({
fileName: 'asset-manifest.json',
publicPath: publicPath,
generate: (seed, files) => {
const manifestFiles = files.reduce(function(manifest, file) {
manifest[file.name] = file.path;
return manifest;
}, seed);
return {
files: manifestFiles,
};
},
}),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
// Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the Webpack build.
isEnvProduction &&
new WorkboxWebpackPlugin.GenerateSW({
clientsClaim: true,
exclude: [/\.map$/, /asset-manifest\.json$/],
importWorkboxFrom: 'cdn',
navigateFallback: publicUrl + '/index.html',
navigateFallbackBlacklist: [
// Exclude URLs starting with /_, as they're likely an API call
new RegExp('^/_'),
// Exclude URLs containing a dot, as they're likely a resource in
// public/ and not a SPA route
new RegExp('/[^/]+\\.[^/]+$'),
],
}),
// TypeScript type checking
useTypeScript &&
new ForkTsCheckerWebpackPlugin({
typescript: resolve.sync('typescript', {
basedir: paths.appNodeModules,
}),
async: isEnvDevelopment,
useTypescriptIncrementalApi: true,
checkSyntacticErrors: true,
resolveModuleNameModule: process.versions.pnp
? `${__dirname}/pnpTs.js`
: undefined,
resolveTypeReferenceDirectiveModule: process.versions.pnp
? `${__dirname}/pnpTs.js`
: undefined,
tsconfig: paths.appTsConfig,
reportFiles: [
'**',
'!**/__tests__/**',
'!**/?(*.)(spec|test).*',
'!**/src/setupProxy.*',
'!**/src/setupTests.*',
],
watch: paths.appSrc,
silent: true,
// The formatter is invoked directly in WebpackDevServerUtils during development
formatter: isEnvProduction ? typescriptFormatter : undefined,
}),
].filter(Boolean),
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
module: 'empty',
dgram: 'empty',
dns: 'mock',
fs: 'empty',
http2: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
// Turn off performance processing because we utilize
// our own hints via the FileSizeReporter
performance: false,
};
};
|
require.config({
shim: {
'c3': ['d3', 'core'],
'd3': ['core'],
},
paths: {
'd3': '/static/assets/plugins/charts-c3/js/d3.v3.min',
'c3': '/static/assets/plugins/charts-c3/js/c3.min',
}
});
|
import React from 'react'
import { graphql } from 'gatsby'
import Helmet from 'react-helmet'
import Layout from 'components/layout'
import HeroVideo from 'sections/hero/HeroVideo.js'
import AboutOne from 'sections/about/AboutOne.js'
import ServicesOne from 'sections/services/ServicesOne.js'
import PortfolioOne from 'sections/portfolio/PortfolioOne.js'
import TestimonialsOne from 'sections/testimonials/TestimonialsOne.js'
import TeamOne from 'sections/team/TeamOne.js'
import ClientsOne from 'sections/clients/ClientsOne.js'
import ContactCreative from 'sections/contact/ContactCreative.js'
class Index extends React.Component {
render() {
const { site } = this.props.data
return (
<div>
<Helmet>
<title>{site.meta.title}</title>
<meta name="description" content={site.meta.description} />
</Helmet>
<Layout
isHome={true}
sections={['home', 'about', 'services', 'portfolio', 'testimonials', 'team', 'clients', 'contact']}
>
<HeroVideo />
<AboutOne />
<ServicesOne />
<PortfolioOne />
<TestimonialsOne />
<TeamOne />
<ClientsOne />
<ContactCreative />
</Layout>
</div>
)
}
}
export default Index
export const creativeVideoOneQuery = graphql`
query {
site {
meta: siteMetadata {
title
description
}
}
}
`
|
const postData = async (url, data) => {
let res = await fetch(url, {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: data
});
return await res.json();
};
async function getResource(url) {
let res = await fetch(url);
if (!res.ok) {
throw new Error(`Could not fetch ${url}, status: ${res.status}`);
}
return await res.json();
}
export {postData};
export {getResource};
|
#!/usr/bin/env node
/* eslint-disable no-console */
const path = require('path');
const fs = require('fs');
const yargs = require('yargs')
const argv = yargs
.option('vm',
{
description: 'path to scratch-vm',
demandOption: true
})
.option('gui',
{
description: 'path to scratch-gui',
default: './'
})
.version(false)
.help()
.argv
const VmRoot = path.resolve(process.cwd(), argv.vm);
const GuiRoot = path.resolve(process.cwd(), argv.gui);
// Make symbolic link
function makeSymbolicLink(to, from) {
try {
const stats = fs.lstatSync(from);
if (stats.isSymbolicLink()) {
if (fs.readlinkSync(from) === to) {
console.log(`Already exists link: ${from} -> ${fs.readlinkSync(from)}`);
return;
}
fs.unlink(from);
} else {
fs.renameSync(from, `${from}~`);
}
} catch (err) {
// File not exists.
}
fs.symlinkSync(to, from, 'dir');
console.log(`Make link: ${from} -> ${fs.readlinkSync(from)}`);
}
// Use local scratch-vm in scratch-gui
try {
const VmModulePath = path.resolve(GuiRoot, './node_modules/scratch-vm');
makeSymbolicLink(VmRoot, VmModulePath);
} catch (err) {
console.error(err);
}
|
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
import AppContent from '@fbcnms/ui/components/layout/AppContent';
import AppContext from '@fbcnms/ui/context/AppContext';
import AppSideBar from '@fbcnms/ui/components/layout/AppSideBar';
import ApplicationMain from '@fbcnms/ui/components/ApplicationMain';
import InventorySuspense from '../../common/InventorySuspense';
import ProjectComparisonView from '../projects/ProjectComparisonView';
import React, {useContext} from 'react';
import RelayEnvironment from '../../common/RelayEnvironment';
import WorkOrderComparisonView from './WorkOrderComparisonView';
import WorkOrderConfigure from './WorkOrderConfigure';
import {DialogShowingContextProvider} from '@fbcnms/ui/components/design-system/Dialog/DialogShowingContext';
import {Redirect, Route, Switch} from 'react-router-dom';
import {RelayEnvironmentProvider} from 'react-relay/hooks';
import {WorkOrdersNavListItems} from './WorkOrdersNavListItems';
import {getProjectLinks} from '@fbcnms/projects/projects';
import {makeStyles} from '@material-ui/styles';
import {useMainContext} from '../../components/MainContext';
import {useRelativeUrl} from '@fbcnms/ui/hooks/useRouter';
const useStyles = makeStyles(theme => ({
root: {
display: 'flex',
},
paper: {
margin: theme.spacing(3),
padding: theme.spacing(),
},
}));
function WorkOrdersMain() {
const classes = useStyles();
const {tabs} = useContext(AppContext);
const relativeUrl = useRelativeUrl();
const {integrationUserDefinition} = useMainContext();
return (
<InventorySuspense isTopLevel={true}>
<DialogShowingContextProvider>
<div className={classes.root}>
<AppSideBar
mainItems={<WorkOrdersNavListItems />}
projects={getProjectLinks(tabs, integrationUserDefinition)}
showSettings={true}
user={integrationUserDefinition}
/>
<AppContent>
<RelayEnvironmentProvider environment={RelayEnvironment}>
<Switch>
<Route
path={relativeUrl('/search')}
component={WorkOrderComparisonView}
/>
<Route
path={relativeUrl('/projects/search')}
component={ProjectComparisonView}
/>
<Route
path={relativeUrl('/configure')}
component={WorkOrderConfigure}
/>
<Redirect to={relativeUrl('/search')} />
</Switch>
</RelayEnvironmentProvider>
</AppContent>
</div>
</DialogShowingContextProvider>
</InventorySuspense>
);
}
export default () => {
return (
<ApplicationMain>
<WorkOrdersMain />
</ApplicationMain>
);
};
|
/**
* JSXTransformer v0.13.3
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JSXTransformer = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/* jshint browser: true */
/* jslint evil: true */
/*eslint-disable no-eval */
/*eslint-disable block-scoped-var */
'use strict';
var ReactTools = _dereq_('../main');
var inlineSourceMap = _dereq_('./inline-source-map');
var headEl;
var dummyAnchor;
var inlineScriptCount = 0;
// The source-map library relies on Object.defineProperty, but IE8 doesn't
// support it fully even with es5-sham. Indeed, es5-sham's defineProperty
// throws when Object.prototype.__defineGetter__ is missing, so we skip building
// the source map in that case.
var supportsAccessors = Object.prototype.hasOwnProperty('__defineGetter__');
/**
* Run provided code through jstransform.
*
* @param {string} source Original source code
* @param {object?} options Options to pass to jstransform
* @return {object} object as returned from jstransform
*/
function transformReact(source, options) {
options = options || {};
// Force the sourcemaps option manually. We don't want to use it if it will
// break (see above note about supportsAccessors). We'll only override the
// value here if sourceMap was specified and is truthy. This guarantees that
// we won't override any user intent (since this method is exposed publicly).
if (options.sourceMap) {
options.sourceMap = supportsAccessors;
}
// Otherwise just pass all options straight through to react-tools.
return ReactTools.transformWithDetails(source, options);
}
/**
* Eval provided source after transforming it.
*
* @param {string} source Original source code
* @param {object?} options Options to pass to jstransform
*/
function exec(source, options) {
return eval(transformReact(source, options).code);
}
/**
* This method returns a nicely formated line of code pointing to the exact
* location of the error `e`. The line is limited in size so big lines of code
* are also shown in a readable way.
*
* Example:
* ... x', overflow:'scroll'}} id={} onScroll={this.scroll} class=" ...
* ^
*
* @param {string} code The full string of code
* @param {Error} e The error being thrown
* @return {string} formatted message
* @internal
*/
function createSourceCodeErrorMessage(code, e) {
var sourceLines = code.split('\n');
// e.lineNumber is non-standard so we can't depend on its availability. If
// we're in a browser where it isn't supported, don't even bother trying to
// format anything. We may also hit a case where the line number is reported
// incorrectly and is outside the bounds of the actual code. Handle that too.
if (!e.lineNumber || e.lineNumber > sourceLines.length) {
return '';
}
var erroneousLine = sourceLines[e.lineNumber - 1];
// Removes any leading indenting spaces and gets the number of
// chars indenting the `erroneousLine`
var indentation = 0;
erroneousLine = erroneousLine.replace(/^\s+/, function(leadingSpaces) {
indentation = leadingSpaces.length;
return '';
});
// Defines the number of characters that are going to show
// before and after the erroneous code
var LIMIT = 30;
var errorColumn = e.column - indentation;
if (errorColumn > LIMIT) {
erroneousLine = '... ' + erroneousLine.slice(errorColumn - LIMIT);
errorColumn = 4 + LIMIT;
}
if (erroneousLine.length - errorColumn > LIMIT) {
erroneousLine = erroneousLine.slice(0, errorColumn + LIMIT) + ' ...';
}
var message = '\n\n' + erroneousLine + '\n';
message += new Array(errorColumn - 1).join(' ') + '^';
return message;
}
/**
* Actually transform the code.
*
* @param {string} code
* @param {string?} url
* @param {object?} options
* @return {string} The transformed code.
* @internal
*/
function transformCode(code, url, options) {
try {
var transformed = transformReact(code, options);
} catch(e) {
e.message += '\n at ';
if (url) {
if ('fileName' in e) {
// We set `fileName` if it's supported by this error object and
// a `url` was provided.
// The error will correctly point to `url` in Firefox.
e.fileName = url;
}
e.message += url + ':' + e.lineNumber + ':' + e.columnNumber;
} else {
e.message += location.href;
}
e.message += createSourceCodeErrorMessage(code, e);
throw e;
}
if (!transformed.sourceMap) {
return transformed.code;
}
var source;
if (url == null) {
source = 'Inline JSX script';
inlineScriptCount++;
if (inlineScriptCount > 1) {
source += ' (' + inlineScriptCount + ')';
}
} else if (dummyAnchor) {
// Firefox has problems when the sourcemap source is a proper URL with a
// protocol and hostname, so use the pathname. We could use just the
// filename, but hopefully using the full path will prevent potential
// issues where the same filename exists in multiple directories.
dummyAnchor.href = url;
source = dummyAnchor.pathname.substr(1);
}
return (
transformed.code +
'\n' +
inlineSourceMap(transformed.sourceMap, code, source)
);
}
/**
* Appends a script element at the end of the <head> with the content of code,
* after transforming it.
*
* @param {string} code The original source code
* @param {string?} url Where the code came from. null if inline
* @param {object?} options Options to pass to jstransform
* @internal
*/
function run(code, url, options) {
var scriptEl = document.createElement('script');
scriptEl.text = transformCode(code, url, options);
headEl.appendChild(scriptEl);
}
/**
* Load script from the provided url and pass the content to the callback.
*
* @param {string} url The location of the script src
* @param {function} callback Function to call with the content of url
* @internal
*/
function load(url, successCallback, errorCallback) {
var xhr;
xhr = window.ActiveXObject ? new window.ActiveXObject('Microsoft.XMLHTTP')
: new XMLHttpRequest();
// async, however scripts will be executed in the order they are in the
// DOM to mirror normal script loading.
xhr.open('GET', url, true);
if ('overrideMimeType' in xhr) {
xhr.overrideMimeType('text/plain');
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 0 || xhr.status === 200) {
successCallback(xhr.responseText);
} else {
errorCallback();
throw new Error('Could not load ' + url);
}
}
};
return xhr.send(null);
}
/**
* Loop over provided script tags and get the content, via innerHTML if an
* inline script, or by using XHR. Transforms are applied if needed. The scripts
* are executed in the order they are found on the page.
*
* @param {array} scripts The <script> elements to load and run.
* @internal
*/
function loadScripts(scripts) {
var result = [];
var count = scripts.length;
function check() {
var script, i;
for (i = 0; i < count; i++) {
script = result[i];
if (script.loaded && !script.executed) {
script.executed = true;
run(script.content, script.url, script.options);
} else if (!script.loaded && !script.error && !script.async) {
break;
}
}
}
scripts.forEach(function(script, i) {
var options = {
sourceMap: true
};
if (/;harmony=true(;|$)/.test(script.type)) {
options.harmony = true;
}
if (/;stripTypes=true(;|$)/.test(script.type)) {
options.stripTypes = true;
}
// script.async is always true for non-javascript script tags
var async = script.hasAttribute('async');
if (script.src) {
result[i] = {
async: async,
error: false,
executed: false,
content: null,
loaded: false,
url: script.src,
options: options
};
load(script.src, function(content) {
result[i].loaded = true;
result[i].content = content;
check();
}, function() {
result[i].error = true;
check();
});
} else {
result[i] = {
async: async,
error: false,
executed: false,
content: script.innerHTML,
loaded: true,
url: null,
options: options
};
}
});
check();
}
/**
* Find and run all script tags with type="text/jsx".
*
* @internal
*/
function runScripts() {
var scripts = document.getElementsByTagName('script');
// Array.prototype.slice cannot be used on NodeList on IE8
var jsxScripts = [];
for (var i = 0; i < scripts.length; i++) {
if (/^text\/jsx(;|$)/.test(scripts.item(i).type)) {
jsxScripts.push(scripts.item(i));
}
}
if (jsxScripts.length < 1) {
return;
}
console.warn(
'You are using the in-browser JSX transformer. Be sure to precompile ' +
'your JSX for production - ' +
'http://facebook.github.io/react/docs/tooling-integration.html#jsx'
);
loadScripts(jsxScripts);
}
// Listen for load event if we're in a browser and then kick off finding and
// running of scripts.
if (typeof window !== 'undefined' && window !== null) {
headEl = document.getElementsByTagName('head')[0];
dummyAnchor = document.createElement('a');
if (window.addEventListener) {
window.addEventListener('DOMContentLoaded', runScripts, false);
} else {
window.attachEvent('onload', runScripts);
}
}
module.exports = {
transform: transformReact,
exec: exec
};
},{"../main":2,"./inline-source-map":41}],2:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
/*eslint-disable no-undef*/
var visitors = _dereq_('./vendor/fbtransform/visitors');
var transform = _dereq_('jstransform').transform;
var typesSyntax = _dereq_('jstransform/visitors/type-syntax');
var inlineSourceMap = _dereq_('./vendor/inline-source-map');
module.exports = {
transform: function(input, options) {
options = processOptions(options);
var output = innerTransform(input, options);
var result = output.code;
if (options.sourceMap) {
var map = inlineSourceMap(
output.sourceMap,
input,
options.filename
);
result += '\n' + map;
}
return result;
},
transformWithDetails: function(input, options) {
options = processOptions(options);
var output = innerTransform(input, options);
var result = {};
result.code = output.code;
if (options.sourceMap) {
result.sourceMap = output.sourceMap.toJSON();
}
if (options.filename) {
result.sourceMap.sources = [options.filename];
}
return result;
}
};
/**
* Only copy the values that we need. We'll do some preprocessing to account for
* converting command line flags to options that jstransform can actually use.
*/
function processOptions(opts) {
opts = opts || {};
var options = {};
options.harmony = opts.harmony;
options.stripTypes = opts.stripTypes;
options.sourceMap = opts.sourceMap;
options.filename = opts.sourceFilename;
if (opts.es6module) {
options.sourceType = 'module';
}
if (opts.nonStrictEs6module) {
options.sourceType = 'nonStrictModule';
}
// Instead of doing any fancy validation, only look for 'es3'. If we have
// that, then use it. Otherwise use 'es5'.
options.es3 = opts.target === 'es3';
options.es5 = !options.es3;
return options;
}
function innerTransform(input, options) {
var visitorSets = ['react'];
if (options.harmony) {
visitorSets.push('harmony');
}
if (options.es3) {
visitorSets.push('es3');
}
if (options.stripTypes) {
// Stripping types needs to happen before the other transforms
// unfortunately, due to bad interactions. For example,
// es6-rest-param-visitors conflict with stripping rest param type
// annotation
input = transform(typesSyntax.visitorList, input, options).code;
}
var visitorList = visitors.getVisitorsBySet(visitorSets);
return transform(visitorList, input, options);
}
},{"./vendor/fbtransform/visitors":40,"./vendor/inline-source-map":41,"jstransform":22,"jstransform/visitors/type-syntax":36}],3:[function(_dereq_,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
var base64 = _dereq_('base64-js')
var ieee754 = _dereq_('ieee754')
var isArray = _dereq_('is-array')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192 // not used by this implementation
var kMaxLength = 0x3fffffff
var rootParent = {}
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Note:
*
* - Implementation must support adding new properties to `Uint8Array` instances.
* Firefox 4-29 lacked support, fixed in Firefox 30+.
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
*
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will
* get the Object implementation, which is slower but will work correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = (function () {
try {
var buf = new ArrayBuffer(0)
var arr = new Uint8Array(buf)
arr.foo = function () { return 42 }
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
})()
/**
* Class: Buffer
* =============
*
* The Buffer constructor returns instances of `Uint8Array` that are augmented
* with function properties for all the node `Buffer` API functions. We use
* `Uint8Array` so that square bracket notation works as expected -- it returns
* a single octet.
*
* By augmenting the instances, we can avoid modifying the `Uint8Array`
* prototype.
*/
function Buffer (subject, encoding) {
var self = this
if (!(self instanceof Buffer)) return new Buffer(subject, encoding)
var type = typeof subject
var length
if (type === 'number') {
length = +subject
} else if (type === 'string') {
length = Buffer.byteLength(subject, encoding)
} else if (type === 'object' && subject !== null) {
// assume object is array-like
if (subject.type === 'Buffer' && isArray(subject.data)) subject = subject.data
length = +subject.length
} else {
throw new TypeError('must start with number, buffer, array or string')
}
if (length > kMaxLength) {
throw new RangeError('Attempt to allocate Buffer larger than maximum size: 0x' +
kMaxLength.toString(16) + ' bytes')
}
if (length < 0) length = 0
else length >>>= 0 // coerce to uint32
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Preferred: Return an augmented `Uint8Array` instance for best performance
self = Buffer._augment(new Uint8Array(length)) // eslint-disable-line consistent-this
} else {
// Fallback: Return THIS instance of Buffer (created by `new`)
self.length = length
self._isBuffer = true
}
var i
if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
// Speed optimization -- use set if we're copying from a typed array
self._set(subject)
} else if (isArrayish(subject)) {
// Treat array-ish objects as a byte array
if (Buffer.isBuffer(subject)) {
for (i = 0; i < length; i++) {
self[i] = subject.readUInt8(i)
}
} else {
for (i = 0; i < length; i++) {
self[i] = ((subject[i] % 256) + 256) % 256
}
}
} else if (type === 'string') {
self.write(subject, 0, encoding)
} else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT) {
for (i = 0; i < length; i++) {
self[i] = 0
}
}
if (length > 0 && length <= Buffer.poolSize) self.parent = rootParent
return self
}
function SlowBuffer (subject, encoding) {
if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
var buf = new Buffer(subject, encoding)
delete buf.parent
return buf
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
if (i !== len) {
x = a[i]
y = b[i]
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'binary':
case 'base64':
case 'raw':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, totalLength) {
if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
if (list.length === 0) {
return new Buffer(0)
} else if (list.length === 1) {
return list[0]
}
var i
if (totalLength === undefined) {
totalLength = 0
for (i = 0; i < list.length; i++) {
totalLength += list[i].length
}
}
var buf = new Buffer(totalLength)
var pos = 0
for (i = 0; i < list.length; i++) {
var item = list[i]
item.copy(buf, pos)
pos += item.length
}
return buf
}
Buffer.byteLength = function byteLength (str, encoding) {
var ret
str = str + ''
switch (encoding || 'utf8') {
case 'ascii':
case 'binary':
case 'raw':
ret = str.length
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = str.length * 2
break
case 'hex':
ret = str.length >>> 1
break
case 'utf8':
case 'utf-8':
ret = utf8ToBytes(str).length
break
case 'base64':
ret = base64ToBytes(str).length
break
default:
ret = str.length
}
return ret
}
// pre-set for values that may exist in the future
Buffer.prototype.length = undefined
Buffer.prototype.parent = undefined
// toString(encoding, start=0, end=buffer.length)
Buffer.prototype.toString = function toString (encoding, start, end) {
var loweredCase = false
start = start >>> 0
end = end === undefined || end === Infinity ? this.length : end >>> 0
if (!encoding) encoding = 'utf8'
if (start < 0) start = 0
if (end > this.length) end = this.length
if (end <= start) return ''
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'binary':
return binarySlice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return 0
return Buffer.compare(this, b)
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
else if (byteOffset < -0x80000000) byteOffset = -0x80000000
byteOffset >>= 0
if (this.length === 0) return -1
if (byteOffset >= this.length) return -1
// Negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
if (typeof val === 'string') {
if (val.length === 0) return -1 // special case: looking for empty string always fails
return String.prototype.indexOf.call(this, val, byteOffset)
}
if (Buffer.isBuffer(val)) {
return arrayIndexOf(this, val, byteOffset)
}
if (typeof val === 'number') {
if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
}
return arrayIndexOf(this, [ val ], byteOffset)
}
function arrayIndexOf (arr, val, byteOffset) {
var foundIndex = -1
for (var i = 0; byteOffset + i < arr.length; i++) {
if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
} else {
foundIndex = -1
}
}
return -1
}
throw new TypeError('val must be string, number or Buffer')
}
// `get` will be removed in Node 0.13+
Buffer.prototype.get = function get (offset) {
console.log('.get() is deprecated. Access using array indexes instead.')
return this.readUInt8(offset)
}
// `set` will be removed in Node 0.13+
Buffer.prototype.set = function set (v, offset) {
console.log('.set() is deprecated. Access using array indexes instead.')
return this.writeUInt8(v, offset)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new Error('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; i++) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) throw new Error('Invalid hex string')
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
var charsWritten = blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
return charsWritten
}
function asciiWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
return charsWritten
}
function binaryWrite (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
return charsWritten
}
function utf16leWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
return charsWritten
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length
length = undefined
}
} else { // legacy
var swap = encoding
encoding = offset
offset = length
length = swap
}
offset = Number(offset) || 0
if (length < 0 || offset < 0 || offset > this.length) {
throw new RangeError('attempt to write outside buffer bounds')
}
var remaining = this.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
encoding = String(encoding || 'utf8').toLowerCase()
var ret
switch (encoding) {
case 'hex':
ret = hexWrite(this, string, offset, length)
break
case 'utf8':
case 'utf-8':
ret = utf8Write(this, string, offset, length)
break
case 'ascii':
ret = asciiWrite(this, string, offset, length)
break
case 'binary':
ret = binaryWrite(this, string, offset, length)
break
case 'base64':
ret = base64Write(this, string, offset, length)
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = utf16leWrite(this, string, offset, length)
break
default:
throw new TypeError('Unknown encoding: ' + encoding)
}
return ret
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
var res = ''
var tmp = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
if (buf[i] <= 0x7F) {
res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
tmp = ''
} else {
tmp += '%' + buf[i].toString(16)
}
}
return res + decodeUtf8Char(tmp)
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function binarySlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; i++) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = Buffer._augment(this.subarray(start, end))
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; i++) {
newBuf[i] = this[i + start]
}
}
if (newBuf.length) newBuf.parent = this.parent || this
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
if (value > max || value < min) throw new RangeError('value is out of bounds')
if (offset + ext > buf.length) throw new RangeError('index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) >>> 0 & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) >>> 0 & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = value
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = value
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkInt(
this, value, offset, byteLength,
Math.pow(2, 8 * byteLength - 1) - 1,
-Math.pow(2, 8 * byteLength - 1)
)
}
var i = 0
var mul = 1
var sub = value < 0 ? 1 : 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkInt(
this, value, offset, byteLength,
Math.pow(2, 8 * byteLength - 1) - 1,
-Math.pow(2, 8 * byteLength - 1)
)
}
var i = byteLength - 1
var mul = 1
var sub = value < 0 ? 1 : 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = value
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (value > max || value < min) throw new RangeError('value is out of bounds')
if (offset + ext > buf.length) throw new RangeError('index out of range')
if (offset < 0) throw new RangeError('index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, target_start, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (target_start >= target.length) target_start = target.length
if (!target_start) target_start = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (target_start < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - target_start < end - start) {
end = target.length - target_start + start
}
var len = end - start
if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < len; i++) {
target[i + target_start] = this[i + start]
}
} else {
target._set(this.subarray(start, start + len), target_start)
}
return len
}
// fill(value, start=0, end=buffer.length)
Buffer.prototype.fill = function fill (value, start, end) {
if (!value) value = 0
if (!start) start = 0
if (!end) end = this.length
if (end < start) throw new RangeError('end < start')
// Fill 0 bytes; we're done
if (end === start) return
if (this.length === 0) return
if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
var i
if (typeof value === 'number') {
for (i = start; i < end; i++) {
this[i] = value
}
} else {
var bytes = utf8ToBytes(value.toString())
var len = bytes.length
for (i = start; i < end; i++) {
this[i] = bytes[i % len]
}
}
return this
}
/**
* Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
* Added in Node 0.12. Only available in browsers that support ArrayBuffer.
*/
Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
if (typeof Uint8Array !== 'undefined') {
if (Buffer.TYPED_ARRAY_SUPPORT) {
return (new Buffer(this)).buffer
} else {
var buf = new Uint8Array(this.length)
for (var i = 0, len = buf.length; i < len; i += 1) {
buf[i] = this[i]
}
return buf.buffer
}
} else {
throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
}
}
// HELPER FUNCTIONS
// ================
var BP = Buffer.prototype
/**
* Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
*/
Buffer._augment = function _augment (arr) {
arr.constructor = Buffer
arr._isBuffer = true
// save reference to original Uint8Array set method before overwriting
arr._set = arr.set
// deprecated, will be removed in node 0.13+
arr.get = BP.get
arr.set = BP.set
arr.write = BP.write
arr.toString = BP.toString
arr.toLocaleString = BP.toString
arr.toJSON = BP.toJSON
arr.equals = BP.equals
arr.compare = BP.compare
arr.indexOf = BP.indexOf
arr.copy = BP.copy
arr.slice = BP.slice
arr.readUIntLE = BP.readUIntLE
arr.readUIntBE = BP.readUIntBE
arr.readUInt8 = BP.readUInt8
arr.readUInt16LE = BP.readUInt16LE
arr.readUInt16BE = BP.readUInt16BE
arr.readUInt32LE = BP.readUInt32LE
arr.readUInt32BE = BP.readUInt32BE
arr.readIntLE = BP.readIntLE
arr.readIntBE = BP.readIntBE
arr.readInt8 = BP.readInt8
arr.readInt16LE = BP.readInt16LE
arr.readInt16BE = BP.readInt16BE
arr.readInt32LE = BP.readInt32LE
arr.readInt32BE = BP.readInt32BE
arr.readFloatLE = BP.readFloatLE
arr.readFloatBE = BP.readFloatBE
arr.readDoubleLE = BP.readDoubleLE
arr.readDoubleBE = BP.readDoubleBE
arr.writeUInt8 = BP.writeUInt8
arr.writeUIntLE = BP.writeUIntLE
arr.writeUIntBE = BP.writeUIntBE
arr.writeUInt16LE = BP.writeUInt16LE
arr.writeUInt16BE = BP.writeUInt16BE
arr.writeUInt32LE = BP.writeUInt32LE
arr.writeUInt32BE = BP.writeUInt32BE
arr.writeIntLE = BP.writeIntLE
arr.writeIntBE = BP.writeIntBE
arr.writeInt8 = BP.writeInt8
arr.writeInt16LE = BP.writeInt16LE
arr.writeInt16BE = BP.writeInt16BE
arr.writeInt32LE = BP.writeInt32LE
arr.writeInt32BE = BP.writeInt32BE
arr.writeFloatLE = BP.writeFloatLE
arr.writeFloatBE = BP.writeFloatBE
arr.writeDoubleLE = BP.writeDoubleLE
arr.writeDoubleBE = BP.writeDoubleBE
arr.fill = BP.fill
arr.inspect = BP.inspect
arr.toArrayBuffer = BP.toArrayBuffer
return arr
}
var INVALID_BASE64_RE = /[^+\/0-9A-z\-]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function isArrayish (subject) {
return isArray(subject) || Buffer.isBuffer(subject) ||
subject && typeof subject === 'object' &&
typeof subject.length === 'number'
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
var i = 0
for (; i < length; i++) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (leadSurrogate) {
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
} else {
// valid surrogate pair
codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
leadSurrogate = null
}
} else {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else {
// valid lead
leadSurrogate = codePoint
continue
}
}
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = null
}
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x200000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; i++) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; i++) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
function decodeUtf8Char (str) {
try {
return decodeURIComponent(str)
} catch (err) {
return String.fromCharCode(0xFFFD) // UTF 8 invalid char
}
}
},{"base64-js":4,"ieee754":5,"is-array":6}],4:[function(_dereq_,module,exports){
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
;(function (exports) {
'use strict';
var Arr = (typeof Uint8Array !== 'undefined')
? Uint8Array
: Array
var PLUS = '+'.charCodeAt(0)
var SLASH = '/'.charCodeAt(0)
var NUMBER = '0'.charCodeAt(0)
var LOWER = 'a'.charCodeAt(0)
var UPPER = 'A'.charCodeAt(0)
var PLUS_URL_SAFE = '-'.charCodeAt(0)
var SLASH_URL_SAFE = '_'.charCodeAt(0)
function decode (elt) {
var code = elt.charCodeAt(0)
if (code === PLUS ||
code === PLUS_URL_SAFE)
return 62 // '+'
if (code === SLASH ||
code === SLASH_URL_SAFE)
return 63 // '/'
if (code < NUMBER)
return -1 //no match
if (code < NUMBER + 10)
return code - NUMBER + 26 + 26
if (code < UPPER + 26)
return code - UPPER
if (code < LOWER + 26)
return code - LOWER + 26
}
function b64ToByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
if (b64.length % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
var len = b64.length
placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(b64.length * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? b64.length - 4 : b64.length
var L = 0
function push (v) {
arr[L++] = v
}
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
push((tmp & 0xFF0000) >> 16)
push((tmp & 0xFF00) >> 8)
push(tmp & 0xFF)
}
if (placeHolders === 2) {
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
push(tmp & 0xFF)
} else if (placeHolders === 1) {
tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
push((tmp >> 8) & 0xFF)
push(tmp & 0xFF)
}
return arr
}
function uint8ToBase64 (uint8) {
var i,
extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
output = "",
temp, length
function encode (num) {
return lookup.charAt(num)
}
function tripletToBase64 (num) {
return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
}
// go through the array every three bytes, we'll deal with trailing stuff later
for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output += tripletToBase64(temp)
}
// pad the end with zeros, but make sure to not forget the extra bytes
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1]
output += encode(temp >> 2)
output += encode((temp << 4) & 0x3F)
output += '=='
break
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
output += encode(temp >> 10)
output += encode((temp >> 4) & 0x3F)
output += encode((temp << 2) & 0x3F)
output += '='
break
}
return output
}
exports.toByteArray = b64ToByteArray
exports.fromByteArray = uint8ToBase64
}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
},{}],5:[function(_dereq_,module,exports){
exports.read = function(buffer, offset, isLE, mLen, nBytes) {
var e, m,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
nBits = -7,
i = isLE ? (nBytes - 1) : 0,
d = isLE ? -1 : 1,
s = buffer[offset + i];
i += d;
e = s & ((1 << (-nBits)) - 1);
s >>= (-nBits);
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
m = e & ((1 << (-nBits)) - 1);
e >>= (-nBits);
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity);
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
i = isLE ? 0 : (nBytes - 1),
d = isLE ? 1 : -1,
s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
e = (e << mLen) | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
buffer[offset + i - d] |= s * 128;
};
},{}],6:[function(_dereq_,module,exports){
/**
* isArray
*/
var isArray = Array.isArray;
/**
* toString
*/
var str = Object.prototype.toString;
/**
* Whether or not the given `val`
* is an array.
*
* example:
*
* isArray([]);
* // > true
* isArray(arguments);
* // > false
* isArray('');
* // > false
*
* @param {mixed} val
* @return {bool}
*/
module.exports = isArray || function (val) {
return !! val && '[object Array]' == str.call(val);
};
},{}],7:[function(_dereq_,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
return splitPathRe.exec(filename).slice(1);
};
// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function(p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function(path) {
var result = splitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
exports.basename = function(path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function(path) {
return splitPath(path)[3];
};
function filter (xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
? function (str, start, len) { return str.substr(start, len) }
: function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
}
;
}).call(this,_dereq_('_process'))
},{"_process":8}],8:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
function drainQueue() {
if (draining) {
return;
}
draining = true;
var currentQueue;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
var i = -1;
while (++i < len) {
currentQueue[i]();
}
len = queue.length;
}
draining = false;
}
process.nextTick = function (fun) {
queue.push(fun);
if (!draining) {
setTimeout(drainQueue, 0);
}
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],9:[function(_dereq_,module,exports){
/*
Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com>
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function (root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
// Rhino, and plain browser loading.
/* istanbul ignore next */
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports);
} else {
factory((root.esprima = {}));
}
}(this, function (exports) {
'use strict';
var Token,
TokenName,
FnExprTokens,
Syntax,
PropertyKind,
Messages,
Regex,
SyntaxTreeDelegate,
XHTMLEntities,
ClassPropertyType,
source,
strict,
index,
lineNumber,
lineStart,
length,
delegate,
lookahead,
state,
extra;
Token = {
BooleanLiteral: 1,
EOF: 2,
Identifier: 3,
Keyword: 4,
NullLiteral: 5,
NumericLiteral: 6,
Punctuator: 7,
StringLiteral: 8,
RegularExpression: 9,
Template: 10,
JSXIdentifier: 11,
JSXText: 12
};
TokenName = {};
TokenName[Token.BooleanLiteral] = 'Boolean';
TokenName[Token.EOF] = '<end>';
TokenName[Token.Identifier] = 'Identifier';
TokenName[Token.Keyword] = 'Keyword';
TokenName[Token.NullLiteral] = 'Null';
TokenName[Token.NumericLiteral] = 'Numeric';
TokenName[Token.Punctuator] = 'Punctuator';
TokenName[Token.StringLiteral] = 'String';
TokenName[Token.JSXIdentifier] = 'JSXIdentifier';
TokenName[Token.JSXText] = 'JSXText';
TokenName[Token.RegularExpression] = 'RegularExpression';
// A function following one of those tokens is an expression.
FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
'return', 'case', 'delete', 'throw', 'void',
// assignment operators
'=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
'&=', '|=', '^=', ',',
// binary/unary operators
'+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
'|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
'<=', '<', '>', '!=', '!=='];
Syntax = {
AnyTypeAnnotation: 'AnyTypeAnnotation',
ArrayExpression: 'ArrayExpression',
ArrayPattern: 'ArrayPattern',
ArrayTypeAnnotation: 'ArrayTypeAnnotation',
ArrowFunctionExpression: 'ArrowFunctionExpression',
AssignmentExpression: 'AssignmentExpression',
BinaryExpression: 'BinaryExpression',
BlockStatement: 'BlockStatement',
BooleanTypeAnnotation: 'BooleanTypeAnnotation',
BreakStatement: 'BreakStatement',
CallExpression: 'CallExpression',
CatchClause: 'CatchClause',
ClassBody: 'ClassBody',
ClassDeclaration: 'ClassDeclaration',
ClassExpression: 'ClassExpression',
ClassImplements: 'ClassImplements',
ClassProperty: 'ClassProperty',
ComprehensionBlock: 'ComprehensionBlock',
ComprehensionExpression: 'ComprehensionExpression',
ConditionalExpression: 'ConditionalExpression',
ContinueStatement: 'ContinueStatement',
DebuggerStatement: 'DebuggerStatement',
DeclareClass: 'DeclareClass',
DeclareFunction: 'DeclareFunction',
DeclareModule: 'DeclareModule',
DeclareVariable: 'DeclareVariable',
DoWhileStatement: 'DoWhileStatement',
EmptyStatement: 'EmptyStatement',
ExportDeclaration: 'ExportDeclaration',
ExportBatchSpecifier: 'ExportBatchSpecifier',
ExportSpecifier: 'ExportSpecifier',
ExpressionStatement: 'ExpressionStatement',
ForInStatement: 'ForInStatement',
ForOfStatement: 'ForOfStatement',
ForStatement: 'ForStatement',
FunctionDeclaration: 'FunctionDeclaration',
FunctionExpression: 'FunctionExpression',
FunctionTypeAnnotation: 'FunctionTypeAnnotation',
FunctionTypeParam: 'FunctionTypeParam',
GenericTypeAnnotation: 'GenericTypeAnnotation',
Identifier: 'Identifier',
IfStatement: 'IfStatement',
ImportDeclaration: 'ImportDeclaration',
ImportDefaultSpecifier: 'ImportDefaultSpecifier',
ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
ImportSpecifier: 'ImportSpecifier',
InterfaceDeclaration: 'InterfaceDeclaration',
InterfaceExtends: 'InterfaceExtends',
IntersectionTypeAnnotation: 'IntersectionTypeAnnotation',
LabeledStatement: 'LabeledStatement',
Literal: 'Literal',
LogicalExpression: 'LogicalExpression',
MemberExpression: 'MemberExpression',
MethodDefinition: 'MethodDefinition',
ModuleSpecifier: 'ModuleSpecifier',
NewExpression: 'NewExpression',
NullableTypeAnnotation: 'NullableTypeAnnotation',
NumberTypeAnnotation: 'NumberTypeAnnotation',
ObjectExpression: 'ObjectExpression',
ObjectPattern: 'ObjectPattern',
ObjectTypeAnnotation: 'ObjectTypeAnnotation',
ObjectTypeCallProperty: 'ObjectTypeCallProperty',
ObjectTypeIndexer: 'ObjectTypeIndexer',
ObjectTypeProperty: 'ObjectTypeProperty',
Program: 'Program',
Property: 'Property',
QualifiedTypeIdentifier: 'QualifiedTypeIdentifier',
ReturnStatement: 'ReturnStatement',
SequenceExpression: 'SequenceExpression',
SpreadElement: 'SpreadElement',
SpreadProperty: 'SpreadProperty',
StringLiteralTypeAnnotation: 'StringLiteralTypeAnnotation',
StringTypeAnnotation: 'StringTypeAnnotation',
SwitchCase: 'SwitchCase',
SwitchStatement: 'SwitchStatement',
TaggedTemplateExpression: 'TaggedTemplateExpression',
TemplateElement: 'TemplateElement',
TemplateLiteral: 'TemplateLiteral',
ThisExpression: 'ThisExpression',
ThrowStatement: 'ThrowStatement',
TupleTypeAnnotation: 'TupleTypeAnnotation',
TryStatement: 'TryStatement',
TypeAlias: 'TypeAlias',
TypeAnnotation: 'TypeAnnotation',
TypeCastExpression: 'TypeCastExpression',
TypeofTypeAnnotation: 'TypeofTypeAnnotation',
TypeParameterDeclaration: 'TypeParameterDeclaration',
TypeParameterInstantiation: 'TypeParameterInstantiation',
UnaryExpression: 'UnaryExpression',
UnionTypeAnnotation: 'UnionTypeAnnotation',
UpdateExpression: 'UpdateExpression',
VariableDeclaration: 'VariableDeclaration',
VariableDeclarator: 'VariableDeclarator',
VoidTypeAnnotation: 'VoidTypeAnnotation',
WhileStatement: 'WhileStatement',
WithStatement: 'WithStatement',
JSXIdentifier: 'JSXIdentifier',
JSXNamespacedName: 'JSXNamespacedName',
JSXMemberExpression: 'JSXMemberExpression',
JSXEmptyExpression: 'JSXEmptyExpression',
JSXExpressionContainer: 'JSXExpressionContainer',
JSXElement: 'JSXElement',
JSXClosingElement: 'JSXClosingElement',
JSXOpeningElement: 'JSXOpeningElement',
JSXAttribute: 'JSXAttribute',
JSXSpreadAttribute: 'JSXSpreadAttribute',
JSXText: 'JSXText',
YieldExpression: 'YieldExpression',
AwaitExpression: 'AwaitExpression'
};
PropertyKind = {
Data: 1,
Get: 2,
Set: 4
};
ClassPropertyType = {
'static': 'static',
prototype: 'prototype'
};
// Error messages should be identical to V8.
Messages = {
UnexpectedToken: 'Unexpected token %0',
UnexpectedNumber: 'Unexpected number',
UnexpectedString: 'Unexpected string',
UnexpectedIdentifier: 'Unexpected identifier',
UnexpectedReserved: 'Unexpected reserved word',
UnexpectedTemplate: 'Unexpected quasi %0',
UnexpectedEOS: 'Unexpected end of input',
NewlineAfterThrow: 'Illegal newline after throw',
InvalidRegExp: 'Invalid regular expression',
UnterminatedRegExp: 'Invalid regular expression: missing /',
InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
InvalidLHSInFormalsList: 'Invalid left-hand side in formals list',
InvalidLHSInForIn: 'Invalid left-hand side in for-in',
MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
NoCatchOrFinally: 'Missing catch or finally after try',
UnknownLabel: 'Undefined label \'%0\'',
Redeclaration: '%0 \'%1\' has already been declared',
IllegalContinue: 'Illegal continue statement',
IllegalBreak: 'Illegal break statement',
IllegalDuplicateClassProperty: 'Illegal duplicate property in class definition',
IllegalClassConstructorProperty: 'Illegal constructor property in class definition',
IllegalReturn: 'Illegal return statement',
IllegalSpread: 'Illegal spread element',
StrictModeWith: 'Strict mode code may not include a with statement',
StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
StrictVarName: 'Variable name may not be eval or arguments in strict mode',
StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
ParameterAfterRestParameter: 'Rest parameter must be final parameter of an argument list',
DefaultRestParameter: 'Rest parameter can not have a default value',
ElementAfterSpreadElement: 'Spread must be the final element of an element list',
PropertyAfterSpreadProperty: 'A rest property must be the final property of an object literal',
ObjectPatternAsRestParameter: 'Invalid rest parameter',
ObjectPatternAsSpread: 'Invalid spread argument',
StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
StrictDelete: 'Delete of an unqualified identifier in strict mode.',
StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',
AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',
AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',
StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
StrictReservedWord: 'Use of future reserved word in strict mode',
MissingFromClause: 'Missing from clause',
NoAsAfterImportNamespace: 'Missing as after import *',
InvalidModuleSpecifier: 'Invalid module specifier',
IllegalImportDeclaration: 'Illegal import declaration',
IllegalExportDeclaration: 'Illegal export declaration',
NoUninitializedConst: 'Const must be initialized',
ComprehensionRequiresBlock: 'Comprehension must have at least one block',
ComprehensionError: 'Comprehension Error',
EachNotAllowed: 'Each is not supported',
InvalidJSXAttributeValue: 'JSX value should be either an expression or a quoted JSX text',
ExpectedJSXClosingTag: 'Expected corresponding JSX closing tag for %0',
AdjacentJSXElements: 'Adjacent JSX elements must be wrapped in an enclosing tag',
ConfusedAboutFunctionType: 'Unexpected token =>. It looks like ' +
'you are trying to write a function type, but you ended up ' +
'writing a grouped type followed by an =>, which is a syntax ' +
'error. Remember, function type parameters are named so function ' +
'types look like (name1: type1, name2: type2) => returnType. You ' +
'probably wrote (type1) => returnType'
};
// See also tools/generate-unicode-regex.py.
Regex = {
NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'),
NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'),
LeadingZeros: new RegExp('^0+(?!$)')
};
// Ensure the condition is true, otherwise throw an error.
// This is only to have a better contract semantic, i.e. another safety net
// to catch a logic error. The condition shall be fulfilled in normal case.
// Do NOT use this to enforce a certain condition on any user input.
function assert(condition, message) {
/* istanbul ignore if */
if (!condition) {
throw new Error('ASSERT: ' + message);
}
}
function StringMap() {
this.$data = {};
}
StringMap.prototype.get = function (key) {
key = '$' + key;
return this.$data[key];
};
StringMap.prototype.set = function (key, value) {
key = '$' + key;
this.$data[key] = value;
return this;
};
StringMap.prototype.has = function (key) {
key = '$' + key;
return Object.prototype.hasOwnProperty.call(this.$data, key);
};
StringMap.prototype["delete"] = function (key) {
key = '$' + key;
return delete this.$data[key];
};
function isDecimalDigit(ch) {
return (ch >= 48 && ch <= 57); // 0..9
}
function isHexDigit(ch) {
return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
}
function isOctalDigit(ch) {
return '01234567'.indexOf(ch) >= 0;
}
// 7.2 White Space
function isWhiteSpace(ch) {
return (ch === 32) || // space
(ch === 9) || // tab
(ch === 0xB) ||
(ch === 0xC) ||
(ch === 0xA0) ||
(ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0);
}
// 7.3 Line Terminators
function isLineTerminator(ch) {
return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029);
}
// 7.6 Identifier Names and Identifiers
function isIdentifierStart(ch) {
return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore)
(ch >= 65 && ch <= 90) || // A..Z
(ch >= 97 && ch <= 122) || // a..z
(ch === 92) || // \ (backslash)
((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch)));
}
function isIdentifierPart(ch) {
return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore)
(ch >= 65 && ch <= 90) || // A..Z
(ch >= 97 && ch <= 122) || // a..z
(ch >= 48 && ch <= 57) || // 0..9
(ch === 92) || // \ (backslash)
((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch)));
}
// 7.6.1.2 Future Reserved Words
function isFutureReservedWord(id) {
switch (id) {
case 'class':
case 'enum':
case 'export':
case 'extends':
case 'import':
case 'super':
return true;
default:
return false;
}
}
function isStrictModeReservedWord(id) {
switch (id) {
case 'implements':
case 'interface':
case 'package':
case 'private':
case 'protected':
case 'public':
case 'static':
case 'yield':
case 'let':
return true;
default:
return false;
}
}
function isRestrictedWord(id) {
return id === 'eval' || id === 'arguments';
}
// 7.6.1.1 Keywords
function isKeyword(id) {
if (strict && isStrictModeReservedWord(id)) {
return true;
}
// 'const' is specialized as Keyword in V8.
// 'yield' is only treated as a keyword in strict mode.
// 'let' is for compatiblity with SpiderMonkey and ES.next.
// Some others are from future reserved words.
switch (id.length) {
case 2:
return (id === 'if') || (id === 'in') || (id === 'do');
case 3:
return (id === 'var') || (id === 'for') || (id === 'new') ||
(id === 'try') || (id === 'let');
case 4:
return (id === 'this') || (id === 'else') || (id === 'case') ||
(id === 'void') || (id === 'with') || (id === 'enum');
case 5:
return (id === 'while') || (id === 'break') || (id === 'catch') ||
(id === 'throw') || (id === 'const') ||
(id === 'class') || (id === 'super');
case 6:
return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
(id === 'switch') || (id === 'export') || (id === 'import');
case 7:
return (id === 'default') || (id === 'finally') || (id === 'extends');
case 8:
return (id === 'function') || (id === 'continue') || (id === 'debugger');
case 10:
return (id === 'instanceof');
default:
return false;
}
}
// 7.4 Comments
function addComment(type, value, start, end, loc) {
var comment;
assert(typeof start === 'number', 'Comment must have valid position');
// Because the way the actual token is scanned, often the comments
// (if any) are skipped twice during the lexical analysis.
// Thus, we need to skip adding a comment if the comment array already
// handled it.
if (state.lastCommentStart >= start) {
return;
}
state.lastCommentStart = start;
comment = {
type: type,
value: value
};
if (extra.range) {
comment.range = [start, end];
}
if (extra.loc) {
comment.loc = loc;
}
extra.comments.push(comment);
if (extra.attachComment) {
extra.leadingComments.push(comment);
extra.trailingComments.push(comment);
}
}
function skipSingleLineComment() {
var start, loc, ch, comment;
start = index - 2;
loc = {
start: {
line: lineNumber,
column: index - lineStart - 2
}
};
while (index < length) {
ch = source.charCodeAt(index);
++index;
if (isLineTerminator(ch)) {
if (extra.comments) {
comment = source.slice(start + 2, index - 1);
loc.end = {
line: lineNumber,
column: index - lineStart - 1
};
addComment('Line', comment, start, index - 1, loc);
}
if (ch === 13 && source.charCodeAt(index) === 10) {
++index;
}
++lineNumber;
lineStart = index;
return;
}
}
if (extra.comments) {
comment = source.slice(start + 2, index);
loc.end = {
line: lineNumber,
column: index - lineStart
};
addComment('Line', comment, start, index, loc);
}
}
function skipMultiLineComment() {
var start, loc, ch, comment;
if (extra.comments) {
start = index - 2;
loc = {
start: {
line: lineNumber,
column: index - lineStart - 2
}
};
}
while (index < length) {
ch = source.charCodeAt(index);
if (isLineTerminator(ch)) {
if (ch === 13 && source.charCodeAt(index + 1) === 10) {
++index;
}
++lineNumber;
++index;
lineStart = index;
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
} else if (ch === 42) {
// Block comment ends with '*/' (char #42, char #47).
if (source.charCodeAt(index + 1) === 47) {
++index;
++index;
if (extra.comments) {
comment = source.slice(start + 2, index - 2);
loc.end = {
line: lineNumber,
column: index - lineStart
};
addComment('Block', comment, start, index, loc);
}
return;
}
++index;
} else {
++index;
}
}
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
function skipComment() {
var ch;
while (index < length) {
ch = source.charCodeAt(index);
if (isWhiteSpace(ch)) {
++index;
} else if (isLineTerminator(ch)) {
++index;
if (ch === 13 && source.charCodeAt(index) === 10) {
++index;
}
++lineNumber;
lineStart = index;
} else if (ch === 47) { // 47 is '/'
ch = source.charCodeAt(index + 1);
if (ch === 47) {
++index;
++index;
skipSingleLineComment();
} else if (ch === 42) { // 42 is '*'
++index;
++index;
skipMultiLineComment();
} else {
break;
}
} else {
break;
}
}
}
function scanHexEscape(prefix) {
var i, len, ch, code = 0;
len = (prefix === 'u') ? 4 : 2;
for (i = 0; i < len; ++i) {
if (index < length && isHexDigit(source[index])) {
ch = source[index++];
code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
} else {
return '';
}
}
return String.fromCharCode(code);
}
function scanUnicodeCodePointEscape() {
var ch, code, cu1, cu2;
ch = source[index];
code = 0;
// At least, one hex digit is required.
if (ch === '}') {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
while (index < length) {
ch = source[index++];
if (!isHexDigit(ch)) {
break;
}
code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
}
if (code > 0x10FFFF || ch !== '}') {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
// UTF-16 Encoding
if (code <= 0xFFFF) {
return String.fromCharCode(code);
}
cu1 = ((code - 0x10000) >> 10) + 0xD800;
cu2 = ((code - 0x10000) & 1023) + 0xDC00;
return String.fromCharCode(cu1, cu2);
}
function getEscapedIdentifier() {
var ch, id;
ch = source.charCodeAt(index++);
id = String.fromCharCode(ch);
// '\u' (char #92, char #117) denotes an escaped character.
if (ch === 92) {
if (source.charCodeAt(index) !== 117) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
++index;
ch = scanHexEscape('u');
if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
id = ch;
}
while (index < length) {
ch = source.charCodeAt(index);
if (!isIdentifierPart(ch)) {
break;
}
++index;
id += String.fromCharCode(ch);
// '\u' (char #92, char #117) denotes an escaped character.
if (ch === 92) {
id = id.substr(0, id.length - 1);
if (source.charCodeAt(index) !== 117) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
++index;
ch = scanHexEscape('u');
if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
id += ch;
}
}
return id;
}
function getIdentifier() {
var start, ch;
start = index++;
while (index < length) {
ch = source.charCodeAt(index);
if (ch === 92) {
// Blackslash (char #92) marks Unicode escape sequence.
index = start;
return getEscapedIdentifier();
}
if (isIdentifierPart(ch)) {
++index;
} else {
break;
}
}
return source.slice(start, index);
}
function scanIdentifier() {
var start, id, type;
start = index;
// Backslash (char #92) starts an escaped character.
id = (source.charCodeAt(index) === 92) ? getEscapedIdentifier() : getIdentifier();
// There is no keyword or literal with only one character.
// Thus, it must be an identifier.
if (id.length === 1) {
type = Token.Identifier;
} else if (isKeyword(id)) {
type = Token.Keyword;
} else if (id === 'null') {
type = Token.NullLiteral;
} else if (id === 'true' || id === 'false') {
type = Token.BooleanLiteral;
} else {
type = Token.Identifier;
}
return {
type: type,
value: id,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
// 7.7 Punctuators
function scanPunctuator() {
var start = index,
code = source.charCodeAt(index),
code2,
ch1 = source[index],
ch2,
ch3,
ch4;
if (state.inJSXTag || state.inJSXChild) {
// Don't need to check for '{' and '}' as it's already handled
// correctly by default.
switch (code) {
case 60: // <
case 62: // >
++index;
return {
type: Token.Punctuator,
value: String.fromCharCode(code),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
}
switch (code) {
// Check for most common single-character punctuators.
case 40: // ( open bracket
case 41: // ) close bracket
case 59: // ; semicolon
case 44: // , comma
case 123: // { open curly brace
case 125: // } close curly brace
case 91: // [
case 93: // ]
case 58: // :
case 63: // ?
case 126: // ~
++index;
if (extra.tokenize) {
if (code === 40) {
extra.openParenToken = extra.tokens.length;
} else if (code === 123) {
extra.openCurlyToken = extra.tokens.length;
}
}
return {
type: Token.Punctuator,
value: String.fromCharCode(code),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
default:
code2 = source.charCodeAt(index + 1);
// '=' (char #61) marks an assignment or comparison operator.
if (code2 === 61) {
switch (code) {
case 37: // %
case 38: // &
case 42: // *:
case 43: // +
case 45: // -
case 47: // /
case 60: // <
case 62: // >
case 94: // ^
case 124: // |
index += 2;
return {
type: Token.Punctuator,
value: String.fromCharCode(code) + String.fromCharCode(code2),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
case 33: // !
case 61: // =
index += 2;
// !== and ===
if (source.charCodeAt(index) === 61) {
++index;
}
return {
type: Token.Punctuator,
value: source.slice(start, index),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
default:
break;
}
}
break;
}
// Peek more characters.
ch2 = source[index + 1];
ch3 = source[index + 2];
ch4 = source[index + 3];
// 4-character punctuator: >>>=
if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
if (ch4 === '=') {
index += 4;
return {
type: Token.Punctuator,
value: '>>>=',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
}
// 3-character punctuators: === !== >>> <<= >>=
if (ch1 === '>' && ch2 === '>' && ch3 === '>' && !state.inType) {
index += 3;
return {
type: Token.Punctuator,
value: '>>>',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '<' && ch2 === '<' && ch3 === '=') {
index += 3;
return {
type: Token.Punctuator,
value: '<<=',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '>' && ch2 === '>' && ch3 === '=') {
index += 3;
return {
type: Token.Punctuator,
value: '>>=',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '.' && ch2 === '.' && ch3 === '.') {
index += 3;
return {
type: Token.Punctuator,
value: '...',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
// Other 2-character punctuators: ++ -- << >> && ||
// Don't match these tokens if we're in a type, since they never can
// occur and can mess up types like Map<string, Array<string>>
if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0) && !state.inType) {
index += 2;
return {
type: Token.Punctuator,
value: ch1 + ch2,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '=' && ch2 === '>') {
index += 2;
return {
type: Token.Punctuator,
value: '=>',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
++index;
return {
type: Token.Punctuator,
value: ch1,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '.') {
++index;
return {
type: Token.Punctuator,
value: ch1,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
// 7.8.3 Numeric Literals
function scanHexLiteral(start) {
var number = '';
while (index < length) {
if (!isHexDigit(source[index])) {
break;
}
number += source[index++];
}
if (number.length === 0) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
if (isIdentifierStart(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseInt('0x' + number, 16),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanBinaryLiteral(start) {
var ch, number;
number = '';
while (index < length) {
ch = source[index];
if (ch !== '0' && ch !== '1') {
break;
}
number += source[index++];
}
if (number.length === 0) {
// only 0b or 0B
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
if (index < length) {
ch = source.charCodeAt(index);
/* istanbul ignore else */
if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
return {
type: Token.NumericLiteral,
value: parseInt(number, 2),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanOctalLiteral(prefix, start) {
var number, octal;
if (isOctalDigit(prefix)) {
octal = true;
number = '0' + source[index++];
} else {
octal = false;
++index;
number = '';
}
while (index < length) {
if (!isOctalDigit(source[index])) {
break;
}
number += source[index++];
}
if (!octal && number.length === 0) {
// only 0o or 0O
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseInt(number, 8),
octal: octal,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanNumericLiteral() {
var number, start, ch;
ch = source[index];
assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
'Numeric literal must start with a decimal digit or a decimal point');
start = index;
number = '';
if (ch !== '.') {
number = source[index++];
ch = source[index];
// Hex number starts with '0x'.
// Octal number starts with '0'.
// Octal number in ES6 starts with '0o'.
// Binary number in ES6 starts with '0b'.
if (number === '0') {
if (ch === 'x' || ch === 'X') {
++index;
return scanHexLiteral(start);
}
if (ch === 'b' || ch === 'B') {
++index;
return scanBinaryLiteral(start);
}
if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) {
return scanOctalLiteral(ch, start);
}
// decimal number starts with '0' such as '09' is illegal.
if (ch && isDecimalDigit(ch.charCodeAt(0))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
ch = source[index];
}
if (ch === '.') {
number += source[index++];
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
ch = source[index];
}
if (ch === 'e' || ch === 'E') {
number += source[index++];
ch = source[index];
if (ch === '+' || ch === '-') {
number += source[index++];
}
if (isDecimalDigit(source.charCodeAt(index))) {
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
} else {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
if (isIdentifierStart(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseFloat(number),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
// 7.8.4 String Literals
function scanStringLiteral() {
var str = '', quote, start, ch, code, unescaped, restore, octal = false;
quote = source[index];
assert((quote === '\'' || quote === '"'),
'String literal must starts with a quote');
start = index;
++index;
while (index < length) {
ch = source[index++];
if (ch === quote) {
quote = '';
break;
} else if (ch === '\\') {
ch = source[index++];
if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
switch (ch) {
case 'n':
str += '\n';
break;
case 'r':
str += '\r';
break;
case 't':
str += '\t';
break;
case 'u':
case 'x':
if (source[index] === '{') {
++index;
str += scanUnicodeCodePointEscape();
} else {
restore = index;
unescaped = scanHexEscape(ch);
if (unescaped) {
str += unescaped;
} else {
index = restore;
str += ch;
}
}
break;
case 'b':
str += '\b';
break;
case 'f':
str += '\f';
break;
case 'v':
str += '\x0B';
break;
default:
if (isOctalDigit(ch)) {
code = '01234567'.indexOf(ch);
// \0 is not octal escape sequence
if (code !== 0) {
octal = true;
}
/* istanbul ignore else */
if (index < length && isOctalDigit(source[index])) {
octal = true;
code = code * 8 + '01234567'.indexOf(source[index++]);
// 3 digits are only allowed when string starts
// with 0, 1, 2, 3
if ('0123'.indexOf(ch) >= 0 &&
index < length &&
isOctalDigit(source[index])) {
code = code * 8 + '01234567'.indexOf(source[index++]);
}
}
str += String.fromCharCode(code);
} else {
str += ch;
}
break;
}
} else {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
}
} else if (isLineTerminator(ch.charCodeAt(0))) {
break;
} else {
str += ch;
}
}
if (quote !== '') {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.StringLiteral,
value: str,
octal: octal,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanTemplate() {
var cooked = '', ch, start, terminated, tail, restore, unescaped, code, octal;
terminated = false;
tail = false;
start = index;
++index;
while (index < length) {
ch = source[index++];
if (ch === '`') {
tail = true;
terminated = true;
break;
} else if (ch === '$') {
if (source[index] === '{') {
++index;
terminated = true;
break;
}
cooked += ch;
} else if (ch === '\\') {
ch = source[index++];
if (!isLineTerminator(ch.charCodeAt(0))) {
switch (ch) {
case 'n':
cooked += '\n';
break;
case 'r':
cooked += '\r';
break;
case 't':
cooked += '\t';
break;
case 'u':
case 'x':
if (source[index] === '{') {
++index;
cooked += scanUnicodeCodePointEscape();
} else {
restore = index;
unescaped = scanHexEscape(ch);
if (unescaped) {
cooked += unescaped;
} else {
index = restore;
cooked += ch;
}
}
break;
case 'b':
cooked += '\b';
break;
case 'f':
cooked += '\f';
break;
case 'v':
cooked += '\v';
break;
default:
if (isOctalDigit(ch)) {
code = '01234567'.indexOf(ch);
// \0 is not octal escape sequence
if (code !== 0) {
octal = true;
}
/* istanbul ignore else */
if (index < length && isOctalDigit(source[index])) {
octal = true;
code = code * 8 + '01234567'.indexOf(source[index++]);
// 3 digits are only allowed when string starts
// with 0, 1, 2, 3
if ('0123'.indexOf(ch) >= 0 &&
index < length &&
isOctalDigit(source[index])) {
code = code * 8 + '01234567'.indexOf(source[index++]);
}
}
cooked += String.fromCharCode(code);
} else {
cooked += ch;
}
break;
}
} else {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
}
} else if (isLineTerminator(ch.charCodeAt(0))) {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
cooked += '\n';
} else {
cooked += ch;
}
}
if (!terminated) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.Template,
value: {
cooked: cooked,
raw: source.slice(start + 1, index - ((tail) ? 1 : 2))
},
tail: tail,
octal: octal,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanTemplateElement(option) {
var startsWith, template;
lookahead = null;
skipComment();
startsWith = (option.head) ? '`' : '}';
if (source[index] !== startsWith) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
template = scanTemplate();
peek();
return template;
}
function testRegExp(pattern, flags) {
var tmp = pattern,
value;
if (flags.indexOf('u') >= 0) {
// Replace each astral symbol and every Unicode code point
// escape sequence with a single ASCII symbol to avoid throwing on
// regular expressions that are only valid in combination with the
// `/u` flag.
// Note: replacing with the ASCII symbol `x` might cause false
// negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
// perfectly valid pattern that is equivalent to `[a-b]`, but it
// would be replaced by `[x-b]` which throws an error.
tmp = tmp
.replace(/\\u\{([0-9a-fA-F]+)\}/g, function ($0, $1) {
if (parseInt($1, 16) <= 0x10FFFF) {
return 'x';
}
throwError({}, Messages.InvalidRegExp);
})
.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x');
}
// First, detect invalid regular expressions.
try {
value = new RegExp(tmp);
} catch (e) {
throwError({}, Messages.InvalidRegExp);
}
// Return a regular expression object for this pattern-flag pair, or
// `null` in case the current environment doesn't support the flags it
// uses.
try {
return new RegExp(pattern, flags);
} catch (exception) {
return null;
}
}
function scanRegExpBody() {
var ch, str, classMarker, terminated, body;
ch = source[index];
assert(ch === '/', 'Regular expression literal must start with a slash');
str = source[index++];
classMarker = false;
terminated = false;
while (index < length) {
ch = source[index++];
str += ch;
if (ch === '\\') {
ch = source[index++];
// ECMA-262 7.8.5
if (isLineTerminator(ch.charCodeAt(0))) {
throwError({}, Messages.UnterminatedRegExp);
}
str += ch;
} else if (isLineTerminator(ch.charCodeAt(0))) {
throwError({}, Messages.UnterminatedRegExp);
} else if (classMarker) {
if (ch === ']') {
classMarker = false;
}
} else {
if (ch === '/') {
terminated = true;
break;
} else if (ch === '[') {
classMarker = true;
}
}
}
if (!terminated) {
throwError({}, Messages.UnterminatedRegExp);
}
// Exclude leading and trailing slash.
body = str.substr(1, str.length - 2);
return {
value: body,
literal: str
};
}
function scanRegExpFlags() {
var ch, str, flags, restore;
str = '';
flags = '';
while (index < length) {
ch = source[index];
if (!isIdentifierPart(ch.charCodeAt(0))) {
break;
}
++index;
if (ch === '\\' && index < length) {
ch = source[index];
if (ch === 'u') {
++index;
restore = index;
ch = scanHexEscape('u');
if (ch) {
flags += ch;
for (str += '\\u'; restore < index; ++restore) {
str += source[restore];
}
} else {
index = restore;
flags += 'u';
str += '\\u';
}
throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');
} else {
str += '\\';
throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');
}
} else {
flags += ch;
str += ch;
}
}
return {
value: flags,
literal: str
};
}
function scanRegExp() {
var start, body, flags, value;
lookahead = null;
skipComment();
start = index;
body = scanRegExpBody();
flags = scanRegExpFlags();
value = testRegExp(body.value, flags.value);
if (extra.tokenize) {
return {
type: Token.RegularExpression,
value: value,
regex: {
pattern: body.value,
flags: flags.value
},
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
return {
literal: body.literal + flags.literal,
value: value,
regex: {
pattern: body.value,
flags: flags.value
},
range: [start, index]
};
}
function isIdentifierName(token) {
return token.type === Token.Identifier ||
token.type === Token.Keyword ||
token.type === Token.BooleanLiteral ||
token.type === Token.NullLiteral;
}
function advanceSlash() {
var prevToken,
checkToken;
// Using the following algorithm:
// https://github.com/mozilla/sweet.js/wiki/design
prevToken = extra.tokens[extra.tokens.length - 1];
if (!prevToken) {
// Nothing before that: it cannot be a division.
return scanRegExp();
}
if (prevToken.type === 'Punctuator') {
if (prevToken.value === ')') {
checkToken = extra.tokens[extra.openParenToken - 1];
if (checkToken &&
checkToken.type === 'Keyword' &&
(checkToken.value === 'if' ||
checkToken.value === 'while' ||
checkToken.value === 'for' ||
checkToken.value === 'with')) {
return scanRegExp();
}
return scanPunctuator();
}
if (prevToken.value === '}') {
// Dividing a function by anything makes little sense,
// but we have to check for that.
if (extra.tokens[extra.openCurlyToken - 3] &&
extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') {
// Anonymous function.
checkToken = extra.tokens[extra.openCurlyToken - 4];
if (!checkToken) {
return scanPunctuator();
}
} else if (extra.tokens[extra.openCurlyToken - 4] &&
extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') {
// Named function.
checkToken = extra.tokens[extra.openCurlyToken - 5];
if (!checkToken) {
return scanRegExp();
}
} else {
return scanPunctuator();
}
// checkToken determines whether the function is
// a declaration or an expression.
if (FnExprTokens.indexOf(checkToken.value) >= 0) {
// It is an expression.
return scanPunctuator();
}
// It is a declaration.
return scanRegExp();
}
return scanRegExp();
}
if (prevToken.type === 'Keyword' && prevToken.value !== 'this') {
return scanRegExp();
}
return scanPunctuator();
}
function advance() {
var ch;
if (!state.inJSXChild) {
skipComment();
}
if (index >= length) {
return {
type: Token.EOF,
lineNumber: lineNumber,
lineStart: lineStart,
range: [index, index]
};
}
if (state.inJSXChild) {
return advanceJSXChild();
}
ch = source.charCodeAt(index);
// Very common: ( and ) and ;
if (ch === 40 || ch === 41 || ch === 58) {
return scanPunctuator();
}
// String literal starts with single quote (#39) or double quote (#34).
if (ch === 39 || ch === 34) {
if (state.inJSXTag) {
return scanJSXStringLiteral();
}
return scanStringLiteral();
}
if (state.inJSXTag && isJSXIdentifierStart(ch)) {
return scanJSXIdentifier();
}
if (ch === 96) {
return scanTemplate();
}
if (isIdentifierStart(ch)) {
return scanIdentifier();
}
// Dot (.) char #46 can also start a floating-point number, hence the need
// to check the next character.
if (ch === 46) {
if (isDecimalDigit(source.charCodeAt(index + 1))) {
return scanNumericLiteral();
}
return scanPunctuator();
}
if (isDecimalDigit(ch)) {
return scanNumericLiteral();
}
// Slash (/) char #47 can also start a regex.
if (extra.tokenize && ch === 47) {
return advanceSlash();
}
return scanPunctuator();
}
function lex() {
var token;
token = lookahead;
index = token.range[1];
lineNumber = token.lineNumber;
lineStart = token.lineStart;
lookahead = advance();
index = token.range[1];
lineNumber = token.lineNumber;
lineStart = token.lineStart;
return token;
}
function peek() {
var pos, line, start;
pos = index;
line = lineNumber;
start = lineStart;
lookahead = advance();
index = pos;
lineNumber = line;
lineStart = start;
}
function lookahead2() {
var adv, pos, line, start, result;
// If we are collecting the tokens, don't grab the next one yet.
/* istanbul ignore next */
adv = (typeof extra.advance === 'function') ? extra.advance : advance;
pos = index;
line = lineNumber;
start = lineStart;
// Scan for the next immediate token.
/* istanbul ignore if */
if (lookahead === null) {
lookahead = adv();
}
index = lookahead.range[1];
lineNumber = lookahead.lineNumber;
lineStart = lookahead.lineStart;
// Grab the token right after.
result = adv();
index = pos;
lineNumber = line;
lineStart = start;
return result;
}
function rewind(token) {
index = token.range[0];
lineNumber = token.lineNumber;
lineStart = token.lineStart;
lookahead = token;
}
function markerCreate() {
if (!extra.loc && !extra.range) {
return undefined;
}
skipComment();
return {offset: index, line: lineNumber, col: index - lineStart};
}
function markerCreatePreserveWhitespace() {
if (!extra.loc && !extra.range) {
return undefined;
}
return {offset: index, line: lineNumber, col: index - lineStart};
}
function processComment(node) {
var lastChild,
trailingComments,
bottomRight = extra.bottomRightStack,
last = bottomRight[bottomRight.length - 1];
if (node.type === Syntax.Program) {
/* istanbul ignore else */
if (node.body.length > 0) {
return;
}
}
if (extra.trailingComments.length > 0) {
if (extra.trailingComments[0].range[0] >= node.range[1]) {
trailingComments = extra.trailingComments;
extra.trailingComments = [];
} else {
extra.trailingComments.length = 0;
}
} else {
if (last && last.trailingComments && last.trailingComments[0].range[0] >= node.range[1]) {
trailingComments = last.trailingComments;
delete last.trailingComments;
}
}
// Eating the stack.
if (last) {
while (last && last.range[0] >= node.range[0]) {
lastChild = last;
last = bottomRight.pop();
}
}
if (lastChild) {
if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) {
node.leadingComments = lastChild.leadingComments;
delete lastChild.leadingComments;
}
} else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) {
node.leadingComments = extra.leadingComments;
extra.leadingComments = [];
}
if (trailingComments) {
node.trailingComments = trailingComments;
}
bottomRight.push(node);
}
function markerApply(marker, node) {
if (extra.range) {
node.range = [marker.offset, index];
}
if (extra.loc) {
node.loc = {
start: {
line: marker.line,
column: marker.col
},
end: {
line: lineNumber,
column: index - lineStart
}
};
node = delegate.postProcess(node);
}
if (extra.attachComment) {
processComment(node);
}
return node;
}
SyntaxTreeDelegate = {
name: 'SyntaxTree',
postProcess: function (node) {
return node;
},
createArrayExpression: function (elements) {
return {
type: Syntax.ArrayExpression,
elements: elements
};
},
createAssignmentExpression: function (operator, left, right) {
return {
type: Syntax.AssignmentExpression,
operator: operator,
left: left,
right: right
};
},
createBinaryExpression: function (operator, left, right) {
var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression :
Syntax.BinaryExpression;
return {
type: type,
operator: operator,
left: left,
right: right
};
},
createBlockStatement: function (body) {
return {
type: Syntax.BlockStatement,
body: body
};
},
createBreakStatement: function (label) {
return {
type: Syntax.BreakStatement,
label: label
};
},
createCallExpression: function (callee, args) {
return {
type: Syntax.CallExpression,
callee: callee,
'arguments': args
};
},
createCatchClause: function (param, body) {
return {
type: Syntax.CatchClause,
param: param,
body: body
};
},
createConditionalExpression: function (test, consequent, alternate) {
return {
type: Syntax.ConditionalExpression,
test: test,
consequent: consequent,
alternate: alternate
};
},
createContinueStatement: function (label) {
return {
type: Syntax.ContinueStatement,
label: label
};
},
createDebuggerStatement: function () {
return {
type: Syntax.DebuggerStatement
};
},
createDoWhileStatement: function (body, test) {
return {
type: Syntax.DoWhileStatement,
body: body,
test: test
};
},
createEmptyStatement: function () {
return {
type: Syntax.EmptyStatement
};
},
createExpressionStatement: function (expression) {
return {
type: Syntax.ExpressionStatement,
expression: expression
};
},
createForStatement: function (init, test, update, body) {
return {
type: Syntax.ForStatement,
init: init,
test: test,
update: update,
body: body
};
},
createForInStatement: function (left, right, body) {
return {
type: Syntax.ForInStatement,
left: left,
right: right,
body: body,
each: false
};
},
createForOfStatement: function (left, right, body) {
return {
type: Syntax.ForOfStatement,
left: left,
right: right,
body: body
};
},
createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression,
isAsync, returnType, typeParameters) {
var funDecl = {
type: Syntax.FunctionDeclaration,
id: id,
params: params,
defaults: defaults,
body: body,
rest: rest,
generator: generator,
expression: expression,
returnType: returnType,
typeParameters: typeParameters
};
if (isAsync) {
funDecl.async = true;
}
return funDecl;
},
createFunctionExpression: function (id, params, defaults, body, rest, generator, expression,
isAsync, returnType, typeParameters) {
var funExpr = {
type: Syntax.FunctionExpression,
id: id,
params: params,
defaults: defaults,
body: body,
rest: rest,
generator: generator,
expression: expression,
returnType: returnType,
typeParameters: typeParameters
};
if (isAsync) {
funExpr.async = true;
}
return funExpr;
},
createIdentifier: function (name) {
return {
type: Syntax.Identifier,
name: name,
// Only here to initialize the shape of the object to ensure
// that the 'typeAnnotation' key is ordered before others that
// are added later (like 'loc' and 'range'). This just helps
// keep the shape of Identifier nodes consistent with everything
// else.
typeAnnotation: undefined,
optional: undefined
};
},
createTypeAnnotation: function (typeAnnotation) {
return {
type: Syntax.TypeAnnotation,
typeAnnotation: typeAnnotation
};
},
createTypeCast: function (expression, typeAnnotation) {
return {
type: Syntax.TypeCastExpression,
expression: expression,
typeAnnotation: typeAnnotation
};
},
createFunctionTypeAnnotation: function (params, returnType, rest, typeParameters) {
return {
type: Syntax.FunctionTypeAnnotation,
params: params,
returnType: returnType,
rest: rest,
typeParameters: typeParameters
};
},
createFunctionTypeParam: function (name, typeAnnotation, optional) {
return {
type: Syntax.FunctionTypeParam,
name: name,
typeAnnotation: typeAnnotation,
optional: optional
};
},
createNullableTypeAnnotation: function (typeAnnotation) {
return {
type: Syntax.NullableTypeAnnotation,
typeAnnotation: typeAnnotation
};
},
createArrayTypeAnnotation: function (elementType) {
return {
type: Syntax.ArrayTypeAnnotation,
elementType: elementType
};
},
createGenericTypeAnnotation: function (id, typeParameters) {
return {
type: Syntax.GenericTypeAnnotation,
id: id,
typeParameters: typeParameters
};
},
createQualifiedTypeIdentifier: function (qualification, id) {
return {
type: Syntax.QualifiedTypeIdentifier,
qualification: qualification,
id: id
};
},
createTypeParameterDeclaration: function (params) {
return {
type: Syntax.TypeParameterDeclaration,
params: params
};
},
createTypeParameterInstantiation: function (params) {
return {
type: Syntax.TypeParameterInstantiation,
params: params
};
},
createAnyTypeAnnotation: function () {
return {
type: Syntax.AnyTypeAnnotation
};
},
createBooleanTypeAnnotation: function () {
return {
type: Syntax.BooleanTypeAnnotation
};
},
createNumberTypeAnnotation: function () {
return {
type: Syntax.NumberTypeAnnotation
};
},
createStringTypeAnnotation: function () {
return {
type: Syntax.StringTypeAnnotation
};
},
createStringLiteralTypeAnnotation: function (token) {
return {
type: Syntax.StringLiteralTypeAnnotation,
value: token.value,
raw: source.slice(token.range[0], token.range[1])
};
},
createVoidTypeAnnotation: function () {
return {
type: Syntax.VoidTypeAnnotation
};
},
createTypeofTypeAnnotation: function (argument) {
return {
type: Syntax.TypeofTypeAnnotation,
argument: argument
};
},
createTupleTypeAnnotation: function (types) {
return {
type: Syntax.TupleTypeAnnotation,
types: types
};
},
createObjectTypeAnnotation: function (properties, indexers, callProperties) {
return {
type: Syntax.ObjectTypeAnnotation,
properties: properties,
indexers: indexers,
callProperties: callProperties
};
},
createObjectTypeIndexer: function (id, key, value, isStatic) {
return {
type: Syntax.ObjectTypeIndexer,
id: id,
key: key,
value: value,
"static": isStatic
};
},
createObjectTypeCallProperty: function (value, isStatic) {
return {
type: Syntax.ObjectTypeCallProperty,
value: value,
"static": isStatic
};
},
createObjectTypeProperty: function (key, value, optional, isStatic) {
return {
type: Syntax.ObjectTypeProperty,
key: key,
value: value,
optional: optional,
"static": isStatic
};
},
createUnionTypeAnnotation: function (types) {
return {
type: Syntax.UnionTypeAnnotation,
types: types
};
},
createIntersectionTypeAnnotation: function (types) {
return {
type: Syntax.IntersectionTypeAnnotation,
types: types
};
},
createTypeAlias: function (id, typeParameters, right) {
return {
type: Syntax.TypeAlias,
id: id,
typeParameters: typeParameters,
right: right
};
},
createInterface: function (id, typeParameters, body, extended) {
return {
type: Syntax.InterfaceDeclaration,
id: id,
typeParameters: typeParameters,
body: body,
"extends": extended
};
},
createInterfaceExtends: function (id, typeParameters) {
return {
type: Syntax.InterfaceExtends,
id: id,
typeParameters: typeParameters
};
},
createDeclareFunction: function (id) {
return {
type: Syntax.DeclareFunction,
id: id
};
},
createDeclareVariable: function (id) {
return {
type: Syntax.DeclareVariable,
id: id
};
},
createDeclareModule: function (id, body) {
return {
type: Syntax.DeclareModule,
id: id,
body: body
};
},
createJSXAttribute: function (name, value) {
return {
type: Syntax.JSXAttribute,
name: name,
value: value || null
};
},
createJSXSpreadAttribute: function (argument) {
return {
type: Syntax.JSXSpreadAttribute,
argument: argument
};
},
createJSXIdentifier: function (name) {
return {
type: Syntax.JSXIdentifier,
name: name
};
},
createJSXNamespacedName: function (namespace, name) {
return {
type: Syntax.JSXNamespacedName,
namespace: namespace,
name: name
};
},
createJSXMemberExpression: function (object, property) {
return {
type: Syntax.JSXMemberExpression,
object: object,
property: property
};
},
createJSXElement: function (openingElement, closingElement, children) {
return {
type: Syntax.JSXElement,
openingElement: openingElement,
closingElement: closingElement,
children: children
};
},
createJSXEmptyExpression: function () {
return {
type: Syntax.JSXEmptyExpression
};
},
createJSXExpressionContainer: function (expression) {
return {
type: Syntax.JSXExpressionContainer,
expression: expression
};
},
createJSXOpeningElement: function (name, attributes, selfClosing) {
return {
type: Syntax.JSXOpeningElement,
name: name,
selfClosing: selfClosing,
attributes: attributes
};
},
createJSXClosingElement: function (name) {
return {
type: Syntax.JSXClosingElement,
name: name
};
},
createIfStatement: function (test, consequent, alternate) {
return {
type: Syntax.IfStatement,
test: test,
consequent: consequent,
alternate: alternate
};
},
createLabeledStatement: function (label, body) {
return {
type: Syntax.LabeledStatement,
label: label,
body: body
};
},
createLiteral: function (token) {
var object = {
type: Syntax.Literal,
value: token.value,
raw: source.slice(token.range[0], token.range[1])
};
if (token.regex) {
object.regex = token.regex;
}
return object;
},
createMemberExpression: function (accessor, object, property) {
return {
type: Syntax.MemberExpression,
computed: accessor === '[',
object: object,
property: property
};
},
createNewExpression: function (callee, args) {
return {
type: Syntax.NewExpression,
callee: callee,
'arguments': args
};
},
createObjectExpression: function (properties) {
return {
type: Syntax.ObjectExpression,
properties: properties
};
},
createPostfixExpression: function (operator, argument) {
return {
type: Syntax.UpdateExpression,
operator: operator,
argument: argument,
prefix: false
};
},
createProgram: function (body) {
return {
type: Syntax.Program,
body: body
};
},
createProperty: function (kind, key, value, method, shorthand, computed) {
return {
type: Syntax.Property,
key: key,
value: value,
kind: kind,
method: method,
shorthand: shorthand,
computed: computed
};
},
createReturnStatement: function (argument) {
return {
type: Syntax.ReturnStatement,
argument: argument
};
},
createSequenceExpression: function (expressions) {
return {
type: Syntax.SequenceExpression,
expressions: expressions
};
},
createSwitchCase: function (test, consequent) {
return {
type: Syntax.SwitchCase,
test: test,
consequent: consequent
};
},
createSwitchStatement: function (discriminant, cases) {
return {
type: Syntax.SwitchStatement,
discriminant: discriminant,
cases: cases
};
},
createThisExpression: function () {
return {
type: Syntax.ThisExpression
};
},
createThrowStatement: function (argument) {
return {
type: Syntax.ThrowStatement,
argument: argument
};
},
createTryStatement: function (block, guardedHandlers, handlers, finalizer) {
return {
type: Syntax.TryStatement,
block: block,
guardedHandlers: guardedHandlers,
handlers: handlers,
finalizer: finalizer
};
},
createUnaryExpression: function (operator, argument) {
if (operator === '++' || operator === '--') {
return {
type: Syntax.UpdateExpression,
operator: operator,
argument: argument,
prefix: true
};
}
return {
type: Syntax.UnaryExpression,
operator: operator,
argument: argument,
prefix: true
};
},
createVariableDeclaration: function (declarations, kind) {
return {
type: Syntax.VariableDeclaration,
declarations: declarations,
kind: kind
};
},
createVariableDeclarator: function (id, init) {
return {
type: Syntax.VariableDeclarator,
id: id,
init: init
};
},
createWhileStatement: function (test, body) {
return {
type: Syntax.WhileStatement,
test: test,
body: body
};
},
createWithStatement: function (object, body) {
return {
type: Syntax.WithStatement,
object: object,
body: body
};
},
createTemplateElement: function (value, tail) {
return {
type: Syntax.TemplateElement,
value: value,
tail: tail
};
},
createTemplateLiteral: function (quasis, expressions) {
return {
type: Syntax.TemplateLiteral,
quasis: quasis,
expressions: expressions
};
},
createSpreadElement: function (argument) {
return {
type: Syntax.SpreadElement,
argument: argument
};
},
createSpreadProperty: function (argument) {
return {
type: Syntax.SpreadProperty,
argument: argument
};
},
createTaggedTemplateExpression: function (tag, quasi) {
return {
type: Syntax.TaggedTemplateExpression,
tag: tag,
quasi: quasi
};
},
createArrowFunctionExpression: function (params, defaults, body, rest, expression, isAsync) {
var arrowExpr = {
type: Syntax.ArrowFunctionExpression,
id: null,
params: params,
defaults: defaults,
body: body,
rest: rest,
generator: false,
expression: expression
};
if (isAsync) {
arrowExpr.async = true;
}
return arrowExpr;
},
createMethodDefinition: function (propertyType, kind, key, value, computed) {
return {
type: Syntax.MethodDefinition,
key: key,
value: value,
kind: kind,
'static': propertyType === ClassPropertyType["static"],
computed: computed
};
},
createClassProperty: function (key, typeAnnotation, computed, isStatic) {
return {
type: Syntax.ClassProperty,
key: key,
typeAnnotation: typeAnnotation,
computed: computed,
"static": isStatic
};
},
createClassBody: function (body) {
return {
type: Syntax.ClassBody,
body: body
};
},
createClassImplements: function (id, typeParameters) {
return {
type: Syntax.ClassImplements,
id: id,
typeParameters: typeParameters
};
},
createClassExpression: function (id, superClass, body, typeParameters, superTypeParameters, implemented) {
return {
type: Syntax.ClassExpression,
id: id,
superClass: superClass,
body: body,
typeParameters: typeParameters,
superTypeParameters: superTypeParameters,
"implements": implemented
};
},
createClassDeclaration: function (id, superClass, body, typeParameters, superTypeParameters, implemented) {
return {
type: Syntax.ClassDeclaration,
id: id,
superClass: superClass,
body: body,
typeParameters: typeParameters,
superTypeParameters: superTypeParameters,
"implements": implemented
};
},
createModuleSpecifier: function (token) {
return {
type: Syntax.ModuleSpecifier,
value: token.value,
raw: source.slice(token.range[0], token.range[1])
};
},
createExportSpecifier: function (id, name) {
return {
type: Syntax.ExportSpecifier,
id: id,
name: name
};
},
createExportBatchSpecifier: function () {
return {
type: Syntax.ExportBatchSpecifier
};
},
createImportDefaultSpecifier: function (id) {
return {
type: Syntax.ImportDefaultSpecifier,
id: id
};
},
createImportNamespaceSpecifier: function (id) {
return {
type: Syntax.ImportNamespaceSpecifier,
id: id
};
},
createExportDeclaration: function (isDefault, declaration, specifiers, src) {
return {
type: Syntax.ExportDeclaration,
'default': !!isDefault,
declaration: declaration,
specifiers: specifiers,
source: src
};
},
createImportSpecifier: function (id, name) {
return {
type: Syntax.ImportSpecifier,
id: id,
name: name
};
},
createImportDeclaration: function (specifiers, src, isType) {
return {
type: Syntax.ImportDeclaration,
specifiers: specifiers,
source: src,
isType: isType
};
},
createYieldExpression: function (argument, dlg) {
return {
type: Syntax.YieldExpression,
argument: argument,
delegate: dlg
};
},
createAwaitExpression: function (argument) {
return {
type: Syntax.AwaitExpression,
argument: argument
};
},
createComprehensionExpression: function (filter, blocks, body) {
return {
type: Syntax.ComprehensionExpression,
filter: filter,
blocks: blocks,
body: body
};
}
};
// Return true if there is a line terminator before the next token.
function peekLineTerminator() {
var pos, line, start, found;
pos = index;
line = lineNumber;
start = lineStart;
skipComment();
found = lineNumber !== line;
index = pos;
lineNumber = line;
lineStart = start;
return found;
}
// Throw an exception
function throwError(token, messageFormat) {
var error,
args = Array.prototype.slice.call(arguments, 2),
msg = messageFormat.replace(
/%(\d)/g,
function (whole, idx) {
assert(idx < args.length, 'Message reference must be in range');
return args[idx];
}
);
if (typeof token.lineNumber === 'number') {
error = new Error('Line ' + token.lineNumber + ': ' + msg);
error.index = token.range[0];
error.lineNumber = token.lineNumber;
error.column = token.range[0] - lineStart + 1;
} else {
error = new Error('Line ' + lineNumber + ': ' + msg);
error.index = index;
error.lineNumber = lineNumber;
error.column = index - lineStart + 1;
}
error.description = msg;
throw error;
}
function throwErrorTolerant() {
try {
throwError.apply(null, arguments);
} catch (e) {
if (extra.errors) {
extra.errors.push(e);
} else {
throw e;
}
}
}
// Throw an exception because of the token.
function throwUnexpected(token) {
if (token.type === Token.EOF) {
throwError(token, Messages.UnexpectedEOS);
}
if (token.type === Token.NumericLiteral) {
throwError(token, Messages.UnexpectedNumber);
}
if (token.type === Token.StringLiteral || token.type === Token.JSXText) {
throwError(token, Messages.UnexpectedString);
}
if (token.type === Token.Identifier) {
throwError(token, Messages.UnexpectedIdentifier);
}
if (token.type === Token.Keyword) {
if (isFutureReservedWord(token.value)) {
throwError(token, Messages.UnexpectedReserved);
} else if (strict && isStrictModeReservedWord(token.value)) {
throwErrorTolerant(token, Messages.StrictReservedWord);
return;
}
throwError(token, Messages.UnexpectedToken, token.value);
}
if (token.type === Token.Template) {
throwError(token, Messages.UnexpectedTemplate, token.value.raw);
}
// BooleanLiteral, NullLiteral, or Punctuator.
throwError(token, Messages.UnexpectedToken, token.value);
}
// Expect the next token to match the specified punctuator.
// If not, an exception will be thrown.
function expect(value) {
var token = lex();
if (token.type !== Token.Punctuator || token.value !== value) {
throwUnexpected(token);
}
}
// Expect the next token to match the specified keyword.
// If not, an exception will be thrown.
function expectKeyword(keyword, contextual) {
var token = lex();
if (token.type !== (contextual ? Token.Identifier : Token.Keyword) ||
token.value !== keyword) {
throwUnexpected(token);
}
}
// Expect the next token to match the specified contextual keyword.
// If not, an exception will be thrown.
function expectContextualKeyword(keyword) {
return expectKeyword(keyword, true);
}
// Return true if the next token matches the specified punctuator.
function match(value) {
return lookahead.type === Token.Punctuator && lookahead.value === value;
}
// Return true if the next token matches the specified keyword
function matchKeyword(keyword, contextual) {
var expectedType = contextual ? Token.Identifier : Token.Keyword;
return lookahead.type === expectedType && lookahead.value === keyword;
}
// Return true if the next token matches the specified contextual keyword
function matchContextualKeyword(keyword) {
return matchKeyword(keyword, true);
}
// Return true if the next token is an assignment operator
function matchAssign() {
var op;
if (lookahead.type !== Token.Punctuator) {
return false;
}
op = lookahead.value;
return op === '=' ||
op === '*=' ||
op === '/=' ||
op === '%=' ||
op === '+=' ||
op === '-=' ||
op === '<<=' ||
op === '>>=' ||
op === '>>>=' ||
op === '&=' ||
op === '^=' ||
op === '|=';
}
// Note that 'yield' is treated as a keyword in strict mode, but a
// contextual keyword (identifier) in non-strict mode, so we need to
// use matchKeyword('yield', false) and matchKeyword('yield', true)
// (i.e. matchContextualKeyword) appropriately.
function matchYield() {
return state.yieldAllowed && matchKeyword('yield', !strict);
}
function matchAsync() {
var backtrackToken = lookahead, matches = false;
if (matchContextualKeyword('async')) {
lex(); // Make sure peekLineTerminator() starts after 'async'.
matches = !peekLineTerminator();
rewind(backtrackToken); // Revert the lex().
}
return matches;
}
function matchAwait() {
return state.awaitAllowed && matchContextualKeyword('await');
}
function consumeSemicolon() {
var line, oldIndex = index, oldLineNumber = lineNumber,
oldLineStart = lineStart, oldLookahead = lookahead;
// Catch the very common case first: immediately a semicolon (char #59).
if (source.charCodeAt(index) === 59) {
lex();
return;
}
line = lineNumber;
skipComment();
if (lineNumber !== line) {
index = oldIndex;
lineNumber = oldLineNumber;
lineStart = oldLineStart;
lookahead = oldLookahead;
return;
}
if (match(';')) {
lex();
return;
}
if (lookahead.type !== Token.EOF && !match('}')) {
throwUnexpected(lookahead);
}
}
// Return true if provided expression is LeftHandSideExpression
function isLeftHandSide(expr) {
return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
}
function isAssignableLeftHandSide(expr) {
return isLeftHandSide(expr) || expr.type === Syntax.ObjectPattern || expr.type === Syntax.ArrayPattern;
}
// 11.1.4 Array Initialiser
function parseArrayInitialiser() {
var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true,
marker = markerCreate();
expect('[');
while (!match(']')) {
if (lookahead.value === 'for' &&
lookahead.type === Token.Keyword) {
if (!possiblecomprehension) {
throwError({}, Messages.ComprehensionError);
}
matchKeyword('for');
tmp = parseForStatement({ignoreBody: true});
tmp.of = tmp.type === Syntax.ForOfStatement;
tmp.type = Syntax.ComprehensionBlock;
if (tmp.left.kind) { // can't be let or const
throwError({}, Messages.ComprehensionError);
}
blocks.push(tmp);
} else if (lookahead.value === 'if' &&
lookahead.type === Token.Keyword) {
if (!possiblecomprehension) {
throwError({}, Messages.ComprehensionError);
}
expectKeyword('if');
expect('(');
filter = parseExpression();
expect(')');
} else if (lookahead.value === ',' &&
lookahead.type === Token.Punctuator) {
possiblecomprehension = false; // no longer allowed.
lex();
elements.push(null);
} else {
tmp = parseSpreadOrAssignmentExpression();
elements.push(tmp);
if (tmp && tmp.type === Syntax.SpreadElement) {
if (!match(']')) {
throwError({}, Messages.ElementAfterSpreadElement);
}
} else if (!(match(']') || matchKeyword('for') || matchKeyword('if'))) {
expect(','); // this lexes.
possiblecomprehension = false;
}
}
}
expect(']');
if (filter && !blocks.length) {
throwError({}, Messages.ComprehensionRequiresBlock);
}
if (blocks.length) {
if (elements.length !== 1) {
throwError({}, Messages.ComprehensionError);
}
return markerApply(marker, delegate.createComprehensionExpression(filter, blocks, elements[0]));
}
return markerApply(marker, delegate.createArrayExpression(elements));
}
// 11.1.5 Object Initialiser
function parsePropertyFunction(options) {
var previousStrict, previousYieldAllowed, previousAwaitAllowed,
params, defaults, body, marker = markerCreate();
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = options.generator;
previousAwaitAllowed = state.awaitAllowed;
state.awaitAllowed = options.async;
params = options.params || [];
defaults = options.defaults || [];
body = parseConciseBody();
if (options.name && strict && isRestrictedWord(params[0].name)) {
throwErrorTolerant(options.name, Messages.StrictParamName);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
state.awaitAllowed = previousAwaitAllowed;
return markerApply(marker, delegate.createFunctionExpression(
null,
params,
defaults,
body,
options.rest || null,
options.generator,
body.type !== Syntax.BlockStatement,
options.async,
options.returnType,
options.typeParameters
));
}
function parsePropertyMethodFunction(options) {
var previousStrict, tmp, method;
previousStrict = strict;
strict = true;
tmp = parseParams();
if (tmp.stricted) {
throwErrorTolerant(tmp.stricted, tmp.message);
}
method = parsePropertyFunction({
params: tmp.params,
defaults: tmp.defaults,
rest: tmp.rest,
generator: options.generator,
async: options.async,
returnType: tmp.returnType,
typeParameters: options.typeParameters
});
strict = previousStrict;
return method;
}
function parseObjectPropertyKey() {
var marker = markerCreate(),
token = lex(),
propertyKey,
result;
// Note: This function is called only from parseObjectProperty(), where
// EOF and Punctuator tokens are already filtered out.
if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
if (strict && token.octal) {
throwErrorTolerant(token, Messages.StrictOctalLiteral);
}
return markerApply(marker, delegate.createLiteral(token));
}
if (token.type === Token.Punctuator && token.value === '[') {
// For computed properties we should skip the [ and ], and
// capture in marker only the assignment expression itself.
marker = markerCreate();
propertyKey = parseAssignmentExpression();
result = markerApply(marker, propertyKey);
expect(']');
return result;
}
return markerApply(marker, delegate.createIdentifier(token.value));
}
function parseObjectProperty() {
var token, key, id, param, computed,
marker = markerCreate(), returnType, typeParameters;
token = lookahead;
computed = (token.value === '[' && token.type === Token.Punctuator);
if (token.type === Token.Identifier || computed || matchAsync()) {
id = parseObjectPropertyKey();
if (match(':')) {
lex();
return markerApply(
marker,
delegate.createProperty(
'init',
id,
parseAssignmentExpression(),
false,
false,
computed
)
);
}
if (match('(') || match('<')) {
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
return markerApply(
marker,
delegate.createProperty(
'init',
id,
parsePropertyMethodFunction({
generator: false,
async: false,
typeParameters: typeParameters
}),
true,
false,
computed
)
);
}
// Property Assignment: Getter and Setter.
if (token.value === 'get') {
computed = (lookahead.value === '[');
key = parseObjectPropertyKey();
expect('(');
expect(')');
if (match(':')) {
returnType = parseTypeAnnotation();
}
return markerApply(
marker,
delegate.createProperty(
'get',
key,
parsePropertyFunction({
generator: false,
async: false,
returnType: returnType
}),
false,
false,
computed
)
);
}
if (token.value === 'set') {
computed = (lookahead.value === '[');
key = parseObjectPropertyKey();
expect('(');
token = lookahead;
param = [ parseTypeAnnotatableIdentifier() ];
expect(')');
if (match(':')) {
returnType = parseTypeAnnotation();
}
return markerApply(
marker,
delegate.createProperty(
'set',
key,
parsePropertyFunction({
params: param,
generator: false,
async: false,
name: token,
returnType: returnType
}),
false,
false,
computed
)
);
}
if (token.value === 'async') {
computed = (lookahead.value === '[');
key = parseObjectPropertyKey();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
return markerApply(
marker,
delegate.createProperty(
'init',
key,
parsePropertyMethodFunction({
generator: false,
async: true,
typeParameters: typeParameters
}),
true,
false,
computed
)
);
}
if (computed) {
// Computed properties can only be used with full notation.
throwUnexpected(lookahead);
}
return markerApply(
marker,
delegate.createProperty('init', id, id, false, true, false)
);
}
if (token.type === Token.EOF || token.type === Token.Punctuator) {
if (!match('*')) {
throwUnexpected(token);
}
lex();
computed = (lookahead.type === Token.Punctuator && lookahead.value === '[');
id = parseObjectPropertyKey();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
if (!match('(')) {
throwUnexpected(lex());
}
return markerApply(marker, delegate.createProperty(
'init',
id,
parsePropertyMethodFunction({
generator: true,
typeParameters: typeParameters
}),
true,
false,
computed
));
}
key = parseObjectPropertyKey();
if (match(':')) {
lex();
return markerApply(marker, delegate.createProperty('init', key, parseAssignmentExpression(), false, false, false));
}
if (match('(') || match('<')) {
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
return markerApply(marker, delegate.createProperty(
'init',
key,
parsePropertyMethodFunction({
generator: false,
typeParameters: typeParameters
}),
true,
false,
false
));
}
throwUnexpected(lex());
}
function parseObjectSpreadProperty() {
var marker = markerCreate();
expect('...');
return markerApply(marker, delegate.createSpreadProperty(parseAssignmentExpression()));
}
function getFieldName(key) {
var toString = String;
if (key.type === Syntax.Identifier) {
return key.name;
}
return toString(key.value);
}
function parseObjectInitialiser() {
var properties = [], property, name, kind, storedKind, map = new StringMap(),
marker = markerCreate(), toString = String;
expect('{');
while (!match('}')) {
if (match('...')) {
property = parseObjectSpreadProperty();
} else {
property = parseObjectProperty();
if (property.key.type === Syntax.Identifier) {
name = property.key.name;
} else {
name = toString(property.key.value);
}
kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;
if (map.has(name)) {
storedKind = map.get(name);
if (storedKind === PropertyKind.Data) {
if (strict && kind === PropertyKind.Data) {
throwErrorTolerant({}, Messages.StrictDuplicateProperty);
} else if (kind !== PropertyKind.Data) {
throwErrorTolerant({}, Messages.AccessorDataProperty);
}
} else {
if (kind === PropertyKind.Data) {
throwErrorTolerant({}, Messages.AccessorDataProperty);
} else if (storedKind & kind) {
throwErrorTolerant({}, Messages.AccessorGetSet);
}
}
map.set(name, storedKind | kind);
} else {
map.set(name, kind);
}
}
properties.push(property);
if (!match('}')) {
expect(',');
}
}
expect('}');
return markerApply(marker, delegate.createObjectExpression(properties));
}
function parseTemplateElement(option) {
var marker = markerCreate(),
token = scanTemplateElement(option);
if (strict && token.octal) {
throwError(token, Messages.StrictOctalLiteral);
}
return markerApply(marker, delegate.createTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail));
}
function parseTemplateLiteral() {
var quasi, quasis, expressions, marker = markerCreate();
quasi = parseTemplateElement({ head: true });
quasis = [ quasi ];
expressions = [];
while (!quasi.tail) {
expressions.push(parseExpression());
quasi = parseTemplateElement({ head: false });
quasis.push(quasi);
}
return markerApply(marker, delegate.createTemplateLiteral(quasis, expressions));
}
// 11.1.6 The Grouping Operator
function parseGroupExpression() {
var expr, marker, typeAnnotation;
expect('(');
++state.parenthesizedCount;
marker = markerCreate();
expr = parseExpression();
if (match(':')) {
typeAnnotation = parseTypeAnnotation();
expr = markerApply(marker, delegate.createTypeCast(
expr,
typeAnnotation
));
}
expect(')');
return expr;
}
function matchAsyncFuncExprOrDecl() {
var token;
if (matchAsync()) {
token = lookahead2();
if (token.type === Token.Keyword && token.value === 'function') {
return true;
}
}
return false;
}
// 11.1 Primary Expressions
function parsePrimaryExpression() {
var marker, type, token, expr;
type = lookahead.type;
if (type === Token.Identifier) {
marker = markerCreate();
return markerApply(marker, delegate.createIdentifier(lex().value));
}
if (type === Token.StringLiteral || type === Token.NumericLiteral) {
if (strict && lookahead.octal) {
throwErrorTolerant(lookahead, Messages.StrictOctalLiteral);
}
marker = markerCreate();
return markerApply(marker, delegate.createLiteral(lex()));
}
if (type === Token.Keyword) {
if (matchKeyword('this')) {
marker = markerCreate();
lex();
return markerApply(marker, delegate.createThisExpression());
}
if (matchKeyword('function')) {
return parseFunctionExpression();
}
if (matchKeyword('class')) {
return parseClassExpression();
}
if (matchKeyword('super')) {
marker = markerCreate();
lex();
return markerApply(marker, delegate.createIdentifier('super'));
}
}
if (type === Token.BooleanLiteral) {
marker = markerCreate();
token = lex();
token.value = (token.value === 'true');
return markerApply(marker, delegate.createLiteral(token));
}
if (type === Token.NullLiteral) {
marker = markerCreate();
token = lex();
token.value = null;
return markerApply(marker, delegate.createLiteral(token));
}
if (match('[')) {
return parseArrayInitialiser();
}
if (match('{')) {
return parseObjectInitialiser();
}
if (match('(')) {
return parseGroupExpression();
}
if (match('/') || match('/=')) {
marker = markerCreate();
expr = delegate.createLiteral(scanRegExp());
peek();
return markerApply(marker, expr);
}
if (type === Token.Template) {
return parseTemplateLiteral();
}
if (match('<')) {
return parseJSXElement();
}
throwUnexpected(lex());
}
// 11.2 Left-Hand-Side Expressions
function parseArguments() {
var args = [], arg;
expect('(');
if (!match(')')) {
while (index < length) {
arg = parseSpreadOrAssignmentExpression();
args.push(arg);
if (match(')')) {
break;
} else if (arg.type === Syntax.SpreadElement) {
throwError({}, Messages.ElementAfterSpreadElement);
}
expect(',');
}
}
expect(')');
return args;
}
function parseSpreadOrAssignmentExpression() {
if (match('...')) {
var marker = markerCreate();
lex();
return markerApply(marker, delegate.createSpreadElement(parseAssignmentExpression()));
}
return parseAssignmentExpression();
}
function parseNonComputedProperty() {
var marker = markerCreate(),
token = lex();
if (!isIdentifierName(token)) {
throwUnexpected(token);
}
return markerApply(marker, delegate.createIdentifier(token.value));
}
function parseNonComputedMember() {
expect('.');
return parseNonComputedProperty();
}
function parseComputedMember() {
var expr;
expect('[');
expr = parseExpression();
expect(']');
return expr;
}
function parseNewExpression() {
var callee, args, marker = markerCreate();
expectKeyword('new');
callee = parseLeftHandSideExpression();
args = match('(') ? parseArguments() : [];
return markerApply(marker, delegate.createNewExpression(callee, args));
}
function parseLeftHandSideExpressionAllowCall() {
var expr, args, marker = markerCreate();
expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
while (match('.') || match('[') || match('(') || lookahead.type === Token.Template) {
if (match('(')) {
args = parseArguments();
expr = markerApply(marker, delegate.createCallExpression(expr, args));
} else if (match('[')) {
expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember()));
} else if (match('.')) {
expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember()));
} else {
expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral()));
}
}
return expr;
}
function parseLeftHandSideExpression() {
var expr, marker = markerCreate();
expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
while (match('.') || match('[') || lookahead.type === Token.Template) {
if (match('[')) {
expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember()));
} else if (match('.')) {
expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember()));
} else {
expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral()));
}
}
return expr;
}
// 11.3 Postfix Expressions
function parsePostfixExpression() {
var marker = markerCreate(),
expr = parseLeftHandSideExpressionAllowCall(),
token;
if (lookahead.type !== Token.Punctuator) {
return expr;
}
if ((match('++') || match('--')) && !peekLineTerminator()) {
// 11.3.1, 11.3.2
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant({}, Messages.StrictLHSPostfix);
}
if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
token = lex();
expr = markerApply(marker, delegate.createPostfixExpression(token.value, expr));
}
return expr;
}
// 11.4 Unary Operators
function parseUnaryExpression() {
var marker, token, expr;
if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
return parsePostfixExpression();
}
if (match('++') || match('--')) {
marker = markerCreate();
token = lex();
expr = parseUnaryExpression();
// 11.4.4, 11.4.5
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant({}, Messages.StrictLHSPrefix);
}
if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
return markerApply(marker, delegate.createUnaryExpression(token.value, expr));
}
if (match('+') || match('-') || match('~') || match('!')) {
marker = markerCreate();
token = lex();
expr = parseUnaryExpression();
return markerApply(marker, delegate.createUnaryExpression(token.value, expr));
}
if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
marker = markerCreate();
token = lex();
expr = parseUnaryExpression();
expr = markerApply(marker, delegate.createUnaryExpression(token.value, expr));
if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
throwErrorTolerant({}, Messages.StrictDelete);
}
return expr;
}
return parsePostfixExpression();
}
function binaryPrecedence(token, allowIn) {
var prec = 0;
if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
return 0;
}
switch (token.value) {
case '||':
prec = 1;
break;
case '&&':
prec = 2;
break;
case '|':
prec = 3;
break;
case '^':
prec = 4;
break;
case '&':
prec = 5;
break;
case '==':
case '!=':
case '===':
case '!==':
prec = 6;
break;
case '<':
case '>':
case '<=':
case '>=':
case 'instanceof':
prec = 7;
break;
case 'in':
prec = allowIn ? 7 : 0;
break;
case '<<':
case '>>':
case '>>>':
prec = 8;
break;
case '+':
case '-':
prec = 9;
break;
case '*':
case '/':
case '%':
prec = 11;
break;
default:
break;
}
return prec;
}
// 11.5 Multiplicative Operators
// 11.6 Additive Operators
// 11.7 Bitwise Shift Operators
// 11.8 Relational Operators
// 11.9 Equality Operators
// 11.10 Binary Bitwise Operators
// 11.11 Binary Logical Operators
function parseBinaryExpression() {
var expr, token, prec, previousAllowIn, stack, right, operator, left, i,
marker, markers;
previousAllowIn = state.allowIn;
state.allowIn = true;
marker = markerCreate();
left = parseUnaryExpression();
token = lookahead;
prec = binaryPrecedence(token, previousAllowIn);
if (prec === 0) {
return left;
}
token.prec = prec;
lex();
markers = [marker, markerCreate()];
right = parseUnaryExpression();
stack = [left, token, right];
while ((prec = binaryPrecedence(lookahead, previousAllowIn)) > 0) {
// Reduce: make a binary expression from the three topmost entries.
while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
right = stack.pop();
operator = stack.pop().value;
left = stack.pop();
expr = delegate.createBinaryExpression(operator, left, right);
markers.pop();
marker = markers.pop();
markerApply(marker, expr);
stack.push(expr);
markers.push(marker);
}
// Shift.
token = lex();
token.prec = prec;
stack.push(token);
markers.push(markerCreate());
expr = parseUnaryExpression();
stack.push(expr);
}
state.allowIn = previousAllowIn;
// Final reduce to clean-up the stack.
i = stack.length - 1;
expr = stack[i];
markers.pop();
while (i > 1) {
expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
i -= 2;
marker = markers.pop();
markerApply(marker, expr);
}
return expr;
}
// 11.12 Conditional Operator
function parseConditionalExpression() {
var expr, previousAllowIn, consequent, alternate, marker = markerCreate();
expr = parseBinaryExpression();
if (match('?')) {
lex();
previousAllowIn = state.allowIn;
state.allowIn = true;
consequent = parseAssignmentExpression();
state.allowIn = previousAllowIn;
expect(':');
alternate = parseAssignmentExpression();
expr = markerApply(marker, delegate.createConditionalExpression(expr, consequent, alternate));
}
return expr;
}
// 11.13 Assignment Operators
// 12.14.5 AssignmentPattern
function reinterpretAsAssignmentBindingPattern(expr) {
var i, len, property, element;
if (expr.type === Syntax.ObjectExpression) {
expr.type = Syntax.ObjectPattern;
for (i = 0, len = expr.properties.length; i < len; i += 1) {
property = expr.properties[i];
if (property.type === Syntax.SpreadProperty) {
if (i < len - 1) {
throwError({}, Messages.PropertyAfterSpreadProperty);
}
reinterpretAsAssignmentBindingPattern(property.argument);
} else {
if (property.kind !== 'init') {
throwError({}, Messages.InvalidLHSInAssignment);
}
reinterpretAsAssignmentBindingPattern(property.value);
}
}
} else if (expr.type === Syntax.ArrayExpression) {
expr.type = Syntax.ArrayPattern;
for (i = 0, len = expr.elements.length; i < len; i += 1) {
element = expr.elements[i];
/* istanbul ignore else */
if (element) {
reinterpretAsAssignmentBindingPattern(element);
}
}
} else if (expr.type === Syntax.Identifier) {
if (isRestrictedWord(expr.name)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
} else if (expr.type === Syntax.SpreadElement) {
reinterpretAsAssignmentBindingPattern(expr.argument);
if (expr.argument.type === Syntax.ObjectPattern) {
throwError({}, Messages.ObjectPatternAsSpread);
}
} else {
/* istanbul ignore else */
if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) {
throwError({}, Messages.InvalidLHSInAssignment);
}
}
}
// 13.2.3 BindingPattern
function reinterpretAsDestructuredParameter(options, expr) {
var i, len, property, element;
if (expr.type === Syntax.ObjectExpression) {
expr.type = Syntax.ObjectPattern;
for (i = 0, len = expr.properties.length; i < len; i += 1) {
property = expr.properties[i];
if (property.type === Syntax.SpreadProperty) {
if (i < len - 1) {
throwError({}, Messages.PropertyAfterSpreadProperty);
}
reinterpretAsDestructuredParameter(options, property.argument);
} else {
if (property.kind !== 'init') {
throwError({}, Messages.InvalidLHSInFormalsList);
}
reinterpretAsDestructuredParameter(options, property.value);
}
}
} else if (expr.type === Syntax.ArrayExpression) {
expr.type = Syntax.ArrayPattern;
for (i = 0, len = expr.elements.length; i < len; i += 1) {
element = expr.elements[i];
if (element) {
reinterpretAsDestructuredParameter(options, element);
}
}
} else if (expr.type === Syntax.Identifier) {
validateParam(options, expr, expr.name);
} else if (expr.type === Syntax.SpreadElement) {
// BindingRestElement only allows BindingIdentifier
if (expr.argument.type !== Syntax.Identifier) {
throwError({}, Messages.InvalidLHSInFormalsList);
}
validateParam(options, expr.argument, expr.argument.name);
} else {
throwError({}, Messages.InvalidLHSInFormalsList);
}
}
function reinterpretAsCoverFormalsList(expressions) {
var i, len, param, params, defaults, defaultCount, options, rest;
params = [];
defaults = [];
defaultCount = 0;
rest = null;
options = {
paramSet: new StringMap()
};
for (i = 0, len = expressions.length; i < len; i += 1) {
param = expressions[i];
if (param.type === Syntax.Identifier) {
params.push(param);
defaults.push(null);
validateParam(options, param, param.name);
} else if (param.type === Syntax.ObjectExpression || param.type === Syntax.ArrayExpression) {
reinterpretAsDestructuredParameter(options, param);
params.push(param);
defaults.push(null);
} else if (param.type === Syntax.SpreadElement) {
assert(i === len - 1, 'It is guaranteed that SpreadElement is last element by parseExpression');
if (param.argument.type !== Syntax.Identifier) {
throwError({}, Messages.InvalidLHSInFormalsList);
}
reinterpretAsDestructuredParameter(options, param.argument);
rest = param.argument;
} else if (param.type === Syntax.AssignmentExpression) {
params.push(param.left);
defaults.push(param.right);
++defaultCount;
validateParam(options, param.left, param.left.name);
} else {
return null;
}
}
if (options.message === Messages.StrictParamDupe) {
throwError(
strict ? options.stricted : options.firstRestricted,
options.message
);
}
if (defaultCount === 0) {
defaults = [];
}
return {
params: params,
defaults: defaults,
rest: rest,
stricted: options.stricted,
firstRestricted: options.firstRestricted,
message: options.message
};
}
function parseArrowFunctionExpression(options, marker) {
var previousStrict, previousYieldAllowed, previousAwaitAllowed, body;
expect('=>');
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = false;
previousAwaitAllowed = state.awaitAllowed;
state.awaitAllowed = !!options.async;
body = parseConciseBody();
if (strict && options.firstRestricted) {
throwError(options.firstRestricted, options.message);
}
if (strict && options.stricted) {
throwErrorTolerant(options.stricted, options.message);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
state.awaitAllowed = previousAwaitAllowed;
return markerApply(marker, delegate.createArrowFunctionExpression(
options.params,
options.defaults,
body,
options.rest,
body.type !== Syntax.BlockStatement,
!!options.async
));
}
function parseAssignmentExpression() {
var marker, expr, token, params, oldParenthesizedCount,
startsWithParen = false, backtrackToken = lookahead,
possiblyAsync = false;
if (matchYield()) {
return parseYieldExpression();
}
if (matchAwait()) {
return parseAwaitExpression();
}
oldParenthesizedCount = state.parenthesizedCount;
marker = markerCreate();
if (matchAsyncFuncExprOrDecl()) {
return parseFunctionExpression();
}
if (matchAsync()) {
// We can't be completely sure that this 'async' token is
// actually a contextual keyword modifying a function
// expression, so we might have to un-lex() it later by
// calling rewind(backtrackToken).
possiblyAsync = true;
lex();
}
if (match('(')) {
token = lookahead2();
if ((token.type === Token.Punctuator && token.value === ')') || token.value === '...') {
params = parseParams();
if (!match('=>')) {
throwUnexpected(lex());
}
params.async = possiblyAsync;
return parseArrowFunctionExpression(params, marker);
}
startsWithParen = true;
}
token = lookahead;
// If the 'async' keyword is not followed by a '(' character or an
// identifier, then it can't be an arrow function modifier, and we
// should interpret it as a normal identifer.
if (possiblyAsync && !match('(') && token.type !== Token.Identifier) {
possiblyAsync = false;
rewind(backtrackToken);
}
expr = parseConditionalExpression();
if (match('=>') &&
(state.parenthesizedCount === oldParenthesizedCount ||
state.parenthesizedCount === (oldParenthesizedCount + 1))) {
if (expr.type === Syntax.Identifier) {
params = reinterpretAsCoverFormalsList([ expr ]);
} else if (expr.type === Syntax.AssignmentExpression ||
expr.type === Syntax.ArrayExpression ||
expr.type === Syntax.ObjectExpression) {
if (!startsWithParen) {
throwUnexpected(lex());
}
params = reinterpretAsCoverFormalsList([ expr ]);
} else if (expr.type === Syntax.SequenceExpression) {
params = reinterpretAsCoverFormalsList(expr.expressions);
}
if (params) {
params.async = possiblyAsync;
return parseArrowFunctionExpression(params, marker);
}
}
// If we haven't returned by now, then the 'async' keyword was not
// a function modifier, and we should rewind and interpret it as a
// normal identifier.
if (possiblyAsync) {
possiblyAsync = false;
rewind(backtrackToken);
expr = parseConditionalExpression();
}
if (matchAssign()) {
// 11.13.1
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant(token, Messages.StrictLHSAssignment);
}
// ES.next draf 11.13 Runtime Semantics step 1
if (match('=') && (expr.type === Syntax.ObjectExpression || expr.type === Syntax.ArrayExpression)) {
reinterpretAsAssignmentBindingPattern(expr);
} else if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
expr = markerApply(marker, delegate.createAssignmentExpression(lex().value, expr, parseAssignmentExpression()));
}
return expr;
}
// 11.14 Comma Operator
function parseExpression() {
var marker, expr, expressions, sequence, spreadFound;
marker = markerCreate();
expr = parseAssignmentExpression();
expressions = [ expr ];
if (match(',')) {
while (index < length) {
if (!match(',')) {
break;
}
lex();
expr = parseSpreadOrAssignmentExpression();
expressions.push(expr);
if (expr.type === Syntax.SpreadElement) {
spreadFound = true;
if (!match(')')) {
throwError({}, Messages.ElementAfterSpreadElement);
}
break;
}
}
sequence = markerApply(marker, delegate.createSequenceExpression(expressions));
}
if (spreadFound && lookahead2().value !== '=>') {
throwError({}, Messages.IllegalSpread);
}
return sequence || expr;
}
// 12.1 Block
function parseStatementList() {
var list = [],
statement;
while (index < length) {
if (match('}')) {
break;
}
statement = parseSourceElement();
if (typeof statement === 'undefined') {
break;
}
list.push(statement);
}
return list;
}
function parseBlock() {
var block, marker = markerCreate();
expect('{');
block = parseStatementList();
expect('}');
return markerApply(marker, delegate.createBlockStatement(block));
}
// 12.2 Variable Statement
function parseTypeParameterDeclaration() {
var marker = markerCreate(), paramTypes = [];
expect('<');
while (!match('>')) {
paramTypes.push(parseTypeAnnotatableIdentifier());
if (!match('>')) {
expect(',');
}
}
expect('>');
return markerApply(marker, delegate.createTypeParameterDeclaration(
paramTypes
));
}
function parseTypeParameterInstantiation() {
var marker = markerCreate(), oldInType = state.inType, paramTypes = [];
state.inType = true;
expect('<');
while (!match('>')) {
paramTypes.push(parseType());
if (!match('>')) {
expect(',');
}
}
expect('>');
state.inType = oldInType;
return markerApply(marker, delegate.createTypeParameterInstantiation(
paramTypes
));
}
function parseObjectTypeIndexer(marker, isStatic) {
var id, key, value;
expect('[');
id = parseObjectPropertyKey();
expect(':');
key = parseType();
expect(']');
expect(':');
value = parseType();
return markerApply(marker, delegate.createObjectTypeIndexer(
id,
key,
value,
isStatic
));
}
function parseObjectTypeMethodish(marker) {
var params = [], rest = null, returnType, typeParameters = null;
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
expect('(');
while (lookahead.type === Token.Identifier) {
params.push(parseFunctionTypeParam());
if (!match(')')) {
expect(',');
}
}
if (match('...')) {
lex();
rest = parseFunctionTypeParam();
}
expect(')');
expect(':');
returnType = parseType();
return markerApply(marker, delegate.createFunctionTypeAnnotation(
params,
returnType,
rest,
typeParameters
));
}
function parseObjectTypeMethod(marker, isStatic, key) {
var optional = false, value;
value = parseObjectTypeMethodish(marker);
return markerApply(marker, delegate.createObjectTypeProperty(
key,
value,
optional,
isStatic
));
}
function parseObjectTypeCallProperty(marker, isStatic) {
var valueMarker = markerCreate();
return markerApply(marker, delegate.createObjectTypeCallProperty(
parseObjectTypeMethodish(valueMarker),
isStatic
));
}
function parseObjectType(allowStatic) {
var callProperties = [], indexers = [], marker, optional = false,
properties = [], propertyKey, propertyTypeAnnotation,
token, isStatic, matchStatic;
expect('{');
while (!match('}')) {
marker = markerCreate();
matchStatic =
strict
? matchKeyword('static')
: matchContextualKeyword('static');
if (allowStatic && matchStatic) {
token = lex();
isStatic = true;
}
if (match('[')) {
indexers.push(parseObjectTypeIndexer(marker, isStatic));
} else if (match('(') || match('<')) {
callProperties.push(parseObjectTypeCallProperty(marker, allowStatic));
} else {
if (isStatic && match(':')) {
propertyKey = markerApply(marker, delegate.createIdentifier(token));
throwErrorTolerant(token, Messages.StrictReservedWord);
} else {
propertyKey = parseObjectPropertyKey();
}
if (match('<') || match('(')) {
// This is a method property
properties.push(parseObjectTypeMethod(marker, isStatic, propertyKey));
} else {
if (match('?')) {
lex();
optional = true;
}
expect(':');
propertyTypeAnnotation = parseType();
properties.push(markerApply(marker, delegate.createObjectTypeProperty(
propertyKey,
propertyTypeAnnotation,
optional,
isStatic
)));
}
}
if (match(';')) {
lex();
} else if (!match('}')) {
throwUnexpected(lookahead);
}
}
expect('}');
return delegate.createObjectTypeAnnotation(
properties,
indexers,
callProperties
);
}
function parseGenericType() {
var marker = markerCreate(),
typeParameters = null, typeIdentifier;
typeIdentifier = parseVariableIdentifier();
while (match('.')) {
expect('.');
typeIdentifier = markerApply(marker, delegate.createQualifiedTypeIdentifier(
typeIdentifier,
parseVariableIdentifier()
));
}
if (match('<')) {
typeParameters = parseTypeParameterInstantiation();
}
return markerApply(marker, delegate.createGenericTypeAnnotation(
typeIdentifier,
typeParameters
));
}
function parseVoidType() {
var marker = markerCreate();
expectKeyword('void');
return markerApply(marker, delegate.createVoidTypeAnnotation());
}
function parseTypeofType() {
var argument, marker = markerCreate();
expectKeyword('typeof');
argument = parsePrimaryType();
return markerApply(marker, delegate.createTypeofTypeAnnotation(
argument
));
}
function parseTupleType() {
var marker = markerCreate(), types = [];
expect('[');
// We allow trailing commas
while (index < length && !match(']')) {
types.push(parseType());
if (match(']')) {
break;
}
expect(',');
}
expect(']');
return markerApply(marker, delegate.createTupleTypeAnnotation(
types
));
}
function parseFunctionTypeParam() {
var marker = markerCreate(), name, optional = false, typeAnnotation;
name = parseVariableIdentifier();
if (match('?')) {
lex();
optional = true;
}
expect(':');
typeAnnotation = parseType();
return markerApply(marker, delegate.createFunctionTypeParam(
name,
typeAnnotation,
optional
));
}
function parseFunctionTypeParams() {
var ret = { params: [], rest: null };
while (lookahead.type === Token.Identifier) {
ret.params.push(parseFunctionTypeParam());
if (!match(')')) {
expect(',');
}
}
if (match('...')) {
lex();
ret.rest = parseFunctionTypeParam();
}
return ret;
}
// The parsing of types roughly parallels the parsing of expressions, and
// primary types are kind of like primary expressions...they're the
// primitives with which other types are constructed.
function parsePrimaryType() {
var params = null, returnType = null,
marker = markerCreate(), rest = null, tmp,
typeParameters, token, type, isGroupedType = false;
switch (lookahead.type) {
case Token.Identifier:
switch (lookahead.value) {
case 'any':
lex();
return markerApply(marker, delegate.createAnyTypeAnnotation());
case 'bool': // fallthrough
case 'boolean':
lex();
return markerApply(marker, delegate.createBooleanTypeAnnotation());
case 'number':
lex();
return markerApply(marker, delegate.createNumberTypeAnnotation());
case 'string':
lex();
return markerApply(marker, delegate.createStringTypeAnnotation());
}
return markerApply(marker, parseGenericType());
case Token.Punctuator:
switch (lookahead.value) {
case '{':
return markerApply(marker, parseObjectType());
case '[':
return parseTupleType();
case '<':
typeParameters = parseTypeParameterDeclaration();
expect('(');
tmp = parseFunctionTypeParams();
params = tmp.params;
rest = tmp.rest;
expect(')');
expect('=>');
returnType = parseType();
return markerApply(marker, delegate.createFunctionTypeAnnotation(
params,
returnType,
rest,
typeParameters
));
case '(':
lex();
// Check to see if this is actually a grouped type
if (!match(')') && !match('...')) {
if (lookahead.type === Token.Identifier) {
token = lookahead2();
isGroupedType = token.value !== '?' && token.value !== ':';
} else {
isGroupedType = true;
}
}
if (isGroupedType) {
type = parseType();
expect(')');
// If we see a => next then someone was probably confused about
// function types, so we can provide a better error message
if (match('=>')) {
throwError({}, Messages.ConfusedAboutFunctionType);
}
return type;
}
tmp = parseFunctionTypeParams();
params = tmp.params;
rest = tmp.rest;
expect(')');
expect('=>');
returnType = parseType();
return markerApply(marker, delegate.createFunctionTypeAnnotation(
params,
returnType,
rest,
null /* typeParameters */
));
}
break;
case Token.Keyword:
switch (lookahead.value) {
case 'void':
return markerApply(marker, parseVoidType());
case 'typeof':
return markerApply(marker, parseTypeofType());
}
break;
case Token.StringLiteral:
token = lex();
if (token.octal) {
throwError(token, Messages.StrictOctalLiteral);
}
return markerApply(marker, delegate.createStringLiteralTypeAnnotation(
token
));
}
throwUnexpected(lookahead);
}
function parsePostfixType() {
var marker = markerCreate(), t = parsePrimaryType();
if (match('[')) {
expect('[');
expect(']');
return markerApply(marker, delegate.createArrayTypeAnnotation(t));
}
return t;
}
function parsePrefixType() {
var marker = markerCreate();
if (match('?')) {
lex();
return markerApply(marker, delegate.createNullableTypeAnnotation(
parsePrefixType()
));
}
return parsePostfixType();
}
function parseIntersectionType() {
var marker = markerCreate(), type, types;
type = parsePrefixType();
types = [type];
while (match('&')) {
lex();
types.push(parsePrefixType());
}
return types.length === 1 ?
type :
markerApply(marker, delegate.createIntersectionTypeAnnotation(
types
));
}
function parseUnionType() {
var marker = markerCreate(), type, types;
type = parseIntersectionType();
types = [type];
while (match('|')) {
lex();
types.push(parseIntersectionType());
}
return types.length === 1 ?
type :
markerApply(marker, delegate.createUnionTypeAnnotation(
types
));
}
function parseType() {
var oldInType = state.inType, type;
state.inType = true;
type = parseUnionType();
state.inType = oldInType;
return type;
}
function parseTypeAnnotation() {
var marker = markerCreate(), type;
expect(':');
type = parseType();
return markerApply(marker, delegate.createTypeAnnotation(type));
}
function parseVariableIdentifier() {
var marker = markerCreate(),
token = lex();
if (token.type !== Token.Identifier) {
throwUnexpected(token);
}
return markerApply(marker, delegate.createIdentifier(token.value));
}
function parseTypeAnnotatableIdentifier(requireTypeAnnotation, canBeOptionalParam) {
var marker = markerCreate(),
ident = parseVariableIdentifier(),
isOptionalParam = false;
if (canBeOptionalParam && match('?')) {
expect('?');
isOptionalParam = true;
}
if (requireTypeAnnotation || match(':')) {
ident.typeAnnotation = parseTypeAnnotation();
ident = markerApply(marker, ident);
}
if (isOptionalParam) {
ident.optional = true;
ident = markerApply(marker, ident);
}
return ident;
}
function parseVariableDeclaration(kind) {
var id,
marker = markerCreate(),
init = null,
typeAnnotationMarker = markerCreate();
if (match('{')) {
id = parseObjectInitialiser();
reinterpretAsAssignmentBindingPattern(id);
if (match(':')) {
id.typeAnnotation = parseTypeAnnotation();
markerApply(typeAnnotationMarker, id);
}
} else if (match('[')) {
id = parseArrayInitialiser();
reinterpretAsAssignmentBindingPattern(id);
if (match(':')) {
id.typeAnnotation = parseTypeAnnotation();
markerApply(typeAnnotationMarker, id);
}
} else {
/* istanbul ignore next */
id = state.allowKeyword ? parseNonComputedProperty() : parseTypeAnnotatableIdentifier();
// 12.2.1
if (strict && isRestrictedWord(id.name)) {
throwErrorTolerant({}, Messages.StrictVarName);
}
}
if (kind === 'const') {
if (!match('=')) {
throwError({}, Messages.NoUninitializedConst);
}
expect('=');
init = parseAssignmentExpression();
} else if (match('=')) {
lex();
init = parseAssignmentExpression();
}
return markerApply(marker, delegate.createVariableDeclarator(id, init));
}
function parseVariableDeclarationList(kind) {
var list = [];
do {
list.push(parseVariableDeclaration(kind));
if (!match(',')) {
break;
}
lex();
} while (index < length);
return list;
}
function parseVariableStatement() {
var declarations, marker = markerCreate();
expectKeyword('var');
declarations = parseVariableDeclarationList();
consumeSemicolon();
return markerApply(marker, delegate.createVariableDeclaration(declarations, 'var'));
}
// kind may be `const` or `let`
// Both are experimental and not in the specification yet.
// see http://wiki.ecmascript.org/doku.php?id=harmony:const
// and http://wiki.ecmascript.org/doku.php?id=harmony:let
function parseConstLetDeclaration(kind) {
var declarations, marker = markerCreate();
expectKeyword(kind);
declarations = parseVariableDeclarationList(kind);
consumeSemicolon();
return markerApply(marker, delegate.createVariableDeclaration(declarations, kind));
}
// people.mozilla.org/~jorendorff/es6-draft.html
function parseModuleSpecifier() {
var marker = markerCreate(),
specifier;
if (lookahead.type !== Token.StringLiteral) {
throwError({}, Messages.InvalidModuleSpecifier);
}
specifier = delegate.createModuleSpecifier(lookahead);
lex();
return markerApply(marker, specifier);
}
function parseExportBatchSpecifier() {
var marker = markerCreate();
expect('*');
return markerApply(marker, delegate.createExportBatchSpecifier());
}
function parseExportSpecifier() {
var id, name = null, marker = markerCreate(), from;
if (matchKeyword('default')) {
lex();
id = markerApply(marker, delegate.createIdentifier('default'));
// export {default} from "something";
} else {
id = parseVariableIdentifier();
}
if (matchContextualKeyword('as')) {
lex();
name = parseNonComputedProperty();
}
return markerApply(marker, delegate.createExportSpecifier(id, name));
}
function parseExportDeclaration() {
var declaration = null,
possibleIdentifierToken, sourceElement,
isExportFromIdentifier,
src = null, specifiers = [],
marker = markerCreate();
expectKeyword('export');
if (matchKeyword('default')) {
// covers:
// export default ...
lex();
if (matchKeyword('function') || matchKeyword('class')) {
possibleIdentifierToken = lookahead2();
if (isIdentifierName(possibleIdentifierToken)) {
// covers:
// export default function foo () {}
// export default class foo {}
sourceElement = parseSourceElement();
return markerApply(marker, delegate.createExportDeclaration(true, sourceElement, [sourceElement.id], null));
}
// covers:
// export default function () {}
// export default class {}
switch (lookahead.value) {
case 'class':
return markerApply(marker, delegate.createExportDeclaration(true, parseClassExpression(), [], null));
case 'function':
return markerApply(marker, delegate.createExportDeclaration(true, parseFunctionExpression(), [], null));
}
}
if (matchContextualKeyword('from')) {
throwError({}, Messages.UnexpectedToken, lookahead.value);
}
// covers:
// export default {};
// export default [];
if (match('{')) {
declaration = parseObjectInitialiser();
} else if (match('[')) {
declaration = parseArrayInitialiser();
} else {
declaration = parseAssignmentExpression();
}
consumeSemicolon();
return markerApply(marker, delegate.createExportDeclaration(true, declaration, [], null));
}
// non-default export
if (lookahead.type === Token.Keyword || matchContextualKeyword('type')) {
// covers:
// export var f = 1;
switch (lookahead.value) {
case 'type':
case 'let':
case 'const':
case 'var':
case 'class':
case 'function':
return markerApply(marker, delegate.createExportDeclaration(false, parseSourceElement(), specifiers, null));
}
}
if (match('*')) {
// covers:
// export * from "foo";
specifiers.push(parseExportBatchSpecifier());
if (!matchContextualKeyword('from')) {
throwError({}, lookahead.value ?
Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
}
lex();
src = parseModuleSpecifier();
consumeSemicolon();
return markerApply(marker, delegate.createExportDeclaration(false, null, specifiers, src));
}
expect('{');
if (!match('}')) {
do {
isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default');
specifiers.push(parseExportSpecifier());
} while (match(',') && lex());
}
expect('}');
if (matchContextualKeyword('from')) {
// covering:
// export {default} from "foo";
// export {foo} from "foo";
lex();
src = parseModuleSpecifier();
consumeSemicolon();
} else if (isExportFromIdentifier) {
// covering:
// export {default}; // missing fromClause
throwError({}, lookahead.value ?
Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
} else {
// cover
// export {foo};
consumeSemicolon();
}
return markerApply(marker, delegate.createExportDeclaration(false, declaration, specifiers, src));
}
function parseImportSpecifier() {
// import {<foo as bar>} ...;
var id, name = null, marker = markerCreate();
id = parseNonComputedProperty();
if (matchContextualKeyword('as')) {
lex();
name = parseVariableIdentifier();
}
return markerApply(marker, delegate.createImportSpecifier(id, name));
}
function parseNamedImports() {
var specifiers = [];
// {foo, bar as bas}
expect('{');
if (!match('}')) {
do {
specifiers.push(parseImportSpecifier());
} while (match(',') && lex());
}
expect('}');
return specifiers;
}
function parseImportDefaultSpecifier() {
// import <foo> ...;
var id, marker = markerCreate();
id = parseNonComputedProperty();
return markerApply(marker, delegate.createImportDefaultSpecifier(id));
}
function parseImportNamespaceSpecifier() {
// import <* as foo> ...;
var id, marker = markerCreate();
expect('*');
if (!matchContextualKeyword('as')) {
throwError({}, Messages.NoAsAfterImportNamespace);
}
lex();
id = parseNonComputedProperty();
return markerApply(marker, delegate.createImportNamespaceSpecifier(id));
}
function parseImportDeclaration() {
var specifiers, src, marker = markerCreate(), isType = false, token2;
expectKeyword('import');
if (matchContextualKeyword('type')) {
token2 = lookahead2();
if ((token2.type === Token.Identifier && token2.value !== 'from') ||
(token2.type === Token.Punctuator &&
(token2.value === '{' || token2.value === '*'))) {
isType = true;
lex();
}
}
specifiers = [];
if (lookahead.type === Token.StringLiteral) {
// covers:
// import "foo";
src = parseModuleSpecifier();
consumeSemicolon();
return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType));
}
if (!matchKeyword('default') && isIdentifierName(lookahead)) {
// covers:
// import foo
// import foo, ...
specifiers.push(parseImportDefaultSpecifier());
if (match(',')) {
lex();
}
}
if (match('*')) {
// covers:
// import foo, * as foo
// import * as foo
specifiers.push(parseImportNamespaceSpecifier());
} else if (match('{')) {
// covers:
// import foo, {bar}
// import {bar}
specifiers = specifiers.concat(parseNamedImports());
}
if (!matchContextualKeyword('from')) {
throwError({}, lookahead.value ?
Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
}
lex();
src = parseModuleSpecifier();
consumeSemicolon();
return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType));
}
// 12.3 Empty Statement
function parseEmptyStatement() {
var marker = markerCreate();
expect(';');
return markerApply(marker, delegate.createEmptyStatement());
}
// 12.4 Expression Statement
function parseExpressionStatement() {
var marker = markerCreate(), expr = parseExpression();
consumeSemicolon();
return markerApply(marker, delegate.createExpressionStatement(expr));
}
// 12.5 If statement
function parseIfStatement() {
var test, consequent, alternate, marker = markerCreate();
expectKeyword('if');
expect('(');
test = parseExpression();
expect(')');
consequent = parseStatement();
if (matchKeyword('else')) {
lex();
alternate = parseStatement();
} else {
alternate = null;
}
return markerApply(marker, delegate.createIfStatement(test, consequent, alternate));
}
// 12.6 Iteration Statements
function parseDoWhileStatement() {
var body, test, oldInIteration, marker = markerCreate();
expectKeyword('do');
oldInIteration = state.inIteration;
state.inIteration = true;
body = parseStatement();
state.inIteration = oldInIteration;
expectKeyword('while');
expect('(');
test = parseExpression();
expect(')');
if (match(';')) {
lex();
}
return markerApply(marker, delegate.createDoWhileStatement(body, test));
}
function parseWhileStatement() {
var test, body, oldInIteration, marker = markerCreate();
expectKeyword('while');
expect('(');
test = parseExpression();
expect(')');
oldInIteration = state.inIteration;
state.inIteration = true;
body = parseStatement();
state.inIteration = oldInIteration;
return markerApply(marker, delegate.createWhileStatement(test, body));
}
function parseForVariableDeclaration() {
var marker = markerCreate(),
token = lex(),
declarations = parseVariableDeclarationList();
return markerApply(marker, delegate.createVariableDeclaration(declarations, token.value));
}
function parseForStatement(opts) {
var init, test, update, left, right, body, operator, oldInIteration,
marker = markerCreate();
init = test = update = null;
expectKeyword('for');
// http://wiki.ecmascript.org/doku.php?id=proposals:iterators_and_generators&s=each
if (matchContextualKeyword('each')) {
throwError({}, Messages.EachNotAllowed);
}
expect('(');
if (match(';')) {
lex();
} else {
if (matchKeyword('var') || matchKeyword('let') || matchKeyword('const')) {
state.allowIn = false;
init = parseForVariableDeclaration();
state.allowIn = true;
if (init.declarations.length === 1) {
if (matchKeyword('in') || matchContextualKeyword('of')) {
operator = lookahead;
if (!((operator.value === 'in' || init.kind !== 'var') && init.declarations[0].init)) {
lex();
left = init;
right = parseExpression();
init = null;
}
}
}
} else {
state.allowIn = false;
init = parseExpression();
state.allowIn = true;
if (matchContextualKeyword('of')) {
operator = lex();
left = init;
right = parseExpression();
init = null;
} else if (matchKeyword('in')) {
// LeftHandSideExpression
if (!isAssignableLeftHandSide(init)) {
throwError({}, Messages.InvalidLHSInForIn);
}
operator = lex();
left = init;
right = parseExpression();
init = null;
}
}
if (typeof left === 'undefined') {
expect(';');
}
}
if (typeof left === 'undefined') {
if (!match(';')) {
test = parseExpression();
}
expect(';');
if (!match(')')) {
update = parseExpression();
}
}
expect(')');
oldInIteration = state.inIteration;
state.inIteration = true;
if (!(opts !== undefined && opts.ignoreBody)) {
body = parseStatement();
}
state.inIteration = oldInIteration;
if (typeof left === 'undefined') {
return markerApply(marker, delegate.createForStatement(init, test, update, body));
}
if (operator.value === 'in') {
return markerApply(marker, delegate.createForInStatement(left, right, body));
}
return markerApply(marker, delegate.createForOfStatement(left, right, body));
}
// 12.7 The continue statement
function parseContinueStatement() {
var label = null, marker = markerCreate();
expectKeyword('continue');
// Optimize the most common form: 'continue;'.
if (source.charCodeAt(index) === 59) {
lex();
if (!state.inIteration) {
throwError({}, Messages.IllegalContinue);
}
return markerApply(marker, delegate.createContinueStatement(null));
}
if (peekLineTerminator()) {
if (!state.inIteration) {
throwError({}, Messages.IllegalContinue);
}
return markerApply(marker, delegate.createContinueStatement(null));
}
if (lookahead.type === Token.Identifier) {
label = parseVariableIdentifier();
if (!state.labelSet.has(label.name)) {
throwError({}, Messages.UnknownLabel, label.name);
}
}
consumeSemicolon();
if (label === null && !state.inIteration) {
throwError({}, Messages.IllegalContinue);
}
return markerApply(marker, delegate.createContinueStatement(label));
}
// 12.8 The break statement
function parseBreakStatement() {
var label = null, marker = markerCreate();
expectKeyword('break');
// Catch the very common case first: immediately a semicolon (char #59).
if (source.charCodeAt(index) === 59) {
lex();
if (!(state.inIteration || state.inSwitch)) {
throwError({}, Messages.IllegalBreak);
}
return markerApply(marker, delegate.createBreakStatement(null));
}
if (peekLineTerminator()) {
if (!(state.inIteration || state.inSwitch)) {
throwError({}, Messages.IllegalBreak);
}
return markerApply(marker, delegate.createBreakStatement(null));
}
if (lookahead.type === Token.Identifier) {
label = parseVariableIdentifier();
if (!state.labelSet.has(label.name)) {
throwError({}, Messages.UnknownLabel, label.name);
}
}
consumeSemicolon();
if (label === null && !(state.inIteration || state.inSwitch)) {
throwError({}, Messages.IllegalBreak);
}
return markerApply(marker, delegate.createBreakStatement(label));
}
// 12.9 The return statement
function parseReturnStatement() {
var argument = null, marker = markerCreate();
expectKeyword('return');
if (!state.inFunctionBody) {
throwErrorTolerant({}, Messages.IllegalReturn);
}
// 'return' followed by a space and an identifier is very common.
if (source.charCodeAt(index) === 32) {
if (isIdentifierStart(source.charCodeAt(index + 1))) {
argument = parseExpression();
consumeSemicolon();
return markerApply(marker, delegate.createReturnStatement(argument));
}
}
if (peekLineTerminator()) {
return markerApply(marker, delegate.createReturnStatement(null));
}
if (!match(';')) {
if (!match('}') && lookahead.type !== Token.EOF) {
argument = parseExpression();
}
}
consumeSemicolon();
return markerApply(marker, delegate.createReturnStatement(argument));
}
// 12.10 The with statement
function parseWithStatement() {
var object, body, marker = markerCreate();
if (strict) {
throwErrorTolerant({}, Messages.StrictModeWith);
}
expectKeyword('with');
expect('(');
object = parseExpression();
expect(')');
body = parseStatement();
return markerApply(marker, delegate.createWithStatement(object, body));
}
// 12.10 The swith statement
function parseSwitchCase() {
var test,
consequent = [],
sourceElement,
marker = markerCreate();
if (matchKeyword('default')) {
lex();
test = null;
} else {
expectKeyword('case');
test = parseExpression();
}
expect(':');
while (index < length) {
if (match('}') || matchKeyword('default') || matchKeyword('case')) {
break;
}
sourceElement = parseSourceElement();
if (typeof sourceElement === 'undefined') {
break;
}
consequent.push(sourceElement);
}
return markerApply(marker, delegate.createSwitchCase(test, consequent));
}
function parseSwitchStatement() {
var discriminant, cases, clause, oldInSwitch, defaultFound, marker = markerCreate();
expectKeyword('switch');
expect('(');
discriminant = parseExpression();
expect(')');
expect('{');
cases = [];
if (match('}')) {
lex();
return markerApply(marker, delegate.createSwitchStatement(discriminant, cases));
}
oldInSwitch = state.inSwitch;
state.inSwitch = true;
defaultFound = false;
while (index < length) {
if (match('}')) {
break;
}
clause = parseSwitchCase();
if (clause.test === null) {
if (defaultFound) {
throwError({}, Messages.MultipleDefaultsInSwitch);
}
defaultFound = true;
}
cases.push(clause);
}
state.inSwitch = oldInSwitch;
expect('}');
return markerApply(marker, delegate.createSwitchStatement(discriminant, cases));
}
// 12.13 The throw statement
function parseThrowStatement() {
var argument, marker = markerCreate();
expectKeyword('throw');
if (peekLineTerminator()) {
throwError({}, Messages.NewlineAfterThrow);
}
argument = parseExpression();
consumeSemicolon();
return markerApply(marker, delegate.createThrowStatement(argument));
}
// 12.14 The try statement
function parseCatchClause() {
var param, body, marker = markerCreate();
expectKeyword('catch');
expect('(');
if (match(')')) {
throwUnexpected(lookahead);
}
param = parseExpression();
// 12.14.1
if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) {
throwErrorTolerant({}, Messages.StrictCatchVariable);
}
expect(')');
body = parseBlock();
return markerApply(marker, delegate.createCatchClause(param, body));
}
function parseTryStatement() {
var block, handlers = [], finalizer = null, marker = markerCreate();
expectKeyword('try');
block = parseBlock();
if (matchKeyword('catch')) {
handlers.push(parseCatchClause());
}
if (matchKeyword('finally')) {
lex();
finalizer = parseBlock();
}
if (handlers.length === 0 && !finalizer) {
throwError({}, Messages.NoCatchOrFinally);
}
return markerApply(marker, delegate.createTryStatement(block, [], handlers, finalizer));
}
// 12.15 The debugger statement
function parseDebuggerStatement() {
var marker = markerCreate();
expectKeyword('debugger');
consumeSemicolon();
return markerApply(marker, delegate.createDebuggerStatement());
}
// 12 Statements
function parseStatement() {
var type = lookahead.type,
marker,
expr,
labeledBody;
if (type === Token.EOF) {
throwUnexpected(lookahead);
}
if (type === Token.Punctuator) {
switch (lookahead.value) {
case ';':
return parseEmptyStatement();
case '{':
return parseBlock();
case '(':
return parseExpressionStatement();
default:
break;
}
}
if (type === Token.Keyword) {
switch (lookahead.value) {
case 'break':
return parseBreakStatement();
case 'continue':
return parseContinueStatement();
case 'debugger':
return parseDebuggerStatement();
case 'do':
return parseDoWhileStatement();
case 'for':
return parseForStatement();
case 'function':
return parseFunctionDeclaration();
case 'class':
return parseClassDeclaration();
case 'if':
return parseIfStatement();
case 'return':
return parseReturnStatement();
case 'switch':
return parseSwitchStatement();
case 'throw':
return parseThrowStatement();
case 'try':
return parseTryStatement();
case 'var':
return parseVariableStatement();
case 'while':
return parseWhileStatement();
case 'with':
return parseWithStatement();
default:
break;
}
}
if (matchAsyncFuncExprOrDecl()) {
return parseFunctionDeclaration();
}
marker = markerCreate();
expr = parseExpression();
// 12.12 Labelled Statements
if ((expr.type === Syntax.Identifier) && match(':')) {
lex();
if (state.labelSet.has(expr.name)) {
throwError({}, Messages.Redeclaration, 'Label', expr.name);
}
state.labelSet.set(expr.name, true);
labeledBody = parseStatement();
state.labelSet["delete"](expr.name);
return markerApply(marker, delegate.createLabeledStatement(expr, labeledBody));
}
consumeSemicolon();
return markerApply(marker, delegate.createExpressionStatement(expr));
}
// 13 Function Definition
function parseConciseBody() {
if (match('{')) {
return parseFunctionSourceElements();
}
return parseAssignmentExpression();
}
function parseFunctionSourceElements() {
var sourceElement, sourceElements = [], token, directive, firstRestricted,
oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesizedCount,
marker = markerCreate();
expect('{');
while (index < length) {
if (lookahead.type !== Token.StringLiteral) {
break;
}
token = lookahead;
sourceElement = parseSourceElement();
sourceElements.push(sourceElement);
if (sourceElement.expression.type !== Syntax.Literal) {
// this is not directive
break;
}
directive = source.slice(token.range[0] + 1, token.range[1] - 1);
if (directive === 'use strict') {
strict = true;
if (firstRestricted) {
throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
}
} else {
if (!firstRestricted && token.octal) {
firstRestricted = token;
}
}
}
oldLabelSet = state.labelSet;
oldInIteration = state.inIteration;
oldInSwitch = state.inSwitch;
oldInFunctionBody = state.inFunctionBody;
oldParenthesizedCount = state.parenthesizedCount;
state.labelSet = new StringMap();
state.inIteration = false;
state.inSwitch = false;
state.inFunctionBody = true;
state.parenthesizedCount = 0;
while (index < length) {
if (match('}')) {
break;
}
sourceElement = parseSourceElement();
if (typeof sourceElement === 'undefined') {
break;
}
sourceElements.push(sourceElement);
}
expect('}');
state.labelSet = oldLabelSet;
state.inIteration = oldInIteration;
state.inSwitch = oldInSwitch;
state.inFunctionBody = oldInFunctionBody;
state.parenthesizedCount = oldParenthesizedCount;
return markerApply(marker, delegate.createBlockStatement(sourceElements));
}
function validateParam(options, param, name) {
if (strict) {
if (isRestrictedWord(name)) {
options.stricted = param;
options.message = Messages.StrictParamName;
}
if (options.paramSet.has(name)) {
options.stricted = param;
options.message = Messages.StrictParamDupe;
}
} else if (!options.firstRestricted) {
if (isRestrictedWord(name)) {
options.firstRestricted = param;
options.message = Messages.StrictParamName;
} else if (isStrictModeReservedWord(name)) {
options.firstRestricted = param;
options.message = Messages.StrictReservedWord;
} else if (options.paramSet.has(name)) {
options.firstRestricted = param;
options.message = Messages.StrictParamDupe;
}
}
options.paramSet.set(name, true);
}
function parseParam(options) {
var marker, token, rest, param, def;
token = lookahead;
if (token.value === '...') {
token = lex();
rest = true;
}
if (match('[')) {
marker = markerCreate();
param = parseArrayInitialiser();
reinterpretAsDestructuredParameter(options, param);
if (match(':')) {
param.typeAnnotation = parseTypeAnnotation();
markerApply(marker, param);
}
} else if (match('{')) {
marker = markerCreate();
if (rest) {
throwError({}, Messages.ObjectPatternAsRestParameter);
}
param = parseObjectInitialiser();
reinterpretAsDestructuredParameter(options, param);
if (match(':')) {
param.typeAnnotation = parseTypeAnnotation();
markerApply(marker, param);
}
} else {
param =
rest
? parseTypeAnnotatableIdentifier(
false, /* requireTypeAnnotation */
false /* canBeOptionalParam */
)
: parseTypeAnnotatableIdentifier(
false, /* requireTypeAnnotation */
true /* canBeOptionalParam */
);
validateParam(options, token, token.value);
}
if (match('=')) {
if (rest) {
throwErrorTolerant(lookahead, Messages.DefaultRestParameter);
}
lex();
def = parseAssignmentExpression();
++options.defaultCount;
}
if (rest) {
if (!match(')')) {
throwError({}, Messages.ParameterAfterRestParameter);
}
options.rest = param;
return false;
}
options.params.push(param);
options.defaults.push(def);
return !match(')');
}
function parseParams(firstRestricted) {
var options, marker = markerCreate();
options = {
params: [],
defaultCount: 0,
defaults: [],
rest: null,
firstRestricted: firstRestricted
};
expect('(');
if (!match(')')) {
options.paramSet = new StringMap();
while (index < length) {
if (!parseParam(options)) {
break;
}
expect(',');
}
}
expect(')');
if (options.defaultCount === 0) {
options.defaults = [];
}
if (match(':')) {
options.returnType = parseTypeAnnotation();
}
return markerApply(marker, options);
}
function parseFunctionDeclaration() {
var id, body, token, tmp, firstRestricted, message, generator, isAsync,
previousStrict, previousYieldAllowed, previousAwaitAllowed,
marker = markerCreate(), typeParameters;
isAsync = false;
if (matchAsync()) {
lex();
isAsync = true;
}
expectKeyword('function');
generator = false;
if (match('*')) {
lex();
generator = true;
}
token = lookahead;
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
if (strict) {
if (isRestrictedWord(token.value)) {
throwErrorTolerant(token, Messages.StrictFunctionName);
}
} else {
if (isRestrictedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictFunctionName;
} else if (isStrictModeReservedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictReservedWord;
}
}
tmp = parseParams(firstRestricted);
firstRestricted = tmp.firstRestricted;
if (tmp.message) {
message = tmp.message;
}
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = generator;
previousAwaitAllowed = state.awaitAllowed;
state.awaitAllowed = isAsync;
body = parseFunctionSourceElements();
if (strict && firstRestricted) {
throwError(firstRestricted, message);
}
if (strict && tmp.stricted) {
throwErrorTolerant(tmp.stricted, message);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
state.awaitAllowed = previousAwaitAllowed;
return markerApply(
marker,
delegate.createFunctionDeclaration(
id,
tmp.params,
tmp.defaults,
body,
tmp.rest,
generator,
false,
isAsync,
tmp.returnType,
typeParameters
)
);
}
function parseFunctionExpression() {
var token, id = null, firstRestricted, message, tmp, body, generator, isAsync,
previousStrict, previousYieldAllowed, previousAwaitAllowed,
marker = markerCreate(), typeParameters;
isAsync = false;
if (matchAsync()) {
lex();
isAsync = true;
}
expectKeyword('function');
generator = false;
if (match('*')) {
lex();
generator = true;
}
if (!match('(')) {
if (!match('<')) {
token = lookahead;
id = parseVariableIdentifier();
if (strict) {
if (isRestrictedWord(token.value)) {
throwErrorTolerant(token, Messages.StrictFunctionName);
}
} else {
if (isRestrictedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictFunctionName;
} else if (isStrictModeReservedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictReservedWord;
}
}
}
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
}
tmp = parseParams(firstRestricted);
firstRestricted = tmp.firstRestricted;
if (tmp.message) {
message = tmp.message;
}
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = generator;
previousAwaitAllowed = state.awaitAllowed;
state.awaitAllowed = isAsync;
body = parseFunctionSourceElements();
if (strict && firstRestricted) {
throwError(firstRestricted, message);
}
if (strict && tmp.stricted) {
throwErrorTolerant(tmp.stricted, message);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
state.awaitAllowed = previousAwaitAllowed;
return markerApply(
marker,
delegate.createFunctionExpression(
id,
tmp.params,
tmp.defaults,
body,
tmp.rest,
generator,
false,
isAsync,
tmp.returnType,
typeParameters
)
);
}
function parseYieldExpression() {
var delegateFlag, expr, marker = markerCreate();
expectKeyword('yield', !strict);
delegateFlag = false;
if (match('*')) {
lex();
delegateFlag = true;
}
expr = parseAssignmentExpression();
return markerApply(marker, delegate.createYieldExpression(expr, delegateFlag));
}
function parseAwaitExpression() {
var expr, marker = markerCreate();
expectContextualKeyword('await');
expr = parseAssignmentExpression();
return markerApply(marker, delegate.createAwaitExpression(expr));
}
// 14 Functions and classes
// 14.1 Functions is defined above (13 in ES5)
// 14.2 Arrow Functions Definitions is defined in (7.3 assignments)
// 14.3 Method Definitions
// 14.3.7
function specialMethod(methodDefinition) {
return methodDefinition.kind === 'get' ||
methodDefinition.kind === 'set' ||
methodDefinition.value.generator;
}
function parseMethodDefinition(key, isStatic, generator, computed) {
var token, param, propType,
isAsync, typeParameters, tokenValue, returnType;
propType = isStatic ? ClassPropertyType["static"] : ClassPropertyType.prototype;
if (generator) {
return delegate.createMethodDefinition(
propType,
'',
key,
parsePropertyMethodFunction({ generator: true }),
computed
);
}
tokenValue = key.type === 'Identifier' && key.name;
if (tokenValue === 'get' && !match('(')) {
key = parseObjectPropertyKey();
expect('(');
expect(')');
if (match(':')) {
returnType = parseTypeAnnotation();
}
return delegate.createMethodDefinition(
propType,
'get',
key,
parsePropertyFunction({ generator: false, returnType: returnType }),
computed
);
}
if (tokenValue === 'set' && !match('(')) {
key = parseObjectPropertyKey();
expect('(');
token = lookahead;
param = [ parseTypeAnnotatableIdentifier() ];
expect(')');
if (match(':')) {
returnType = parseTypeAnnotation();
}
return delegate.createMethodDefinition(
propType,
'set',
key,
parsePropertyFunction({
params: param,
generator: false,
name: token,
returnType: returnType
}),
computed
);
}
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
isAsync = tokenValue === 'async' && !match('(');
if (isAsync) {
key = parseObjectPropertyKey();
}
return delegate.createMethodDefinition(
propType,
'',
key,
parsePropertyMethodFunction({
generator: false,
async: isAsync,
typeParameters: typeParameters
}),
computed
);
}
function parseClassProperty(key, computed, isStatic) {
var typeAnnotation;
typeAnnotation = parseTypeAnnotation();
expect(';');
return delegate.createClassProperty(
key,
typeAnnotation,
computed,
isStatic
);
}
function parseClassElement() {
var computed = false, generator = false, key, marker = markerCreate(),
isStatic = false, possiblyOpenBracketToken;
if (match(';')) {
lex();
return undefined;
}
if (lookahead.value === 'static') {
lex();
isStatic = true;
}
if (match('*')) {
lex();
generator = true;
}
possiblyOpenBracketToken = lookahead;
if (matchContextualKeyword('get') || matchContextualKeyword('set')) {
possiblyOpenBracketToken = lookahead2();
}
if (possiblyOpenBracketToken.type === Token.Punctuator
&& possiblyOpenBracketToken.value === '[') {
computed = true;
}
key = parseObjectPropertyKey();
if (!generator && lookahead.value === ':') {
return markerApply(marker, parseClassProperty(key, computed, isStatic));
}
return markerApply(marker, parseMethodDefinition(
key,
isStatic,
generator,
computed
));
}
function parseClassBody() {
var classElement, classElements = [], existingProps = {},
marker = markerCreate(), propName, propType;
existingProps[ClassPropertyType["static"]] = new StringMap();
existingProps[ClassPropertyType.prototype] = new StringMap();
expect('{');
while (index < length) {
if (match('}')) {
break;
}
classElement = parseClassElement(existingProps);
if (typeof classElement !== 'undefined') {
classElements.push(classElement);
propName = !classElement.computed && getFieldName(classElement.key);
if (propName !== false) {
propType = classElement["static"] ?
ClassPropertyType["static"] :
ClassPropertyType.prototype;
if (classElement.type === Syntax.MethodDefinition) {
if (propName === 'constructor' && !classElement["static"]) {
if (specialMethod(classElement)) {
throwError(classElement, Messages.IllegalClassConstructorProperty);
}
if (existingProps[ClassPropertyType.prototype].has('constructor')) {
throwError(classElement.key, Messages.IllegalDuplicateClassProperty);
}
}
existingProps[propType].set(propName, true);
}
}
}
}
expect('}');
return markerApply(marker, delegate.createClassBody(classElements));
}
function parseClassImplements() {
var id, implemented = [], marker, typeParameters;
if (strict) {
expectKeyword('implements');
} else {
expectContextualKeyword('implements');
}
while (index < length) {
marker = markerCreate();
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterInstantiation();
} else {
typeParameters = null;
}
implemented.push(markerApply(marker, delegate.createClassImplements(
id,
typeParameters
)));
if (!match(',')) {
break;
}
expect(',');
}
return implemented;
}
function parseClassExpression() {
var id, implemented, previousYieldAllowed, superClass = null,
superTypeParameters, marker = markerCreate(), typeParameters,
matchImplements;
expectKeyword('class');
matchImplements =
strict
? matchKeyword('implements')
: matchContextualKeyword('implements');
if (!matchKeyword('extends') && !matchImplements && !match('{')) {
id = parseVariableIdentifier();
}
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
if (matchKeyword('extends')) {
expectKeyword('extends');
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = false;
superClass = parseLeftHandSideExpressionAllowCall();
if (match('<')) {
superTypeParameters = parseTypeParameterInstantiation();
}
state.yieldAllowed = previousYieldAllowed;
}
if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) {
implemented = parseClassImplements();
}
return markerApply(marker, delegate.createClassExpression(
id,
superClass,
parseClassBody(),
typeParameters,
superTypeParameters,
implemented
));
}
function parseClassDeclaration() {
var id, implemented, previousYieldAllowed, superClass = null,
superTypeParameters, marker = markerCreate(), typeParameters;
expectKeyword('class');
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
if (matchKeyword('extends')) {
expectKeyword('extends');
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = false;
superClass = parseLeftHandSideExpressionAllowCall();
if (match('<')) {
superTypeParameters = parseTypeParameterInstantiation();
}
state.yieldAllowed = previousYieldAllowed;
}
if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) {
implemented = parseClassImplements();
}
return markerApply(marker, delegate.createClassDeclaration(
id,
superClass,
parseClassBody(),
typeParameters,
superTypeParameters,
implemented
));
}
// 15 Program
function parseSourceElement() {
var token;
if (lookahead.type === Token.Keyword) {
switch (lookahead.value) {
case 'const':
case 'let':
return parseConstLetDeclaration(lookahead.value);
case 'function':
return parseFunctionDeclaration();
case 'export':
throwErrorTolerant({}, Messages.IllegalExportDeclaration);
return parseExportDeclaration();
case 'import':
throwErrorTolerant({}, Messages.IllegalImportDeclaration);
return parseImportDeclaration();
case 'interface':
if (lookahead2().type === Token.Identifier) {
return parseInterface();
}
return parseStatement();
default:
return parseStatement();
}
}
if (matchContextualKeyword('type')
&& lookahead2().type === Token.Identifier) {
return parseTypeAlias();
}
if (matchContextualKeyword('interface')
&& lookahead2().type === Token.Identifier) {
return parseInterface();
}
if (matchContextualKeyword('declare')) {
token = lookahead2();
if (token.type === Token.Keyword) {
switch (token.value) {
case 'class':
return parseDeclareClass();
case 'function':
return parseDeclareFunction();
case 'var':
return parseDeclareVariable();
}
} else if (token.type === Token.Identifier
&& token.value === 'module') {
return parseDeclareModule();
}
}
if (lookahead.type !== Token.EOF) {
return parseStatement();
}
}
function parseProgramElement() {
var isModule = extra.sourceType === 'module' || extra.sourceType === 'nonStrictModule';
if (isModule && lookahead.type === Token.Keyword) {
switch (lookahead.value) {
case 'export':
return parseExportDeclaration();
case 'import':
return parseImportDeclaration();
}
}
return parseSourceElement();
}
function parseProgramElements() {
var sourceElement, sourceElements = [], token, directive, firstRestricted;
while (index < length) {
token = lookahead;
if (token.type !== Token.StringLiteral) {
break;
}
sourceElement = parseProgramElement();
sourceElements.push(sourceElement);
if (sourceElement.expression.type !== Syntax.Literal) {
// this is not directive
break;
}
directive = source.slice(token.range[0] + 1, token.range[1] - 1);
if (directive === 'use strict') {
strict = true;
if (firstRestricted) {
throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
}
} else {
if (!firstRestricted && token.octal) {
firstRestricted = token;
}
}
}
while (index < length) {
sourceElement = parseProgramElement();
if (typeof sourceElement === 'undefined') {
break;
}
sourceElements.push(sourceElement);
}
return sourceElements;
}
function parseProgram() {
var body, marker = markerCreate();
strict = extra.sourceType === 'module';
peek();
body = parseProgramElements();
return markerApply(marker, delegate.createProgram(body));
}
// 16 JSX
XHTMLEntities = {
quot: '\u0022',
amp: '&',
apos: '\u0027',
lt: '<',
gt: '>',
nbsp: '\u00A0',
iexcl: '\u00A1',
cent: '\u00A2',
pound: '\u00A3',
curren: '\u00A4',
yen: '\u00A5',
brvbar: '\u00A6',
sect: '\u00A7',
uml: '\u00A8',
copy: '\u00A9',
ordf: '\u00AA',
laquo: '\u00AB',
not: '\u00AC',
shy: '\u00AD',
reg: '\u00AE',
macr: '\u00AF',
deg: '\u00B0',
plusmn: '\u00B1',
sup2: '\u00B2',
sup3: '\u00B3',
acute: '\u00B4',
micro: '\u00B5',
para: '\u00B6',
middot: '\u00B7',
cedil: '\u00B8',
sup1: '\u00B9',
ordm: '\u00BA',
raquo: '\u00BB',
frac14: '\u00BC',
frac12: '\u00BD',
frac34: '\u00BE',
iquest: '\u00BF',
Agrave: '\u00C0',
Aacute: '\u00C1',
Acirc: '\u00C2',
Atilde: '\u00C3',
Auml: '\u00C4',
Aring: '\u00C5',
AElig: '\u00C6',
Ccedil: '\u00C7',
Egrave: '\u00C8',
Eacute: '\u00C9',
Ecirc: '\u00CA',
Euml: '\u00CB',
Igrave: '\u00CC',
Iacute: '\u00CD',
Icirc: '\u00CE',
Iuml: '\u00CF',
ETH: '\u00D0',
Ntilde: '\u00D1',
Ograve: '\u00D2',
Oacute: '\u00D3',
Ocirc: '\u00D4',
Otilde: '\u00D5',
Ouml: '\u00D6',
times: '\u00D7',
Oslash: '\u00D8',
Ugrave: '\u00D9',
Uacute: '\u00DA',
Ucirc: '\u00DB',
Uuml: '\u00DC',
Yacute: '\u00DD',
THORN: '\u00DE',
szlig: '\u00DF',
agrave: '\u00E0',
aacute: '\u00E1',
acirc: '\u00E2',
atilde: '\u00E3',
auml: '\u00E4',
aring: '\u00E5',
aelig: '\u00E6',
ccedil: '\u00E7',
egrave: '\u00E8',
eacute: '\u00E9',
ecirc: '\u00EA',
euml: '\u00EB',
igrave: '\u00EC',
iacute: '\u00ED',
icirc: '\u00EE',
iuml: '\u00EF',
eth: '\u00F0',
ntilde: '\u00F1',
ograve: '\u00F2',
oacute: '\u00F3',
ocirc: '\u00F4',
otilde: '\u00F5',
ouml: '\u00F6',
divide: '\u00F7',
oslash: '\u00F8',
ugrave: '\u00F9',
uacute: '\u00FA',
ucirc: '\u00FB',
uuml: '\u00FC',
yacute: '\u00FD',
thorn: '\u00FE',
yuml: '\u00FF',
OElig: '\u0152',
oelig: '\u0153',
Scaron: '\u0160',
scaron: '\u0161',
Yuml: '\u0178',
fnof: '\u0192',
circ: '\u02C6',
tilde: '\u02DC',
Alpha: '\u0391',
Beta: '\u0392',
Gamma: '\u0393',
Delta: '\u0394',
Epsilon: '\u0395',
Zeta: '\u0396',
Eta: '\u0397',
Theta: '\u0398',
Iota: '\u0399',
Kappa: '\u039A',
Lambda: '\u039B',
Mu: '\u039C',
Nu: '\u039D',
Xi: '\u039E',
Omicron: '\u039F',
Pi: '\u03A0',
Rho: '\u03A1',
Sigma: '\u03A3',
Tau: '\u03A4',
Upsilon: '\u03A5',
Phi: '\u03A6',
Chi: '\u03A7',
Psi: '\u03A8',
Omega: '\u03A9',
alpha: '\u03B1',
beta: '\u03B2',
gamma: '\u03B3',
delta: '\u03B4',
epsilon: '\u03B5',
zeta: '\u03B6',
eta: '\u03B7',
theta: '\u03B8',
iota: '\u03B9',
kappa: '\u03BA',
lambda: '\u03BB',
mu: '\u03BC',
nu: '\u03BD',
xi: '\u03BE',
omicron: '\u03BF',
pi: '\u03C0',
rho: '\u03C1',
sigmaf: '\u03C2',
sigma: '\u03C3',
tau: '\u03C4',
upsilon: '\u03C5',
phi: '\u03C6',
chi: '\u03C7',
psi: '\u03C8',
omega: '\u03C9',
thetasym: '\u03D1',
upsih: '\u03D2',
piv: '\u03D6',
ensp: '\u2002',
emsp: '\u2003',
thinsp: '\u2009',
zwnj: '\u200C',
zwj: '\u200D',
lrm: '\u200E',
rlm: '\u200F',
ndash: '\u2013',
mdash: '\u2014',
lsquo: '\u2018',
rsquo: '\u2019',
sbquo: '\u201A',
ldquo: '\u201C',
rdquo: '\u201D',
bdquo: '\u201E',
dagger: '\u2020',
Dagger: '\u2021',
bull: '\u2022',
hellip: '\u2026',
permil: '\u2030',
prime: '\u2032',
Prime: '\u2033',
lsaquo: '\u2039',
rsaquo: '\u203A',
oline: '\u203E',
frasl: '\u2044',
euro: '\u20AC',
image: '\u2111',
weierp: '\u2118',
real: '\u211C',
trade: '\u2122',
alefsym: '\u2135',
larr: '\u2190',
uarr: '\u2191',
rarr: '\u2192',
darr: '\u2193',
harr: '\u2194',
crarr: '\u21B5',
lArr: '\u21D0',
uArr: '\u21D1',
rArr: '\u21D2',
dArr: '\u21D3',
hArr: '\u21D4',
forall: '\u2200',
part: '\u2202',
exist: '\u2203',
empty: '\u2205',
nabla: '\u2207',
isin: '\u2208',
notin: '\u2209',
ni: '\u220B',
prod: '\u220F',
sum: '\u2211',
minus: '\u2212',
lowast: '\u2217',
radic: '\u221A',
prop: '\u221D',
infin: '\u221E',
ang: '\u2220',
and: '\u2227',
or: '\u2228',
cap: '\u2229',
cup: '\u222A',
'int': '\u222B',
there4: '\u2234',
sim: '\u223C',
cong: '\u2245',
asymp: '\u2248',
ne: '\u2260',
equiv: '\u2261',
le: '\u2264',
ge: '\u2265',
sub: '\u2282',
sup: '\u2283',
nsub: '\u2284',
sube: '\u2286',
supe: '\u2287',
oplus: '\u2295',
otimes: '\u2297',
perp: '\u22A5',
sdot: '\u22C5',
lceil: '\u2308',
rceil: '\u2309',
lfloor: '\u230A',
rfloor: '\u230B',
lang: '\u2329',
rang: '\u232A',
loz: '\u25CA',
spades: '\u2660',
clubs: '\u2663',
hearts: '\u2665',
diams: '\u2666'
};
function getQualifiedJSXName(object) {
if (object.type === Syntax.JSXIdentifier) {
return object.name;
}
if (object.type === Syntax.JSXNamespacedName) {
return object.namespace.name + ':' + object.name.name;
}
/* istanbul ignore else */
if (object.type === Syntax.JSXMemberExpression) {
return (
getQualifiedJSXName(object.object) + '.' +
getQualifiedJSXName(object.property)
);
}
/* istanbul ignore next */
throwUnexpected(object);
}
function isJSXIdentifierStart(ch) {
// exclude backslash (\)
return (ch !== 92) && isIdentifierStart(ch);
}
function isJSXIdentifierPart(ch) {
// exclude backslash (\) and add hyphen (-)
return (ch !== 92) && (ch === 45 || isIdentifierPart(ch));
}
function scanJSXIdentifier() {
var ch, start, value = '';
start = index;
while (index < length) {
ch = source.charCodeAt(index);
if (!isJSXIdentifierPart(ch)) {
break;
}
value += source[index++];
}
return {
type: Token.JSXIdentifier,
value: value,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanJSXEntity() {
var ch, str = '', start = index, count = 0, code;
ch = source[index];
assert(ch === '&', 'Entity must start with an ampersand');
index++;
while (index < length && count++ < 10) {
ch = source[index++];
if (ch === ';') {
break;
}
str += ch;
}
// Well-formed entity (ending was found).
if (ch === ';') {
// Numeric entity.
if (str[0] === '#') {
if (str[1] === 'x') {
code = +('0' + str.substr(1));
} else {
// Removing leading zeros in order to avoid treating as octal in old browsers.
code = +str.substr(1).replace(Regex.LeadingZeros, '');
}
if (!isNaN(code)) {
return String.fromCharCode(code);
}
/* istanbul ignore else */
} else if (XHTMLEntities[str]) {
return XHTMLEntities[str];
}
}
// Treat non-entity sequences as regular text.
index = start + 1;
return '&';
}
function scanJSXText(stopChars) {
var ch, str = '', start;
start = index;
while (index < length) {
ch = source[index];
if (stopChars.indexOf(ch) !== -1) {
break;
}
if (ch === '&') {
str += scanJSXEntity();
} else {
index++;
if (ch === '\r' && source[index] === '\n') {
str += ch;
ch = source[index];
index++;
}
if (isLineTerminator(ch.charCodeAt(0))) {
++lineNumber;
lineStart = index;
}
str += ch;
}
}
return {
type: Token.JSXText,
value: str,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanJSXStringLiteral() {
var innerToken, quote, start;
quote = source[index];
assert((quote === '\'' || quote === '"'),
'String literal must starts with a quote');
start = index;
++index;
innerToken = scanJSXText([quote]);
if (quote !== source[index]) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
++index;
innerToken.range = [start, index];
return innerToken;
}
/**
* Between JSX opening and closing tags (e.g. <foo>HERE</foo>), anything that
* is not another JSX tag and is not an expression wrapped by {} is text.
*/
function advanceJSXChild() {
var ch = source.charCodeAt(index);
// '<' 60, '>' 62, '{' 123, '}' 125
if (ch !== 60 && ch !== 62 && ch !== 123 && ch !== 125) {
return scanJSXText(['<', '>', '{', '}']);
}
return scanPunctuator();
}
function parseJSXIdentifier() {
var token, marker = markerCreate();
if (lookahead.type !== Token.JSXIdentifier) {
throwUnexpected(lookahead);
}
token = lex();
return markerApply(marker, delegate.createJSXIdentifier(token.value));
}
function parseJSXNamespacedName() {
var namespace, name, marker = markerCreate();
namespace = parseJSXIdentifier();
expect(':');
name = parseJSXIdentifier();
return markerApply(marker, delegate.createJSXNamespacedName(namespace, name));
}
function parseJSXMemberExpression() {
var marker = markerCreate(),
expr = parseJSXIdentifier();
while (match('.')) {
lex();
expr = markerApply(marker, delegate.createJSXMemberExpression(expr, parseJSXIdentifier()));
}
return expr;
}
function parseJSXElementName() {
if (lookahead2().value === ':') {
return parseJSXNamespacedName();
}
if (lookahead2().value === '.') {
return parseJSXMemberExpression();
}
return parseJSXIdentifier();
}
function parseJSXAttributeName() {
if (lookahead2().value === ':') {
return parseJSXNamespacedName();
}
return parseJSXIdentifier();
}
function parseJSXAttributeValue() {
var value, marker;
if (match('{')) {
value = parseJSXExpressionContainer();
if (value.expression.type === Syntax.JSXEmptyExpression) {
throwError(
value,
'JSX attributes must only be assigned a non-empty ' +
'expression'
);
}
} else if (match('<')) {
value = parseJSXElement();
} else if (lookahead.type === Token.JSXText) {
marker = markerCreate();
value = markerApply(marker, delegate.createLiteral(lex()));
} else {
throwError({}, Messages.InvalidJSXAttributeValue);
}
return value;
}
function parseJSXEmptyExpression() {
var marker = markerCreatePreserveWhitespace();
while (source.charAt(index) !== '}') {
index++;
}
return markerApply(marker, delegate.createJSXEmptyExpression());
}
function parseJSXExpressionContainer() {
var expression, origInJSXChild, origInJSXTag, marker = markerCreate();
origInJSXChild = state.inJSXChild;
origInJSXTag = state.inJSXTag;
state.inJSXChild = false;
state.inJSXTag = false;
expect('{');
if (match('}')) {
expression = parseJSXEmptyExpression();
} else {
expression = parseExpression();
}
state.inJSXChild = origInJSXChild;
state.inJSXTag = origInJSXTag;
expect('}');
return markerApply(marker, delegate.createJSXExpressionContainer(expression));
}
function parseJSXSpreadAttribute() {
var expression, origInJSXChild, origInJSXTag, marker = markerCreate();
origInJSXChild = state.inJSXChild;
origInJSXTag = state.inJSXTag;
state.inJSXChild = false;
state.inJSXTag = false;
expect('{');
expect('...');
expression = parseAssignmentExpression();
state.inJSXChild = origInJSXChild;
state.inJSXTag = origInJSXTag;
expect('}');
return markerApply(marker, delegate.createJSXSpreadAttribute(expression));
}
function parseJSXAttribute() {
var name, marker;
if (match('{')) {
return parseJSXSpreadAttribute();
}
marker = markerCreate();
name = parseJSXAttributeName();
// HTML empty attribute
if (match('=')) {
lex();
return markerApply(marker, delegate.createJSXAttribute(name, parseJSXAttributeValue()));
}
return markerApply(marker, delegate.createJSXAttribute(name));
}
function parseJSXChild() {
var token, marker;
if (match('{')) {
token = parseJSXExpressionContainer();
} else if (lookahead.type === Token.JSXText) {
marker = markerCreatePreserveWhitespace();
token = markerApply(marker, delegate.createLiteral(lex()));
} else if (match('<')) {
token = parseJSXElement();
} else {
throwUnexpected(lookahead);
}
return token;
}
function parseJSXClosingElement() {
var name, origInJSXChild, origInJSXTag, marker = markerCreate();
origInJSXChild = state.inJSXChild;
origInJSXTag = state.inJSXTag;
state.inJSXChild = false;
state.inJSXTag = true;
expect('<');
expect('/');
name = parseJSXElementName();
// Because advance() (called by lex() called by expect()) expects there
// to be a valid token after >, it needs to know whether to look for a
// standard JS token or an JSX text node
state.inJSXChild = origInJSXChild;
state.inJSXTag = origInJSXTag;
expect('>');
return markerApply(marker, delegate.createJSXClosingElement(name));
}
function parseJSXOpeningElement() {
var name, attributes = [], selfClosing = false, origInJSXChild, origInJSXTag, marker = markerCreate();
origInJSXChild = state.inJSXChild;
origInJSXTag = state.inJSXTag;
state.inJSXChild = false;
state.inJSXTag = true;
expect('<');
name = parseJSXElementName();
while (index < length &&
lookahead.value !== '/' &&
lookahead.value !== '>') {
attributes.push(parseJSXAttribute());
}
state.inJSXTag = origInJSXTag;
if (lookahead.value === '/') {
expect('/');
// Because advance() (called by lex() called by expect()) expects
// there to be a valid token after >, it needs to know whether to
// look for a standard JS token or an JSX text node
state.inJSXChild = origInJSXChild;
expect('>');
selfClosing = true;
} else {
state.inJSXChild = true;
expect('>');
}
return markerApply(marker, delegate.createJSXOpeningElement(name, attributes, selfClosing));
}
function parseJSXElement() {
var openingElement, closingElement = null, children = [], origInJSXChild, origInJSXTag, marker = markerCreate();
origInJSXChild = state.inJSXChild;
origInJSXTag = state.inJSXTag;
openingElement = parseJSXOpeningElement();
if (!openingElement.selfClosing) {
while (index < length) {
state.inJSXChild = false; // Call lookahead2() with inJSXChild = false because </ should not be considered in the child
if (lookahead.value === '<' && lookahead2().value === '/') {
break;
}
state.inJSXChild = true;
children.push(parseJSXChild());
}
state.inJSXChild = origInJSXChild;
state.inJSXTag = origInJSXTag;
closingElement = parseJSXClosingElement();
if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
throwError({}, Messages.ExpectedJSXClosingTag, getQualifiedJSXName(openingElement.name));
}
}
// When (erroneously) writing two adjacent tags like
//
// var x = <div>one</div><div>two</div>;
//
// the default error message is a bit incomprehensible. Since it's
// rarely (never?) useful to write a less-than sign after an JSX
// element, we disallow it here in the parser in order to provide a
// better error message. (In the rare case that the less-than operator
// was intended, the left tag can be wrapped in parentheses.)
if (!origInJSXChild && match('<')) {
throwError(lookahead, Messages.AdjacentJSXElements);
}
return markerApply(marker, delegate.createJSXElement(openingElement, closingElement, children));
}
function parseTypeAlias() {
var id, marker = markerCreate(), typeParameters = null, right;
expectContextualKeyword('type');
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
expect('=');
right = parseType();
consumeSemicolon();
return markerApply(marker, delegate.createTypeAlias(id, typeParameters, right));
}
function parseInterfaceExtends() {
var marker = markerCreate(), id, typeParameters = null;
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterInstantiation();
}
return markerApply(marker, delegate.createInterfaceExtends(
id,
typeParameters
));
}
function parseInterfaceish(marker, allowStatic) {
var body, bodyMarker, extended = [], id,
typeParameters = null;
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
if (matchKeyword('extends')) {
expectKeyword('extends');
while (index < length) {
extended.push(parseInterfaceExtends());
if (!match(',')) {
break;
}
expect(',');
}
}
bodyMarker = markerCreate();
body = markerApply(bodyMarker, parseObjectType(allowStatic));
return markerApply(marker, delegate.createInterface(
id,
typeParameters,
body,
extended
));
}
function parseInterface() {
var marker = markerCreate();
if (strict) {
expectKeyword('interface');
} else {
expectContextualKeyword('interface');
}
return parseInterfaceish(marker, /* allowStatic */false);
}
function parseDeclareClass() {
var marker = markerCreate(), ret;
expectContextualKeyword('declare');
expectKeyword('class');
ret = parseInterfaceish(marker, /* allowStatic */true);
ret.type = Syntax.DeclareClass;
return ret;
}
function parseDeclareFunction() {
var id, idMarker,
marker = markerCreate(), params, returnType, rest, tmp,
typeParameters = null, value, valueMarker;
expectContextualKeyword('declare');
expectKeyword('function');
idMarker = markerCreate();
id = parseVariableIdentifier();
valueMarker = markerCreate();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
expect('(');
tmp = parseFunctionTypeParams();
params = tmp.params;
rest = tmp.rest;
expect(')');
expect(':');
returnType = parseType();
value = markerApply(valueMarker, delegate.createFunctionTypeAnnotation(
params,
returnType,
rest,
typeParameters
));
id.typeAnnotation = markerApply(valueMarker, delegate.createTypeAnnotation(
value
));
markerApply(idMarker, id);
consumeSemicolon();
return markerApply(marker, delegate.createDeclareFunction(
id
));
}
function parseDeclareVariable() {
var id, marker = markerCreate();
expectContextualKeyword('declare');
expectKeyword('var');
id = parseTypeAnnotatableIdentifier();
consumeSemicolon();
return markerApply(marker, delegate.createDeclareVariable(
id
));
}
function parseDeclareModule() {
var body = [], bodyMarker, id, idMarker, marker = markerCreate(), token;
expectContextualKeyword('declare');
expectContextualKeyword('module');
if (lookahead.type === Token.StringLiteral) {
if (strict && lookahead.octal) {
throwErrorTolerant(lookahead, Messages.StrictOctalLiteral);
}
idMarker = markerCreate();
id = markerApply(idMarker, delegate.createLiteral(lex()));
} else {
id = parseVariableIdentifier();
}
bodyMarker = markerCreate();
expect('{');
while (index < length && !match('}')) {
token = lookahead2();
switch (token.value) {
case 'class':
body.push(parseDeclareClass());
break;
case 'function':
body.push(parseDeclareFunction());
break;
case 'var':
body.push(parseDeclareVariable());
break;
default:
throwUnexpected(lookahead);
}
}
expect('}');
return markerApply(marker, delegate.createDeclareModule(
id,
markerApply(bodyMarker, delegate.createBlockStatement(body))
));
}
function collectToken() {
var loc, token, range, value, entry;
/* istanbul ignore else */
if (!state.inJSXChild) {
skipComment();
}
loc = {
start: {
line: lineNumber,
column: index - lineStart
}
};
token = extra.advance();
loc.end = {
line: lineNumber,
column: index - lineStart
};
if (token.type !== Token.EOF) {
range = [token.range[0], token.range[1]];
value = source.slice(token.range[0], token.range[1]);
entry = {
type: TokenName[token.type],
value: value,
range: range,
loc: loc
};
if (token.regex) {
entry.regex = {
pattern: token.regex.pattern,
flags: token.regex.flags
};
}
extra.tokens.push(entry);
}
return token;
}
function collectRegex() {
var pos, loc, regex, token;
skipComment();
pos = index;
loc = {
start: {
line: lineNumber,
column: index - lineStart
}
};
regex = extra.scanRegExp();
loc.end = {
line: lineNumber,
column: index - lineStart
};
if (!extra.tokenize) {
/* istanbul ignore next */
// Pop the previous token, which is likely '/' or '/='
if (extra.tokens.length > 0) {
token = extra.tokens[extra.tokens.length - 1];
if (token.range[0] === pos && token.type === 'Punctuator') {
if (token.value === '/' || token.value === '/=') {
extra.tokens.pop();
}
}
}
extra.tokens.push({
type: 'RegularExpression',
value: regex.literal,
regex: regex.regex,
range: [pos, index],
loc: loc
});
}
return regex;
}
function filterTokenLocation() {
var i, entry, token, tokens = [];
for (i = 0; i < extra.tokens.length; ++i) {
entry = extra.tokens[i];
token = {
type: entry.type,
value: entry.value
};
if (entry.regex) {
token.regex = {
pattern: entry.regex.pattern,
flags: entry.regex.flags
};
}
if (extra.range) {
token.range = entry.range;
}
if (extra.loc) {
token.loc = entry.loc;
}
tokens.push(token);
}
extra.tokens = tokens;
}
function patch() {
if (typeof extra.tokens !== 'undefined') {
extra.advance = advance;
extra.scanRegExp = scanRegExp;
advance = collectToken;
scanRegExp = collectRegex;
}
}
function unpatch() {
if (typeof extra.scanRegExp === 'function') {
advance = extra.advance;
scanRegExp = extra.scanRegExp;
}
}
// This is used to modify the delegate.
function extend(object, properties) {
var entry, result = {};
for (entry in object) {
/* istanbul ignore else */
if (object.hasOwnProperty(entry)) {
result[entry] = object[entry];
}
}
for (entry in properties) {
/* istanbul ignore else */
if (properties.hasOwnProperty(entry)) {
result[entry] = properties[entry];
}
}
return result;
}
function tokenize(code, options) {
var toString,
token,
tokens;
toString = String;
if (typeof code !== 'string' && !(code instanceof String)) {
code = toString(code);
}
delegate = SyntaxTreeDelegate;
source = code;
index = 0;
lineNumber = (source.length > 0) ? 1 : 0;
lineStart = 0;
length = source.length;
lookahead = null;
state = {
allowKeyword: true,
allowIn: true,
labelSet: new StringMap(),
inFunctionBody: false,
inIteration: false,
inSwitch: false,
lastCommentStart: -1
};
extra = {};
// Options matching.
options = options || {};
// Of course we collect tokens here.
options.tokens = true;
extra.tokens = [];
extra.tokenize = true;
// The following two fields are necessary to compute the Regex tokens.
extra.openParenToken = -1;
extra.openCurlyToken = -1;
extra.range = (typeof options.range === 'boolean') && options.range;
extra.loc = (typeof options.loc === 'boolean') && options.loc;
if (typeof options.comment === 'boolean' && options.comment) {
extra.comments = [];
}
if (typeof options.tolerant === 'boolean' && options.tolerant) {
extra.errors = [];
}
patch();
try {
peek();
if (lookahead.type === Token.EOF) {
return extra.tokens;
}
token = lex();
while (lookahead.type !== Token.EOF) {
try {
token = lex();
} catch (lexError) {
token = lookahead;
if (extra.errors) {
extra.errors.push(lexError);
// We have to break on the first error
// to avoid infinite loops.
break;
} else {
throw lexError;
}
}
}
filterTokenLocation();
tokens = extra.tokens;
if (typeof extra.comments !== 'undefined') {
tokens.comments = extra.comments;
}
if (typeof extra.errors !== 'undefined') {
tokens.errors = extra.errors;
}
} catch (e) {
throw e;
} finally {
unpatch();
extra = {};
}
return tokens;
}
function parse(code, options) {
var program, toString;
toString = String;
if (typeof code !== 'string' && !(code instanceof String)) {
code = toString(code);
}
delegate = SyntaxTreeDelegate;
source = code;
index = 0;
lineNumber = (source.length > 0) ? 1 : 0;
lineStart = 0;
length = source.length;
lookahead = null;
state = {
allowKeyword: false,
allowIn: true,
labelSet: new StringMap(),
parenthesizedCount: 0,
inFunctionBody: false,
inIteration: false,
inSwitch: false,
inJSXChild: false,
inJSXTag: false,
inType: false,
lastCommentStart: -1,
yieldAllowed: false,
awaitAllowed: false
};
extra = {};
if (typeof options !== 'undefined') {
extra.range = (typeof options.range === 'boolean') && options.range;
extra.loc = (typeof options.loc === 'boolean') && options.loc;
extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;
if (extra.loc && options.source !== null && options.source !== undefined) {
delegate = extend(delegate, {
'postProcess': function (node) {
node.loc.source = toString(options.source);
return node;
}
});
}
extra.sourceType = options.sourceType;
if (typeof options.tokens === 'boolean' && options.tokens) {
extra.tokens = [];
}
if (typeof options.comment === 'boolean' && options.comment) {
extra.comments = [];
}
if (typeof options.tolerant === 'boolean' && options.tolerant) {
extra.errors = [];
}
if (extra.attachComment) {
extra.range = true;
extra.comments = [];
extra.bottomRightStack = [];
extra.trailingComments = [];
extra.leadingComments = [];
}
}
patch();
try {
program = parseProgram();
if (typeof extra.comments !== 'undefined') {
program.comments = extra.comments;
}
if (typeof extra.tokens !== 'undefined') {
filterTokenLocation();
program.tokens = extra.tokens;
}
if (typeof extra.errors !== 'undefined') {
program.errors = extra.errors;
}
} catch (e) {
throw e;
} finally {
unpatch();
extra = {};
}
return program;
}
// Sync with *.json manifests.
exports.version = '13001.1001.0-dev-harmony-fb';
exports.tokenize = tokenize;
exports.parse = parse;
// Deep copy.
/* istanbul ignore next */
exports.Syntax = (function () {
var name, types = {};
if (typeof Object.create === 'function') {
types = Object.create(null);
}
for (name in Syntax) {
if (Syntax.hasOwnProperty(name)) {
types[name] = Syntax[name];
}
}
if (typeof Object.freeze === 'function') {
Object.freeze(types);
}
return types;
}());
}));
/* vim: set sw=4 ts=4 et tw=80 : */
},{}],10:[function(_dereq_,module,exports){
var Base62 = (function (my) {
my.chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
my.encode = function(i){
if (i === 0) {return '0'}
var s = ''
while (i > 0) {
s = this.chars[i % 62] + s
i = Math.floor(i/62)
}
return s
};
my.decode = function(a,b,c,d){
for (
b = c = (
a === (/\W|_|^$/.test(a += "") || a)
) - 1;
d = a.charCodeAt(c++);
)
b = b * 62 + d - [, 48, 29, 87][d >> 5];
return b
};
return my;
}({}));
module.exports = Base62
},{}],11:[function(_dereq_,module,exports){
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = _dereq_('./source-map/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = _dereq_('./source-map/source-map-consumer').SourceMapConsumer;
exports.SourceNode = _dereq_('./source-map/source-node').SourceNode;
},{"./source-map/source-map-consumer":16,"./source-map/source-map-generator":17,"./source-map/source-node":18}],12:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var util = _dereq_('./util');
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
function ArraySet() {
this._array = [];
this._set = {};
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
};
/**
* Add the given string to this set.
*
* @param String aStr
*/
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
var isDuplicate = this.has(aStr);
var idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
this._set[util.toSetString(aStr)] = idx;
}
};
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
ArraySet.prototype.has = function ArraySet_has(aStr) {
return Object.prototype.hasOwnProperty.call(this._set,
util.toSetString(aStr));
};
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
if (this.has(aStr)) {
return this._set[util.toSetString(aStr)];
}
throw new Error('"' + aStr + '" is not in the set.');
};
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error('No element indexed by ' + aIdx);
};
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports.ArraySet = ArraySet;
});
},{"./util":19,"amdefine":20}],13:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
*
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var base64 = _dereq_('./base64');
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
var VLQ_BASE_SHIFT = 5;
// binary: 100000
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
var VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
var VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(aValue) {
return aValue < 0
? ((-aValue) << 1) + 1
: (aValue << 1) + 0;
}
/**
* Converts to a two-complement value from a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative
? -shifted
: shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
/**
* Decodes the next base 64 VLQ value from the given string and returns the
* value and the rest of the string.
*/
exports.decode = function base64VLQ_decode(aStr) {
var i = 0;
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (i >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charAt(i++));
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
return {
value: fromVLQSigned(result),
rest: aStr.slice(i)
};
};
});
},{"./base64":14,"amdefine":20}],14:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var charToIntMap = {};
var intToCharMap = {};
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
.split('')
.forEach(function (ch, index) {
charToIntMap[ch] = index;
intToCharMap[index] = ch;
});
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
*/
exports.encode = function base64_encode(aNumber) {
if (aNumber in intToCharMap) {
return intToCharMap[aNumber];
}
throw new TypeError("Must be between 0 and 63: " + aNumber);
};
/**
* Decode a single base 64 digit to an integer.
*/
exports.decode = function base64_decode(aChar) {
if (aChar in charToIntMap) {
return charToIntMap[aChar];
}
throw new TypeError("Not a valid base 64 digit: " + aChar);
};
});
},{"amdefine":20}],15:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the next
// closest element that is less than that element.
//
// 3. We did not find the exact element, and there is no next-closest
// element which is less than the one we are searching for, so we
// return null.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return aHaystack[mid];
}
else if (cmp > 0) {
// aHaystack[mid] is greater than our needle.
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
}
// We did not find an exact match, return the next closest one
// (termination case 2).
return aHaystack[mid];
}
else {
// aHaystack[mid] is less than our needle.
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (2) or (3) and return the appropriate thing.
return aLow < 0
? null
: aHaystack[aLow];
}
}
/**
* This is an implementation of binary search which will always try and return
* the next lowest value checked if there is no exact hit. This is because
* mappings between original and generated line/col pairs are single points,
* and there is an implicit region between each of them, so a miss just means
* that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
*/
exports.search = function search(aNeedle, aHaystack, aCompare) {
return aHaystack.length > 0
? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
: null;
};
});
},{"amdefine":20}],16:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var util = _dereq_('./util');
var binarySearch = _dereq_('./binary-search');
var ArraySet = _dereq_('./array-set').ArraySet;
var base64VLQ = _dereq_('./base64-vlq');
/**
* A SourceMapConsumer instance represents a parsed source map which we can
* query for information about the original file positions by giving it a file
* position in the generated source.
*
* The only parameter is the raw source map (either as a JSON string, or
* already parsed to an object). According to the spec, source maps have the
* following attributes:
*
* - version: Which version of the source map spec this map is following.
* - sources: An array of URLs to the original source files.
* - names: An array of identifiers which can be referrenced by individual mappings.
* - sourceRoot: Optional. The URL root from which all sources are relative.
* - sourcesContent: Optional. An array of contents of the original source files.
* - mappings: A string of base64 VLQs which contain the actual mappings.
* - file: The generated file this source map is associated with.
*
* Here is an example source map, taken from the source map spec[0]:
*
* {
* version : 3,
* file: "out.js",
* sourceRoot : "",
* sources: ["foo.js", "bar.js"],
* names: ["src", "maps", "are", "fun"],
* mappings: "AA,AB;;ABCDE;"
* }
*
* [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
*/
function SourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
var version = util.getArg(sourceMap, 'version');
var sources = util.getArg(sourceMap, 'sources');
// Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
// requires the array) to play nice here.
var names = util.getArg(sourceMap, 'names', []);
var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
var mappings = util.getArg(sourceMap, 'mappings');
var file = util.getArg(sourceMap, 'file', null);
// Once again, Sass deviates from the spec and supplies the version as a
// string rather than a number, so we use loose equality checking here.
if (version != this._version) {
throw new Error('Unsupported version: ' + version);
}
// Pass `true` below to allow duplicate names and sources. While source maps
// are intended to be compressed and deduplicated, the TypeScript compiler
// sometimes generates source maps with duplicates in them. See Github issue
// #72 and bugzil.la/889492.
this._names = ArraySet.fromArray(names, true);
this._sources = ArraySet.fromArray(sources, true);
this.sourceRoot = sourceRoot;
this.sourcesContent = sourcesContent;
this._mappings = mappings;
this.file = file;
}
/**
* Create a SourceMapConsumer from a SourceMapGenerator.
*
* @param SourceMapGenerator aSourceMap
* The source map that will be consumed.
* @returns SourceMapConsumer
*/
SourceMapConsumer.fromSourceMap =
function SourceMapConsumer_fromSourceMap(aSourceMap) {
var smc = Object.create(SourceMapConsumer.prototype);
smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
smc.sourceRoot = aSourceMap._sourceRoot;
smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
smc.sourceRoot);
smc.file = aSourceMap._file;
smc.__generatedMappings = aSourceMap._mappings.slice()
.sort(util.compareByGeneratedPositions);
smc.__originalMappings = aSourceMap._mappings.slice()
.sort(util.compareByOriginalPositions);
return smc;
};
/**
* The version of the source mapping spec that we are consuming.
*/
SourceMapConsumer.prototype._version = 3;
/**
* The list of original sources.
*/
Object.defineProperty(SourceMapConsumer.prototype, 'sources', {
get: function () {
return this._sources.toArray().map(function (s) {
return this.sourceRoot ? util.join(this.sourceRoot, s) : s;
}, this);
}
});
// `__generatedMappings` and `__originalMappings` are arrays that hold the
// parsed mapping coordinates from the source map's "mappings" attribute. They
// are lazily instantiated, accessed via the `_generatedMappings` and
// `_originalMappings` getters respectively, and we only parse the mappings
// and create these arrays once queried for a source location. We jump through
// these hoops because there can be many thousands of mappings, and parsing
// them is expensive, so we only want to do it if we must.
//
// Each object in the arrays is of the form:
//
// {
// generatedLine: The line number in the generated code,
// generatedColumn: The column number in the generated code,
// source: The path to the original source file that generated this
// chunk of code,
// originalLine: The line number in the original source that
// corresponds to this chunk of generated code,
// originalColumn: The column number in the original source that
// corresponds to this chunk of generated code,
// name: The name of the original symbol which generated this chunk of
// code.
// }
//
// All properties except for `generatedLine` and `generatedColumn` can be
// `null`.
//
// `_generatedMappings` is ordered by the generated positions.
//
// `_originalMappings` is ordered by the original positions.
SourceMapConsumer.prototype.__generatedMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
get: function () {
if (!this.__generatedMappings) {
this.__generatedMappings = [];
this.__originalMappings = [];
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__generatedMappings;
}
});
SourceMapConsumer.prototype.__originalMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
get: function () {
if (!this.__originalMappings) {
this.__generatedMappings = [];
this.__originalMappings = [];
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__originalMappings;
}
});
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
SourceMapConsumer.prototype._parseMappings =
function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
var generatedLine = 1;
var previousGeneratedColumn = 0;
var previousOriginalLine = 0;
var previousOriginalColumn = 0;
var previousSource = 0;
var previousName = 0;
var mappingSeparator = /^[,;]/;
var str = aStr;
var mapping;
var temp;
while (str.length > 0) {
if (str.charAt(0) === ';') {
generatedLine++;
str = str.slice(1);
previousGeneratedColumn = 0;
}
else if (str.charAt(0) === ',') {
str = str.slice(1);
}
else {
mapping = {};
mapping.generatedLine = generatedLine;
// Generated column.
temp = base64VLQ.decode(str);
mapping.generatedColumn = previousGeneratedColumn + temp.value;
previousGeneratedColumn = mapping.generatedColumn;
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
// Original source.
temp = base64VLQ.decode(str);
mapping.source = this._sources.at(previousSource + temp.value);
previousSource += temp.value;
str = temp.rest;
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
throw new Error('Found a source, but no line and column');
}
// Original line.
temp = base64VLQ.decode(str);
mapping.originalLine = previousOriginalLine + temp.value;
previousOriginalLine = mapping.originalLine;
// Lines are stored 0-based
mapping.originalLine += 1;
str = temp.rest;
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
throw new Error('Found a source and line, but no column');
}
// Original column.
temp = base64VLQ.decode(str);
mapping.originalColumn = previousOriginalColumn + temp.value;
previousOriginalColumn = mapping.originalColumn;
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
// Original name.
temp = base64VLQ.decode(str);
mapping.name = this._names.at(previousName + temp.value);
previousName += temp.value;
str = temp.rest;
}
}
this.__generatedMappings.push(mapping);
if (typeof mapping.originalLine === 'number') {
this.__originalMappings.push(mapping);
}
}
}
this.__originalMappings.sort(util.compareByOriginalPositions);
};
/**
* Find the mapping that best matches the hypothetical "needle" mapping that
* we are searching for in the given "haystack" of mappings.
*/
SourceMapConsumer.prototype._findMapping =
function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
aColumnName, aComparator) {
// To return the position we are searching for, we must first find the
// mapping for the given position and then return the opposite position it
// points to. Because the mappings are sorted, we can use binary search to
// find the best mapping.
if (aNeedle[aLineName] <= 0) {
throw new TypeError('Line must be greater than or equal to 1, got '
+ aNeedle[aLineName]);
}
if (aNeedle[aColumnName] < 0) {
throw new TypeError('Column must be greater than or equal to 0, got '
+ aNeedle[aColumnName]);
}
return binarySearch.search(aNeedle, aMappings, aComparator);
};
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
SourceMapConsumer.prototype.originalPositionFor =
function SourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
};
var mapping = this._findMapping(needle,
this._generatedMappings,
"generatedLine",
"generatedColumn",
util.compareByGeneratedPositions);
if (mapping) {
var source = util.getArg(mapping, 'source', null);
if (source && this.sourceRoot) {
source = util.join(this.sourceRoot, source);
}
return {
source: source,
line: util.getArg(mapping, 'originalLine', null),
column: util.getArg(mapping, 'originalColumn', null),
name: util.getArg(mapping, 'name', null)
};
}
return {
source: null,
line: null,
column: null,
name: null
};
};
/**
* Returns the original source content. The only argument is the url of the
* original source file. Returns null if no original source content is
* availible.
*/
SourceMapConsumer.prototype.sourceContentFor =
function SourceMapConsumer_sourceContentFor(aSource) {
if (!this.sourcesContent) {
return null;
}
if (this.sourceRoot) {
aSource = util.relative(this.sourceRoot, aSource);
}
if (this._sources.has(aSource)) {
return this.sourcesContent[this._sources.indexOf(aSource)];
}
var url;
if (this.sourceRoot
&& (url = util.urlParse(this.sourceRoot))) {
// XXX: file:// URIs and absolute paths lead to unexpected behavior for
// many users. We can help them out when they expect file:// URIs to
// behave like it would if they were running a local HTTP server. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
if (url.scheme == "file"
&& this._sources.has(fileUriAbsPath)) {
return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
}
if ((!url.path || url.path == "/")
&& this._sources.has("/" + aSource)) {
return this.sourcesContent[this._sources.indexOf("/" + aSource)];
}
}
throw new Error('"' + aSource + '" is not in the SourceMap.');
};
/**
* Returns the generated line and column information for the original source,
* line, and column positions provided. The only argument is an object with
* the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: The column number in the original source.
*
* and an object is returned with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
SourceMapConsumer.prototype.generatedPositionFor =
function SourceMapConsumer_generatedPositionFor(aArgs) {
var needle = {
source: util.getArg(aArgs, 'source'),
originalLine: util.getArg(aArgs, 'line'),
originalColumn: util.getArg(aArgs, 'column')
};
if (this.sourceRoot) {
needle.source = util.relative(this.sourceRoot, needle.source);
}
var mapping = this._findMapping(needle,
this._originalMappings,
"originalLine",
"originalColumn",
util.compareByOriginalPositions);
if (mapping) {
return {
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null)
};
}
return {
line: null,
column: null
};
};
SourceMapConsumer.GENERATED_ORDER = 1;
SourceMapConsumer.ORIGINAL_ORDER = 2;
/**
* Iterate over each mapping between an original source/line/column and a
* generated line/column in this source map.
*
* @param Function aCallback
* The function that is called with each mapping.
* @param Object aContext
* Optional. If specified, this object will be the value of `this` every
* time that `aCallback` is called.
* @param aOrder
* Either `SourceMapConsumer.GENERATED_ORDER` or
* `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
* iterate over the mappings sorted by the generated file's line/column
* order or the original's source/line/column order, respectively. Defaults to
* `SourceMapConsumer.GENERATED_ORDER`.
*/
SourceMapConsumer.prototype.eachMapping =
function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
var context = aContext || null;
var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
var mappings;
switch (order) {
case SourceMapConsumer.GENERATED_ORDER:
mappings = this._generatedMappings;
break;
case SourceMapConsumer.ORIGINAL_ORDER:
mappings = this._originalMappings;
break;
default:
throw new Error("Unknown order of iteration.");
}
var sourceRoot = this.sourceRoot;
mappings.map(function (mapping) {
var source = mapping.source;
if (source && sourceRoot) {
source = util.join(sourceRoot, source);
}
return {
source: source,
generatedLine: mapping.generatedLine,
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: mapping.name
};
}).forEach(aCallback, context);
};
exports.SourceMapConsumer = SourceMapConsumer;
});
},{"./array-set":12,"./base64-vlq":13,"./binary-search":15,"./util":19,"amdefine":20}],17:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var base64VLQ = _dereq_('./base64-vlq');
var util = _dereq_('./util');
var ArraySet = _dereq_('./array-set').ArraySet;
/**
* An instance of the SourceMapGenerator represents a source map which is
* being built incrementally. To create a new one, you must pass an object
* with the following properties:
*
* - file: The filename of the generated source.
* - sourceRoot: An optional root for all URLs in this source map.
*/
function SourceMapGenerator(aArgs) {
this._file = util.getArg(aArgs, 'file');
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = [];
this._sourcesContents = null;
}
SourceMapGenerator.prototype._version = 3;
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param aSourceMapConsumer The SourceMap.
*/
SourceMapGenerator.fromSourceMap =
function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot: sourceRoot
});
aSourceMapConsumer.eachMapping(function (mapping) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
};
if (mapping.source) {
newMapping.source = mapping.source;
if (sourceRoot) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
SourceMapGenerator.prototype.addMapping =
function SourceMapGenerator_addMapping(aArgs) {
var generated = util.getArg(aArgs, 'generated');
var original = util.getArg(aArgs, 'original', null);
var source = util.getArg(aArgs, 'source', null);
var name = util.getArg(aArgs, 'name', null);
this._validateMapping(generated, original, source, name);
if (source && !this._sources.has(source)) {
this._sources.add(source);
}
if (name && !this._names.has(name)) {
this._names.add(name);
}
this._mappings.push({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source: source,
name: name
});
};
/**
* Set the source content for a source file.
*/
SourceMapGenerator.prototype.setSourceContent =
function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
var source = aSourceFile;
if (this._sourceRoot) {
source = util.relative(this._sourceRoot, source);
}
if (aSourceContent !== null) {
// Add the source content to the _sourcesContents map.
// Create a new _sourcesContents map if the property is null.
if (!this._sourcesContents) {
this._sourcesContents = {};
}
this._sourcesContents[util.toSetString(source)] = aSourceContent;
} else {
// Remove the source file from the _sourcesContents map.
// If the _sourcesContents map is empty, set the property to null.
delete this._sourcesContents[util.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
};
/**
* Applies the mappings of a sub-source-map for a specific source file to the
* source map being generated. Each mapping to the supplied source file is
* rewritten using the supplied source map. Note: The resolution for the
* resulting mappings is the minimium of this map and the supplied map.
*
* @param aSourceMapConsumer The source map to be applied.
* @param aSourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
*/
SourceMapGenerator.prototype.applySourceMap =
function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) {
// If aSourceFile is omitted, we will use the file property of the SourceMap
if (!aSourceFile) {
aSourceFile = aSourceMapConsumer.file;
}
var sourceRoot = this._sourceRoot;
// Make "aSourceFile" relative if an absolute Url is passed.
if (sourceRoot) {
aSourceFile = util.relative(sourceRoot, aSourceFile);
}
// Applying the SourceMap can add and remove items from the sources and
// the names array.
var newSources = new ArraySet();
var newNames = new ArraySet();
// Find mappings for the "aSourceFile"
this._mappings.forEach(function (mapping) {
if (mapping.source === aSourceFile && mapping.originalLine) {
// Check if it can be mapped by the source map, then update the mapping.
var original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
if (original.source !== null) {
// Copy mapping
if (sourceRoot) {
mapping.source = util.relative(sourceRoot, original.source);
} else {
mapping.source = original.source;
}
mapping.originalLine = original.line;
mapping.originalColumn = original.column;
if (original.name !== null && mapping.name !== null) {
// Only use the identifier name if it's an identifier
// in both SourceMaps
mapping.name = original.name;
}
}
}
var source = mapping.source;
if (source && !newSources.has(source)) {
newSources.add(source);
}
var name = mapping.name;
if (name && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
// Copy sourcesContents of applied map.
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
if (sourceRoot) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
this.setSourceContent(sourceFile, content);
}
}, this);
};
/**
* A mapping can have one of the three levels of data:
*
* 1. Just the generated position.
* 2. The Generated position, original position, and original source.
* 3. Generated and original position, original source, as well as a name
* token.
*
* To maintain consistency, we validate that any new mapping being added falls
* in to one of these categories.
*/
SourceMapGenerator.prototype._validateMapping =
function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
aName) {
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aGenerated.line > 0 && aGenerated.column >= 0
&& !aOriginal && !aSource && !aName) {
// Case 1.
return;
}
else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aOriginal && 'line' in aOriginal && 'column' in aOriginal
&& aGenerated.line > 0 && aGenerated.column >= 0
&& aOriginal.line > 0 && aOriginal.column >= 0
&& aSource) {
// Cases 2 and 3.
return;
}
else {
throw new Error('Invalid mapping: ' + JSON.stringify({
generated: aGenerated,
source: aSource,
orginal: aOriginal,
name: aName
}));
}
};
/**
* Serialize the accumulated mappings in to the stream of base 64 VLQs
* specified by the source map format.
*/
SourceMapGenerator.prototype._serializeMappings =
function SourceMapGenerator_serializeMappings() {
var previousGeneratedColumn = 0;
var previousGeneratedLine = 1;
var previousOriginalColumn = 0;
var previousOriginalLine = 0;
var previousName = 0;
var previousSource = 0;
var result = '';
var mapping;
// The mappings must be guaranteed to be in sorted order before we start
// serializing them or else the generated line numbers (which are defined
// via the ';' separators) will be all messed up. Note: it might be more
// performant to maintain the sorting as we insert them, rather than as we
// serialize them, but the big O is the same either way.
this._mappings.sort(util.compareByGeneratedPositions);
for (var i = 0, len = this._mappings.length; i < len; i++) {
mapping = this._mappings[i];
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
result += ';';
previousGeneratedLine++;
}
}
else {
if (i > 0) {
if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) {
continue;
}
result += ',';
}
}
result += base64VLQ.encode(mapping.generatedColumn
- previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source) {
result += base64VLQ.encode(this._sources.indexOf(mapping.source)
- previousSource);
previousSource = this._sources.indexOf(mapping.source);
// lines are stored 0-based in SourceMap spec version 3
result += base64VLQ.encode(mapping.originalLine - 1
- previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
result += base64VLQ.encode(mapping.originalColumn
- previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name) {
result += base64VLQ.encode(this._names.indexOf(mapping.name)
- previousName);
previousName = this._names.indexOf(mapping.name);
}
}
}
return result;
};
SourceMapGenerator.prototype._generateSourcesContent =
function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function (source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot) {
source = util.relative(aSourceRoot, source);
}
var key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents,
key)
? this._sourcesContents[key]
: null;
}, this);
};
/**
* Externalize the source map.
*/
SourceMapGenerator.prototype.toJSON =
function SourceMapGenerator_toJSON() {
var map = {
version: this._version,
file: this._file,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._sourceRoot) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
}
return map;
};
/**
* Render the source map being generated to a string.
*/
SourceMapGenerator.prototype.toString =
function SourceMapGenerator_toString() {
return JSON.stringify(this);
};
exports.SourceMapGenerator = SourceMapGenerator;
});
},{"./array-set":12,"./base64-vlq":13,"./util":19,"amdefine":20}],18:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var SourceMapGenerator = _dereq_('./source-map-generator').SourceMapGenerator;
var util = _dereq_('./util');
/**
* SourceNodes provide a way to abstract over interpolating/concatenating
* snippets of generated JavaScript source code while maintaining the line and
* column information associated with the original source code.
*
* @param aLine The original line number.
* @param aColumn The original column number.
* @param aSource The original source's filename.
* @param aChunks Optional. An array of strings which are snippets of
* generated JS, or other SourceNodes.
* @param aName The original identifier.
*/
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine === undefined ? null : aLine;
this.column = aColumn === undefined ? null : aColumn;
this.source = aSource === undefined ? null : aSource;
this.name = aName === undefined ? null : aName;
if (aChunks != null) this.add(aChunks);
}
/**
* Creates a SourceNode from generated code and a SourceMapConsumer.
*
* @param aGeneratedCode The generated code
* @param aSourceMapConsumer The SourceMap for the generated code
*/
SourceNode.fromStringWithSourceMap =
function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
var node = new SourceNode();
// The generated code
// Processed fragments are removed from this array.
var remainingLines = aGeneratedCode.split('\n');
// We need to remember the position of "remainingLines"
var lastGeneratedLine = 1, lastGeneratedColumn = 0;
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
var lastMapping = null;
aSourceMapConsumer.eachMapping(function (mapping) {
if (lastMapping === null) {
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine < mapping.generatedLine) {
node.add(remainingLines.shift() + "\n");
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[0];
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
} else {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine < mapping.generatedLine) {
var code = "";
// Associate full lines with "lastMapping"
do {
code += remainingLines.shift() + "\n";
lastGeneratedLine++;
lastGeneratedColumn = 0;
} while (lastGeneratedLine < mapping.generatedLine);
// When we reached the correct line, we add code until we
// reach the correct column too.
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[0];
code += nextLine.substr(0, mapping.generatedColumn);
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
// Create the SourceNode.
addMappingWithCode(lastMapping, code);
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
var nextLine = remainingLines[0];
var code = nextLine.substr(0, mapping.generatedColumn -
lastGeneratedColumn);
remainingLines[0] = nextLine.substr(mapping.generatedColumn -
lastGeneratedColumn);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
}
}
lastMapping = mapping;
}, this);
// We have processed all mappings.
// Associate the remaining code in the current line with "lastMapping"
// and add the remaining lines without any mapping
addMappingWithCode(lastMapping, remainingLines.join("\n"));
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn,
mapping.source,
code,
mapping.name));
}
}
};
/**
* Add a chunk of generated JS to this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.add = function SourceNode_add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function (chunk) {
this.add(chunk);
}, this);
}
else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Add a chunk of generated JS to the beginning of this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (var i = aChunk.length-1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
}
else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
this.children.unshift(aChunk);
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Walk over the tree of JS snippets in this node and its children. The
* walking function is called once for each snippet of JS and is passed that
* snippet and the its original associated source's line/column location.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
var chunk;
for (var i = 0, len = this.children.length; i < len; i++) {
chunk = this.children[i];
if (chunk instanceof SourceNode) {
chunk.walk(aFn);
}
else {
if (chunk !== '') {
aFn(chunk, { source: this.source,
line: this.line,
column: this.column,
name: this.name });
}
}
}
};
/**
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
* each of `this.children`.
*
* @param aSep The separator.
*/
SourceNode.prototype.join = function SourceNode_join(aSep) {
var newChildren;
var i;
var len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len-1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
};
/**
* Call String.prototype.replace on the very right-most source snippet. Useful
* for trimming whitespace from the end of a source node, etc.
*
* @param aPattern The pattern to replace.
* @param aReplacement The thing to replace the pattern with.
*/
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
var lastChild = this.children[this.children.length - 1];
if (lastChild instanceof SourceNode) {
lastChild.replaceRight(aPattern, aReplacement);
}
else if (typeof lastChild === 'string') {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
}
else {
this.children.push(''.replace(aPattern, aReplacement));
}
return this;
};
/**
* Set the source content for a source file. This will be added to the SourceMapGenerator
* in the sourcesContent field.
*
* @param aSourceFile The filename of the source file
* @param aSourceContent The content of the source file
*/
SourceNode.prototype.setSourceContent =
function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
/**
* Walk over the tree of SourceNodes. The walking function is called for each
* source file content and is passed the filename and source content.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walkSourceContents =
function SourceNode_walkSourceContents(aFn) {
for (var i = 0, len = this.children.length; i < len; i++) {
if (this.children[i] instanceof SourceNode) {
this.children[i].walkSourceContents(aFn);
}
}
var sources = Object.keys(this.sourceContents);
for (var i = 0, len = sources.length; i < len; i++) {
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
}
};
/**
* Return the string representation of this source node. Walks over the tree
* and concatenates all the various snippets together to one string.
*/
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
this.walk(function (chunk) {
str += chunk;
});
return str;
};
/**
* Returns the string representation of this source node along with a source
* map.
*/
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function (chunk, original) {
generated.code += chunk;
if (original.source !== null
&& original.line !== null
&& original.column !== null) {
if(lastOriginalSource !== original.source
|| lastOriginalLine !== original.line
|| lastOriginalColumn !== original.column
|| lastOriginalName !== original.name) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({
generated: {
line: generated.line,
column: generated.column
}
});
lastOriginalSource = null;
sourceMappingActive = false;
}
chunk.split('').forEach(function (ch) {
if (ch === '\n') {
generated.line++;
generated.column = 0;
} else {
generated.column++;
}
});
});
this.walkSourceContents(function (sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
return { code: generated.code, map: map };
};
exports.SourceNode = SourceNode;
});
},{"./source-map-generator":17,"./util":19,"amdefine":20}],19:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/;
var dataUrlRegexp = /^data:.+\,.+/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[3],
host: match[4],
port: match[6],
path: match[7]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = aParsedUrl.scheme + "://";
if (aParsedUrl.auth) {
url += aParsedUrl.auth + "@"
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
function join(aRoot, aPath) {
var url;
if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) {
return aPath;
}
if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) {
url.path = aPath;
return urlGenerate(url);
}
return aRoot.replace(/\/$/, '') + '/' + aPath;
}
exports.join = join;
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
return '$' + aStr;
}
exports.toSetString = toSetString;
function fromSetString(aStr) {
return aStr.substr(1);
}
exports.fromSetString = fromSetString;
function relative(aRoot, aPath) {
aRoot = aRoot.replace(/\/$/, '');
var url = urlParse(aRoot);
if (aPath.charAt(0) == "/" && url && url.path == "/") {
return aPath.slice(1);
}
return aPath.indexOf(aRoot + '/') === 0
? aPath.substr(aRoot.length + 1)
: aPath;
}
exports.relative = relative;
function strcmp(aStr1, aStr2) {
var s1 = aStr1 || "";
var s2 = aStr2 || "";
return (s1 > s2) - (s1 < s2);
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp;
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp || onlyCompareOriginal) {
return cmp;
}
cmp = strcmp(mappingA.name, mappingB.name);
if (cmp) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
return mappingA.generatedColumn - mappingB.generatedColumn;
};
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings where the generated positions are
* compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
var cmp;
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp || onlyCompareGenerated) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
};
exports.compareByGeneratedPositions = compareByGeneratedPositions;
});
},{"amdefine":20}],20:[function(_dereq_,module,exports){
(function (process,__filename){
/** vim: et:ts=4:sw=4:sts=4
* @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/amdefine for details
*/
/*jslint node: true */
/*global module, process */
'use strict';
/**
* Creates a define for node.
* @param {Object} module the "module" object that is defined by Node for the
* current module.
* @param {Function} [requireFn]. Node's require function for the current module.
* It only needs to be passed in Node versions before 0.5, when module.require
* did not exist.
* @returns {Function} a define function that is usable for the current node
* module.
*/
function amdefine(module, requireFn) {
'use strict';
var defineCache = {},
loaderCache = {},
alreadyCalled = false,
path = _dereq_('path'),
makeRequire, stringRequire;
/**
* Trims the . and .. from an array of path segments.
* It will keep a leading path segment if a .. will become
* the first path segment, to help with module name lookups,
* which act like paths, but can be remapped. But the end result,
* all paths that use this function should look normalized.
* NOTE: this method MODIFIES the input array.
* @param {Array} ary the array of path segments.
*/
function trimDots(ary) {
var i, part;
for (i = 0; ary[i]; i+= 1) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
function normalize(name, baseName) {
var baseParts;
//Adjust any relative paths.
if (name && name.charAt(0) === '.') {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
baseParts = baseName.split('/');
baseParts = baseParts.slice(0, baseParts.length - 1);
baseParts = baseParts.concat(name.split('/'));
trimDots(baseParts);
name = baseParts.join('/');
}
}
return name;
}
/**
* Create the normalize() function passed to a loader plugin's
* normalize method.
*/
function makeNormalize(relName) {
return function (name) {
return normalize(name, relName);
};
}
function makeLoad(id) {
function load(value) {
loaderCache[id] = value;
}
load.fromText = function (id, text) {
//This one is difficult because the text can/probably uses
//define, and any relative paths and requires should be relative
//to that id was it would be found on disk. But this would require
//bootstrapping a module/require fairly deeply from node core.
//Not sure how best to go about that yet.
throw new Error('amdefine does not implement load.fromText');
};
return load;
}
makeRequire = function (systemRequire, exports, module, relId) {
function amdRequire(deps, callback) {
if (typeof deps === 'string') {
//Synchronous, single module require('')
return stringRequire(systemRequire, exports, module, deps, relId);
} else {
//Array of dependencies with a callback.
//Convert the dependencies to modules.
deps = deps.map(function (depName) {
return stringRequire(systemRequire, exports, module, depName, relId);
});
//Wait for next tick to call back the require call.
process.nextTick(function () {
callback.apply(null, deps);
});
}
}
amdRequire.toUrl = function (filePath) {
if (filePath.indexOf('.') === 0) {
return normalize(filePath, path.dirname(module.filename));
} else {
return filePath;
}
};
return amdRequire;
};
//Favor explicit value, passed in if the module wants to support Node 0.4.
requireFn = requireFn || function req() {
return module.require.apply(module, arguments);
};
function runFactory(id, deps, factory) {
var r, e, m, result;
if (id) {
e = loaderCache[id] = {};
m = {
id: id,
uri: __filename,
exports: e
};
r = makeRequire(requireFn, e, m, id);
} else {
//Only support one define call per file
if (alreadyCalled) {
throw new Error('amdefine with no module ID cannot be called more than once per file.');
}
alreadyCalled = true;
//Use the real variables from node
//Use module.exports for exports, since
//the exports in here is amdefine exports.
e = module.exports;
m = module;
r = makeRequire(requireFn, e, m, module.id);
}
//If there are dependencies, they are strings, so need
//to convert them to dependency values.
if (deps) {
deps = deps.map(function (depName) {
return r(depName);
});
}
//Call the factory with the right dependencies.
if (typeof factory === 'function') {
result = factory.apply(m.exports, deps);
} else {
result = factory;
}
if (result !== undefined) {
m.exports = result;
if (id) {
loaderCache[id] = m.exports;
}
}
}
stringRequire = function (systemRequire, exports, module, id, relId) {
//Split the ID by a ! so that
var index = id.indexOf('!'),
originalId = id,
prefix, plugin;
if (index === -1) {
id = normalize(id, relId);
//Straight module lookup. If it is one of the special dependencies,
//deal with it, otherwise, delegate to node.
if (id === 'require') {
return makeRequire(systemRequire, exports, module, relId);
} else if (id === 'exports') {
return exports;
} else if (id === 'module') {
return module;
} else if (loaderCache.hasOwnProperty(id)) {
return loaderCache[id];
} else if (defineCache[id]) {
runFactory.apply(null, defineCache[id]);
return loaderCache[id];
} else {
if(systemRequire) {
return systemRequire(originalId);
} else {
throw new Error('No module with ID: ' + id);
}
}
} else {
//There is a plugin in play.
prefix = id.substring(0, index);
id = id.substring(index + 1, id.length);
plugin = stringRequire(systemRequire, exports, module, prefix, relId);
if (plugin.normalize) {
id = plugin.normalize(id, makeNormalize(relId));
} else {
//Normalize the ID normally.
id = normalize(id, relId);
}
if (loaderCache[id]) {
return loaderCache[id];
} else {
plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
return loaderCache[id];
}
}
};
//Create a define function specific to the module asking for amdefine.
function define(id, deps, factory) {
if (Array.isArray(id)) {
factory = deps;
deps = id;
id = undefined;
} else if (typeof id !== 'string') {
factory = id;
id = deps = undefined;
}
if (deps && !Array.isArray(deps)) {
factory = deps;
deps = undefined;
}
if (!deps) {
deps = ['require', 'exports', 'module'];
}
//Set up properties for this module. If an ID, then use
//internal cache. If no ID, then use the external variables
//for this node module.
if (id) {
//Put the module in deep freeze until there is a
//require call for it.
defineCache[id] = [id, deps, factory];
} else {
runFactory(id, deps, factory);
}
}
//define.require, which has access to all the values in the
//cache. Useful for AMD modules that all have IDs in the file,
//but need to finally export a value to node based on one of those
//IDs.
define.require = function (id) {
if (loaderCache[id]) {
return loaderCache[id];
}
if (defineCache[id]) {
runFactory.apply(null, defineCache[id]);
return loaderCache[id];
}
};
define.amd = {};
return define;
}
module.exports = amdefine;
}).call(this,_dereq_('_process'),"/node_modules/jstransform/node_modules/source-map/node_modules/amdefine/amdefine.js")
},{"_process":8,"path":7}],21:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* 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.
*/
var docblockRe = /^\s*(\/\*\*(.|\r?\n)*?\*\/)/;
var ltrimRe = /^\s*/;
/**
* @param {String} contents
* @return {String}
*/
function extract(contents) {
var match = contents.match(docblockRe);
if (match) {
return match[0].replace(ltrimRe, '') || '';
}
return '';
}
var commentStartRe = /^\/\*\*?/;
var commentEndRe = /\*+\/$/;
var wsRe = /[\t ]+/g;
var stringStartRe = /(\r?\n|^) *\*/g;
var multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
var propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
/**
* @param {String} contents
* @return {Array}
*/
function parse(docblock) {
docblock = docblock
.replace(commentStartRe, '')
.replace(commentEndRe, '')
.replace(wsRe, ' ')
.replace(stringStartRe, '$1');
// Normalize multi-line directives
var prev = '';
while (prev != docblock) {
prev = docblock;
docblock = docblock.replace(multilineRe, "\n$1 $2\n");
}
docblock = docblock.trim();
var result = [];
var match;
while (match = propertyRe.exec(docblock)) {
result.push([match[1], match[2]]);
}
return result;
}
/**
* Same as parse but returns an object of prop: value instead of array of paris
* If a property appers more than once the last one will be returned
*
* @param {String} contents
* @return {Object}
*/
function parseAsObject(docblock) {
var pairs = parse(docblock);
var result = {};
for (var i = 0; i < pairs.length; i++) {
result[pairs[i][0]] = pairs[i][1];
}
return result;
}
exports.extract = extract;
exports.parse = parse;
exports.parseAsObject = parseAsObject;
},{}],22:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* 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.
*/
/*jslint node: true*/
"use strict";
var esprima = _dereq_('esprima-fb');
var utils = _dereq_('./utils');
var getBoundaryNode = utils.getBoundaryNode;
var declareIdentInScope = utils.declareIdentInLocalScope;
var initScopeMetadata = utils.initScopeMetadata;
var Syntax = esprima.Syntax;
/**
* @param {object} node
* @param {object} parentNode
* @return {boolean}
*/
function _nodeIsClosureScopeBoundary(node, parentNode) {
if (node.type === Syntax.Program) {
return true;
}
var parentIsFunction =
parentNode.type === Syntax.FunctionDeclaration
|| parentNode.type === Syntax.FunctionExpression
|| parentNode.type === Syntax.ArrowFunctionExpression;
var parentIsCurlylessArrowFunc =
parentNode.type === Syntax.ArrowFunctionExpression
&& node === parentNode.body;
return parentIsFunction
&& (node.type === Syntax.BlockStatement || parentIsCurlylessArrowFunc);
}
function _nodeIsBlockScopeBoundary(node, parentNode) {
if (node.type === Syntax.Program) {
return false;
}
return node.type === Syntax.BlockStatement
&& parentNode.type === Syntax.CatchClause;
}
/**
* @param {object} node
* @param {array} path
* @param {object} state
*/
function traverse(node, path, state) {
/*jshint -W004*/
// Create a scope stack entry if this is the first node we've encountered in
// its local scope
var startIndex = null;
var parentNode = path[0];
if (!Array.isArray(node) && state.localScope.parentNode !== parentNode) {
if (_nodeIsClosureScopeBoundary(node, parentNode)) {
var scopeIsStrict = state.scopeIsStrict;
if (!scopeIsStrict
&& (node.type === Syntax.BlockStatement
|| node.type === Syntax.Program)) {
scopeIsStrict =
node.body.length > 0
&& node.body[0].type === Syntax.ExpressionStatement
&& node.body[0].expression.type === Syntax.Literal
&& node.body[0].expression.value === 'use strict';
}
if (node.type === Syntax.Program) {
startIndex = state.g.buffer.length;
state = utils.updateState(state, {
scopeIsStrict: scopeIsStrict
});
} else {
startIndex = state.g.buffer.length + 1;
state = utils.updateState(state, {
localScope: {
parentNode: parentNode,
parentScope: state.localScope,
identifiers: {},
tempVarIndex: 0,
tempVars: []
},
scopeIsStrict: scopeIsStrict
});
// All functions have an implicit 'arguments' object in scope
declareIdentInScope('arguments', initScopeMetadata(node), state);
// Include function arg identifiers in the scope boundaries of the
// function
if (parentNode.params.length > 0) {
var param;
var metadata = initScopeMetadata(parentNode, path.slice(1), path[0]);
for (var i = 0; i < parentNode.params.length; i++) {
param = parentNode.params[i];
if (param.type === Syntax.Identifier) {
declareIdentInScope(param.name, metadata, state);
}
}
}
// Include rest arg identifiers in the scope boundaries of their
// functions
if (parentNode.rest) {
var metadata = initScopeMetadata(
parentNode,
path.slice(1),
path[0]
);
declareIdentInScope(parentNode.rest.name, metadata, state);
}
// Named FunctionExpressions scope their name within the body block of
// themselves only
if (parentNode.type === Syntax.FunctionExpression && parentNode.id) {
var metaData =
initScopeMetadata(parentNode, path.parentNodeslice, parentNode);
declareIdentInScope(parentNode.id.name, metaData, state);
}
}
// Traverse and find all local identifiers in this closure first to
// account for function/variable declaration hoisting
collectClosureIdentsAndTraverse(node, path, state);
}
if (_nodeIsBlockScopeBoundary(node, parentNode)) {
startIndex = state.g.buffer.length;
state = utils.updateState(state, {
localScope: {
parentNode: parentNode,
parentScope: state.localScope,
identifiers: {},
tempVarIndex: 0,
tempVars: []
}
});
if (parentNode.type === Syntax.CatchClause) {
var metadata = initScopeMetadata(
parentNode,
path.slice(1),
parentNode
);
declareIdentInScope(parentNode.param.name, metadata, state);
}
collectBlockIdentsAndTraverse(node, path, state);
}
}
// Only catchup() before and after traversing a child node
function traverser(node, path, state) {
node.range && utils.catchup(node.range[0], state);
traverse(node, path, state);
node.range && utils.catchup(node.range[1], state);
}
utils.analyzeAndTraverse(walker, traverser, node, path, state);
// Inject temp variables into the scope.
if (startIndex !== null) {
utils.injectTempVarDeclarations(state, startIndex);
}
}
function collectClosureIdentsAndTraverse(node, path, state) {
utils.analyzeAndTraverse(
visitLocalClosureIdentifiers,
collectClosureIdentsAndTraverse,
node,
path,
state
);
}
function collectBlockIdentsAndTraverse(node, path, state) {
utils.analyzeAndTraverse(
visitLocalBlockIdentifiers,
collectBlockIdentsAndTraverse,
node,
path,
state
);
}
function visitLocalClosureIdentifiers(node, path, state) {
var metaData;
switch (node.type) {
case Syntax.ArrowFunctionExpression:
case Syntax.FunctionExpression:
// Function expressions don't get their names (if there is one) added to
// the closure scope they're defined in
return false;
case Syntax.ClassDeclaration:
case Syntax.ClassExpression:
case Syntax.FunctionDeclaration:
if (node.id) {
metaData = initScopeMetadata(getBoundaryNode(path), path.slice(), node);
declareIdentInScope(node.id.name, metaData, state);
}
return false;
case Syntax.VariableDeclarator:
// Variables have function-local scope
if (path[0].kind === 'var') {
metaData = initScopeMetadata(getBoundaryNode(path), path.slice(), node);
declareIdentInScope(node.id.name, metaData, state);
}
break;
}
}
function visitLocalBlockIdentifiers(node, path, state) {
// TODO: Support 'let' here...maybe...one day...or something...
if (node.type === Syntax.CatchClause) {
return false;
}
}
function walker(node, path, state) {
var visitors = state.g.visitors;
for (var i = 0; i < visitors.length; i++) {
if (visitors[i].test(node, path, state)) {
return visitors[i](traverse, node, path, state);
}
}
}
var _astCache = {};
function getAstForSource(source, options) {
if (_astCache[source] && !options.disableAstCache) {
return _astCache[source];
}
var ast = esprima.parse(source, {
comment: true,
loc: true,
range: true,
sourceType: options.sourceType
});
if (!options.disableAstCache) {
_astCache[source] = ast;
}
return ast;
}
/**
* Applies all available transformations to the source
* @param {array} visitors
* @param {string} source
* @param {?object} options
* @return {object}
*/
function transform(visitors, source, options) {
options = options || {};
var ast;
try {
ast = getAstForSource(source, options);
} catch (e) {
e.message = 'Parse Error: ' + e.message;
throw e;
}
var state = utils.createState(source, ast, options);
state.g.visitors = visitors;
if (options.sourceMap) {
var SourceMapGenerator = _dereq_('source-map').SourceMapGenerator;
state.g.sourceMap = new SourceMapGenerator({file: options.filename || 'transformed.js'});
}
traverse(ast, [], state);
utils.catchup(source.length, state);
var ret = {code: state.g.buffer, extra: state.g.extra};
if (options.sourceMap) {
ret.sourceMap = state.g.sourceMap;
ret.sourceMapFilename = options.filename || 'source.js';
}
return ret;
}
exports.transform = transform;
exports.Syntax = Syntax;
},{"./utils":23,"esprima-fb":9,"source-map":11}],23:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* 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.
*/
/*jslint node: true*/
var Syntax = _dereq_('esprima-fb').Syntax;
var leadingIndentRegexp = /(^|\n)( {2}|\t)/g;
var nonWhiteRegexp = /(\S)/g;
/**
* A `state` object represents the state of the parser. It has "local" and
* "global" parts. Global contains parser position, source, etc. Local contains
* scope based properties like current class name. State should contain all the
* info required for transformation. It's the only mandatory object that is
* being passed to every function in transform chain.
*
* @param {string} source
* @param {object} transformOptions
* @return {object}
*/
function createState(source, rootNode, transformOptions) {
return {
/**
* A tree representing the current local scope (and its lexical scope chain)
* Useful for tracking identifiers from parent scopes, etc.
* @type {Object}
*/
localScope: {
parentNode: rootNode,
parentScope: null,
identifiers: {},
tempVarIndex: 0,
tempVars: []
},
/**
* The name (and, if applicable, expression) of the super class
* @type {Object}
*/
superClass: null,
/**
* The namespace to use when munging identifiers
* @type {String}
*/
mungeNamespace: '',
/**
* Ref to the node for the current MethodDefinition
* @type {Object}
*/
methodNode: null,
/**
* Ref to the node for the FunctionExpression of the enclosing
* MethodDefinition
* @type {Object}
*/
methodFuncNode: null,
/**
* Name of the enclosing class
* @type {String}
*/
className: null,
/**
* Whether we're currently within a `strict` scope
* @type {Bool}
*/
scopeIsStrict: null,
/**
* Indentation offset
* @type {Number}
*/
indentBy: 0,
/**
* Global state (not affected by updateState)
* @type {Object}
*/
g: {
/**
* A set of general options that transformations can consider while doing
* a transformation:
*
* - minify
* Specifies that transformation steps should do their best to minify
* the output source when possible. This is useful for places where
* minification optimizations are possible with higher-level context
* info than what jsxmin can provide.
*
* For example, the ES6 class transform will minify munged private
* variables if this flag is set.
*/
opts: transformOptions,
/**
* Current position in the source code
* @type {Number}
*/
position: 0,
/**
* Auxiliary data to be returned by transforms
* @type {Object}
*/
extra: {},
/**
* Buffer containing the result
* @type {String}
*/
buffer: '',
/**
* Source that is being transformed
* @type {String}
*/
source: source,
/**
* Cached parsed docblock (see getDocblock)
* @type {object}
*/
docblock: null,
/**
* Whether the thing was used
* @type {Boolean}
*/
tagNamespaceUsed: false,
/**
* If using bolt xjs transformation
* @type {Boolean}
*/
isBolt: undefined,
/**
* Whether to record source map (expensive) or not
* @type {SourceMapGenerator|null}
*/
sourceMap: null,
/**
* Filename of the file being processed. Will be returned as a source
* attribute in the source map
*/
sourceMapFilename: 'source.js',
/**
* Only when source map is used: last line in the source for which
* source map was generated
* @type {Number}
*/
sourceLine: 1,
/**
* Only when source map is used: last line in the buffer for which
* source map was generated
* @type {Number}
*/
bufferLine: 1,
/**
* The top-level Program AST for the original file.
*/
originalProgramAST: null,
sourceColumn: 0,
bufferColumn: 0
}
};
}
/**
* Updates a copy of a given state with "update" and returns an updated state.
*
* @param {object} state
* @param {object} update
* @return {object}
*/
function updateState(state, update) {
var ret = Object.create(state);
Object.keys(update).forEach(function(updatedKey) {
ret[updatedKey] = update[updatedKey];
});
return ret;
}
/**
* Given a state fill the resulting buffer from the original source up to
* the end
*
* @param {number} end
* @param {object} state
* @param {?function} contentTransformer Optional callback to transform newly
* added content.
*/
function catchup(end, state, contentTransformer) {
if (end < state.g.position) {
// cannot move backwards
return;
}
var source = state.g.source.substring(state.g.position, end);
var transformed = updateIndent(source, state);
if (state.g.sourceMap && transformed) {
// record where we are
state.g.sourceMap.addMapping({
generated: { line: state.g.bufferLine, column: state.g.bufferColumn },
original: { line: state.g.sourceLine, column: state.g.sourceColumn },
source: state.g.sourceMapFilename
});
// record line breaks in transformed source
var sourceLines = source.split('\n');
var transformedLines = transformed.split('\n');
// Add line break mappings between last known mapping and the end of the
// added piece. So for the code piece
// (foo, bar);
// > var x = 2;
// > var b = 3;
// var c =
// only add lines marked with ">": 2, 3.
for (var i = 1; i < sourceLines.length - 1; i++) {
state.g.sourceMap.addMapping({
generated: { line: state.g.bufferLine, column: 0 },
original: { line: state.g.sourceLine, column: 0 },
source: state.g.sourceMapFilename
});
state.g.sourceLine++;
state.g.bufferLine++;
}
// offset for the last piece
if (sourceLines.length > 1) {
state.g.sourceLine++;
state.g.bufferLine++;
state.g.sourceColumn = 0;
state.g.bufferColumn = 0;
}
state.g.sourceColumn += sourceLines[sourceLines.length - 1].length;
state.g.bufferColumn +=
transformedLines[transformedLines.length - 1].length;
}
state.g.buffer +=
contentTransformer ? contentTransformer(transformed) : transformed;
state.g.position = end;
}
/**
* Returns original source for an AST node.
* @param {object} node
* @param {object} state
* @return {string}
*/
function getNodeSourceText(node, state) {
return state.g.source.substring(node.range[0], node.range[1]);
}
function _replaceNonWhite(value) {
return value.replace(nonWhiteRegexp, ' ');
}
/**
* Removes all non-whitespace characters
*/
function _stripNonWhite(value) {
return value.replace(nonWhiteRegexp, '');
}
/**
* Finds the position of the next instance of the specified syntactic char in
* the pending source.
*
* NOTE: This will skip instances of the specified char if they sit inside a
* comment body.
*
* NOTE: This function also assumes that the buffer's current position is not
* already within a comment or a string. This is rarely the case since all
* of the buffer-advancement utility methods tend to be used on syntactic
* nodes' range values -- but it's a small gotcha that's worth mentioning.
*/
function getNextSyntacticCharOffset(char, state) {
var pendingSource = state.g.source.substring(state.g.position);
var pendingSourceLines = pendingSource.split('\n');
var charOffset = 0;
var line;
var withinBlockComment = false;
var withinString = false;
lineLoop: while ((line = pendingSourceLines.shift()) !== undefined) {
var lineEndPos = charOffset + line.length;
charLoop: for (; charOffset < lineEndPos; charOffset++) {
var currChar = pendingSource[charOffset];
if (currChar === '"' || currChar === '\'') {
withinString = !withinString;
continue charLoop;
} else if (withinString) {
continue charLoop;
} else if (charOffset + 1 < lineEndPos) {
var nextTwoChars = currChar + line[charOffset + 1];
if (nextTwoChars === '//') {
charOffset = lineEndPos + 1;
continue lineLoop;
} else if (nextTwoChars === '/*') {
withinBlockComment = true;
charOffset += 1;
continue charLoop;
} else if (nextTwoChars === '*/') {
withinBlockComment = false;
charOffset += 1;
continue charLoop;
}
}
if (!withinBlockComment && currChar === char) {
return charOffset + state.g.position;
}
}
// Account for '\n'
charOffset++;
withinString = false;
}
throw new Error('`' + char + '` not found!');
}
/**
* Catches up as `catchup` but replaces non-whitespace chars with spaces.
*/
function catchupWhiteOut(end, state) {
catchup(end, state, _replaceNonWhite);
}
/**
* Catches up as `catchup` but removes all non-whitespace characters.
*/
function catchupWhiteSpace(end, state) {
catchup(end, state, _stripNonWhite);
}
/**
* Removes all non-newline characters
*/
var reNonNewline = /[^\n]/g;
function stripNonNewline(value) {
return value.replace(reNonNewline, function() {
return '';
});
}
/**
* Catches up as `catchup` but removes all non-newline characters.
*
* Equivalent to appending as many newlines as there are in the original source
* between the current position and `end`.
*/
function catchupNewlines(end, state) {
catchup(end, state, stripNonNewline);
}
/**
* Same as catchup but does not touch the buffer
*
* @param {number} end
* @param {object} state
*/
function move(end, state) {
// move the internal cursors
if (state.g.sourceMap) {
if (end < state.g.position) {
state.g.position = 0;
state.g.sourceLine = 1;
state.g.sourceColumn = 0;
}
var source = state.g.source.substring(state.g.position, end);
var sourceLines = source.split('\n');
if (sourceLines.length > 1) {
state.g.sourceLine += sourceLines.length - 1;
state.g.sourceColumn = 0;
}
state.g.sourceColumn += sourceLines[sourceLines.length - 1].length;
}
state.g.position = end;
}
/**
* Appends a string of text to the buffer
*
* @param {string} str
* @param {object} state
*/
function append(str, state) {
if (state.g.sourceMap && str) {
state.g.sourceMap.addMapping({
generated: { line: state.g.bufferLine, column: state.g.bufferColumn },
original: { line: state.g.sourceLine, column: state.g.sourceColumn },
source: state.g.sourceMapFilename
});
var transformedLines = str.split('\n');
if (transformedLines.length > 1) {
state.g.bufferLine += transformedLines.length - 1;
state.g.bufferColumn = 0;
}
state.g.bufferColumn +=
transformedLines[transformedLines.length - 1].length;
}
state.g.buffer += str;
}
/**
* Update indent using state.indentBy property. Indent is measured in
* double spaces. Updates a single line only.
*
* @param {string} str
* @param {object} state
* @return {string}
*/
function updateIndent(str, state) {
/*jshint -W004*/
var indentBy = state.indentBy;
if (indentBy < 0) {
for (var i = 0; i < -indentBy; i++) {
str = str.replace(leadingIndentRegexp, '$1');
}
} else {
for (var i = 0; i < indentBy; i++) {
str = str.replace(leadingIndentRegexp, '$1$2$2');
}
}
return str;
}
/**
* Calculates indent from the beginning of the line until "start" or the first
* character before start.
* @example
* " foo.bar()"
* ^
* start
* indent will be " "
*
* @param {number} start
* @param {object} state
* @return {string}
*/
function indentBefore(start, state) {
var end = start;
start = start - 1;
while (start > 0 && state.g.source[start] != '\n') {
if (!state.g.source[start].match(/[ \t]/)) {
end = start;
}
start--;
}
return state.g.source.substring(start + 1, end);
}
function getDocblock(state) {
if (!state.g.docblock) {
var docblock = _dereq_('./docblock');
state.g.docblock =
docblock.parseAsObject(docblock.extract(state.g.source));
}
return state.g.docblock;
}
function identWithinLexicalScope(identName, state, stopBeforeNode) {
var currScope = state.localScope;
while (currScope) {
if (currScope.identifiers[identName] !== undefined) {
return true;
}
if (stopBeforeNode && currScope.parentNode === stopBeforeNode) {
break;
}
currScope = currScope.parentScope;
}
return false;
}
function identInLocalScope(identName, state) {
return state.localScope.identifiers[identName] !== undefined;
}
/**
* @param {object} boundaryNode
* @param {?array} path
* @return {?object} node
*/
function initScopeMetadata(boundaryNode, path, node) {
return {
boundaryNode: boundaryNode,
bindingPath: path,
bindingNode: node
};
}
function declareIdentInLocalScope(identName, metaData, state) {
state.localScope.identifiers[identName] = {
boundaryNode: metaData.boundaryNode,
path: metaData.bindingPath,
node: metaData.bindingNode,
state: Object.create(state)
};
}
function getLexicalBindingMetadata(identName, state) {
var currScope = state.localScope;
while (currScope) {
if (currScope.identifiers[identName] !== undefined) {
return currScope.identifiers[identName];
}
currScope = currScope.parentScope;
}
}
function getLocalBindingMetadata(identName, state) {
return state.localScope.identifiers[identName];
}
/**
* Apply the given analyzer function to the current node. If the analyzer
* doesn't return false, traverse each child of the current node using the given
* traverser function.
*
* @param {function} analyzer
* @param {function} traverser
* @param {object} node
* @param {array} path
* @param {object} state
*/
function analyzeAndTraverse(analyzer, traverser, node, path, state) {
if (node.type) {
if (analyzer(node, path, state) === false) {
return;
}
path.unshift(node);
}
getOrderedChildren(node).forEach(function(child) {
traverser(child, path, state);
});
node.type && path.shift();
}
/**
* It is crucial that we traverse in order, or else catchup() on a later
* node that is processed out of order can move the buffer past a node
* that we haven't handled yet, preventing us from modifying that node.
*
* This can happen when a node has multiple properties containing children.
* For example, XJSElement nodes have `openingElement`, `closingElement` and
* `children`. If we traverse `openingElement`, then `closingElement`, then
* when we get to `children`, the buffer has already caught up to the end of
* the closing element, after the children.
*
* This is basically a Schwartzian transform. Collects an array of children,
* each one represented as [child, startIndex]; sorts the array by start
* index; then traverses the children in that order.
*/
function getOrderedChildren(node) {
var queue = [];
for (var key in node) {
if (node.hasOwnProperty(key)) {
enqueueNodeWithStartIndex(queue, node[key]);
}
}
queue.sort(function(a, b) { return a[1] - b[1]; });
return queue.map(function(pair) { return pair[0]; });
}
/**
* Helper function for analyzeAndTraverse which queues up all of the children
* of the given node.
*
* Children can also be found in arrays, so we basically want to merge all of
* those arrays together so we can sort them and then traverse the children
* in order.
*
* One example is the Program node. It contains `body` and `comments`, both
* arrays. Lexographically, comments are interspersed throughout the body
* nodes, but esprima's AST groups them together.
*/
function enqueueNodeWithStartIndex(queue, node) {
if (typeof node !== 'object' || node === null) {
return;
}
if (node.range) {
queue.push([node, node.range[0]]);
} else if (Array.isArray(node)) {
for (var ii = 0; ii < node.length; ii++) {
enqueueNodeWithStartIndex(queue, node[ii]);
}
}
}
/**
* Checks whether a node or any of its sub-nodes contains
* a syntactic construct of the passed type.
* @param {object} node - AST node to test.
* @param {string} type - node type to lookup.
*/
function containsChildOfType(node, type) {
return containsChildMatching(node, function(node) {
return node.type === type;
});
}
function containsChildMatching(node, matcher) {
var foundMatchingChild = false;
function nodeTypeAnalyzer(node) {
if (matcher(node) === true) {
foundMatchingChild = true;
return false;
}
}
function nodeTypeTraverser(child, path, state) {
if (!foundMatchingChild) {
foundMatchingChild = containsChildMatching(child, matcher);
}
}
analyzeAndTraverse(
nodeTypeAnalyzer,
nodeTypeTraverser,
node,
[]
);
return foundMatchingChild;
}
var scopeTypes = {};
scopeTypes[Syntax.ArrowFunctionExpression] = true;
scopeTypes[Syntax.FunctionExpression] = true;
scopeTypes[Syntax.FunctionDeclaration] = true;
scopeTypes[Syntax.Program] = true;
function getBoundaryNode(path) {
for (var ii = 0; ii < path.length; ++ii) {
if (scopeTypes[path[ii].type]) {
return path[ii];
}
}
throw new Error(
'Expected to find a node with one of the following types in path:\n' +
JSON.stringify(Object.keys(scopeTypes))
);
}
function getTempVar(tempVarIndex) {
return '$__' + tempVarIndex;
}
function injectTempVar(state) {
var tempVar = '$__' + (state.localScope.tempVarIndex++);
state.localScope.tempVars.push(tempVar);
return tempVar;
}
function injectTempVarDeclarations(state, index) {
if (state.localScope.tempVars.length) {
state.g.buffer =
state.g.buffer.slice(0, index) +
'var ' + state.localScope.tempVars.join(', ') + ';' +
state.g.buffer.slice(index);
state.localScope.tempVars = [];
}
}
exports.analyzeAndTraverse = analyzeAndTraverse;
exports.append = append;
exports.catchup = catchup;
exports.catchupNewlines = catchupNewlines;
exports.catchupWhiteOut = catchupWhiteOut;
exports.catchupWhiteSpace = catchupWhiteSpace;
exports.containsChildMatching = containsChildMatching;
exports.containsChildOfType = containsChildOfType;
exports.createState = createState;
exports.declareIdentInLocalScope = declareIdentInLocalScope;
exports.getBoundaryNode = getBoundaryNode;
exports.getDocblock = getDocblock;
exports.getLexicalBindingMetadata = getLexicalBindingMetadata;
exports.getLocalBindingMetadata = getLocalBindingMetadata;
exports.getNextSyntacticCharOffset = getNextSyntacticCharOffset;
exports.getNodeSourceText = getNodeSourceText;
exports.getOrderedChildren = getOrderedChildren;
exports.getTempVar = getTempVar;
exports.identInLocalScope = identInLocalScope;
exports.identWithinLexicalScope = identWithinLexicalScope;
exports.indentBefore = indentBefore;
exports.initScopeMetadata = initScopeMetadata;
exports.injectTempVar = injectTempVar;
exports.injectTempVarDeclarations = injectTempVarDeclarations;
exports.move = move;
exports.scopeTypes = scopeTypes;
exports.updateIndent = updateIndent;
exports.updateState = updateState;
},{"./docblock":21,"esprima-fb":9}],24:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* 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.
*/
/*global exports:true*/
/**
* Desugars ES6 Arrow functions to ES3 function expressions.
* If the function contains `this` expression -- automatically
* binds the function to current value of `this`.
*
* Single parameter, simple expression:
*
* [1, 2, 3].map(x => x * x);
*
* [1, 2, 3].map(function(x) { return x * x; });
*
* Several parameters, complex block:
*
* this.users.forEach((user, idx) => {
* return this.isActive(idx) && this.send(user);
* });
*
* this.users.forEach(function(user, idx) {
* return this.isActive(idx) && this.send(user);
* }.bind(this));
*
*/
var restParamVisitors = _dereq_('./es6-rest-param-visitors');
var destructuringVisitors = _dereq_('./es6-destructuring-visitors');
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
/**
* @public
*/
function visitArrowFunction(traverse, node, path, state) {
var notInExpression = (path[0].type === Syntax.ExpressionStatement);
// Wrap a function into a grouping operator, if it's not
// in the expression position.
if (notInExpression) {
utils.append('(', state);
}
utils.append('function', state);
renderParams(traverse, node, path, state);
// Skip arrow.
utils.catchupWhiteSpace(node.body.range[0], state);
var renderBody = node.body.type == Syntax.BlockStatement
? renderStatementBody
: renderExpressionBody;
path.unshift(node);
renderBody(traverse, node, path, state);
path.shift();
// Bind the function only if `this` value is used
// inside it or inside any sub-expression.
var containsBindingSyntax =
utils.containsChildMatching(node.body, function(node) {
return node.type === Syntax.ThisExpression
|| (node.type === Syntax.Identifier
&& node.name === "super");
});
if (containsBindingSyntax) {
utils.append('.bind(this)', state);
}
utils.catchupWhiteSpace(node.range[1], state);
// Close wrapper if not in the expression.
if (notInExpression) {
utils.append(')', state);
}
return false;
}
function renderParams(traverse, node, path, state) {
// To preserve inline typechecking directives, we
// distinguish between parens-free and paranthesized single param.
if (isParensFreeSingleParam(node, state) || !node.params.length) {
utils.append('(', state);
}
if (node.params.length !== 0) {
path.unshift(node);
traverse(node.params, path, state);
path.unshift();
}
utils.append(')', state);
}
function isParensFreeSingleParam(node, state) {
return node.params.length === 1 &&
state.g.source[state.g.position] !== '(';
}
function renderExpressionBody(traverse, node, path, state) {
// Wrap simple expression bodies into a block
// with explicit return statement.
utils.append('{', state);
// Special handling of rest param.
if (node.rest) {
utils.append(
restParamVisitors.renderRestParamSetup(node, state),
state
);
}
// Special handling of destructured params.
destructuringVisitors.renderDestructuredComponents(
node,
utils.updateState(state, {
localScope: {
parentNode: state.parentNode,
parentScope: state.parentScope,
identifiers: state.identifiers,
tempVarIndex: 0
}
})
);
utils.append('return ', state);
renderStatementBody(traverse, node, path, state);
utils.append(';}', state);
}
function renderStatementBody(traverse, node, path, state) {
traverse(node.body, path, state);
utils.catchup(node.body.range[1], state);
}
visitArrowFunction.test = function(node, path, state) {
return node.type === Syntax.ArrowFunctionExpression;
};
exports.visitorList = [
visitArrowFunction
];
},{"../src/utils":23,"./es6-destructuring-visitors":27,"./es6-rest-param-visitors":30,"esprima-fb":9}],25:[function(_dereq_,module,exports){
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*/
/*global exports:true*/
/**
* Implements ES6 call spread.
*
* instance.method(a, b, c, ...d)
*
* instance.method.apply(instance, [a, b, c].concat(d))
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
function process(traverse, node, path, state) {
utils.move(node.range[0], state);
traverse(node, path, state);
utils.catchup(node.range[1], state);
}
function visitCallSpread(traverse, node, path, state) {
utils.catchup(node.range[0], state);
if (node.type === Syntax.NewExpression) {
// Input = new Set(1, 2, ...list)
// Output = new (Function.prototype.bind.apply(Set, [null, 1, 2].concat(list)))
utils.append('new (Function.prototype.bind.apply(', state);
process(traverse, node.callee, path, state);
} else if (node.callee.type === Syntax.MemberExpression) {
// Input = get().fn(1, 2, ...more)
// Output = (_ = get()).fn.apply(_, [1, 2].apply(more))
var tempVar = utils.injectTempVar(state);
utils.append('(' + tempVar + ' = ', state);
process(traverse, node.callee.object, path, state);
utils.append(')', state);
if (node.callee.property.type === Syntax.Identifier) {
utils.append('.', state);
process(traverse, node.callee.property, path, state);
} else {
utils.append('[', state);
process(traverse, node.callee.property, path, state);
utils.append(']', state);
}
utils.append('.apply(' + tempVar, state);
} else {
// Input = max(1, 2, ...list)
// Output = max.apply(null, [1, 2].concat(list))
var needsToBeWrappedInParenthesis =
node.callee.type === Syntax.FunctionDeclaration ||
node.callee.type === Syntax.FunctionExpression;
if (needsToBeWrappedInParenthesis) {
utils.append('(', state);
}
process(traverse, node.callee, path, state);
if (needsToBeWrappedInParenthesis) {
utils.append(')', state);
}
utils.append('.apply(null', state);
}
utils.append(', ', state);
var args = node.arguments.slice();
var spread = args.pop();
if (args.length || node.type === Syntax.NewExpression) {
utils.append('[', state);
if (node.type === Syntax.NewExpression) {
utils.append('null' + (args.length ? ', ' : ''), state);
}
while (args.length) {
var arg = args.shift();
utils.move(arg.range[0], state);
traverse(arg, path, state);
if (args.length) {
utils.catchup(args[0].range[0], state);
} else {
utils.catchup(arg.range[1], state);
}
}
utils.append('].concat(', state);
process(traverse, spread.argument, path, state);
utils.append(')', state);
} else {
process(traverse, spread.argument, path, state);
}
utils.append(node.type === Syntax.NewExpression ? '))' : ')', state);
utils.move(node.range[1], state);
return false;
}
visitCallSpread.test = function(node, path, state) {
return (
(
node.type === Syntax.CallExpression ||
node.type === Syntax.NewExpression
) &&
node.arguments.length > 0 &&
node.arguments[node.arguments.length - 1].type === Syntax.SpreadElement
);
};
exports.visitorList = [
visitCallSpread
];
},{"../src/utils":23,"esprima-fb":9}],26:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* 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.
*/
/*jslint node:true*/
/**
* @typechecks
*/
'use strict';
var base62 = _dereq_('base62');
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
var reservedWordsHelper = _dereq_('./reserved-words-helper');
var declareIdentInLocalScope = utils.declareIdentInLocalScope;
var initScopeMetadata = utils.initScopeMetadata;
var SUPER_PROTO_IDENT_PREFIX = '____SuperProtoOf';
var _anonClassUUIDCounter = 0;
var _mungedSymbolMaps = {};
function resetSymbols() {
_anonClassUUIDCounter = 0;
_mungedSymbolMaps = {};
}
/**
* Used to generate a unique class for use with code-gens for anonymous class
* expressions.
*
* @param {object} state
* @return {string}
*/
function _generateAnonymousClassName(state) {
var mungeNamespace = state.mungeNamespace || '';
return '____Class' + mungeNamespace + base62.encode(_anonClassUUIDCounter++);
}
/**
* Given an identifier name, munge it using the current state's mungeNamespace.
*
* @param {string} identName
* @param {object} state
* @return {string}
*/
function _getMungedName(identName, state) {
var mungeNamespace = state.mungeNamespace;
var shouldMinify = state.g.opts.minify;
if (shouldMinify) {
if (!_mungedSymbolMaps[mungeNamespace]) {
_mungedSymbolMaps[mungeNamespace] = {
symbolMap: {},
identUUIDCounter: 0
};
}
var symbolMap = _mungedSymbolMaps[mungeNamespace].symbolMap;
if (!symbolMap[identName]) {
symbolMap[identName] =
base62.encode(_mungedSymbolMaps[mungeNamespace].identUUIDCounter++);
}
identName = symbolMap[identName];
}
return '$' + mungeNamespace + identName;
}
/**
* Extracts super class information from a class node.
*
* Information includes name of the super class and/or the expression string
* (if extending from an expression)
*
* @param {object} node
* @param {object} state
* @return {object}
*/
function _getSuperClassInfo(node, state) {
var ret = {
name: null,
expression: null
};
if (node.superClass) {
if (node.superClass.type === Syntax.Identifier) {
ret.name = node.superClass.name;
} else {
// Extension from an expression
ret.name = _generateAnonymousClassName(state);
ret.expression = state.g.source.substring(
node.superClass.range[0],
node.superClass.range[1]
);
}
}
return ret;
}
/**
* Used with .filter() to find the constructor method in a list of
* MethodDefinition nodes.
*
* @param {object} classElement
* @return {boolean}
*/
function _isConstructorMethod(classElement) {
return classElement.type === Syntax.MethodDefinition &&
classElement.key.type === Syntax.Identifier &&
classElement.key.name === 'constructor';
}
/**
* @param {object} node
* @param {object} state
* @return {boolean}
*/
function _shouldMungeIdentifier(node, state) {
return (
!!state.methodFuncNode &&
!utils.getDocblock(state).hasOwnProperty('preventMunge') &&
/^_(?!_)/.test(node.name)
);
}
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassMethod(traverse, node, path, state) {
if (!state.g.opts.es5 && (node.kind === 'get' || node.kind === 'set')) {
throw new Error(
'This transform does not support ' + node.kind + 'ter methods for ES6 ' +
'classes. (line: ' + node.loc.start.line + ', col: ' +
node.loc.start.column + ')'
);
}
state = utils.updateState(state, {
methodNode: node
});
utils.catchup(node.range[0], state);
path.unshift(node);
traverse(node.value, path, state);
path.shift();
return false;
}
visitClassMethod.test = function(node, path, state) {
return node.type === Syntax.MethodDefinition;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassFunctionExpression(traverse, node, path, state) {
var methodNode = path[0];
var isGetter = methodNode.kind === 'get';
var isSetter = methodNode.kind === 'set';
state = utils.updateState(state, {
methodFuncNode: node
});
if (methodNode.key.name === 'constructor') {
utils.append('function ' + state.className, state);
} else {
var methodAccessorComputed = false;
var methodAccessor;
var prototypeOrStatic = methodNode["static"] ? '' : '.prototype';
var objectAccessor = state.className + prototypeOrStatic;
if (methodNode.key.type === Syntax.Identifier) {
// foo() {}
methodAccessor = methodNode.key.name;
if (_shouldMungeIdentifier(methodNode.key, state)) {
methodAccessor = _getMungedName(methodAccessor, state);
}
if (isGetter || isSetter) {
methodAccessor = JSON.stringify(methodAccessor);
} else if (reservedWordsHelper.isReservedWord(methodAccessor)) {
methodAccessorComputed = true;
methodAccessor = JSON.stringify(methodAccessor);
}
} else if (methodNode.key.type === Syntax.Literal) {
// 'foo bar'() {} | get 'foo bar'() {} | set 'foo bar'() {}
methodAccessor = JSON.stringify(methodNode.key.value);
methodAccessorComputed = true;
}
if (isSetter || isGetter) {
utils.append(
'Object.defineProperty(' +
objectAccessor + ',' +
methodAccessor + ',' +
'{configurable:true,' +
methodNode.kind + ':function',
state
);
} else {
if (state.g.opts.es3) {
if (methodAccessorComputed) {
methodAccessor = '[' + methodAccessor + ']';
} else {
methodAccessor = '.' + methodAccessor;
}
utils.append(
objectAccessor +
methodAccessor + '=function' + (node.generator ? '*' : ''),
state
);
} else {
if (!methodAccessorComputed) {
methodAccessor = JSON.stringify(methodAccessor);
}
utils.append(
'Object.defineProperty(' +
objectAccessor + ',' +
methodAccessor + ',' +
'{writable:true,configurable:true,' +
'value:function' + (node.generator ? '*' : ''),
state
);
}
}
}
utils.move(methodNode.key.range[1], state);
utils.append('(', state);
var params = node.params;
if (params.length > 0) {
utils.catchupNewlines(params[0].range[0], state);
for (var i = 0; i < params.length; i++) {
utils.catchup(node.params[i].range[0], state);
path.unshift(node);
traverse(params[i], path, state);
path.shift();
}
}
var closingParenPosition = utils.getNextSyntacticCharOffset(')', state);
utils.catchupWhiteSpace(closingParenPosition, state);
var openingBracketPosition = utils.getNextSyntacticCharOffset('{', state);
utils.catchup(openingBracketPosition + 1, state);
if (!state.scopeIsStrict) {
utils.append('"use strict";', state);
state = utils.updateState(state, {
scopeIsStrict: true
});
}
utils.move(node.body.range[0] + '{'.length, state);
path.unshift(node);
traverse(node.body, path, state);
path.shift();
utils.catchup(node.body.range[1], state);
if (methodNode.key.name !== 'constructor') {
if (isGetter || isSetter || !state.g.opts.es3) {
utils.append('})', state);
}
utils.append(';', state);
}
return false;
}
visitClassFunctionExpression.test = function(node, path, state) {
return node.type === Syntax.FunctionExpression
&& path[0].type === Syntax.MethodDefinition;
};
function visitClassMethodParam(traverse, node, path, state) {
var paramName = node.name;
if (_shouldMungeIdentifier(node, state)) {
paramName = _getMungedName(node.name, state);
}
utils.append(paramName, state);
utils.move(node.range[1], state);
}
visitClassMethodParam.test = function(node, path, state) {
if (!path[0] || !path[1]) {
return;
}
var parentFuncExpr = path[0];
var parentClassMethod = path[1];
return parentFuncExpr.type === Syntax.FunctionExpression
&& parentClassMethod.type === Syntax.MethodDefinition
&& node.type === Syntax.Identifier;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function _renderClassBody(traverse, node, path, state) {
var className = state.className;
var superClass = state.superClass;
// Set up prototype of constructor on same line as `extends` for line-number
// preservation. This relies on function-hoisting if a constructor function is
// defined in the class body.
if (superClass.name) {
// If the super class is an expression, we need to memoize the output of the
// expression into the generated class name variable and use that to refer
// to the super class going forward. Example:
//
// class Foo extends mixin(Bar, Baz) {}
// --transforms to--
// function Foo() {} var ____Class0Blah = mixin(Bar, Baz);
if (superClass.expression !== null) {
utils.append(
'var ' + superClass.name + '=' + superClass.expression + ';',
state
);
}
var keyName = superClass.name + '____Key';
var keyNameDeclarator = '';
if (!utils.identWithinLexicalScope(keyName, state)) {
keyNameDeclarator = 'var ';
declareIdentInLocalScope(keyName, initScopeMetadata(node), state);
}
utils.append(
'for(' + keyNameDeclarator + keyName + ' in ' + superClass.name + '){' +
'if(' + superClass.name + '.hasOwnProperty(' + keyName + ')){' +
className + '[' + keyName + ']=' +
superClass.name + '[' + keyName + '];' +
'}' +
'}',
state
);
var superProtoIdentStr = SUPER_PROTO_IDENT_PREFIX + superClass.name;
if (!utils.identWithinLexicalScope(superProtoIdentStr, state)) {
utils.append(
'var ' + superProtoIdentStr + '=' + superClass.name + '===null?' +
'null:' + superClass.name + '.prototype;',
state
);
declareIdentInLocalScope(superProtoIdentStr, initScopeMetadata(node), state);
}
utils.append(
className + '.prototype=Object.create(' + superProtoIdentStr + ');',
state
);
utils.append(
className + '.prototype.constructor=' + className + ';',
state
);
utils.append(
className + '.__superConstructor__=' + superClass.name + ';',
state
);
}
// If there's no constructor method specified in the class body, create an
// empty constructor function at the top (same line as the class keyword)
if (!node.body.body.filter(_isConstructorMethod).pop()) {
utils.append('function ' + className + '(){', state);
if (!state.scopeIsStrict) {
utils.append('"use strict";', state);
}
if (superClass.name) {
utils.append(
'if(' + superClass.name + '!==null){' +
superClass.name + '.apply(this,arguments);}',
state
);
}
utils.append('}', state);
}
utils.move(node.body.range[0] + '{'.length, state);
traverse(node.body, path, state);
utils.catchupWhiteSpace(node.range[1], state);
}
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassDeclaration(traverse, node, path, state) {
var className = node.id.name;
var superClass = _getSuperClassInfo(node, state);
state = utils.updateState(state, {
mungeNamespace: className,
className: className,
superClass: superClass
});
_renderClassBody(traverse, node, path, state);
return false;
}
visitClassDeclaration.test = function(node, path, state) {
return node.type === Syntax.ClassDeclaration;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassExpression(traverse, node, path, state) {
var className = node.id && node.id.name || _generateAnonymousClassName(state);
var superClass = _getSuperClassInfo(node, state);
utils.append('(function(){', state);
state = utils.updateState(state, {
mungeNamespace: className,
className: className,
superClass: superClass
});
_renderClassBody(traverse, node, path, state);
utils.append('return ' + className + ';})()', state);
return false;
}
visitClassExpression.test = function(node, path, state) {
return node.type === Syntax.ClassExpression;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitPrivateIdentifier(traverse, node, path, state) {
utils.append(_getMungedName(node.name, state), state);
utils.move(node.range[1], state);
}
visitPrivateIdentifier.test = function(node, path, state) {
if (node.type === Syntax.Identifier && _shouldMungeIdentifier(node, state)) {
// Always munge non-computed properties of MemberExpressions
// (a la preventing access of properties of unowned objects)
if (path[0].type === Syntax.MemberExpression && path[0].object !== node
&& path[0].computed === false) {
return true;
}
// Always munge identifiers that were declared within the method function
// scope
if (utils.identWithinLexicalScope(node.name, state, state.methodFuncNode)) {
return true;
}
// Always munge private keys on object literals defined within a method's
// scope.
if (path[0].type === Syntax.Property
&& path[1].type === Syntax.ObjectExpression) {
return true;
}
// Always munge function parameters
if (path[0].type === Syntax.FunctionExpression
|| path[0].type === Syntax.FunctionDeclaration
|| path[0].type === Syntax.ArrowFunctionExpression) {
for (var i = 0; i < path[0].params.length; i++) {
if (path[0].params[i] === node) {
return true;
}
}
}
}
return false;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitSuperCallExpression(traverse, node, path, state) {
var superClassName = state.superClass.name;
if (node.callee.type === Syntax.Identifier) {
if (_isConstructorMethod(state.methodNode)) {
utils.append(superClassName + '.call(', state);
} else {
var protoProp = SUPER_PROTO_IDENT_PREFIX + superClassName;
if (state.methodNode.key.type === Syntax.Identifier) {
protoProp += '.' + state.methodNode.key.name;
} else if (state.methodNode.key.type === Syntax.Literal) {
protoProp += '[' + JSON.stringify(state.methodNode.key.value) + ']';
}
utils.append(protoProp + ".call(", state);
}
utils.move(node.callee.range[1], state);
} else if (node.callee.type === Syntax.MemberExpression) {
utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state);
utils.move(node.callee.object.range[1], state);
if (node.callee.computed) {
// ["a" + "b"]
utils.catchup(node.callee.property.range[1] + ']'.length, state);
} else {
// .ab
utils.append('.' + node.callee.property.name, state);
}
utils.append('.call(', state);
utils.move(node.callee.range[1], state);
}
utils.append('this', state);
if (node.arguments.length > 0) {
utils.append(',', state);
utils.catchupWhiteSpace(node.arguments[0].range[0], state);
traverse(node.arguments, path, state);
}
utils.catchupWhiteSpace(node.range[1], state);
utils.append(')', state);
return false;
}
visitSuperCallExpression.test = function(node, path, state) {
if (state.superClass && node.type === Syntax.CallExpression) {
var callee = node.callee;
if (callee.type === Syntax.Identifier && callee.name === 'super'
|| callee.type == Syntax.MemberExpression
&& callee.object.name === 'super') {
return true;
}
}
return false;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitSuperMemberExpression(traverse, node, path, state) {
var superClassName = state.superClass.name;
utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state);
utils.move(node.object.range[1], state);
}
visitSuperMemberExpression.test = function(node, path, state) {
return state.superClass
&& node.type === Syntax.MemberExpression
&& node.object.type === Syntax.Identifier
&& node.object.name === 'super';
};
exports.resetSymbols = resetSymbols;
exports.visitorList = [
visitClassDeclaration,
visitClassExpression,
visitClassFunctionExpression,
visitClassMethod,
visitClassMethodParam,
visitPrivateIdentifier,
visitSuperCallExpression,
visitSuperMemberExpression
];
},{"../src/utils":23,"./reserved-words-helper":34,"base62":10,"esprima-fb":9}],27:[function(_dereq_,module,exports){
/**
* Copyright 2014 Facebook, Inc.
*
* 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.
*/
/*global exports:true*/
/**
* Implements ES6 destructuring assignment and pattern matchng.
*
* function init({port, ip, coords: [x, y]}) {
* return (x && y) ? {id, port} : {ip};
* };
*
* function init($__0) {
* var
* port = $__0.port,
* ip = $__0.ip,
* $__1 = $__0.coords,
* x = $__1[0],
* y = $__1[1];
* return (x && y) ? {id, port} : {ip};
* }
*
* var x, {ip, port} = init({ip, port});
*
* var x, $__0 = init({ip, port}), ip = $__0.ip, port = $__0.port;
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
var reservedWordsHelper = _dereq_('./reserved-words-helper');
var restParamVisitors = _dereq_('./es6-rest-param-visitors');
var restPropertyHelpers = _dereq_('./es7-rest-property-helpers');
// -------------------------------------------------------
// 1. Structured variable declarations.
//
// var [a, b] = [b, a];
// var {x, y} = {y, x};
// -------------------------------------------------------
function visitStructuredVariable(traverse, node, path, state) {
// Allocate new temp for the pattern.
utils.append(utils.getTempVar(state.localScope.tempVarIndex) + '=', state);
// Skip the pattern and assign the init to the temp.
utils.catchupWhiteSpace(node.init.range[0], state);
traverse(node.init, path, state);
utils.catchup(node.init.range[1], state);
// Render the destructured data.
utils.append(',' + getDestructuredComponents(node.id, state), state);
state.localScope.tempVarIndex++;
return false;
}
visitStructuredVariable.test = function(node, path, state) {
return node.type === Syntax.VariableDeclarator &&
isStructuredPattern(node.id);
};
function isStructuredPattern(node) {
return node.type === Syntax.ObjectPattern ||
node.type === Syntax.ArrayPattern;
}
// Main function which does actual recursive destructuring
// of nested complex structures.
function getDestructuredComponents(node, state) {
var tmpIndex = state.localScope.tempVarIndex;
var components = [];
var patternItems = getPatternItems(node);
for (var idx = 0; idx < patternItems.length; idx++) {
var item = patternItems[idx];
if (!item) {
continue;
}
if (item.type === Syntax.SpreadElement) {
// Spread/rest of an array.
// TODO(dmitrys): support spread in the middle of a pattern
// and also for function param patterns: [x, ...xs, y]
components.push(item.argument.name +
'=Array.prototype.slice.call(' +
utils.getTempVar(tmpIndex) + ',' + idx + ')'
);
continue;
}
if (item.type === Syntax.SpreadProperty) {
var restExpression = restPropertyHelpers.renderRestExpression(
utils.getTempVar(tmpIndex),
patternItems
);
components.push(item.argument.name + '=' + restExpression);
continue;
}
// Depending on pattern type (Array or Object), we get
// corresponding pattern item parts.
var accessor = getPatternItemAccessor(node, item, tmpIndex, idx);
var value = getPatternItemValue(node, item);
// TODO(dmitrys): implement default values: {x, y=5}
if (value.type === Syntax.Identifier) {
// Simple pattern item.
components.push(value.name + '=' + accessor);
} else {
// Complex sub-structure.
components.push(
utils.getTempVar(++state.localScope.tempVarIndex) + '=' + accessor +
',' + getDestructuredComponents(value, state)
);
}
}
return components.join(',');
}
function getPatternItems(node) {
return node.properties || node.elements;
}
function getPatternItemAccessor(node, patternItem, tmpIndex, idx) {
var tmpName = utils.getTempVar(tmpIndex);
if (node.type === Syntax.ObjectPattern) {
if (reservedWordsHelper.isReservedWord(patternItem.key.name)) {
return tmpName + '["' + patternItem.key.name + '"]';
} else if (patternItem.key.type === Syntax.Literal) {
return tmpName + '[' + JSON.stringify(patternItem.key.value) + ']';
} else if (patternItem.key.type === Syntax.Identifier) {
return tmpName + '.' + patternItem.key.name;
}
} else if (node.type === Syntax.ArrayPattern) {
return tmpName + '[' + idx + ']';
}
}
function getPatternItemValue(node, patternItem) {
return node.type === Syntax.ObjectPattern
? patternItem.value
: patternItem;
}
// -------------------------------------------------------
// 2. Assignment expression.
//
// [a, b] = [b, a];
// ({x, y} = {y, x});
// -------------------------------------------------------
function visitStructuredAssignment(traverse, node, path, state) {
var exprNode = node.expression;
utils.append('var ' + utils.getTempVar(state.localScope.tempVarIndex) + '=', state);
utils.catchupWhiteSpace(exprNode.right.range[0], state);
traverse(exprNode.right, path, state);
utils.catchup(exprNode.right.range[1], state);
utils.append(
';' + getDestructuredComponents(exprNode.left, state) + ';',
state
);
utils.catchupWhiteSpace(node.range[1], state);
state.localScope.tempVarIndex++;
return false;
}
visitStructuredAssignment.test = function(node, path, state) {
// We consider the expression statement rather than just assignment
// expression to cover case with object patters which should be
// wrapped in grouping operator: ({x, y} = {y, x});
return node.type === Syntax.ExpressionStatement &&
node.expression.type === Syntax.AssignmentExpression &&
isStructuredPattern(node.expression.left);
};
// -------------------------------------------------------
// 3. Structured parameter.
//
// function foo({x, y}) { ... }
// -------------------------------------------------------
function visitStructuredParameter(traverse, node, path, state) {
utils.append(utils.getTempVar(getParamIndex(node, path)), state);
utils.catchupWhiteSpace(node.range[1], state);
return true;
}
function getParamIndex(paramNode, path) {
var funcNode = path[0];
var tmpIndex = 0;
for (var k = 0; k < funcNode.params.length; k++) {
var param = funcNode.params[k];
if (param === paramNode) {
break;
}
if (isStructuredPattern(param)) {
tmpIndex++;
}
}
return tmpIndex;
}
visitStructuredParameter.test = function(node, path, state) {
return isStructuredPattern(node) && isFunctionNode(path[0]);
};
function isFunctionNode(node) {
return (node.type == Syntax.FunctionDeclaration ||
node.type == Syntax.FunctionExpression ||
node.type == Syntax.MethodDefinition ||
node.type == Syntax.ArrowFunctionExpression);
}
// -------------------------------------------------------
// 4. Function body for structured parameters.
//
// function foo({x, y}) { x; y; }
// -------------------------------------------------------
function visitFunctionBodyForStructuredParameter(traverse, node, path, state) {
var funcNode = path[0];
utils.catchup(funcNode.body.range[0] + 1, state);
renderDestructuredComponents(funcNode, state);
if (funcNode.rest) {
utils.append(
restParamVisitors.renderRestParamSetup(funcNode, state),
state
);
}
return true;
}
function renderDestructuredComponents(funcNode, state) {
var destructuredComponents = [];
for (var k = 0; k < funcNode.params.length; k++) {
var param = funcNode.params[k];
if (isStructuredPattern(param)) {
destructuredComponents.push(
getDestructuredComponents(param, state)
);
state.localScope.tempVarIndex++;
}
}
if (destructuredComponents.length) {
utils.append('var ' + destructuredComponents.join(',') + ';', state);
}
}
visitFunctionBodyForStructuredParameter.test = function(node, path, state) {
return node.type === Syntax.BlockStatement && isFunctionNode(path[0]);
};
exports.visitorList = [
visitStructuredVariable,
visitStructuredAssignment,
visitStructuredParameter,
visitFunctionBodyForStructuredParameter
];
exports.renderDestructuredComponents = renderDestructuredComponents;
},{"../src/utils":23,"./es6-rest-param-visitors":30,"./es7-rest-property-helpers":32,"./reserved-words-helper":34,"esprima-fb":9}],28:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* 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.
*/
/*jslint node:true*/
/**
* Desugars concise methods of objects to function expressions.
*
* var foo = {
* method(x, y) { ... }
* };
*
* var foo = {
* method: function(x, y) { ... }
* };
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
var reservedWordsHelper = _dereq_('./reserved-words-helper');
function visitObjectConciseMethod(traverse, node, path, state) {
var isGenerator = node.value.generator;
if (isGenerator) {
utils.catchupWhiteSpace(node.range[0] + 1, state);
}
if (node.computed) { // [<expr>]() { ...}
utils.catchup(node.key.range[1] + 1, state);
} else if (reservedWordsHelper.isReservedWord(node.key.name)) {
utils.catchup(node.key.range[0], state);
utils.append('"', state);
utils.catchup(node.key.range[1], state);
utils.append('"', state);
}
utils.catchup(node.key.range[1], state);
utils.append(
':function' + (isGenerator ? '*' : ''),
state
);
path.unshift(node);
traverse(node.value, path, state);
path.shift();
return false;
}
visitObjectConciseMethod.test = function(node, path, state) {
return node.type === Syntax.Property &&
node.value.type === Syntax.FunctionExpression &&
node.method === true;
};
exports.visitorList = [
visitObjectConciseMethod
];
},{"../src/utils":23,"./reserved-words-helper":34,"esprima-fb":9}],29:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* 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.
*/
/*jslint node: true*/
/**
* Desugars ES6 Object Literal short notations into ES3 full notation.
*
* // Easier return values.
* function foo(x, y) {
* return {x, y}; // {x: x, y: y}
* };
*
* // Destructuring.
* function init({port, ip, coords: {x, y}}) { ... }
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
/**
* @public
*/
function visitObjectLiteralShortNotation(traverse, node, path, state) {
utils.catchup(node.key.range[1], state);
utils.append(':' + node.key.name, state);
return false;
}
visitObjectLiteralShortNotation.test = function(node, path, state) {
return node.type === Syntax.Property &&
node.kind === 'init' &&
node.shorthand === true &&
path[0].type !== Syntax.ObjectPattern;
};
exports.visitorList = [
visitObjectLiteralShortNotation
];
},{"../src/utils":23,"esprima-fb":9}],30:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* 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.
*/
/*jslint node:true*/
/**
* Desugars ES6 rest parameters into an ES3 arguments array.
*
* function printf(template, ...args) {
* args.forEach(...);
* }
*
* We could use `Array.prototype.slice.call`, but that usage of arguments causes
* functions to be deoptimized in V8, so instead we use a for-loop.
*
* function printf(template) {
* for (var args = [], $__0 = 1, $__1 = arguments.length; $__0 < $__1; $__0++)
* args.push(arguments[$__0]);
* args.forEach(...);
* }
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
function _nodeIsFunctionWithRestParam(node) {
return (node.type === Syntax.FunctionDeclaration
|| node.type === Syntax.FunctionExpression
|| node.type === Syntax.ArrowFunctionExpression)
&& node.rest;
}
function visitFunctionParamsWithRestParam(traverse, node, path, state) {
if (node.parametricType) {
utils.catchup(node.parametricType.range[0], state);
path.unshift(node);
traverse(node.parametricType, path, state);
path.shift();
}
// Render params.
if (node.params.length) {
path.unshift(node);
traverse(node.params, path, state);
path.shift();
} else {
// -3 is for ... of the rest.
utils.catchup(node.rest.range[0] - 3, state);
}
utils.catchupWhiteSpace(node.rest.range[1], state);
path.unshift(node);
traverse(node.body, path, state);
path.shift();
return false;
}
visitFunctionParamsWithRestParam.test = function(node, path, state) {
return _nodeIsFunctionWithRestParam(node);
};
function renderRestParamSetup(functionNode, state) {
var idx = state.localScope.tempVarIndex++;
var len = state.localScope.tempVarIndex++;
return 'for (var ' + functionNode.rest.name + '=[],' +
utils.getTempVar(idx) + '=' + functionNode.params.length + ',' +
utils.getTempVar(len) + '=arguments.length;' +
utils.getTempVar(idx) + '<' + utils.getTempVar(len) + ';' +
utils.getTempVar(idx) + '++) ' +
functionNode.rest.name + '.push(arguments[' + utils.getTempVar(idx) + ']);';
}
function visitFunctionBodyWithRestParam(traverse, node, path, state) {
utils.catchup(node.range[0] + 1, state);
var parentNode = path[0];
utils.append(renderRestParamSetup(parentNode, state), state);
return true;
}
visitFunctionBodyWithRestParam.test = function(node, path, state) {
return node.type === Syntax.BlockStatement
&& _nodeIsFunctionWithRestParam(path[0]);
};
exports.renderRestParamSetup = renderRestParamSetup;
exports.visitorList = [
visitFunctionParamsWithRestParam,
visitFunctionBodyWithRestParam
];
},{"../src/utils":23,"esprima-fb":9}],31:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* 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.
*/
/*jslint node:true*/
/**
* @typechecks
*/
'use strict';
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
/**
* http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.1.9
*/
function visitTemplateLiteral(traverse, node, path, state) {
var templateElements = node.quasis;
utils.append('(', state);
for (var ii = 0; ii < templateElements.length; ii++) {
var templateElement = templateElements[ii];
if (templateElement.value.raw !== '') {
utils.append(getCookedValue(templateElement), state);
if (!templateElement.tail) {
// + between element and substitution
utils.append(' + ', state);
}
// maintain line numbers
utils.move(templateElement.range[0], state);
utils.catchupNewlines(templateElement.range[1], state);
} else { // templateElement.value.raw === ''
// Concatenat adjacent substitutions, e.g. `${x}${y}`. Empty templates
// appear before the first and after the last element - nothing to add in
// those cases.
if (ii > 0 && !templateElement.tail) {
// + between substitution and substitution
utils.append(' + ', state);
}
}
utils.move(templateElement.range[1], state);
if (!templateElement.tail) {
var substitution = node.expressions[ii];
if (substitution.type === Syntax.Identifier ||
substitution.type === Syntax.MemberExpression ||
substitution.type === Syntax.CallExpression) {
utils.catchup(substitution.range[1], state);
} else {
utils.append('(', state);
traverse(substitution, path, state);
utils.catchup(substitution.range[1], state);
utils.append(')', state);
}
// if next templateElement isn't empty...
if (templateElements[ii + 1].value.cooked !== '') {
utils.append(' + ', state);
}
}
}
utils.move(node.range[1], state);
utils.append(')', state);
return false;
}
visitTemplateLiteral.test = function(node, path, state) {
return node.type === Syntax.TemplateLiteral;
};
/**
* http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.2.6
*/
function visitTaggedTemplateExpression(traverse, node, path, state) {
var template = node.quasi;
var numQuasis = template.quasis.length;
// print the tag
utils.move(node.tag.range[0], state);
traverse(node.tag, path, state);
utils.catchup(node.tag.range[1], state);
// print array of template elements
utils.append('(function() { var siteObj = [', state);
for (var ii = 0; ii < numQuasis; ii++) {
utils.append(getCookedValue(template.quasis[ii]), state);
if (ii !== numQuasis - 1) {
utils.append(', ', state);
}
}
utils.append(']; siteObj.raw = [', state);
for (ii = 0; ii < numQuasis; ii++) {
utils.append(getRawValue(template.quasis[ii]), state);
if (ii !== numQuasis - 1) {
utils.append(', ', state);
}
}
utils.append(
']; Object.freeze(siteObj.raw); Object.freeze(siteObj); return siteObj; }()',
state
);
// print substitutions
if (numQuasis > 1) {
for (ii = 0; ii < template.expressions.length; ii++) {
var expression = template.expressions[ii];
utils.append(', ', state);
// maintain line numbers by calling catchupWhiteSpace over the whole
// previous TemplateElement
utils.move(template.quasis[ii].range[0], state);
utils.catchupNewlines(template.quasis[ii].range[1], state);
utils.move(expression.range[0], state);
traverse(expression, path, state);
utils.catchup(expression.range[1], state);
}
}
// print blank lines to push the closing ) down to account for the final
// TemplateElement.
utils.catchupNewlines(node.range[1], state);
utils.append(')', state);
return false;
}
visitTaggedTemplateExpression.test = function(node, path, state) {
return node.type === Syntax.TaggedTemplateExpression;
};
function getCookedValue(templateElement) {
return JSON.stringify(templateElement.value.cooked);
}
function getRawValue(templateElement) {
return JSON.stringify(templateElement.value.raw);
}
exports.visitorList = [
visitTemplateLiteral,
visitTaggedTemplateExpression
];
},{"../src/utils":23,"esprima-fb":9}],32:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* 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.
*/
/*jslint node:true*/
/**
* Desugars ES7 rest properties into ES5 object iteration.
*/
var Syntax = _dereq_('esprima-fb').Syntax;
// TODO: This is a pretty massive helper, it should only be defined once, in the
// transform's runtime environment. We don't currently have a runtime though.
var restFunction =
'(function(source, exclusion) {' +
'var rest = {};' +
'var hasOwn = Object.prototype.hasOwnProperty;' +
'if (source == null) {' +
'throw new TypeError();' +
'}' +
'for (var key in source) {' +
'if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {' +
'rest[key] = source[key];' +
'}' +
'}' +
'return rest;' +
'})';
function getPropertyNames(properties) {
var names = [];
for (var i = 0; i < properties.length; i++) {
var property = properties[i];
if (property.type === Syntax.SpreadProperty) {
continue;
}
if (property.type === Syntax.Identifier) {
names.push(property.name);
} else {
names.push(property.key.name);
}
}
return names;
}
function getRestFunctionCall(source, exclusion) {
return restFunction + '(' + source + ',' + exclusion + ')';
}
function getSimpleShallowCopy(accessorExpression) {
// This could be faster with 'Object.assign({}, ' + accessorExpression + ')'
// but to unify code paths and avoid a ES6 dependency we use the same
// helper as for the exclusion case.
return getRestFunctionCall(accessorExpression, '{}');
}
function renderRestExpression(accessorExpression, excludedProperties) {
var excludedNames = getPropertyNames(excludedProperties);
if (!excludedNames.length) {
return getSimpleShallowCopy(accessorExpression);
}
return getRestFunctionCall(
accessorExpression,
'{' + excludedNames.join(':1,') + ':1}'
);
}
exports.renderRestExpression = renderRestExpression;
},{"esprima-fb":9}],33:[function(_dereq_,module,exports){
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*/
/*global exports:true*/
/**
* Implements ES7 object spread property.
* https://gist.github.com/sebmarkbage/aa849c7973cb4452c547
*
* { ...a, x: 1 }
*
* Object.assign({}, a, {x: 1 })
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
function visitObjectLiteralSpread(traverse, node, path, state) {
utils.catchup(node.range[0], state);
utils.append('Object.assign({', state);
// Skip the original {
utils.move(node.range[0] + 1, state);
var previousWasSpread = false;
for (var i = 0; i < node.properties.length; i++) {
var property = node.properties[i];
if (property.type === Syntax.SpreadProperty) {
// Close the previous object or initial object
if (!previousWasSpread) {
utils.append('}', state);
}
if (i === 0) {
// Normally there will be a comma when we catch up, but not before
// the first property.
utils.append(',', state);
}
utils.catchup(property.range[0], state);
// skip ...
utils.move(property.range[0] + 3, state);
traverse(property.argument, path, state);
utils.catchup(property.range[1], state);
previousWasSpread = true;
} else {
utils.catchup(property.range[0], state);
if (previousWasSpread) {
utils.append('{', state);
}
traverse(property, path, state);
utils.catchup(property.range[1], state);
previousWasSpread = false;
}
}
// Strip any non-whitespace between the last item and the end.
// We only catch up on whitespace so that we ignore any trailing commas which
// are stripped out for IE8 support. Unfortunately, this also strips out any
// trailing comments.
utils.catchupWhiteSpace(node.range[1] - 1, state);
// Skip the trailing }
utils.move(node.range[1], state);
if (!previousWasSpread) {
utils.append('}', state);
}
utils.append(')', state);
return false;
}
visitObjectLiteralSpread.test = function(node, path, state) {
if (node.type !== Syntax.ObjectExpression) {
return false;
}
// Tight loop optimization
var hasAtLeastOneSpreadProperty = false;
for (var i = 0; i < node.properties.length; i++) {
var property = node.properties[i];
if (property.type === Syntax.SpreadProperty) {
hasAtLeastOneSpreadProperty = true;
} else if (property.kind !== 'init') {
return false;
}
}
return hasAtLeastOneSpreadProperty;
};
exports.visitorList = [
visitObjectLiteralSpread
];
},{"../src/utils":23,"esprima-fb":9}],34:[function(_dereq_,module,exports){
/**
* Copyright 2014 Facebook, Inc.
*
* 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.
*/
var KEYWORDS = [
'break', 'do', 'in', 'typeof', 'case', 'else', 'instanceof', 'var', 'catch',
'export', 'new', 'void', 'class', 'extends', 'return', 'while', 'const',
'finally', 'super', 'with', 'continue', 'for', 'switch', 'yield', 'debugger',
'function', 'this', 'default', 'if', 'throw', 'delete', 'import', 'try'
];
var FUTURE_RESERVED_WORDS = [
'enum', 'await', 'implements', 'package', 'protected', 'static', 'interface',
'private', 'public'
];
var LITERALS = [
'null',
'true',
'false'
];
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-reserved-words
var RESERVED_WORDS = [].concat(
KEYWORDS,
FUTURE_RESERVED_WORDS,
LITERALS
);
var reservedWordsMap = Object.create(null);
RESERVED_WORDS.forEach(function(k) {
reservedWordsMap[k] = true;
});
/**
* This list should not grow as new reserved words are introdued. This list is
* of words that need to be quoted because ES3-ish browsers do not allow their
* use as identifier names.
*/
var ES3_FUTURE_RESERVED_WORDS = [
'enum', 'implements', 'package', 'protected', 'static', 'interface',
'private', 'public'
];
var ES3_RESERVED_WORDS = [].concat(
KEYWORDS,
ES3_FUTURE_RESERVED_WORDS,
LITERALS
);
var es3ReservedWordsMap = Object.create(null);
ES3_RESERVED_WORDS.forEach(function(k) {
es3ReservedWordsMap[k] = true;
});
exports.isReservedWord = function(word) {
return !!reservedWordsMap[word];
};
exports.isES3ReservedWord = function(word) {
return !!es3ReservedWordsMap[word];
};
},{}],35:[function(_dereq_,module,exports){
/**
* Copyright 2014 Facebook, Inc.
*
* 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.
*
*/
/*global exports:true*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
var reserverdWordsHelper = _dereq_('./reserved-words-helper');
/**
* Code adapted from https://github.com/spicyj/es3ify
* The MIT License (MIT)
* Copyright (c) 2014 Ben Alpert
*/
function visitProperty(traverse, node, path, state) {
utils.catchup(node.key.range[0], state);
utils.append('"', state);
utils.catchup(node.key.range[1], state);
utils.append('"', state);
utils.catchup(node.value.range[0], state);
traverse(node.value, path, state);
return false;
}
visitProperty.test = function(node) {
return node.type === Syntax.Property &&
node.key.type === Syntax.Identifier &&
!node.method &&
!node.shorthand &&
!node.computed &&
reserverdWordsHelper.isES3ReservedWord(node.key.name);
};
function visitMemberExpression(traverse, node, path, state) {
traverse(node.object, path, state);
utils.catchup(node.property.range[0] - 1, state);
utils.append('[', state);
utils.catchupWhiteSpace(node.property.range[0], state);
utils.append('"', state);
utils.catchup(node.property.range[1], state);
utils.append('"]', state);
return false;
}
visitMemberExpression.test = function(node) {
return node.type === Syntax.MemberExpression &&
node.property.type === Syntax.Identifier &&
reserverdWordsHelper.isES3ReservedWord(node.property.name);
};
exports.visitorList = [
visitProperty,
visitMemberExpression
];
},{"../src/utils":23,"./reserved-words-helper":34,"esprima-fb":9}],36:[function(_dereq_,module,exports){
var esprima = _dereq_('esprima-fb');
var utils = _dereq_('../src/utils');
var Syntax = esprima.Syntax;
function _isFunctionNode(node) {
return node.type === Syntax.FunctionDeclaration
|| node.type === Syntax.FunctionExpression
|| node.type === Syntax.ArrowFunctionExpression;
}
function visitClassProperty(traverse, node, path, state) {
utils.catchup(node.range[0], state);
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitClassProperty.test = function(node, path, state) {
return node.type === Syntax.ClassProperty;
};
function visitTypeAlias(traverse, node, path, state) {
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitTypeAlias.test = function(node, path, state) {
return node.type === Syntax.TypeAlias;
};
function visitTypeCast(traverse, node, path, state) {
path.unshift(node);
traverse(node.expression, path, state);
path.shift();
utils.catchup(node.typeAnnotation.range[0], state);
utils.catchupWhiteOut(node.typeAnnotation.range[1], state);
return false;
}
visitTypeCast.test = function(node, path, state) {
return node.type === Syntax.TypeCastExpression;
};
function visitInterfaceDeclaration(traverse, node, path, state) {
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitInterfaceDeclaration.test = function(node, path, state) {
return node.type === Syntax.InterfaceDeclaration;
};
function visitDeclare(traverse, node, path, state) {
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitDeclare.test = function(node, path, state) {
switch (node.type) {
case Syntax.DeclareVariable:
case Syntax.DeclareFunction:
case Syntax.DeclareClass:
case Syntax.DeclareModule:
return true;
}
return false;
};
function visitFunctionParametricAnnotation(traverse, node, path, state) {
utils.catchup(node.range[0], state);
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitFunctionParametricAnnotation.test = function(node, path, state) {
return node.type === Syntax.TypeParameterDeclaration
&& path[0]
&& _isFunctionNode(path[0])
&& node === path[0].typeParameters;
};
function visitFunctionReturnAnnotation(traverse, node, path, state) {
utils.catchup(node.range[0], state);
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitFunctionReturnAnnotation.test = function(node, path, state) {
return path[0] && _isFunctionNode(path[0]) && node === path[0].returnType;
};
function visitOptionalFunctionParameterAnnotation(traverse, node, path, state) {
utils.catchup(node.range[0] + node.name.length, state);
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitOptionalFunctionParameterAnnotation.test = function(node, path, state) {
return node.type === Syntax.Identifier
&& node.optional
&& path[0]
&& _isFunctionNode(path[0]);
};
function visitTypeAnnotatedIdentifier(traverse, node, path, state) {
utils.catchup(node.typeAnnotation.range[0], state);
utils.catchupWhiteOut(node.typeAnnotation.range[1], state);
return false;
}
visitTypeAnnotatedIdentifier.test = function(node, path, state) {
return node.type === Syntax.Identifier && node.typeAnnotation;
};
function visitTypeAnnotatedObjectOrArrayPattern(traverse, node, path, state) {
utils.catchup(node.typeAnnotation.range[0], state);
utils.catchupWhiteOut(node.typeAnnotation.range[1], state);
return false;
}
visitTypeAnnotatedObjectOrArrayPattern.test = function(node, path, state) {
var rightType = node.type === Syntax.ObjectPattern
|| node.type === Syntax.ArrayPattern;
return rightType && node.typeAnnotation;
};
/**
* Methods cause trouble, since esprima parses them as a key/value pair, where
* the location of the value starts at the method body. For example
* { bar(x:number,...y:Array<number>):number {} }
* is parsed as
* { bar: function(x: number, ...y:Array<number>): number {} }
* except that the location of the FunctionExpression value is 40-something,
* which is the location of the function body. This means that by the time we
* visit the params, rest param, and return type organically, we've already
* catchup()'d passed them.
*/
function visitMethod(traverse, node, path, state) {
path.unshift(node);
traverse(node.key, path, state);
path.unshift(node.value);
traverse(node.value.params, path, state);
node.value.rest && traverse(node.value.rest, path, state);
node.value.returnType && traverse(node.value.returnType, path, state);
traverse(node.value.body, path, state);
path.shift();
path.shift();
return false;
}
visitMethod.test = function(node, path, state) {
return (node.type === "Property" && (node.method || node.kind === "set" || node.kind === "get"))
|| (node.type === "MethodDefinition");
};
function visitImportType(traverse, node, path, state) {
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitImportType.test = function(node, path, state) {
return node.type === 'ImportDeclaration'
&& node.isType;
};
exports.visitorList = [
visitClassProperty,
visitDeclare,
visitImportType,
visitInterfaceDeclaration,
visitFunctionParametricAnnotation,
visitFunctionReturnAnnotation,
visitMethod,
visitOptionalFunctionParameterAnnotation,
visitTypeAlias,
visitTypeCast,
visitTypeAnnotatedIdentifier,
visitTypeAnnotatedObjectOrArrayPattern
];
},{"../src/utils":23,"esprima-fb":9}],37:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/*global exports:true*/
'use strict';
var Syntax = _dereq_('jstransform').Syntax;
var utils = _dereq_('jstransform/src/utils');
function renderJSXLiteral(object, isLast, state, start, end) {
var lines = object.value.split(/\r\n|\n|\r/);
if (start) {
utils.append(start, state);
}
var lastNonEmptyLine = 0;
lines.forEach(function(line, index) {
if (line.match(/[^ \t]/)) {
lastNonEmptyLine = index;
}
});
lines.forEach(function(line, index) {
var isFirstLine = index === 0;
var isLastLine = index === lines.length - 1;
var isLastNonEmptyLine = index === lastNonEmptyLine;
// replace rendered whitespace tabs with spaces
var trimmedLine = line.replace(/\t/g, ' ');
// trim whitespace touching a newline
if (!isFirstLine) {
trimmedLine = trimmedLine.replace(/^[ ]+/, '');
}
if (!isLastLine) {
trimmedLine = trimmedLine.replace(/[ ]+$/, '');
}
if (!isFirstLine) {
utils.append(line.match(/^[ \t]*/)[0], state);
}
if (trimmedLine || isLastNonEmptyLine) {
utils.append(
JSON.stringify(trimmedLine) +
(!isLastNonEmptyLine ? ' + \' \' +' : ''),
state);
if (isLastNonEmptyLine) {
if (end) {
utils.append(end, state);
}
if (!isLast) {
utils.append(', ', state);
}
}
// only restore tail whitespace if line had literals
if (trimmedLine && !isLastLine) {
utils.append(line.match(/[ \t]*$/)[0], state);
}
}
if (!isLastLine) {
utils.append('\n', state);
}
});
utils.move(object.range[1], state);
}
function renderJSXExpressionContainer(traverse, object, isLast, path, state) {
// Plus 1 to skip `{`.
utils.move(object.range[0] + 1, state);
utils.catchup(object.expression.range[0], state);
traverse(object.expression, path, state);
if (!isLast && object.expression.type !== Syntax.JSXEmptyExpression) {
// If we need to append a comma, make sure to do so after the expression.
utils.catchup(object.expression.range[1], state, trimLeft);
utils.append(', ', state);
}
// Minus 1 to skip `}`.
utils.catchup(object.range[1] - 1, state, trimLeft);
utils.move(object.range[1], state);
return false;
}
function quoteAttrName(attr) {
// Quote invalid JS identifiers.
if (!/^[a-z_$][a-z\d_$]*$/i.test(attr)) {
return '"' + attr + '"';
}
return attr;
}
function trimLeft(value) {
return value.replace(/^[ ]+/, '');
}
exports.renderJSXExpressionContainer = renderJSXExpressionContainer;
exports.renderJSXLiteral = renderJSXLiteral;
exports.quoteAttrName = quoteAttrName;
exports.trimLeft = trimLeft;
},{"jstransform":22,"jstransform/src/utils":23}],38:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/*global exports:true*/
'use strict';
var Syntax = _dereq_('jstransform').Syntax;
var utils = _dereq_('jstransform/src/utils');
var renderJSXExpressionContainer =
_dereq_('./jsx').renderJSXExpressionContainer;
var renderJSXLiteral = _dereq_('./jsx').renderJSXLiteral;
var quoteAttrName = _dereq_('./jsx').quoteAttrName;
var trimLeft = _dereq_('./jsx').trimLeft;
/**
* Customized desugar processor for React JSX. Currently:
*
* <X> </X> => React.createElement(X, null)
* <X prop="1" /> => React.createElement(X, {prop: '1'}, null)
* <X prop="2"><Y /></X> => React.createElement(X, {prop:'2'},
* React.createElement(Y, null)
* )
* <div /> => React.createElement("div", null)
*/
/**
* Removes all non-whitespace/parenthesis characters
*/
var reNonWhiteParen = /([^\s\(\)])/g;
function stripNonWhiteParen(value) {
return value.replace(reNonWhiteParen, '');
}
var tagConvention = /^[a-z]|\-/;
function isTagName(name) {
return tagConvention.test(name);
}
function visitReactTag(traverse, object, path, state) {
var openingElement = object.openingElement;
var nameObject = openingElement.name;
var attributesObject = openingElement.attributes;
utils.catchup(openingElement.range[0], state, trimLeft);
if (nameObject.type === Syntax.JSXNamespacedName && nameObject.namespace) {
throw new Error('Namespace tags are not supported. ReactJSX is not XML.');
}
// We assume that the React runtime is already in scope
utils.append('React.createElement(', state);
if (nameObject.type === Syntax.JSXIdentifier && isTagName(nameObject.name)) {
utils.append('"' + nameObject.name + '"', state);
utils.move(nameObject.range[1], state);
} else {
// Use utils.catchup in this case so we can easily handle
// JSXMemberExpressions which look like Foo.Bar.Baz. This also handles
// JSXIdentifiers that aren't fallback tags.
utils.move(nameObject.range[0], state);
utils.catchup(nameObject.range[1], state);
}
utils.append(', ', state);
var hasAttributes = attributesObject.length;
var hasAtLeastOneSpreadProperty = attributesObject.some(function(attr) {
return attr.type === Syntax.JSXSpreadAttribute;
});
// if we don't have any attributes, pass in null
if (hasAtLeastOneSpreadProperty) {
utils.append('React.__spread({', state);
} else if (hasAttributes) {
utils.append('{', state);
} else {
utils.append('null', state);
}
// keep track of if the previous attribute was a spread attribute
var previousWasSpread = false;
// write attributes
attributesObject.forEach(function(attr, index) {
var isLast = index === attributesObject.length - 1;
if (attr.type === Syntax.JSXSpreadAttribute) {
// Close the previous object or initial object
if (!previousWasSpread) {
utils.append('}, ', state);
}
// Move to the expression start, ignoring everything except parenthesis
// and whitespace.
utils.catchup(attr.range[0], state, stripNonWhiteParen);
// Plus 1 to skip `{`.
utils.move(attr.range[0] + 1, state);
utils.catchup(attr.argument.range[0], state, stripNonWhiteParen);
traverse(attr.argument, path, state);
utils.catchup(attr.argument.range[1], state);
// Move to the end, ignoring parenthesis and the closing `}`
utils.catchup(attr.range[1] - 1, state, stripNonWhiteParen);
if (!isLast) {
utils.append(', ', state);
}
utils.move(attr.range[1], state);
previousWasSpread = true;
return;
}
// If the next attribute is a spread, we're effective last in this object
if (!isLast) {
isLast = attributesObject[index + 1].type === Syntax.JSXSpreadAttribute;
}
if (attr.name.namespace) {
throw new Error(
'Namespace attributes are not supported. ReactJSX is not XML.');
}
var name = attr.name.name;
utils.catchup(attr.range[0], state, trimLeft);
if (previousWasSpread) {
utils.append('{', state);
}
utils.append(quoteAttrName(name), state);
utils.append(': ', state);
if (!attr.value) {
state.g.buffer += 'true';
state.g.position = attr.name.range[1];
if (!isLast) {
utils.append(', ', state);
}
} else {
utils.move(attr.name.range[1], state);
// Use catchupNewlines to skip over the '=' in the attribute
utils.catchupNewlines(attr.value.range[0], state);
if (attr.value.type === Syntax.Literal) {
renderJSXLiteral(attr.value, isLast, state);
} else {
renderJSXExpressionContainer(traverse, attr.value, isLast, path, state);
}
}
utils.catchup(attr.range[1], state, trimLeft);
previousWasSpread = false;
});
if (!openingElement.selfClosing) {
utils.catchup(openingElement.range[1] - 1, state, trimLeft);
utils.move(openingElement.range[1], state);
}
if (hasAttributes && !previousWasSpread) {
utils.append('}', state);
}
if (hasAtLeastOneSpreadProperty) {
utils.append(')', state);
}
// filter out whitespace
var childrenToRender = object.children.filter(function(child) {
return !(child.type === Syntax.Literal
&& typeof child.value === 'string'
&& child.value.match(/^[ \t]*[\r\n][ \t\r\n]*$/));
});
if (childrenToRender.length > 0) {
var lastRenderableIndex;
childrenToRender.forEach(function(child, index) {
if (child.type !== Syntax.JSXExpressionContainer ||
child.expression.type !== Syntax.JSXEmptyExpression) {
lastRenderableIndex = index;
}
});
if (lastRenderableIndex !== undefined) {
utils.append(', ', state);
}
childrenToRender.forEach(function(child, index) {
utils.catchup(child.range[0], state, trimLeft);
var isLast = index >= lastRenderableIndex;
if (child.type === Syntax.Literal) {
renderJSXLiteral(child, isLast, state);
} else if (child.type === Syntax.JSXExpressionContainer) {
renderJSXExpressionContainer(traverse, child, isLast, path, state);
} else {
traverse(child, path, state);
if (!isLast) {
utils.append(', ', state);
}
}
utils.catchup(child.range[1], state, trimLeft);
});
}
if (openingElement.selfClosing) {
// everything up to />
utils.catchup(openingElement.range[1] - 2, state, trimLeft);
utils.move(openingElement.range[1], state);
} else {
// everything up to </ sdflksjfd>
utils.catchup(object.closingElement.range[0], state, trimLeft);
utils.move(object.closingElement.range[1], state);
}
utils.append(')', state);
return false;
}
visitReactTag.test = function(object, path, state) {
return object.type === Syntax.JSXElement;
};
exports.visitorList = [
visitReactTag
];
},{"./jsx":37,"jstransform":22,"jstransform/src/utils":23}],39:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/*global exports:true*/
'use strict';
var Syntax = _dereq_('jstransform').Syntax;
var utils = _dereq_('jstransform/src/utils');
function addDisplayName(displayName, object, state) {
if (object &&
object.type === Syntax.CallExpression &&
object.callee.type === Syntax.MemberExpression &&
object.callee.object.type === Syntax.Identifier &&
object.callee.object.name === 'React' &&
object.callee.property.type === Syntax.Identifier &&
object.callee.property.name === 'createClass' &&
object.arguments.length === 1 &&
object.arguments[0].type === Syntax.ObjectExpression) {
// Verify that the displayName property isn't already set
var properties = object.arguments[0].properties;
var safe = properties.every(function(property) {
var value = property.key.type === Syntax.Identifier ?
property.key.name :
property.key.value;
return value !== 'displayName';
});
if (safe) {
utils.catchup(object.arguments[0].range[0] + 1, state);
utils.append('displayName: "' + displayName + '",', state);
}
}
}
/**
* Transforms the following:
*
* var MyComponent = createReactClass({
* render: ...
* });
*
* into:
*
* var MyComponent = createReactClass({
* displayName: 'MyComponent',
* render: ...
* });
*
* Also catches:
*
* MyComponent = createReactClass(...);
* exports.MyComponent = createReactClass(...);
* module.exports = {MyComponent: createReactClass(...)};
*/
function visitReactDisplayName(traverse, object, path, state) {
var left, right;
if (object.type === Syntax.AssignmentExpression) {
left = object.left;
right = object.right;
} else if (object.type === Syntax.Property) {
left = object.key;
right = object.value;
} else if (object.type === Syntax.VariableDeclarator) {
left = object.id;
right = object.init;
}
if (left && left.type === Syntax.MemberExpression) {
left = left.property;
}
if (left && left.type === Syntax.Identifier) {
addDisplayName(left.name, right, state);
}
}
visitReactDisplayName.test = function(object, path, state) {
return (
object.type === Syntax.AssignmentExpression ||
object.type === Syntax.Property ||
object.type === Syntax.VariableDeclarator
);
};
exports.visitorList = [
visitReactDisplayName
];
},{"jstransform":22,"jstransform/src/utils":23}],40:[function(_dereq_,module,exports){
/*global exports:true*/
'use strict';
var es6ArrowFunctions =
_dereq_('jstransform/visitors/es6-arrow-function-visitors');
var es6Classes = _dereq_('jstransform/visitors/es6-class-visitors');
var es6Destructuring =
_dereq_('jstransform/visitors/es6-destructuring-visitors');
var es6ObjectConciseMethod =
_dereq_('jstransform/visitors/es6-object-concise-method-visitors');
var es6ObjectShortNotation =
_dereq_('jstransform/visitors/es6-object-short-notation-visitors');
var es6RestParameters = _dereq_('jstransform/visitors/es6-rest-param-visitors');
var es6Templates = _dereq_('jstransform/visitors/es6-template-visitors');
var es6CallSpread =
_dereq_('jstransform/visitors/es6-call-spread-visitors');
var es7SpreadProperty =
_dereq_('jstransform/visitors/es7-spread-property-visitors');
var react = _dereq_('./transforms/react');
var reactDisplayName = _dereq_('./transforms/reactDisplayName');
var reservedWords = _dereq_('jstransform/visitors/reserved-words-visitors');
/**
* Map from transformName => orderedListOfVisitors.
*/
var transformVisitors = {
'es6-arrow-functions': es6ArrowFunctions.visitorList,
'es6-classes': es6Classes.visitorList,
'es6-destructuring': es6Destructuring.visitorList,
'es6-object-concise-method': es6ObjectConciseMethod.visitorList,
'es6-object-short-notation': es6ObjectShortNotation.visitorList,
'es6-rest-params': es6RestParameters.visitorList,
'es6-templates': es6Templates.visitorList,
'es6-call-spread': es6CallSpread.visitorList,
'es7-spread-property': es7SpreadProperty.visitorList,
'react': react.visitorList.concat(reactDisplayName.visitorList),
'reserved-words': reservedWords.visitorList
};
var transformSets = {
'harmony': [
'es6-arrow-functions',
'es6-object-concise-method',
'es6-object-short-notation',
'es6-classes',
'es6-rest-params',
'es6-templates',
'es6-destructuring',
'es6-call-spread',
'es7-spread-property'
],
'es3': [
'reserved-words'
],
'react': [
'react'
]
};
/**
* Specifies the order in which each transform should run.
*/
var transformRunOrder = [
'reserved-words',
'es6-arrow-functions',
'es6-object-concise-method',
'es6-object-short-notation',
'es6-classes',
'es6-rest-params',
'es6-templates',
'es6-destructuring',
'es6-call-spread',
'es7-spread-property',
'react'
];
/**
* Given a list of transform names, return the ordered list of visitors to be
* passed to the transform() function.
*
* @param {array?} excludes
* @return {array}
*/
function getAllVisitors(excludes) {
var ret = [];
for (var i = 0, il = transformRunOrder.length; i < il; i++) {
if (!excludes || excludes.indexOf(transformRunOrder[i]) === -1) {
ret = ret.concat(transformVisitors[transformRunOrder[i]]);
}
}
return ret;
}
/**
* Given a list of visitor set names, return the ordered list of visitors to be
* passed to jstransform.
*
* @param {array}
* @return {array}
*/
function getVisitorsBySet(sets) {
var visitorsToInclude = sets.reduce(function(visitors, set) {
if (!transformSets.hasOwnProperty(set)) {
throw new Error('Unknown visitor set: ' + set);
}
transformSets[set].forEach(function(visitor) {
visitors[visitor] = true;
});
return visitors;
}, {});
var visitorList = [];
for (var i = 0; i < transformRunOrder.length; i++) {
if (visitorsToInclude.hasOwnProperty(transformRunOrder[i])) {
visitorList = visitorList.concat(transformVisitors[transformRunOrder[i]]);
}
}
return visitorList;
}
exports.getVisitorsBySet = getVisitorsBySet;
exports.getAllVisitors = getAllVisitors;
exports.transformVisitors = transformVisitors;
},{"./transforms/react":38,"./transforms/reactDisplayName":39,"jstransform/visitors/es6-arrow-function-visitors":24,"jstransform/visitors/es6-call-spread-visitors":25,"jstransform/visitors/es6-class-visitors":26,"jstransform/visitors/es6-destructuring-visitors":27,"jstransform/visitors/es6-object-concise-method-visitors":28,"jstransform/visitors/es6-object-short-notation-visitors":29,"jstransform/visitors/es6-rest-param-visitors":30,"jstransform/visitors/es6-template-visitors":31,"jstransform/visitors/es7-spread-property-visitors":33,"jstransform/visitors/reserved-words-visitors":35}],41:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
/*eslint-disable no-undef*/
var Buffer = _dereq_('buffer').Buffer;
function inlineSourceMap(sourceMap, sourceCode, sourceFilename) {
// This can be used with a sourcemap that has already has toJSON called on it.
// Check first.
var json = sourceMap;
if (typeof sourceMap.toJSON === 'function') {
json = sourceMap.toJSON();
}
json.sources = [sourceFilename];
json.sourcesContent = [sourceCode];
var base64 = Buffer(JSON.stringify(json)).toString('base64');
return '//# sourceMappingURL=data:application/json;base64,' + base64;
}
module.exports = inlineSourceMap;
},{"buffer":3}]},{},[1])(1)
});
|
function appendTag(data){
// debugger;
var tag = data.post.tags.slice(-1)[0];
if ($('#new-tag').val() != '') {
// debugger;
$('#tags').append(showTag(tag))
$('#new-tag').val('');
deleteTag()
$('#numberoftags').html(data.post.tags.length);
}
}
var getAllTags = function() {
$.getJSON(path).done(function(response) {
showTags(response.post.tags)
createTagModel(response)
deleteTag()
})
}
function jsonTags(){
tags =[];
$.getJSON(path).done(function(response){
createTagModel(response)
$('#numberoftags').html(tags.length)
})
}
var tags =[];
var createTagModel = function(response){
tags =[];
response.post.tags.forEach(function(tag){
tags.push(new tagObject(tag.name))
})
}
function tagObject(tag){
this.name = tag;
}
function deleteTag(){
$(".delete_class").click(function(e){
$('#numberoftags').html(tags.length -1);
var id = $(this).attr('data-tag-id');
$('#listed-tag-'+id ).hide();
$.ajax({
url: path + '/delete_tag',
method: "DELETE",
data:{
tag_id: $(this).attr("data-tag-id")
}
}).success(function(data){
$('#numberoftags').html(data.posts.length)
})
})
}
var showTag = function(tag) {
// return $('<li>', {'data-name': tag.name, 'data-tagid': tag.id, text: tag.name });
var tag =
'<li class="list-group-item" id="listed-tag-'+tag.id+'" data-name=" ' + tag.name+ ' " data-tag-id="'+tag.id+'">' +
tag.name +
'<button class="delete_class" data-tag-id="'+tag.id+'">X</button>' +
'</li>';
return tag;
}
var showTags = function(tags) {
var dom = "";
tags.forEach(function(tag) {
dom += (showTag(tag));
});
$("#tags").html(dom);
}
|
module.exports={A:{A:{"1":"B","2":"I F E D A hB"},B:{"2":"C O P H J K L S UB M HB"},C:{"1":"0 1 O P H J K L W X Y Z a b c d e f g h i j k l m n o p q r s t u v w Q y z","2":"2 3 4 5 6 7 8 9 aB OB G V I F E D A B C WB BB GB DB EB CB AB T R N IB JB KB LB MB NB FB PB QB RB S gB oB"},D:{"1":"0 1 G V I F E D A B C O P H J K L W X Y Z a b c d e f g h i j k l m n o p q r s t u v w Q y z","2":"2 3 4 5 6 7 8 9 WB BB GB DB EB CB AB T R N IB JB KB LB MB NB FB PB QB RB S UB M HB pB rB YB"},E:{"1":"E D A B C eB TB U","2":"G V I F ZB SB bB cB dB","129":"O P x iB jB"},F:{"1":"H J K L W X Y Z a b c d e f g h i j k l m n o p q t v x","2":"0 1 2 3 4 5 6 7 8 9 D B C r s u w Q y z BB DB EB CB AB T R N kB lB mB nB U VB PC"},G:{"1":"E vB wB xB yB zB 0B 1B 2B","2":"SB qB XB sB tB uB","257":"3B 4B 5B 6B 7B 8B"},H:{"2":"9B"},I:{"1":"OB G DC XB EC FC","2":"M AC BC CC"},J:{"2":"F A"},K:{"1":"x","2":"A B C Q U VB"},L:{"2":"M"},M:{"2":"N"},N:{"1":"B","2":"A"},O:{"2":"GC"},P:{"1":"G","2":"HC IC JC KC LC TB MC"},Q:{"2":"NC"},R:{"16":"OC"},S:{"1":"fB"}},B:7,C:"SPDY protocol"};
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireDefault(require("react"));
var _offset = _interopRequireDefault(require("dom-helpers/offset"));
var _scrollTop = _interopRequireDefault(require("dom-helpers/scrollTop"));
var _scrollLeft = _interopRequireDefault(require("dom-helpers/scrollLeft"));
var _EventCell = _interopRequireDefault(require("./EventCell"));
var _selection = require("./utils/selection");
var Popup = /*#__PURE__*/function (_React$Component) {
(0, _inheritsLoose2.default)(Popup, _React$Component);
function Popup() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Popup.prototype;
_proto.componentDidMount = function componentDidMount() {
var _this$props = this.props,
_this$props$popupOffs = _this$props.popupOffset,
popupOffset = _this$props$popupOffs === void 0 ? 5 : _this$props$popupOffs,
popperRef = _this$props.popperRef,
_getOffset = (0, _offset.default)(popperRef.current),
top = _getOffset.top,
left = _getOffset.left,
width = _getOffset.width,
height = _getOffset.height,
viewBottom = window.innerHeight + (0, _scrollTop.default)(window),
viewRight = window.innerWidth + (0, _scrollLeft.default)(window),
bottom = top + height,
right = left + width;
if (bottom > viewBottom || right > viewRight) {
var topOffset, leftOffset;
if (bottom > viewBottom) topOffset = bottom - viewBottom + (popupOffset.y || +popupOffset || 0);
if (right > viewRight) leftOffset = right - viewRight + (popupOffset.x || +popupOffset || 0);
this.setState({
topOffset: topOffset,
leftOffset: leftOffset
}); //eslint-disable-line
}
};
_proto.render = function render() {
var _this = this;
var _this$props2 = this.props,
events = _this$props2.events,
selected = _this$props2.selected,
getters = _this$props2.getters,
accessors = _this$props2.accessors,
components = _this$props2.components,
onSelect = _this$props2.onSelect,
onDoubleClick = _this$props2.onDoubleClick,
onKeyPress = _this$props2.onKeyPress,
slotStart = _this$props2.slotStart,
slotEnd = _this$props2.slotEnd,
localizer = _this$props2.localizer,
popperRef = _this$props2.popperRef;
var width = this.props.position.width,
topOffset = (this.state || {}).topOffset || 0,
leftOffset = (this.state || {}).leftOffset || 0;
var style = {
top: -topOffset,
left: -leftOffset,
minWidth: width + width / 2
};
return /*#__PURE__*/_react.default.createElement("div", {
style: (0, _extends2.default)({}, this.props.style, style),
className: "rbc-overlay",
ref: popperRef
}, /*#__PURE__*/_react.default.createElement("div", {
className: "rbc-overlay-header"
}, localizer.format(slotStart, 'dayHeaderFormat')), events.map(function (event, idx) {
return /*#__PURE__*/_react.default.createElement(_EventCell.default, {
key: idx,
type: "popup",
localizer: localizer,
event: event,
getters: getters,
onSelect: onSelect,
accessors: accessors,
components: components,
onDoubleClick: onDoubleClick,
onKeyPress: onKeyPress,
continuesPrior: localizer.lt(accessors.end(event), slotStart, 'day'),
continuesAfter: localizer.gte(accessors.start(event), slotEnd, 'day'),
slotStart: slotStart,
slotEnd: slotEnd,
selected: (0, _selection.isSelected)(event, selected),
draggable: true,
onDragStart: function onDragStart() {
return _this.props.handleDragStart(event);
},
onDragEnd: function onDragEnd() {
return _this.props.show();
}
});
}));
};
return Popup;
}(_react.default.Component);
Popup.propTypes = process.env.NODE_ENV !== "production" ? {
position: _propTypes.default.object,
popupOffset: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.shape({
x: _propTypes.default.number,
y: _propTypes.default.number
})]),
events: _propTypes.default.array,
selected: _propTypes.default.object,
accessors: _propTypes.default.object.isRequired,
components: _propTypes.default.object.isRequired,
getters: _propTypes.default.object.isRequired,
localizer: _propTypes.default.object.isRequired,
onSelect: _propTypes.default.func,
onDoubleClick: _propTypes.default.func,
onKeyPress: _propTypes.default.func,
handleDragStart: _propTypes.default.func,
show: _propTypes.default.func,
slotStart: _propTypes.default.instanceOf(Date),
slotEnd: _propTypes.default.number,
popperRef: _propTypes.default.oneOfType([_propTypes.default.func, _propTypes.default.shape({
current: _propTypes.default.Element
})])
} : {};
/**
* The Overlay component, of react-overlays, creates a ref that is passed to the Popup, and
* requires proper ref forwarding to be used without error
*/
var _default = /*#__PURE__*/_react.default.forwardRef(function (props, ref) {
return /*#__PURE__*/_react.default.createElement(Popup, (0, _extends2.default)({
popperRef: ref
}, props));
});
exports.default = _default;
module.exports = exports.default;
|
(function(a){jQuery.fn.buildContainers=function(b){return this.each(function(){if(a(this).is("[inited=true]")){return}this.options={containment:"document",elementsPath:"elements/",onCollapse:function(){},onIconize:function(){},onClose:function(){},onResize:function(){},onDrag:function(){},onRestore:function(){},minimizeEffect:"slide",effectDuration:300};a.extend(this.options,b);var d=a(this);d.attr("inited","true");d.attr("iconized","false");d.attr("collapsed","false");d.attr("closed","false");d.attr("options",this.options);d.css({position:"relative"});if(a.metadata){a.metadata.setType("class");if(d.metadata().skin){d.attr("skin",d.metadata().skin)}if(d.metadata().collapsed){d.attr("collapsed",d.metadata().collapsed)}if(d.metadata().iconized){d.attr("iconized",d.metadata().iconized)}if(d.metadata().icon){d.attr("icon",d.metadata().icon)}if(d.metadata().buttons){d.attr("buttons",d.metadata().buttons)}if(d.metadata().content){d.attr("content",d.metadata().content)}if(d.metadata().aspectRatio){d.attr("aspectRatio",d.metadata().aspectRatio)}if(d.metadata().grid){d.attr("grid",d.metadata().grid)}if(d.metadata().gridx){d.attr("gridx",d.metadata().gridx)}if(d.metadata().gridy){d.attr("gridy",d.metadata().gridy)}if(d.metadata().handles){d.attr("handles",d.metadata().handles)}if(d.metadata().dock){d.attr("dock",d.metadata().dock)}if(d.metadata().width){d.attr("width",d.metadata().width)}if(d.metadata().height){d.attr("height",d.metadata().height)}}if(d.attr("content")){d.mb_changeContainerContent(d.attr("content"))}d.addClass(d.attr("skin"));d.find(".n:first").attr("unselectable","on");if(!d.find(".n:first").html()){d.find(".n:first").html(" ")}d.containerSetIcon(d.attr("icon"),this.options.elementsPath);if(d.attr("buttons")){d.containerSetButtons(d.attr("buttons"),this.options)}d.css({width:"99.9%"});if(d.attr("width")){var c=a.browser.msie?d.attr("width"):d.attr("width")+"px";d.css({width:c})}if(d.attr("height")){d.find(".c:first , .mbcontainercontent:first").css("height",d.attr("height")-d.find(".n:first").outerHeight()-(d.find(".s:first").outerHeight()))}if(d.hasClass("draggable")){d.css({position:"absolute",margin:0});d.find(".n:first").css({cursor:"move"});d.mb_BringToFront();d.draggable({handle:".n:first",delay:0,containment:this.options.containment,stop:function(){var f=a(this).attr("options");if(f.onDrag){f.onDrag(a(this))}}});if(d.attr("grid")||(d.attr("gridx")&&d.attr("gridy"))){var e=d.attr("grid")?[d.attr("grid"),d.attr("grid")]:[d.attr("gridx"),d.attr("gridy")];d.draggable("option","grid",e)}d.bind("mousedown",function(){a(this).mb_BringToFront()})}if(d.hasClass("resizable")){d.containerResize()}if(d.attr("collapsed")=="true"){d.attr("collapsed","false");d.containerCollapse(this.options)}if(d.attr("iconized")=="true"){d.attr("iconized","false");d.containerIconize(this.options)}setTimeout(function(){d.css("visibility","visible")},500)})};jQuery.fn.containerResize=function(){var c=a(this).hasClass("draggable");var b=a(this).attr("handles")?a(this).attr("handles"):"s";var d=a(this).attr("aspectRatio")?a(this).attr("aspectRatio"):false;a(this).resizable({handles:c?"":b,aspectRatio:d,minWidth:350,minHeight:150,iframeFix:true,helper:"mbproxy",start:function(f,g){g.helper.mb_BringToFront()},stop:function(){var h=a(this);var e=h.outerHeight()-a(this).find(".n:first").outerHeight()-(a(this).find(".s:first").outerHeight());a(this).find(".c:first , .mbcontainercontent:first").css({height:e});if(!c&&!a(this).attr("handles")){var g=a(this).attr("width")&&a(this).attr("width")>0?a(this).attr("width"):"99.9%";a(this).css({width:g})}var f=a(this).attr("options");if(f.onResize){f.onResize(a(this))}}});a(this).find(".ui-resizable-n").addClass("mb-resize").addClass("mb-resize-resizable-n");a(this).find(".ui-resizable-e").addClass("mb-resize").addClass("mb-resize-resizable-e");a(this).find(".ui-resizable-w").addClass("mb-resize").addClass("mb-resize-resizable-w");a(this).find(".ui-resizable-s").addClass("mb-resize").addClass("mb-resize-resizable-s");a(this).find(".ui-resizable-se").addClass("mb-resize").addClass("mb-resize-resizable-se")};jQuery.fn.containerSetIcon=function(b,c){if(b&&b!=""){a(this).find(".ne:first").prepend("<img class='icon' src='"+c+"icons/"+b+"' style='position:absolute'/>");a(this).find(".n:first").css({paddingLeft:25})}else{a(this).find(".n:first").css({paddingLeft:0})}};jQuery.fn.containerSetButtons=function(g,f){if(!f){f=a(this).attr("options")}var h=f.elementsPath;var b=a(this);if(g!=""){var e=g.split(",");a(this).find(".ne:first").append("<div class='buttonBar'></div>");for(var d in e){if(e[d]=="c"){a(this).find(".buttonBar:first").append("<img src='"+h+a(this).attr("skin")+"/close.png' class='close'/>");a(this).find(".close:first").bind("click",function(){if(!a.browser.msie){b.fadeOut(f.effectDuration)}else{b.hide()}b.attr("closed","true");if(f.onClose){f.onClose(b)}})}if(e[d]=="m"){a(this).find(".buttonBar:first").append("<img src='"+h+a(this).attr("skin")+"/min.png' class='collapsedContainer'/>");a(this).find(".collapsedContainer:first").bind("click",function(){b.containerCollapse(f)});a(this).find(".n:first").bind("dblclick",function(){b.containerCollapse(f)})}if(e[d]=="p"){a(this).find(".buttonBar:first").append("<img src='"+h+a(this).attr("skin")+"/print.png' class='printContainer'/>");a(this).find(".printContainer:first").bind("click",function(){})}if(e[d]=="i"){a(this).find(".buttonBar:first").append("<img src='"+h+a(this).attr("skin")+"/iconize.png' class='iconizeContainer'/>");a(this).find(".iconizeContainer:first").bind("click",function(){b.containerIconize(f)})}}var c=a.browser.mozilla||a.browser.safari;if(c){a(this).find(".buttonBar:first img").css({opacity:0.5,cursor:"pointer",mozUserSelect:"none",khtmlUserSelect:"none"}).mouseover(function(){a(this).fadeTo(200,1)}).mouseout(function(){if(c){a(this).fadeTo(200,0.5)}})}a(this).find(".buttonBar:first img").attr("unselectable","on")}};jQuery.fn.containerCollapse=function(b){this.each(function(){if(!b){b=a(this).attr("options")}var c=a(this);if(a(this).attr("collapsed")=="false"){c.attr("w",c.outerWidth());c.attr("h",c.outerHeight());if(b.minimizeEffect=="fade"){c.find(".o:first").fadeOut(b.effectDuration,function(){})}else{c.find(".icon:first").hide();c.find(".o:first").slideUp(b.effectDuration,function(){});c.animate({height:c.find(".n:first").outerHeight()+c.find(".s:first").outerHeight()},b.effectDuration,function(){c.find(".icon:first").show()})}c.attr("collapsed","true");c.find(".collapsedContainer:first").attr("src",b.elementsPath+a(this).attr("skin")+"/max.png");c.resizable("disable");if(b.onCollapse){b.onCollapse(c)}}else{if(b.minimizeEffect=="fade"){c.find(".o:first").fadeIn(b.effectDuration,function(){})}else{c.find(".o:first").slideDown(b.effectDuration,function(){});c.find(".icon:first").hide();c.animate({height:c.attr("h")},b.effectDuration,function(){c.find(".icon:first").show()})}if(c.hasClass("resizable")){c.resizable("enable")}c.attr("collapsed","false");c.find(".collapsedContainer:first").attr("src",b.elementsPath+a(this).attr("skin")+"/min.png");c.find(".mbcontainercontent:first").css("overflow","auto")}})};jQuery.fn.containerIconize=function(b){if(!b){b=a(this).attr("options")}return this.each(function(){var d=a(this);d.attr("iconized","true");if(d.attr("collapsed")=="false"){d.attr("h",d.outerHeight())}d.attr("w",d.attr("width")&&d.attr("width")>0?(!d.hasClass("resizable")?d.attr("width"):d.width()):!a(this).attr("handles")?"99.9%":d.width());d.attr("t",d.css("top"));d.attr("l",d.css("left"));d.resizable("disable");var c=0;var e=d.css("top");var f=d;if(d.attr("dock")){f=a("#"+d.attr("dock"));var g=f.find("img").size();c=a("#"+d.attr("dock")).offset().left+(32*g);e=a("#"+d.attr("dock")).offset().top}this.dockIcon=a("<img src='"+b.elementsPath+"icons/"+(d.attr("icon")?d.attr("icon"):"restore.png")+"' class='restoreContainer' width='32'/>").appendTo(f).css("cursor","pointer").hide().attr("contTitle",d.find(".n:first").html()).bind("click",function(){d.attr("iconized","false");if(d.is(".draggable")){d.css({top:a(this).offset().top,left:a(this).offset().left})}else{d.css({left:"auto",top:"auto"})}d.show();if(!a.browser.msie){d.find(".no:first").fadeIn("fast");if(d.attr("collapsed")=="false"){d.animate({height:d.attr("h"),width:d.attr("w"),left:d.attr("l"),top:d.attr("t")},b.effectDuration,function(){d.find(".mbcontainercontent:first").css("overflow","auto");if(d.hasClass("draggable")){d.mb_BringToFront()}});d.find(".c:first , .mbcontainercontent:first").css("height",d.attr("h")-d.find(".n:first").outerHeight()-(d.find(".s:first").outerHeight()))}else{d.animate({height:"60px",width:d.attr("w"),left:d.attr("l"),top:d.attr("t")},b.effectDuration)}}else{d.find(".no:first").show();if(d.attr("collapsed")=="false"){d.css({height:d.attr("h"),width:d.attr("w"),left:d.attr("l"),top:d.attr("t")},b.effectDuration);d.find(".c:first , .mbcontainercontent:first").css("height",d.attr("h")-d.find(".n:first").outerHeight()-(d.find(".s:first").outerHeight()))}else{d.css({height:"60px",width:d.attr("w"),left:d.attr("l"),top:d.attr("t")},b.effectDuration)}}if(d.hasClass("resizable")&&d.attr("collapsed")=="false"){d.resizable("enable")}a(this).remove();if(d.hasClass("draggable")){d.mb_BringToFront()}a(".iconLabel").remove();if(b.onRestore){b.onRestore(d)}}).bind("mouseenter",function(){var h="<div class='iconLabel'>"+a(this).attr("contTitle")+"</div>";a("body").append(h);a(".iconLabel").hide().css({position:"absolute",top:a(this).offset().top-15,left:a(this).offset().left+15,opacity:0.9}).fadeIn("slow").mb_BringToFront()}).bind("mouseleave",function(){a(".iconLabel").remove()});if(!a.browser.msie){d.find(".mbcontainercontent:first").css("overflow","hidden");d.find(".no:first").slideUp("fast");d.animate({height:"32px",width:"32px",left:c,top:e},b.effectDuration,function(){a(this.dockIcon).show();if(d.attr("dock")){d.hide()}})}else{d.find(".no:first").hide();d.css({height:"32px",width:"32px",left:c,top:e});a(this.dockIcon).show();if(d.attr("dock")){d.hide()}}if(b.onIconize){b.onIconize(d)}})};jQuery.fn.mb_resizeTo=function(c,b){if(!b){b=a(this).outerWidth()}if(!c){c=a(this).outerHeight()}a(this).animate({height:c,width:b},500,function(){var d=a(this).outerHeight()-a(this).find(".n:first").outerHeight()-(a(this).find(".s:first").outerHeight());a(this).find(".c:first , .mbcontainercontent:first").animate({height:d})})};jQuery.fn.mb_iconize=function(){if(a(this).attr("closed")=="false"){if(a(this).attr("iconized")=="true"){var b=a(this)[0].dockIcon;a(b).click();a(this).mb_BringToFront()}else{a(this).containerIconize()}}};jQuery.fn.mbOpenBox=function(b,c){if(a(this).attr("closed")=="true"){if(!c){c=""}if(b){a(this).mb_changeContainerContent(b,c)}if(!a.browser.msie){a(this).fadeIn(300)}else{a(this).show()}a(this).attr("closed","false");a(this).mb_BringToFront()}};jQuery.fn.mbCloseBox=function(){if(a(this).attr("closed")=="false"){a(this).find(".close:first").click()}};jQuery.fn.mb_toggle=function(){if(a(this).attr("closed")=="false"&&a(this).attr("iconized")=="false"){a(this).containerCollapse()}};jQuery.fn.mb_BringToFront=function(){var b=10;a("*").each(function(){if(a(this).css("position")=="absolute"){var c=parseInt(a(this).css("zIndex"));b=c>b?parseInt(a(this).css("zIndex")):b}});a(this).css("zIndex",b+=1)};jQuery.fn.mb_changeContent=function(c,d){var b=a(this);if(!d){d=""}a.ajax({type:"POST",url:c,data:d,success:function(e){b.html(e)}})};jQuery.fn.mb_changeContainerContent=function(b,c){a(this).find(".mbcontainercontent:first").mb_changeContent(b,c)};jQuery.fn.mb_getState=function(b){var c=a(this).attr(b);c=c=="true";return c};jQuery.fn.mb_fullscreen=function(){if(!a(this).is(".draggable")||a(this).is("[iconized='true']")||a(this).is("[collapsed='true']")){return}a(this).attr("w",a(this).width());a(this).attr("h",a(this).height());a(this).attr("t",a(this).css("top"));a(this).attr("l",a(this).css("left"));a(this).animate({top:10,left:10,position:"relative"});a(this).mb_resizeTo("98%","98%")}})(jQuery);
|
// eslint-disable-next-line filenames/match-exported
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import ExampleShapes from '../examples/example-shapes'
import { shapeExampleStyles } from './styles'
const SectionShapes = ({ shapes }) =>
shapes ? <ExampleShapes styles={shapeExampleStyles} /> : <></>
SectionShapes.propTypes = {
shapes: PropTypes.bool.isRequired,
}
const mapStateToProps = state => ({
shapes: state.getIn(['app', 'shapes']),
})
export default connect(mapStateToProps)(SectionShapes)
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(async function() {
TestRunner.addResult(`Tests the Timeline events for Timers\n`);
await TestRunner.loadModule('performance_test_runner');
await TestRunner.showPanel('timeline');
await TestRunner.evaluateInPagePromise(`
function performActions()
{
var callback;
var promise = new Promise((fulfill) => callback = fulfill);
var timerOne = setTimeout("1 + 1", 10);
var timerTwo = setInterval(intervalTimerWork, 20);
var iteration = 0;
function intervalTimerWork()
{
if (++iteration < 2)
return;
clearInterval(timerTwo);
callback();
}
return promise;
}
`);
UI.panels.timeline._disableCaptureJSProfileSetting.set(true);
await PerformanceTestRunner.invokeAsyncWithTimeline('performActions');
await PerformanceTestRunner.printTimelineRecordsWithDetails('TimerInstall');
await PerformanceTestRunner.printTimelineRecordsWithDetails('TimerFire');
await PerformanceTestRunner.printTimelineRecordsWithDetails('TimerRemove');
PerformanceTestRunner.printTimelineRecords('FunctionCall');
await PerformanceTestRunner.printTimelineRecordsWithDetails('EvaluateScript');
TestRunner.completeTest();
})();
|
var searchData=
[
['timer_5fcontinuous_5fcallback',['Timer_CONTINUOUS_CALLBACK',['../_timer_8h.html#ab0e86a066b5c68c55183cd680090a9b7ae8bfe2f9b37749ebc20b9905a459843b',1,'Timer.h']]],
['timer_5ffree_5frunning',['Timer_FREE_RUNNING',['../_timer_8h.html#ab0e86a066b5c68c55183cd680090a9b7a90581a353ae32c561dfbc6c60b9ec49e',1,'Timer.h']]],
['timer_5foneshot_5fblocking',['Timer_ONESHOT_BLOCKING',['../_timer_8h.html#ab0e86a066b5c68c55183cd680090a9b7ac93d728c52e809e9c179ff8da526ca00',1,'Timer.h']]],
['timer_5foneshot_5fcallback',['Timer_ONESHOT_CALLBACK',['../_timer_8h.html#ab0e86a066b5c68c55183cd680090a9b7a01f0c06391bb2ea1ec530ba502a795a5',1,'Timer.h']]],
['timer_5fperiod_5fcounts',['Timer_PERIOD_COUNTS',['../_timer_8h.html#ae5b37c2cc77a2a426ba45d2c8544d439ac22836849686dc6b10a6cdf2c689d142',1,'Timer.h']]],
['timer_5fperiod_5fhz',['Timer_PERIOD_HZ',['../_timer_8h.html#ae5b37c2cc77a2a426ba45d2c8544d439afe77ce02e894805812fd4b497b2ba41c',1,'Timer.h']]],
['timer_5fperiod_5fus',['Timer_PERIOD_US',['../_timer_8h.html#ae5b37c2cc77a2a426ba45d2c8544d439a03cfd261fae09a76a370acd8240181b1',1,'Timer.h']]],
['timercc32xx_5ftimer16a',['TimerCC32XX_timer16A',['../_timer_c_c32_x_x_8h.html#a97bb0318f72dfc66cb16aa018a374216a43b7adae2f0ef1ee10e9da49473fb773',1,'TimerCC32XX.h']]],
['timercc32xx_5ftimer16b',['TimerCC32XX_timer16B',['../_timer_c_c32_x_x_8h.html#a97bb0318f72dfc66cb16aa018a374216aa51314518db28d1b5c91f8d6e5e80347',1,'TimerCC32XX.h']]],
['timercc32xx_5ftimer32',['TimerCC32XX_timer32',['../_timer_c_c32_x_x_8h.html#a97bb0318f72dfc66cb16aa018a374216a538222c3d455a024fc5081a58f6d47c8',1,'TimerCC32XX.h']]]
];
|
// pages/home/childComponents/w-popular/w-popular.js
Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
}
})
|
/*jshint node:true*/
function reportFormat() {
return _circleTestDirectory() ? 'xunit' : 'tap';
}
function outputFile() {
if (_circleTestDirectory()) {
return _ouputLocation(_circleTestDirectory(), _emberTryVersion());
}
}
function _ouputLocation(directory, version) {
var output = directory + '/testem';
if (version) {
output += '-' + version;
}
return output + '.xml';
}
function _circleTestDirectory() {
return process.env['CIRCLE_TEST_REPORTS'];
}
function _emberTryVersion() {
return process.env['EMBER_TRY_CURRENT_SCENARIO'];
}
module.exports = {
"framework": "qunit",
"test_page": "tests/index.html?hidepassed",
"disable_watching": true,
"launch_in_ci": [
"Chrome",
"Firefox"
],
"launch_in_dev": [
"Chrome"
],
reporter: reportFormat(),
report_file: outputFile(),
xunit_intermediate_output: true
};
|
/**
* Auto-generated action file for "StackExchange" API.
*
* Generated at: 2019-05-07T14:44:12.456Z
* Mass generator version: 1.1.0
*
* flowground :- Telekom iPaaS / stackexchange-com-connector
* Copyright © 2019, Deutsche Telekom AG
* contact: flowground@telekom.de
*
* All files of this connector are licensed under the Apache 2.0 License. For details
* see the file LICENSE on the toplevel directory.
*
*
* Operation: undefined
* Endpoint Path: '/tags/{tag}/top-askers/{period}'
* Method: 'get'
*
*/
const Swagger = require('swagger-client');
const processWrapper = require('../services/process-wrapper');
const spec = require('../spec.json');
// this wrapers offers a simplified emitData(data) function
module.exports.process = processWrapper(processAction);
// parameter names for this call
const PARAMETERS = [
"tag",
"period",
"pagesize",
"page",
"filter",
"callback",
"site"
];
// mappings from connector field names to API field names
const FIELD_MAP = {
"tag": "tag",
"period": "period",
"pagesize": "pagesize",
"page": "page",
"filter": "filter",
"callback": "callback",
"site": "site"
};
function processAction(msg, cfg) {
var isVerbose = process.env.debug || cfg.verbose;
if (isVerbose) {
console.log(`---MSG: ${JSON.stringify(msg)}`);
console.log(`---CFG: ${JSON.stringify(cfg)}`);
console.log(`---ENV: ${JSON.stringify(process.env)}`);
}
const contentType = undefined;
const body = msg.body;
mapFieldNames(body);
let parameters = {};
for(let param of PARAMETERS) {
parameters[param] = body[param];
}
// credentials for this operation
let securities = {};
securities['oauth_2_0'] = {token: cfg['oauth_2_0']};
let callParams = {
spec: spec,
operationId: undefined,
pathName: '/tags/{tag}/top-askers/{period}',
method: 'get',
parameters: parameters,
requestContentType: contentType,
requestBody: body.requestBody,
securities: {authorized: securities},
server: spec.servers[cfg.server] || cfg.otherServer,
};
if (isVerbose) {
let out = Object.assign({}, callParams);
out.spec = '[omitted]';
console.log(`--SWAGGER CALL: ${JSON.stringify(out)}`);
}
// Call operation via Swagger client
return Swagger.execute(callParams).then(data => {
// emit a single message with data
this.emitData(data);
// if the response contains an array of entities, you can emit them one by one:
// data.obj.someItems.forEach((item) => {
// this.emitData(item);
// }
});
}
function mapFieldNames(obj) {
if(Array.isArray(obj)) {
obj.forEach(mapFieldNames);
}
else if(typeof obj === 'object' && obj) {
Object.keys(obj).forEach(key => {
mapFieldNames(obj[key]);
let goodKey = FIELD_MAP[key];
if(goodKey && goodKey !== key) {
obj[goodKey] = obj[key];
delete obj[key];
}
});
}
}
|
"use strict";
var path = require("path");
var phtm = require("./lib/phtm-wrapper")(path.resolve(__dirname, "./lib/script.js"));
function visit(url, script, options, callback) {
if (!url || !script) return callback(new TypeError("Incorrect arguments."));
if (!callback) {
callback = options;
options = {};
}
phtm(url, script, options, function(err, result) {
callback(err, result);
});
}
function visitPages(urls, script, options, callback) {
if (!urls || !script) return callback(new TypeError("Incorrect arguments."));
if (!callback) {
callback = options;
options = {};
}
urls = urls.slice(0);
var output = [];
function next(err, result) {
if (err) {
callback(err);
return;
}
output.push(result);
if (urls.length) {
visit(urls.shift(), script, next);
} else {
callback(null, output);
}
}
visit(urls.shift(), script, options, next);
};
module.exports = visit;
module.exports.visit = visit;
module.exports.visitPages = visitPages;
|
import React from 'react';
import ArtistService from '../../../services/ArtistService';
import {NavLink} from 'react-router-dom';
import { url } from '../../../util/helpers';
export default class ListArtistsPage extends React.Component {
constructor(props) {
super(props);
this.state = {
artists: null,
loaded: false
}
}
load() {
ArtistService
.all()
.then(artists => this.setState({ artists: artists, loaded: true}))
.catch(console.log);
}
delete(artist){
ArtistService
.destroy(artist.id)
.then(()=>this.load())
.catch(console.log);
}
componentDidMount = this.load;
render() {
const artists = this.state.artists;
return (
<div className="w-full h-full flex flex-col items-start px-8 py-4">
<h3 className="text-gray-200 font-bold tracking-tight text-3xl border-gray-800 border-b">Artists</h3>
<NavLink exact={true} to="/editor/artist/add">
<div className="mt-4 bg-green-600 text-gray-200 py-2 px-8 rounded-full font-bold text-lg shadow focus:outline-none hover:bg-green-700 active:bg-green-500" >
Create artist
</div>
</NavLink>
{ this.state.loaded && <>
<div className="mt-4 w-full">
{ (artists.length === 0) &&
<p className="mt-2 text-gray-200 text-lg">There are no Artists.</p>
}
<ul className="mt-4 mb-8 w-full flex flex-col items-start justify-start">
{ artists.map(artist => (
<li className="flex items-center w-full px-4 py-1">
<div className="flex items-center w-1/2">
<img src={url() + "/" + artist.photo} alt="Artist" className="rounded-full h-10 w-10"/>
<p className="ml-4 text-gray-100 text-xl tracking-tight font-bold">{artist.name}</p>
</div>
<div className="flex items-center w-1/2">
<NavLink exact={true} className="text-gray-600 hover:text-gray-500" to={`/editor/artist/edit/${artist.id}`}>
<svg className="h-6 w-6" viewBox="0 0 24 24" fill="none">
<path d="M19 13v5a2 2 0 01-2 2H6a2 2 0 01-2-2V7a2 2 0 012-2h5l2.672 2.5m3.914-3.914a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</NavLink>
<button className="text-red-700 hover:text-red-600 ml-4 " onClick={()=>this.delete(artist)}>
<svg className="h-4 w-4" viewBox="0 0 24 24" fill="none">
<path fill-rule="evenodd" clip-rule="evenodd" d="M3.56 1.44l9.547 9.545a1.5 1.5 0 010 2.122L3.56 22.653a1.5 1.5 0 11-2.122-2.122l8.486-8.485L1.439 3.56a1.5 1.5 0 112.122-2.122z" fill="currentColor"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M19.925 22.652l-9.546-9.545a1.5 1.5 0 010-2.122l9.546-9.546a1.5 1.5 0 112.12 2.122l-8.484 8.485 8.485 8.485a1.5 1.5 0 11-2.121 2.122z" fill="currentColor"/>
</svg>
</button>
</div>
</li>
))}
</ul>
</div>
</>}
</div>
);
}
}
|
// Copyright IBM Corp. 2018,2019. All Rights Reserved.
// Node module: @loopback/cli
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
('use strict');
// Imports
const path = require('path');
const assert = require('yeoman-assert');
const testlab = require('@loopback/testlab');
const expect = testlab.expect;
const TestSandbox = testlab.TestSandbox;
const generator = path.join(__dirname, '../../../generators/model');
const tests = require('../lib/artifact-generator')(generator);
const baseTests = require('../lib/base-generator')(generator);
const testUtils = require('../../test-utils');
const basicModelFileChecks = require('../lib/file-check').basicModelFileChecks;
// Test Sandbox
const SANDBOX_PATH = path.resolve(__dirname, '../.sandbox');
const DISCOVER_SANDBOX_FILES = require('../../fixtures/discover').SANDBOX_FILES;
const sandbox = new TestSandbox(SANDBOX_PATH);
// Basic CLI Input
const basicCLIInput = {
name: 'test',
};
// Expected File Paths & File Contents
const expectedIndexFile = path.join(SANDBOX_PATH, 'src/models/index.ts');
const expectedModelFile = path.join(SANDBOX_PATH, 'src/models/test.model.ts');
// Base Tests
describe('model-generator extending BaseGenerator', baseTests);
describe('generator-loopback4:model', tests);
describe('lb4 model integration', () => {
beforeEach('reset sandbox', () => sandbox.reset());
it('does not run without package.json', () => {
return expect(
testUtils
.executeGenerator(generator)
.inDir(SANDBOX_PATH, () =>
testUtils.givenLBProject(SANDBOX_PATH, {excludePackageJSON: true}),
)
.withPrompts(basicCLIInput),
).to.be.rejectedWith(/No package.json found in/);
});
it('does not run without the "@loopback/core" dependency', () => {
return expect(
testUtils
.executeGenerator(generator)
.inDir(SANDBOX_PATH, () =>
testUtils.givenLBProject(SANDBOX_PATH, {excludeLoopbackCore: true}),
)
.withPrompts(basicCLIInput),
).to.be.rejectedWith(/No `@loopback\/core` package found/);
});
it('does not run if passed an invalid model from command line', () => {
return expect(
testUtils
.executeGenerator(generator)
.inDir(SANDBOX_PATH, () =>
testUtils.givenLBProject(SANDBOX_PATH, {excludeLoopbackCore: false}),
)
.withArguments('myNewModel --base InvalidModel'),
).to.be.rejectedWith(/Model was not found in/);
});
it('run if passed a valid base model from command line', async () => {
await testUtils
.executeGenerator(generator)
.inDir(SANDBOX_PATH, () => testUtils.givenLBProject(SANDBOX_PATH))
.withArguments('test --base Model');
assert.file(expectedModelFile);
});
it('will discover a model through a datasource', async () => {
await testUtils
.executeGenerator(generator)
.inDir(SANDBOX_PATH, () =>
testUtils.givenLBProject(SANDBOX_PATH, {
additionalFiles: DISCOVER_SANDBOX_FILES,
}),
)
.withArguments('--dataSource mem --table Test');
assert.file(expectedModelFile);
});
it('will fail gracefully if datasource discovery does not find the model ', async () => {
return expect(
testUtils
.executeGenerator(generator)
.inDir(SANDBOX_PATH, () =>
testUtils.givenLBProject(SANDBOX_PATH, {
additionalFiles: DISCOVER_SANDBOX_FILES,
}),
)
.withArguments('--dataSource mem --table Foo'),
).to.be.rejectedWith(/Could not locate table:/);
});
describe('model generator', () => {
it('scaffolds correct files with input', async () => {
await testUtils
.executeGenerator(generator)
.inDir(SANDBOX_PATH, () => testUtils.givenLBProject(SANDBOX_PATH))
.withPrompts({
name: 'test',
propName: null,
});
basicModelFileChecks(expectedModelFile, expectedIndexFile);
});
it('scaffolds correct files with model base class', async () => {
await testUtils
.executeGenerator(generator)
.inDir(SANDBOX_PATH, () => testUtils.givenLBProject(SANDBOX_PATH))
.withPrompts({
name: 'test',
propName: null,
modelBaseClass: 'Model',
allowAdditionalProperties: false,
});
assert.file(expectedModelFile);
assert.file(expectedIndexFile);
// Actual Model File
assert.fileContent(
expectedModelFile,
/import {Model, model, property} from '@loopback\/repository';/,
);
assert.fileContent(expectedModelFile, /@model()/);
assert.fileContent(
expectedModelFile,
/export class Test extends Model {/,
);
});
it('scaffolds correct files with model custom class', async () => {
await testUtils
.executeGenerator(generator)
.inDir(SANDBOX_PATH, () =>
testUtils.givenLBProject(SANDBOX_PATH, {includeDummyModel: true}),
)
.withPrompts({
name: 'test',
propName: null,
modelBaseClass: 'ProductReview',
});
assert.file(expectedModelFile);
assert.file(expectedIndexFile);
// Actual Model File
assert.fileContent(
expectedModelFile,
/import {model, property} from '@loopback\/repository';/,
);
assert.fileContent(expectedModelFile, /@model()/);
assert.fileContent(
expectedModelFile,
/export class Test extends ProductReview {/,
);
});
it('scaffolds model with strict setting disabled', async () => {
await testUtils
.executeGenerator(generator)
.inDir(SANDBOX_PATH, () => testUtils.givenLBProject(SANDBOX_PATH))
.withPrompts({
name: 'test',
propName: null,
modelBaseClass: 'Entity',
allowAdditionalProperties: true,
});
assert.file(expectedModelFile);
assert.file(expectedIndexFile);
assert.fileContent(
expectedModelFile,
/import {Entity, model, property} from '@loopback\/repository';/,
);
assert.fileContent(
expectedModelFile,
/@model\({settings: {strict: false}}\)/,
);
assert.fileContent(
expectedModelFile,
/export class Test extends Entity {/,
);
assert.fileContent(expectedModelFile, /\[prop: string\]: any;/);
});
it('scaffolds correct files with args', async () => {
await testUtils
.executeGenerator(generator)
.inDir(SANDBOX_PATH, () => testUtils.givenLBProject(SANDBOX_PATH))
.withArguments('test')
.withPrompts({
propName: null,
});
basicModelFileChecks(expectedModelFile, expectedIndexFile);
});
});
});
describe('model generator using --config option', () => {
it('create models with valid json', async () => {
await testUtils
.executeGenerator(generator)
.inDir(SANDBOX_PATH, () => testUtils.givenLBProject(SANDBOX_PATH))
.withArguments(['--config', '{"name":"test", "base":"Entity"}', '--yes']);
basicModelFileChecks(expectedModelFile, expectedIndexFile);
});
it('does not run if pass invalid json', () => {
return expect(
testUtils
.executeGenerator(generator)
.inDir(SANDBOX_PATH, () => testUtils.givenLBProject(SANDBOX_PATH))
.withArguments([
'--config',
'{"name":"test", "base":"InvalidBaseModel"}',
'--yes',
]),
).to.be.rejectedWith(/Model was not found in/);
});
describe('model generator using --config option with model settings', () => {
it('creates a model with valid settings', async () => {
await testUtils
.executeGenerator(generator)
.inDir(SANDBOX_PATH, () => testUtils.givenLBProject(SANDBOX_PATH))
.withArguments([
'--config',
'{"name":"test", "base":"Entity", \
"modelSettings": {"annotations": \
[{"destinationClass": "class1","argument": 0}],\
"foreignKeys": {"fk_destination": {"name": "fk_destination"}}},\
"allowAdditionalProperties":true}',
'--yes',
]);
basicModelFileChecks(expectedModelFile, expectedIndexFile);
assert.fileContent(
expectedModelFile,
/@model\({\n settings: {\n annotations: \[{destinationClass: 'class1', argument: 0}],\n foreignKeys: {fk_destination: {name: 'fk_destination'}},\n strict: false\n }\n}\)/,
);
});
});
});
|
import React from 'react'
import Layout from '../components/layout'
import Head from '../components/head'
const ContactPage=()=>{
return(
<Layout>
<Head title={'home'}/>
<h1>Contacts</h1>
<p>the Best way to reach me is via My Twitter <a href='https://twitter.com/OUALI_Meriem' target='block' >@OUALI_Meriem</a></p>
</Layout>
)
}
export default ContactPage
|
var util = require('util');
var events = require('events');
var config = require('config');
var redis = require('redis-scanstreams')(require('redis')).createClient(6379, config.get('redis.host'));
var redisChan = require('redis').createClient(6379, config.get('redis.host'), {return_buffers: true});
var tredis = require('then-redis').createClient(config.get('redis'));
var Promise = require('bluebird');
var models = require('./models');
var msgpack = require('msgpack-js');
function Playback() {
this.dispatch();
redisChan.subscribe('musicpicker.playback');
}
util.inherits(Playback, events.EventEmitter);
Playback.prototype.dispatch = function() {
redisChan.on('message', function(channel, message) {
if (channel !== 'musicpicker.playback') {
return;
}
var message = msgpack.decode(message);
this.emit(message.Event, message.Device, message.Options);
}.bind(this));
};
Playback.prototype.publish = function(eventName, deviceId, opts) {
redis.publish('musicpicker.playback', msgpack.encode({
Device: deviceId,
Event: eventName,
Options: opts
}));
};
Playback.prototype.state = function (deviceId) {
return new Promise(function(resolve, reject) {
Promise.props({
Connected: tredis.exists('musichub.device.' + deviceId + '.connection'),
Current: tredis.get('musichub.device.' + deviceId + '.current'),
Duration: tredis.get('musichub.device.' + deviceId + '.duration'),
Playing: tredis.get('musichub.device.' + deviceId + '.playing'),
Paused: tredis.get('musichub.device.' + deviceId + '.paused'),
FromTime: tredis.get('musichub.device.' + deviceId + '.fromtime'),
Position: tredis.get('musichub.device.' + deviceId + '.position'),
Queue: tredis.lrange('musichub.device.' + deviceId + '.queue', 0, -1)
}).then(function(result) {
resolve({
Device: deviceId,
Connected: Boolean(parseInt(result.Connected)),
Current: parseInt(result.Current),
Duration: parseInt(result.Duration),
Playing: Boolean(parseInt(result.Playing)),
Paused: Boolean(parseInt(result.Paused)),
FromTime: parseInt(result.FromTime),
Position: parseInt(result.Position),
Queue: result.Queue.map(function(item) {
return parseInt(item);
})
});
});
});
}
Playback.prototype.updateState = function (deviceId) {
return new Promise(function(resolve, reject) {
Promise.props({
current: tredis.lpop('musichub.device.' + deviceId + '.queue'),
currentDeviceTrack: tredis.lpop('musichub.device.' + deviceId + '.queue.device'),
}).then(function(props) {
tredis.set('musichub.device.' + deviceId + '.current', props.current).then(function() {
new models.DeviceTrack({
DeviceId: deviceId,
TrackId: props.current
}).fetch().then(function(dt) {
tredis.set('musichub.device.' + deviceId + '.duration', dt.get('TrackDuration')).then(function() {
resolve(props.currentDeviceTrack);
})
});
});
})
});
}
Playback.prototype.updatePosition = function (deviceId) {
return new Promise(function(resolve, reject) {
tredis.get('musichub.device.' + deviceId + '.position').then(function(currentPosition) {
tredis.get('musichub.device.' + deviceId + '.fromtime').then(function(fromTime) {
var newPosition = parseInt(currentPosition) + (Date.now() - parseInt(fromTime));
tredis.set('musichub.device.' + deviceId + '.position', newPosition).then(function() {
resolve();
});
});
});
});
}
Playback.prototype.addTrackToQueue = function (deviceId, trackId) {
return new Promise(function(resolve, reject) {
new models.DeviceTrack({
DeviceId: deviceId,
TrackId: trackId
}).fetch().then(function(dt) {
var deviceTrackId = dt.get('DeviceTrackId');
Promise.all([
tredis.rpush('musichub.device.' + deviceId + '.queue', trackId),
tredis.rpush('musichub.device.' + deviceId + '.queue.device', deviceTrackId)
]).then(function() {
resolve();
})
});
});
}
Playback.prototype.requestNext = function (deviceId) {
return new Promise(function(resolve, reject) {
tredis.set('musichub.device.' + deviceId + '.playing', 0).then(function() {
this.publish('RequestNext', deviceId);
resolve();
}.bind(this));
}.bind(this));
}
Playback.prototype.play = function (deviceId) {
return new Promise(function(resolve, reject) {
Promise.all([
tredis.set('musichub.device.' + deviceId + '.playing', 1),
tredis.set('musichub.device.' + deviceId + '.paused', 0),
tredis.set('musichub.device.' + deviceId + '.fromtime', Date.now())
]).then(function() {
this.publish('Play', deviceId);
resolve();
}.bind(this));
}.bind(this));
}
Playback.prototype.pause = function(deviceId) {
return new Promise(function(resolve, reject) {
Promise.all([
tredis.set('musichub.device.' + deviceId + '.paused', 1),
this.updatePosition(deviceId)
]).then(function() {
this.publish('Pause', deviceId);
resolve();
}.bind(this));
}.bind(this));
}
Playback.prototype.next = function (deviceId) {
return new Promise(function(resolve, reject) {
tredis.llen('musichub.device.' + deviceId + '.queue').then(function(queueLen) {
if (parseInt(queueLen) > 0) {
Promise.all([
tredis.set('musichub.device.' + deviceId + '.playing', 1),
tredis.set('musichub.device.' + deviceId + '.paused', 0)
]).then(function() {
this.updateState(deviceId).then(function(currentDeviceTrack) {
tredis.set('musichub.device.' + deviceId + '.fromtime', Date.now()).then(function() {
tredis.set('musichub.device.' + deviceId + '.position', 0).then(function() {
this.publish('Next', deviceId, currentDeviceTrack);
resolve(currentDeviceTrack);
}.bind(this));
}.bind(this));
}.bind(this));
}.bind(this));
}
else {
Promise.all([
tredis.del('musichub.device.' + deviceId + '.current'),
tredis.del('musichub.device.' + deviceId + '.duration'),
tredis.del('musichub.device.' + deviceId + '.playing'),
tredis.del('musichub.device.' + deviceId + '.paused'),
tredis.del('musichub.device.' + deviceId + '.fromtime'),
tredis.del('musichub.device.' + deviceId + '.position'),
tredis.del('musichub.device.' + deviceId + '.queue')
]).then(function() {
this.publish('Next', deviceId, null);
resolve(null);
}.bind(this));
}
}.bind(this));
}.bind(this));
}
Playback.prototype.queue = function(deviceId, trackIds) {
return new Promise(function(resolve, reject) {
Promise.all([
tredis.del('musichub.device.' + deviceId + '.queue'),
tredis.del('musichub.device.' + deviceId + '.queue.device')
]).then(function() {
Promise.each(trackIds, function(trackId) {
return this.addTrackToQueue(deviceId, trackId);
}.bind(this)).then(function() {
tredis.get('musichub.device.' + deviceId + '.playing').then(function(playing) {
if (Boolean(parseInt(playing))) {
this.requestNext(deviceId);
resolve();
}
else {
tredis.set('musichub.device.' + deviceId + '.playing', 0).then(function() {
this.next(deviceId);
resolve();
}.bind(this));
}
}.bind(this));
}.bind(this));
}.bind(this));
}.bind(this));
}
module.exports = Playback;
|
import React, { Component } from 'react'
import { browserHistory, Router } from 'react-router'
import { Provider } from 'react-redux'
class AppContainer extends Component {
shouldComponentUpdate () {
return false
}
render () {
const { routes, store } = this.props
return (
<Provider store={store}>
<div style={{ height: '100%' }}>
<Router history={browserHistory} children={routes} />
</div>
</Provider>
)
}
}
export default AppContainer
|
//// [test.ts]
export async function fn() {
const req = await import('./test') // ONE
}
export class cl1 {
public async m() {
const req = await import('./test') // TWO
}
}
export const obj = {
m: async () => {
const req = await import('./test') // THREE
}
}
export class cl2 {
public p = {
m: async () => {
const req = await import('./test') // FOUR
}
}
}
export const l = async () => {
const req = await import('./test') // FIVE
}
//// [test.js]
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
var __syncRequire = typeof module === "object" && typeof module.exports === "object";
var _this = this;
exports.__esModule = true;
function fn() {
return __awaiter(this, void 0, void 0, function () {
var req;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_1, reject_1) { require(['./test'], resolve_1, reject_1); })]; // ONE
case 1:
req = _a.sent() // ONE
;
return [2 /*return*/];
}
});
});
}
exports.fn = fn;
var cl1 = /** @class */ (function () {
function cl1() {
}
cl1.prototype.m = function () {
return __awaiter(this, void 0, void 0, function () {
var req;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_2, reject_2) { require(['./test'], resolve_2, reject_2); })]; // TWO
case 1:
req = _a.sent() // TWO
;
return [2 /*return*/];
}
});
});
};
return cl1;
}());
exports.cl1 = cl1;
exports.obj = {
m: function () { return __awaiter(_this, void 0, void 0, function () {
var req;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_3, reject_3) { require(['./test'], resolve_3, reject_3); })]; // THREE
case 1:
req = _a.sent() // THREE
;
return [2 /*return*/];
}
});
}); }
};
var cl2 = /** @class */ (function () {
function cl2() {
var _this = this;
this.p = {
m: function () { return __awaiter(_this, void 0, void 0, function () {
var req;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_4, reject_4) { require(['./test'], resolve_4, reject_4); })]; // FOUR
case 1:
req = _a.sent() // FOUR
;
return [2 /*return*/];
}
});
}); }
};
}
return cl2;
}());
exports.cl2 = cl2;
exports.l = function () { return __awaiter(_this, void 0, void 0, function () {
var req;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_5, reject_5) { require(['./test'], resolve_5, reject_5); })]; // FIVE
case 1:
req = _a.sent() // FIVE
;
return [2 /*return*/];
}
});
}); };
});
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Dolittle. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import {BindingSyntax} from '../BindingSyntax';
import * as Context from './given/an_empty_container';
describe('when binding service', () => {
const service = 'Some service';
let context = null;
let result = null;
beforeEach(() => {
context = new Context.default();
(function becauseOf() {
result = context.container.bind(service);
})();
});
it('should be returning a binding syntax', () => result.should.be.instanceof(BindingSyntax));
it('should have passed the container to the binding syntax', () => result.container.should.equal(context.container));
it('should have passed the service to the binding syntax', () => result.service.should.equal(service));
});
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('emoticons', function(K) {
var self = this, name = 'emoticons',
path = (self.emoticonsPath || self.pluginsPath + 'emoticons/images/'),
allowPreview = self.allowPreviewEmoticons === undefined ? true : self.allowPreviewEmoticons,
currentPageNum = 1;
self.clickToolbar(name, function() {
var rows = 5, cols = 9, total = 135, startNum = 0,
cells = rows * cols, pages = Math.ceil(total / cells),
colsHalf = Math.floor(cols / 2),
wrapperDiv = K('<div class="ke-plugin-emoticons"></div>'),
elements = [],
menu = self.createMenu({
name : name,
beforeRemove : function() {
removeEvent();
}
});
menu.div.append(wrapperDiv);
var previewDiv, previewImg;
if (allowPreview) {
previewDiv = K('<div class="ke-preview"></div>').css('right', 0);
previewImg = K('<img class="ke-preview-img" src="' + path + startNum + '.gif" />');
wrapperDiv.append(previewDiv);
previewDiv.append(previewImg);
}
function bindCellEvent(cell, j, num) {
if (previewDiv) {
cell.mouseover(function() {
if (j > colsHalf) {
previewDiv.css('left', 0);
previewDiv.css('right', '');
} else {
previewDiv.css('left', '');
previewDiv.css('right', 0);
}
previewImg.attr('src', path + num + '.gif');
K(this).addClass('ke-on');
});
} else {
cell.mouseover(function() {
K(this).addClass('ke-on');
});
}
cell.mouseout(function() {
K(this).removeClass('ke-on');
});
cell.click(function(e) {
self.insertHtml('<img src="' + path + num + '.gif" border="0" alt="" />').hideMenu().focus();
e.stop();
});
}
function createEmoticonsTable(pageNum, parentDiv) {
var table = document.createElement('table');
parentDiv.append(table);
if (previewDiv) {
K(table).mouseover(function() {
previewDiv.show();
});
K(table).mouseout(function() {
previewDiv.hide();
});
elements.push(K(table));
}
table.className = 'ke-table';
table.cellPadding = 0;
table.cellSpacing = 0;
table.border = 0;
var num = (pageNum - 1) * cells + startNum;
for (var i = 0; i < rows; i++) {
var row = table.insertRow(i);
for (var j = 0; j < cols; j++) {
var cell = K(row.insertCell(j));
cell.addClass('ke-cell');
bindCellEvent(cell, j, num);
var span = K('<span class="ke-img"></span>')
.css('background-position', '-' + (24 * num) + 'px 0px')
.css('background-image', 'url(' + path + 'static.gif)');
cell.append(span);
elements.push(cell);
num++;
}
}
return table;
}
var table = createEmoticonsTable(currentPageNum, wrapperDiv);
function removeEvent() {
K.each(elements, function() {
this.unbind();
});
}
var pageDiv;
function bindPageEvent(el, pageNum) {
el.click(function(e) {
removeEvent();
table.parentNode.removeChild(table);
pageDiv.remove();
table = createEmoticonsTable(pageNum, wrapperDiv);
createPageTable(pageNum);
currentPageNum = pageNum;
e.stop();
});
}
function createPageTable(currentPageNum) {
pageDiv = K('<div class="ke-page"></div>');
wrapperDiv.append(pageDiv);
for (var pageNum = 1; pageNum <= pages; pageNum++) {
if (currentPageNum !== pageNum) {
var a = K('<a href="javascript:;">[' + pageNum + ']</a>');
bindPageEvent(a, pageNum);
pageDiv.append(a);
elements.push(a);
} else {
pageDiv.append(K('@[' + pageNum + ']'));
}
pageDiv.append(K('@ '));
}
}
createPageTable(currentPageNum);
});
});
|
import React, { useState } from "react";
import { Modal, ModalHeader, ModalBody, ModalFooter, Button } from "reactstrap";
import buttonPriseDeRDVIcon from "../../public/images/icons/fake_feature_btn.svg";
const FakeFeature = ({
buttonText,
tagName,
modalTitleBeforeSelection,
modalTextBeforeSelection,
modalTitleAfterSelection,
modalTextAfterSelection,
questionsAndTags,
}) => {
const handleClick = () => {
setIsOptionSelected(true);
};
const [modal, setModal] = useState(false);
const [isOptionSelected, setIsOptionSelected] = useState(false);
const toggle = () => setModal(!modal);
return (
<>
<div className="avenir">
<button onClick={toggle} className={tagName}>
{buttonText}
</button>
</div>
<Modal isOpen={modal} toggle={toggle} backdrop="static" className="avenirModale">
{isOptionSelected && (
<>
<ModalHeader toggle={toggle}>{modalTitleAfterSelection}</ModalHeader>
<ModalBody>{modalTextAfterSelection}</ModalBody>
</>
)}
{!isOptionSelected && (
<>
<ModalHeader toggle={toggle}>{modalTitleBeforeSelection}</ModalHeader>
{questionsAndTags ? (
<ModalBody>
{modalTextBeforeSelection}
{questionsAndTags.map((question, idx) => (
<div key={idx}>
<Button color="white" className={`${question.tagName} question`} onClick={handleClick}>
{question.question}
</Button>
</div>
))}
</ModalBody>
) : (
""
)}
</>
)}
{isOptionSelected && (
<ModalFooter>
<Button color="secondary" onClick={toggle}>
Retour
</Button>
</ModalFooter>
)}
</Modal>
</>
);
};
export default FakeFeature;
|
var openpgp = require('openpgp')
var base64 = require('base64-js')
var autocrypt = require('..')
var memdb = require('memdb')
module.exports = {
setup: function (fromAddr, cb) {
var crypt = autocrypt({storage: memdb({valueEncoding: 'json'})})
openpgp.initWorker({ path: 'openpgp.worker.js' }) // set the relative web worker path
openpgp.config.aead_protect = true // activate fast AES-GCM mode (not yet OpenPGP standard)
openpgp.generateKey({
userIds: [{ name: 'Jon Smith', email: fromAddr }],
numBits: 1096,
passphrase: 'super long and hard to guess'
}
).then((key) => cb(crypt, decode(key.publicKeyArmored), done)
).catch((err) => { throw err })
function done (cb) {
crypt.storage.close(cb)
}
},
decode: decode
}
function decode (key) {
return base64.fromByteArray(openpgp.armor.decode(key).data)
}
|
import * as t from "../../../types";
export var metadata = {
group: "builtin-pre"
};
const THIS_BREAK_KEYS = ["FunctionExpression", "FunctionDeclaration", "ClassExpression", "ClassDeclaration"];
/**
* [Please add a description.]
*/
export var visitor = {
/**
* [Please add a description.]
*/
Program: {
enter(program) {
var first = program.body[0];
var directive;
if (t.isExpressionStatement(first) && t.isLiteral(first.expression, { value: "use strict" })) {
directive = first;
} else {
directive = t.expressionStatement(t.literal("use strict"));
this.unshiftContainer("body", directive);
if (first) {
directive.leadingComments = first.leadingComments;
first.leadingComments = [];
}
}
directive._blockHoist = Infinity;
}
},
/**
* [Please add a description.]
*/
ThisExpression() {
if (!this.findParent((path) => !path.is("shadow") && THIS_BREAK_KEYS.indexOf(path.type) >= 0)) {
return t.identifier("undefined");
}
}
};
|
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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.
*/
var showControllersOnly = false;
var seriesFilter = "";
var filtersOnlySampleSeries = true;
/*
* Add header in statistics table to group metrics by category
* format
*
*/
function summaryTableHeader(header) {
var newRow = header.insertRow(-1);
newRow.className = "tablesorter-no-sort";
var cell = document.createElement('th');
cell.setAttribute("data-sorter", false);
cell.colSpan = 1;
cell.innerHTML = "Requests";
newRow.appendChild(cell);
cell = document.createElement('th');
cell.setAttribute("data-sorter", false);
cell.colSpan = 3;
cell.innerHTML = "Executions";
newRow.appendChild(cell);
cell = document.createElement('th');
cell.setAttribute("data-sorter", false);
cell.colSpan = 7;
cell.innerHTML = "Response Times (ms)";
newRow.appendChild(cell);
cell = document.createElement('th');
cell.setAttribute("data-sorter", false);
cell.colSpan = 1;
cell.innerHTML = "Throughput";
newRow.appendChild(cell);
cell = document.createElement('th');
cell.setAttribute("data-sorter", false);
cell.colSpan = 2;
cell.innerHTML = "Network (KB/sec)";
newRow.appendChild(cell);
}
/*
* Populates the table identified by id parameter with the specified data and
* format
*
*/
function createTable(table, info, formatter, defaultSorts, seriesIndex, headerCreator) {
var tableRef = table[0];
// Create header and populate it with data.titles array
var header = tableRef.createTHead();
// Call callback is available
if(headerCreator) {
headerCreator(header);
}
var newRow = header.insertRow(-1);
for (var index = 0; index < info.titles.length; index++) {
var cell = document.createElement('th');
cell.innerHTML = info.titles[index];
newRow.appendChild(cell);
}
var tBody;
// Create overall body if defined
if(info.overall){
tBody = document.createElement('tbody');
tBody.className = "tablesorter-no-sort";
tableRef.appendChild(tBody);
var newRow = tBody.insertRow(-1);
var data = info.overall.data;
for(var index=0;index < data.length; index++){
var cell = newRow.insertCell(-1);
cell.innerHTML = formatter ? formatter(index, data[index]): data[index];
}
}
// Create regular body
tBody = document.createElement('tbody');
tableRef.appendChild(tBody);
var regexp;
if(seriesFilter) {
regexp = new RegExp(seriesFilter, 'i');
}
// Populate body with data.items array
for(var index=0; index < info.items.length; index++){
var item = info.items[index];
if((!regexp || filtersOnlySampleSeries && !info.supportsControllersDiscrimination || regexp.test(item.data[seriesIndex]))
&&
(!showControllersOnly || !info.supportsControllersDiscrimination || item.isController)){
if(item.data.length > 0) {
var newRow = tBody.insertRow(-1);
for(var col=0; col < item.data.length; col++){
var cell = newRow.insertCell(-1);
cell.innerHTML = formatter ? formatter(col, item.data[col]) : item.data[col];
}
}
}
}
// Add support of columns sort
table.tablesorter({sortList : defaultSorts});
}
$(document).ready(function() {
// Customize table sorter default options
$.extend( $.tablesorter.defaults, {
theme: 'blue',
cssInfoBlock: "tablesorter-no-sort",
widthFixed: true,
widgets: ['zebra']
});
var data = {"OkPercent": 100.0, "KoPercent": 0.0};
var dataset = [
{
"label" : "FAIL",
"data" : data.KoPercent,
"color" : "#FF6347"
},
{
"label" : "PASS",
"data" : data.OkPercent,
"color" : "#9ACD32"
}];
$.plot($("#flot-requests-summary"), dataset, {
series : {
pie : {
show : true,
radius : 1,
label : {
show : true,
radius : 3 / 4,
formatter : function(label, series) {
return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'
+ label
+ '<br/>'
+ Math.round10(series.percent, -2)
+ '%</div>';
},
background : {
opacity : 0.5,
color : '#000'
}
}
}
},
legend : {
show : true
}
});
// Creates APDEX table
createTable($("#apdexTable"), {"supportsControllersDiscrimination": true, "overall": {"data": [0.0, 500, 1500, "Total"], "isController": false}, "titles": ["Apdex", "T (Toleration threshold)", "F (Frustration threshold)", "Label"], "items": [{"data": [0.0, 500, 1500, "Data Forecasting"], "isController": false}, {"data": [0.0, 500, 1500, "Weather Forecasting"], "isController": false}]}, function(index, item){
switch(index){
case 0:
item = item.toFixed(3);
break;
case 1:
case 2:
item = formatDuration(item);
break;
}
return item;
}, [[0, 0]], 3);
// Create statistics table
createTable($("#statisticsTable"), {"supportsControllersDiscrimination": true, "overall": {"data": ["Total", 20, 0, 0.0, 40163.00000000001, 7824, 72031, 40624.0, 65990.6, 71729.79999999999, 72031.0, 0.24517916467458598, 0.056865284775599774, 0.0420204525394432], "isController": false}, "titles": ["Label", "#Samples", "FAIL", "Error %", "Average", "Min", "Max", "Median", "90th pct", "95th pct", "99th pct", "Transactions/s", "Received", "Sent"], "items": [{"data": ["Data Forecasting", 10, 0, 0.0, 41719.0, 7824, 72031, 43638.0, 71412.2, 72031.0, 72031.0, 0.13728908963604664, 0.030434202487678304, 0.025071347423770235], "isController": false}, {"data": ["Weather Forecasting", 10, 0, 0.0, 38607.0, 8729, 66007, 37566.0, 65907.8, 66007.0, 66007.0, 0.13561712573063725, 0.032844772637888715, 0.021719930292797375], "isController": false}]}, function(index, item){
switch(index){
// Errors pct
case 3:
item = item.toFixed(2) + '%';
break;
// Mean
case 4:
// Mean
case 7:
// Median
case 8:
// Percentile 1
case 9:
// Percentile 2
case 10:
// Percentile 3
case 11:
// Throughput
case 12:
// Kbytes/s
case 13:
// Sent Kbytes/s
item = item.toFixed(2);
break;
}
return item;
}, [[0, 0]], 0, summaryTableHeader);
// Create error table
createTable($("#errorsTable"), {"supportsControllersDiscrimination": false, "titles": ["Type of error", "Number of errors", "% in errors", "% in all samples"], "items": []}, function(index, item){
switch(index){
case 2:
case 3:
item = item.toFixed(2) + '%';
break;
}
return item;
}, [[1, 1]]);
// Create top5 errors by sampler
createTable($("#top5ErrorsBySamplerTable"), {"supportsControllersDiscrimination": false, "overall": {"data": ["Total", 20, 0, null, null, null, null, null, null, null, null, null, null], "isController": false}, "titles": ["Sample", "#Samples", "#Errors", "Error", "#Errors", "Error", "#Errors", "Error", "#Errors", "Error", "#Errors", "Error", "#Errors"], "items": [{"data": [], "isController": false}, {"data": [], "isController": false}]}, function(index, item){
return item;
}, [[0, 0]], 0);
});
|
import drivers from './driver';
import passengers from './passenger';
import rideOffers from './rides';
const db = {
drivers, passengers, rideOffers,
};
export default db;
|
#!/usr/bin/env node
require('../dist/brisky-cli.cjs')
|
/*Связь с автором*/
$(document).ready(function () {
$('#upgrade-item-menu').addClass('nav-item active');
});
|
const faker = require('faker');
const Car = require('./../src/entities/car');
const CarCategory = require('./../src/entities/carCategory');
const Customer = require('./../src/entities/customer');
const { join } = require('path');
const { writeFile } = require('fs/promises');
const seederBaseFolder = join(__dirname, '../','database');
const ITEMS_AMOUNT = 2
const carCategory = new CarCategory({
id: faker.random.uuid(),
name: faker.vehicle.type(),
carIds: [],
price: faker.finance.amount(20,100)
})
const cars =[]
const customers =[]
for(let index = 0; index <= ITEMS_AMOUNT; index++){
const car = new Car({
id: faker.random.uuid(),
name: faker.vehicle.model(),
available: true,
gasAvailable: true,
releaseYear: faker.date.past().getFullYear()
})
carCategory.carIds.push(car.id)
cars.push(car)
const customer = new Customer({
id: faker.random.uuid(),
name: faker.name.findName(),
age: faker.random.number({min: 18,max: 50})
})
customers.push(customer)
}
const write = (filename, data) => writeFile(join(seederBaseFolder, filename), JSON.stringify(data))
;(async() => {
await write('cars.json', cars)
await write('curtomers.json', customers)
await write('carCategories.json', [carCategory])
console.log('cars', cars);
console.log('carCategory', CarCategory);
})()
|
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var Father = /** @class */ (function () {
function Father(occupation) {
this.occupation = occupation;
}
Father.prototype.display_father = function () {
console.log('Occupation of Father is : ' + this.occupation);
};
return Father;
}());
var Son = /** @class */ (function (_super) {
__extends(Son, _super);
function Son(foccupation, school) {
var _this = _super.call(this, foccupation) || this;
_this.school = school;
return _this;
}
Son.prototype.display_son = function () {
console.log('School of Son is : ' + this.school);
};
return Son;
}(Father));
var Daughter = /** @class */ (function (_super) {
__extends(Daughter, _super);
function Daughter(foccupation, college) {
var _this = _super.call(this, foccupation) || this;
_this.college = college;
return _this;
}
Daughter.prototype.display_daughter = function () {
console.log('College of Daughter is : ' + this.college);
};
return Daughter;
}(Father));
var son = new Son('CEO of Company', 'M.S. Junior');
son.display_father();
son.display_son();
var daughter = new Daughter('Trainer', 'Deccan College');
daughter.display_father();
daughter.display_daughter();
var NewCompany = /** @class */ (function () {
function NewCompany(cname) {
this.cname = cname;
}
NewCompany.prototype.display_company = function () {
console.log('Company name is: ' + this.cname);
};
return NewCompany;
}());
var cts = new NewCompany('CTS');
cts.display_company();
var Actor = /** @class */ (function () {
function Actor(name) {
this.name = name;
}
Actor.prototype.display = function () {
console.log('Profession of ' + this.name + ' is: ' + Actor.profession);
};
return Actor;
}());
var srk = new Actor('Shahrukh Khan');
Actor.profession = 'Hero';
srk.display();
var arijit = new Actor('Arijit Singh');
Actor.profession = 'Singer';
arijit.display();
srk.display();
|
(function() {
if (typeof getToolTest === "undefined") {
load('jstests/configs/plain_28.config.js');
}
// Testing exporting with various type specifiers
jsTest.log('Testing exporting with various type specifiers');
var toolTest = getToolTest('export_types');
var commonToolArgs = getCommonToolArguments();
// the db and collections we'll use
var testDB = toolTest.db.getSiblingDB('test');
var sourceColl = testDB.source;
// the export target
var exportTarget = 'type_export';
// insert some data
sourceColl.insert({a: 1});
sourceColl.insert({a: 1, b: 1});
sourceColl.insert({a: 1, b: 2, c: 3});
// sanity check the insertion worked
assert.eq(3, sourceColl.count());
// first validate that invalid types are rejected
var ret = toolTest.runTool.apply(toolTest, ['export',
'--out', exportTarget,
'--db', 'test',
'--collection', 'source',
'--type="foobar"',
'--fields', 'a']
.concat(commonToolArgs));
assert.eq(1, ret);
// create a dump file using a lowercase csv type
ret = toolTest.runTool.apply(toolTest, ['export',
'--out', exportTarget + ".csv",
'--db', 'test',
'--collection', 'source',
'--type="csv"',
'--fields', 'a']
.concat(commonToolArgs));
assert.eq(0, ret);
var csvmd5 = md5sumFile(exportTarget + ".csv");
// create a dump file using a uppercase csv type
ret = toolTest.runTool.apply(toolTest, ['export',
'--out', exportTarget + ".CSV",
'--db', 'test',
'--collection', 'source',
'--type="CSV"',
'--fields', 'a']
.concat(commonToolArgs));
var CSVmd5 = md5sumFile(exportTarget + ".CSV");
// the files for the uppercase and lowercase types should match
assert.eq(csvmd5, CSVmd5);
// create a dump file using a mixedcase csv type
ret = toolTest.runTool.apply(toolTest, ['export',
'--out', exportTarget + ".cSv",
'--db', 'test',
'--collection', 'source',
'--type="cSv"',
'--fields', 'a']
.concat(commonToolArgs));
var cSvmd5 = md5sumFile(exportTarget + ".cSv");
// the files for the uppercase and lowercase types should match
assert.eq(csvmd5, cSvmd5);
// then some json type tests
// create a dump file using a lowercase json type
ret = toolTest.runTool.apply(toolTest, ['export',
'--out', exportTarget + ".json",
'--db', 'test',
'--collection', 'source',
'--type="json"',
'--fields', 'a']
.concat(commonToolArgs));
assert.eq(0, ret);
var jsonmd5 = md5sumFile(exportTarget + ".json");
// create a dump file using a uppercase json type
ret = toolTest.runTool.apply(toolTest, ['export',
'--out', exportTarget + ".JSON",
'--db', 'test',
'--collection', 'source',
'--type="JSON"',
'--fields', 'a']
.concat(commonToolArgs));
assert.eq(0, ret);
var JSONmd5 = md5sumFile(exportTarget + ".JSON");
// create a dump file using a uppercase blank (json) type
ret = toolTest.runTool.apply(toolTest, ['export',
'--out', exportTarget + ".blank",
'--db', 'test',
'--collection', 'source',
'--fields', 'a']
.concat(commonToolArgs));
assert.eq(0, ret);
var blankmd5 = md5sumFile(exportTarget + ".blank");
assert.eq(JSONmd5, jsonmd5);
assert.eq(blankmd5, jsonmd5);
// sanity check
assert.neq(csvmd5, jsonmd5);
// success
toolTest.stop();
}());
|
const Twig = require('twig');
const createUuid = require('uuid/v4');
Twig.extend((TwigCore) => {
/**
* Remove tokens 2, 3, 4 and 8.
* This tokens are used for functions and data output.
* Since the data binding is done in Vue this could lead to syntax issues.
* We are only using the block system for template inheritance.
*
* @type {Array<any>}
*/
TwigCore.token.definitions = [
TwigCore.token.definitions[0],
TwigCore.token.definitions[1],
TwigCore.token.definitions[5],
TwigCore.token.definitions[6],
TwigCore.token.definitions[7],
TwigCore.token.definitions[9],
TwigCore.token.definitions[10]
];
/**
* Twig inheritance extension.
* The parent function is used as a statement tag.
* This is used to prevent syntax issues between Twig and Vue.
* Use `{% parent %}` to print out the parent content of a block.
*/
TwigCore.exports.extendTag({
type: 'parent',
regex: /^parent/,
next: [],
open: true,
parse(token, context, chain) {
return {
chain,
output: TwigCore.placeholders.parent
};
}
});
/** Make the placeholders available in the exposed Twig object. */
TwigCore.exports.placeholders = TwigCore.placeholders;
/** Make the Twig template cache registry available. */
TwigCore.exports.getRegistry = function getRegistry() {
return TwigCore.Templates.registry;
};
/** Provide possibility to clear the template cache registry */
TwigCore.exports.clearRegistry = function clearRegistry() {
TwigCore.Templates.registry = {};
};
});
module.exports = function render(src) {
const templateConfig = {
id: createUuid(),
data: src
};
const template = Twig.twig(templateConfig);
return template.render();
};
|
const fs = require('fs')
const assert = require('assert')
const data_folder = 'data/italy-data'
const data_file = 'Daily Covis19 Italian Data Cumulative'
// translations
let en2zh = JSON.parse(fs.readFileSync('data/map-translations/en2zh.json'))
let output_italy = {}
output_italy = {
ENGLISH: 'Italy',
confirmedCount: {},
deadCount: {},
curedCount: {}
}
const data = fs.readFileSync(`${data_folder}/${data_file}`, 'utf8').split(/\r?\n/)
data.forEach((line, index) => {
if (index === 0) return
const lineSplit = line.split(',')
const date = lineSplit[0]
if (date.length !== 10) return
let regionEnglish = lineSplit[1].replace(/"/g, '')
const confirmedCount = parseInt(lineSplit[2], 10) + parseInt(lineSplit[3], 10) + parseInt(lineSplit[4], 10)
const curedCount = parseInt(lineSplit[5], 10)
const deadCount = parseInt(lineSplit[6], 10)
if ([ 'Trento', 'Bolzano' ].includes(regionEnglish)) {
regionEnglish = 'Trentino-Alto Adige'
}
const region = en2zh[regionEnglish]
assert(region != null, `${regionEnglish} does not exist!`)
// initialization
if (!(region in output_italy)) {
output_italy[region] = { ENGLISH: regionEnglish, confirmedCount: {}, curedCount: {}, deadCount: {} }
}
if (!(date in output_italy[region]['confirmedCount'])) {
output_italy[region]['confirmedCount'][date] = confirmedCount
output_italy[region]['curedCount'][date] = curedCount
output_italy[region]['deadCount'][date] = deadCount
} else {
output_italy[region]['confirmedCount'][date] += confirmedCount
output_italy[region]['curedCount'][date] += curedCount
output_italy[region]['deadCount'][date] += deadCount
}
if (!(date in output_italy['confirmedCount'])) {
output_italy['confirmedCount'][date] = confirmedCount
output_italy['curedCount'][date] = curedCount
output_italy['deadCount'][date] = deadCount
} else {
output_italy['confirmedCount'][date] += confirmedCount
output_italy['curedCount'][date] += curedCount
output_italy['deadCount'][date] += deadCount
}
})
fs.writeFileSync(`public/data/italy.json`, JSON.stringify(output_italy))
// modify map
const mapName = 'gadm36_ITA_1'
let map = JSON.parse(fs.readFileSync(`public/maps/${mapName}.json`))
let geometries = map.objects[mapName].geometries
geometries.forEach((geo) => {
let regionEnglish = geo.properties.NAME_1
if (regionEnglish === 'Emilia-Romagna') regionEnglish = 'Emilia Romagna'
if (regionEnglish === 'Friuli-Venezia Giulia') regionEnglish = 'Friuli V.G.'
if (regionEnglish === 'Sicily') regionEnglish = 'Sicilia'
if (regionEnglish === "Valle d'Aosta") regionEnglish = 'Valle D’Aosta'
const region = en2zh[regionEnglish]
geo.properties.NAME_1 = regionEnglish
geo.properties.CHINESE_NAME = region
geo.properties.REGION = `意大利.${region}`
})
map.objects[mapName].geometries = geometries
fs.writeFileSync(`public/maps/${mapName}.json`, JSON.stringify(map))
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import _ from 'lodash';
import { i18n } from '@kbn/i18n';
import { parse } from 'wellknown';
import {
DECIMAL_DEGREES_PRECISION,
ES_GEO_FIELD_TYPE,
ES_SPATIAL_RELATIONS,
GEO_JSON_TYPE,
POLYGON_COORDINATES_EXTERIOR_INDEX,
LON_INDEX,
LAT_INDEX,
} from '../common/constants';
import { getEsSpatialRelationLabel } from '../common/i18n_getters';
import { SPATIAL_FILTER_TYPE } from './kibana_services';
function ensureGeoField(type) {
const expectedTypes = [ES_GEO_FIELD_TYPE.GEO_POINT, ES_GEO_FIELD_TYPE.GEO_SHAPE];
if (!expectedTypes.includes(type)) {
const errorMessage = i18n.translate(
'xpack.maps.es_geo_utils.unsupportedFieldTypeErrorMessage',
{
defaultMessage:
'Unsupported field type, expected: {expectedTypes}, you provided: {fieldType}',
values: {
fieldType: type,
expectedTypes: expectedTypes.join(','),
},
}
);
throw new Error(errorMessage);
}
}
function ensureGeometryType(type, expectedTypes) {
if (!expectedTypes.includes(type)) {
const errorMessage = i18n.translate(
'xpack.maps.es_geo_utils.unsupportedGeometryTypeErrorMessage',
{
defaultMessage:
'Unsupported geometry type, expected: {expectedTypes}, you provided: {geometryType}',
values: {
geometryType: type,
expectedTypes: expectedTypes.join(','),
},
}
);
throw new Error(errorMessage);
}
}
/**
* Converts Elasticsearch search results into GeoJson FeatureCollection
*
* @param {array} hits Elasticsearch search response hits array
* @param {function} flattenHit Method to flatten hits._source and hits.fields into properties object.
* Should just be IndexPattern.flattenHit but wanted to avoid coupling this method to IndexPattern.
* @param {string} geoFieldName Geometry field name
* @param {string} geoFieldType Geometry field type ["geo_point", "geo_shape"]
* @returns {number}
*/
export function hitsToGeoJson(hits, flattenHit, geoFieldName, geoFieldType) {
const features = [];
const tmpGeometriesAccumulator = [];
for (let i = 0; i < hits.length; i++) {
const properties = flattenHit(hits[i]);
tmpGeometriesAccumulator.length = 0; //truncate accumulator
ensureGeoField(geoFieldType);
if (geoFieldType === ES_GEO_FIELD_TYPE.GEO_POINT) {
geoPointToGeometry(properties[geoFieldName], tmpGeometriesAccumulator);
} else {
geoShapeToGeometry(properties[geoFieldName], tmpGeometriesAccumulator);
}
// don't include geometry field value in properties
delete properties[geoFieldName];
//create new geojson Feature for every individual geojson geometry.
for (let j = 0; j < tmpGeometriesAccumulator.length; j++) {
features.push({
type: 'Feature',
geometry: tmpGeometriesAccumulator[j],
// _id is not unique across Kibana index pattern. Multiple ES indices could have _id collisions
// Need to prefix with _index to guarantee uniqueness
id: `${properties._index}:${properties._id}:${j}`,
properties,
});
}
}
return {
type: 'FeatureCollection',
features: features,
};
}
// Parse geo_point docvalue_field
// Either
// 1) Array of latLon strings
// 2) latLon string
export function geoPointToGeometry(value, accumulator) {
if (!value) {
return;
}
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i++) {
geoPointToGeometry(value[i], accumulator);
}
return;
}
const commaSplit = value.split(',');
const lat = parseFloat(commaSplit[0]);
const lon = parseFloat(commaSplit[1]);
accumulator.push({
type: GEO_JSON_TYPE.POINT,
coordinates: [lon, lat],
});
}
export function convertESShapeToGeojsonGeometry(value) {
const geoJson = {
type: value.type,
coordinates: value.coordinates,
};
// https://www.elastic.co/guide/en/elasticsearch/reference/current/geo-shape.html#input-structure
// For some unknown compatibility nightmarish reason, Elasticsearch types are not capitalized the same as geojson types
// For example: 'LineString' geojson type is 'linestring' in elasticsearch
// Convert feature types to geojson spec values
// Sometimes, the type in ES is capitalized correctly. Sometimes it is not. It depends on how the doc was ingested
// The below is the correction in-place.
switch (value.type) {
case 'point':
geoJson.type = GEO_JSON_TYPE.POINT;
break;
case 'linestring':
geoJson.type = GEO_JSON_TYPE.LINE_STRING;
break;
case 'polygon':
geoJson.type = GEO_JSON_TYPE.POLYGON;
break;
case 'multipoint':
geoJson.type = GEO_JSON_TYPE.MULTI_POINT;
break;
case 'multilinestring':
geoJson.type = GEO_JSON_TYPE.MULTI_LINE_STRING;
break;
case 'multipolygon':
geoJson.type = GEO_JSON_TYPE.MULTI_POLYGON;
break;
case 'geometrycollection':
geoJson.type = GEO_JSON_TYPE.GEOMETRY_COLLECTION;
break;
case 'envelope':
case 'circle':
const errorMessage = i18n.translate(
'xpack.maps.es_geo_utils.convert.unsupportedGeometryTypeErrorMessage',
{
defaultMessage: `Unable to convert {geometryType} geometry to geojson, not supported`,
values: {
geometryType: geoJson.type,
},
}
);
throw new Error(errorMessage);
}
return geoJson;
}
function convertWKTStringToGeojson(value) {
try {
return parse(value);
} catch (e) {
const errorMessage = i18n.translate('xpack.maps.es_geo_utils.wkt.invalidWKTErrorMessage', {
defaultMessage: `Unable to convert {wkt} to geojson. Valid WKT expected.`,
values: {
wkt: value,
},
});
throw new Error(errorMessage);
}
}
export function geoShapeToGeometry(value, accumulator) {
if (!value) {
return;
}
if (Array.isArray(value)) {
// value expressed as an array of values
for (let i = 0; i < value.length; i++) {
geoShapeToGeometry(value[i], accumulator);
}
return;
}
let geoJson;
if (typeof value === 'string') {
geoJson = convertWKTStringToGeojson(value);
} else {
geoJson = convertESShapeToGeojsonGeometry(value);
}
accumulator.push(geoJson);
}
function createGeoBoundBoxFilter(geometry, geoFieldName, filterProps = {}) {
ensureGeometryType(geometry.type, [GEO_JSON_TYPE.POLYGON]);
const TOP_LEFT_INDEX = 0;
const BOTTOM_RIGHT_INDEX = 2;
const verticies = geometry.coordinates[POLYGON_COORDINATES_EXTERIOR_INDEX];
return {
geo_bounding_box: {
[geoFieldName]: {
top_left: verticies[TOP_LEFT_INDEX],
bottom_right: verticies[BOTTOM_RIGHT_INDEX],
},
},
...filterProps,
};
}
function createGeoPolygonFilter(polygonCoordinates, geoFieldName, filterProps = {}) {
return {
geo_polygon: {
ignore_unmapped: true,
[geoFieldName]: {
points: polygonCoordinates[POLYGON_COORDINATES_EXTERIOR_INDEX].map(coordinatePair => {
return {
lon: coordinatePair[LON_INDEX],
lat: coordinatePair[LAT_INDEX],
};
}),
},
},
...filterProps,
};
}
export function createExtentFilter(mapExtent, geoFieldName, geoFieldType) {
ensureGeoField(geoFieldType);
const safePolygon = convertMapExtentToPolygon(mapExtent);
if (geoFieldType === ES_GEO_FIELD_TYPE.GEO_POINT) {
return createGeoBoundBoxFilter(safePolygon, geoFieldName);
}
return {
geo_shape: {
[geoFieldName]: {
shape: safePolygon,
relation: ES_SPATIAL_RELATIONS.INTERSECTS,
},
},
};
}
export function createSpatialFilterWithBoundingBox(options) {
return createGeometryFilterWithMeta({ ...options, isBoundingBox: true });
}
export function createSpatialFilterWithGeometry(options) {
return createGeometryFilterWithMeta(options);
}
function createGeometryFilterWithMeta({
preIndexedShape,
geometry,
geometryLabel,
indexPatternId,
geoFieldName,
geoFieldType,
relation = ES_SPATIAL_RELATIONS.INTERSECTS,
isBoundingBox = false,
}) {
ensureGeoField(geoFieldType);
const relationLabel =
geoFieldType === ES_GEO_FIELD_TYPE.GEO_POINT
? i18n.translate('xpack.maps.es_geo_utils.shapeFilter.geoPointRelationLabel', {
defaultMessage: 'in',
})
: getEsSpatialRelationLabel(relation);
const meta = {
type: SPATIAL_FILTER_TYPE,
negate: false,
index: indexPatternId,
key: geoFieldName,
alias: `${geoFieldName} ${relationLabel} ${geometryLabel}`,
};
if (geoFieldType === ES_GEO_FIELD_TYPE.GEO_SHAPE) {
const shapeQuery = {
relation,
};
if (preIndexedShape) {
shapeQuery.indexed_shape = preIndexedShape;
} else {
shapeQuery.shape = geometry;
}
return {
meta,
geo_shape: {
ignore_unmapped: true,
[geoFieldName]: shapeQuery,
},
};
}
// geo_points supports limited geometry types
ensureGeometryType(geometry.type, [GEO_JSON_TYPE.POLYGON, GEO_JSON_TYPE.MULTI_POLYGON]);
if (geometry.type === GEO_JSON_TYPE.MULTI_POLYGON) {
return {
meta,
query: {
bool: {
should: geometry.coordinates.map(polygonCoordinates => {
return createGeoPolygonFilter(polygonCoordinates, geoFieldName);
}),
},
},
};
}
if (isBoundingBox) {
return createGeoBoundBoxFilter(geometry, geoFieldName, { meta });
}
return createGeoPolygonFilter(geometry.coordinates, geoFieldName, { meta });
}
export function createDistanceFilterWithMeta({
alias,
distanceKm,
geoFieldName,
indexPatternId,
point,
}) {
const meta = {
type: SPATIAL_FILTER_TYPE,
negate: false,
index: indexPatternId,
key: geoFieldName,
alias: alias
? alias
: i18n.translate('xpack.maps.es_geo_utils.distanceFilterAlias', {
defaultMessage: '{geoFieldName} within {distanceKm}km of {pointLabel}',
values: {
distanceKm,
geoFieldName,
pointLabel: point.join(','),
},
}),
};
return {
geo_distance: {
distance: `${distanceKm}km`,
[geoFieldName]: point,
},
meta,
};
}
export function roundCoordinates(coordinates) {
for (let i = 0; i < coordinates.length; i++) {
const value = coordinates[i];
if (Array.isArray(value)) {
roundCoordinates(value);
} else if (!isNaN(value)) {
coordinates[i] = _.round(value, DECIMAL_DEGREES_PRECISION);
}
}
}
/*
* returns Polygon geometry where coordinates define a bounding box that contains the input geometry
*/
export function getBoundingBoxGeometry(geometry) {
ensureGeometryType(geometry.type, [GEO_JSON_TYPE.POLYGON]);
const exterior = geometry.coordinates[POLYGON_COORDINATES_EXTERIOR_INDEX];
const extent = {
minLon: exterior[0][LON_INDEX],
minLat: exterior[0][LAT_INDEX],
maxLon: exterior[0][LON_INDEX],
maxLat: exterior[0][LAT_INDEX],
};
for (let i = 1; i < exterior.length; i++) {
extent.minLon = Math.min(exterior[i][LON_INDEX], extent.minLon);
extent.minLat = Math.min(exterior[i][LAT_INDEX], extent.minLat);
extent.maxLon = Math.max(exterior[i][LON_INDEX], extent.maxLon);
extent.maxLat = Math.max(exterior[i][LAT_INDEX], extent.maxLat);
}
return convertMapExtentToPolygon(extent);
}
function formatEnvelopeAsPolygon({ maxLat, maxLon, minLat, minLon }) {
// GeoJSON mandates that the outer polygon must be counterclockwise to avoid ambiguous polygons
// when the shape crosses the dateline
const left = minLon;
const right = maxLon;
const top = maxLat > 90 ? 90 : maxLat;
const bottom = minLat < -90 ? -90 : minLat;
const topLeft = [left, top];
const bottomLeft = [left, bottom];
const bottomRight = [right, bottom];
const topRight = [right, top];
return {
type: GEO_JSON_TYPE.POLYGON,
coordinates: [[topLeft, bottomLeft, bottomRight, topRight, topLeft]],
};
}
/*
* Convert map bounds to polygon
*/
export function convertMapExtentToPolygon({ maxLat, maxLon, minLat, minLon }) {
const lonDelta = maxLon - minLon;
if (lonDelta >= 360) {
return formatEnvelopeAsPolygon({
maxLat,
maxLon: 180,
minLat,
minLon: -180,
});
}
if (maxLon > 180) {
// bounds cross dateline east to west
const overlapWestOfDateLine = maxLon - 180;
return formatEnvelopeAsPolygon({
maxLat,
maxLon: -180 + overlapWestOfDateLine,
minLat,
minLon,
});
}
if (minLon < -180) {
// bounds cross dateline west to east
const overlapEastOfDateLine = Math.abs(minLon) - 180;
return formatEnvelopeAsPolygon({
maxLat,
maxLon,
minLat,
minLon: 180 - overlapEastOfDateLine,
});
}
return formatEnvelopeAsPolygon({ maxLat, maxLon, minLat, minLon });
}
export function clampToLatBounds(lat) {
return clamp(lat, -89, 89);
}
export function clampToLonBounds(lon) {
return clamp(lon, -180, 180);
}
export function clamp(val, min, max) {
if (val > max) {
return max;
} else if (val < min) {
return min;
} else {
return val;
}
}
|
'use strict';
var base = require('./base'),
should = base.should,
Instruments = require('../../lib/main').Instruments,
utils = require('../../lib/main').utils,
logger = require('../../lib/main').logger,
exec = require('child_process').exec,
path = require('path'),
_ =require('underscore'),
rimraf = require('rimraf'),
fs = require('fs');
if (process.env.VERBOSE) logger.setConsoleLevel('debug');
var LAUNCH_HANDLER_TIMEOUT = 10000;
describe('intruments tests', function () {
this.timeout(90000);
function newInstrument(opts) {
_.extend(opts, {
app: path.resolve(__dirname, '../assets/TestApp.app'),
bootstrap: path.resolve(__dirname, '../assets/bootstrap.js'),
});
return utils.quickInstrument(opts);
}
function checkLaunched(instruments, done) {
var _checkLaunched = function (remaining) {
if (remaining === 0) done(new Error('didn\'t launch'));
setTimeout(function () {
if (instruments.didLaunch) return done();
_checkLaunched(remaining -1);
},1000);
};
_checkLaunched(20);
}
function test(appendDesc , opts, checks) {
checks = checks || {};
var instruments;
it('should start' + appendDesc, function (done) {
utils.killAllSimulators();
newInstrument(opts).then(function (_instruments) {
instruments = _instruments;
if (checks.afterCreate) checks.afterCreate(instruments);
setTimeout(function () {
instruments.launchHandler();
}, LAUNCH_HANDLER_TIMEOUT);
instruments.start();
checkLaunched(instruments, function (err) {
if (err) return done(err);
if (checks.afterLaunch) checks.afterLaunch(instruments);
done();
});
}).done();
});
it('should shutdown' + appendDesc, function (done) {
instruments.shutdown(done);
});
}
describe('regular timeout', function () {
test('', {launchTimeout: 60000});
});
describe('smart timeout', function () {
test('', {launchTimeout: {global: 60000, afterSimLaunch: 10000}});
});
describe("using different tmp dir", function () {
var altTmpDir = '/tmp/abcd';
before(function () {
rimraf.sync(altTmpDir);
});
test(" (1)", {
launchTimeout: {global: 60000, afterSimLaunch: 10000},
tmpDir: altTmpDir
}, {
afterCreate: function (instruments) { instruments.tmpDir.should.equal(altTmpDir); },
afterLaunch: function () {
fs.existsSync('/tmp/abcd').should.be.ok;
fs.existsSync('/tmp/abcd/instrumentscli0.trace').should.be.ok;
}
});
test(" (2)", {
launchTimeout: {global: 60000, afterSimLaunch: 10000},
tmpDir: altTmpDir
}, {
afterCreate: function (instruments) { instruments.tmpDir.should.equal(altTmpDir); },
afterLaunch: function () {
fs.existsSync('/tmp/abcd').should.be.ok;
// tmp dir is deleted at startup so trace file is not incremented
fs.existsSync('/tmp/abcd/instrumentscli0.trace').should.be.ok;
}
});
});
describe("using different trace dir", function () {
var altTraceDir = '/tmp/abcd';
before(function () {
rimraf.sync(altTraceDir);
});
test(" (1)", {
launchTimeout: {global: 60000, afterSimLaunch: 10000},
traceDir: altTraceDir
}, {
afterCreate: function (instruments) {
instruments.tmpDir.should.equal('/tmp/appium-instruments');
},
afterLaunch: function () {
fs.existsSync('/tmp/abcd').should.be.ok;
fs.existsSync('/tmp/abcd/instrumentscli0.trace').should.be.ok;
}
});
test(" (2)", {
launchTimeout: {global: 60000, afterSimLaunch: 10000},
traceDir: altTraceDir
}, {
afterCreate: function (instruments) { instruments.tmpDir.should.equal('/tmp/appium-instruments'); },
afterLaunch: function () {
fs.existsSync('/tmp/abcd').should.be.ok;
fs.existsSync('/tmp/abcd/instrumentscli1.trace').should.be.ok;
}
});
});
describe("shutdown without startup", function () {
var instruments;
it('should start', function (done) {
utils.killAllSimulators();
newInstrument({launchTimeout: 60000}).then(function (_instruments) {
instruments = _instruments;
instruments.shutdown(function (err) {
err.should.include('Didn\'t not shutdown within');
done();
});
})
.done();
});
});
// works only on 7.1
describe("getting devices", function () {
utils.killAllSimulators();
it('should get all available devices', function (done) {
exec('xcrun --sdk iphonesimulator --show-sdk-version', function (err, stdout) {
var onErr = function () {
console.error("Couldn't get iOS sdk version, skipping test");
done();
};
if (err) return onErr();
var iosVer = parseFloat(stdout);
if (typeof iosVer !== "number" || isNaN(iosVer)) {
return onErr();
}
Instruments.getAvailableDevices(function (err, devices) {
should.not.exist(err);
if (iosVer >= 7.1) {
devices.length.should.be.above(0);
devices.should.contain("iPhone - Simulator - iOS 7.1");
} else {
devices.length.should.equal(0);
}
done();
});
});
});
});
});
|
export * from '@styled-icons/material/BrokenImage';
|
const os = require('os');
const fs = require('fs');
const util = require('util');
const fdk = require('@fnproject/fdk');
const mds = require('@maddonkeysoftware/mds-sdk-node');
const OS = require('opensubtitles-api');
const { GraphQLClient } = require('graphql-request');
const bunyan = require('bunyan');
const BunyanLogstashHttp = require('./bunyan-logstash-http');
const utils = require('./utils');
const BATCH_SIZE = 10;
const qsClient = mds.getQueueServiceClient(process.env.MDS_QS_URL);
const fsClient = mds.getFileServiceClient(process.env.MDS_FS_URL);
const graphQLClient = new GraphQLClient(process.env.MDS_PASS_URL);
const OpenSubtitles = new OS({
useragent: 'PASSAgent',
username: process.env.PASS_OPEN_SUBTITLES_USER,
password: process.env.PASS_OPEN_SUBTITLES_PASS,
ssl: true
});
const fsDelete = util.promisify(fs.unlink);
const loggerMetadata = { func: 'fetchSubtitles', fromLocal: process.env.DEBUG };
const logger = bunyan.createLogger({
name: 'fetchSubtitles',
level: bunyan.TRACE,
serializers: bunyan.stdSerializers,
streams: [
{
stream: process.stdout
},
{
stream: new BunyanLogstashHttp({
loggingEndpoint: process.env.MDS_LOG_URL,
level: 'debug',
metadata: loggerMetadata
}),
}
]
});
const getQueueMessages = (messages) => {
runningMessages = messages || [];
return qsClient.fetchMessage(process.env.PASS_SUBTITLES_NEEDED_QUEUE)
.then((message) => {
if (message && message.id) {
runningMessages.push(message)
if (runningMessages.length < BATCH_SIZE) {
return getQueueMessages(runningMessages);
}
}
return runningMessages;
});
}
const dequeueMessages = (messages) => {
logger.debug('Cleaning up processed messages.');
return Promise.all(messages.map((e) => qsClient.deleteMessage(process.env.PASS_SUBTITLES_NEEDED_QUEUE, e.id))).then(() => messages.length);
};
const findSubtitles = (query, language) => {
return OpenSubtitles.search({
sublanguageid: language,
query
})
.then((results) => results[language]);
};
const obtainEpisodeMetadata = (episodeId) => {
const query = `query {
getEpisodeDetails(episodeId: ${episodeId}) {
show { name }
episodeName
dvdEpisodeNumber
}
}`;
return graphQLClient.request(query)
.then(resp => resp.getEpisodeDetails);
};
const obtainMovieMetadata = (imdbId) => {
const query = `query {
getMovieDetails(imdbId: "${imdbId}") {
title
year
}
}`
return graphQLClient.request(query)
.then(resp => resp.getMovieDetails);
};
const generateOpenSubtitlesQuery = (metadata) => metadata.show ? `${metadata.show.name} ${metadata.episodeName}` : `${metadata.title}`;
const findAndStoreSubtitles = async (message) => {
const args = JSON.parse(message.message);
const { type, showId, episodeId, movieId, language, fileHash } = args;
logger.trace({ metadata: args } , 'Beginning to process message');
// console.dir(args);
switch (type) {
case 'show':
const metadata = await obtainEpisodeMetadata(episodeId);
if (metadata) {
logger.trace({ metadata }, 'Show metadata obtained');
const query = generateOpenSubtitlesQuery(metadata);
const fileEpisodeNumber = ('0' + metadata.dvdEpisodeNumber).slice(-2);
const containerPath = `${process.env.PASS_SUBTITLES_CONTAINER}/show/${showId}/${episodeId}/${language}`;
const data = await findSubtitles(query, language);
if (data) {
logger.trace({ metadata: data }, 'Subtitle data obtained.');
const filename = `${fileEpisodeNumber} - ${metadata.episodeName}.${data.format}`;
const localFilePath = `${os.tmpdir()}/${filename}`;
await utils.download(data.url, os.tmpdir(), { filename });
try {
await fsClient.createContainer(containerPath);
} catch {}
await fsClient.uploadFile(containerPath, localFilePath);
await fsDelete(localFilePath);
return;
} else {
logger.info({ showMetadata: metadata, language }, 'Could not obtain subtitle data for show.');
}
}
return;
case 'movie':
return obtainMovieMetadata(movieId)
.then((metadata) => {
logger.trace({ metadata }, 'Movie metadata obtained');
const query = generateOpenSubtitlesQuery(metadata);
const containerPath = `${process.env.PASS_SUBTITLES_CONTAINER}/movie/${movieId}/${language}`;
return findSubtitles(query, language)
.then((data) => {
if (data) {
logger.trace({ metadata: data }, 'Subtitle data obtained.');
const filename = `${metadata.title} (${metadata.year}).${data.format}`;
const localFilePath = `${os.tmpdir()}/${filename}`;
return utils.download(data.url, os.tmpdir(), { filename })
.then(() => fsClient.createContainer(containerPath))
.catch(() => {})
.then(() => fsClient.uploadFile(containerPath, localFilePath))
.then(() => fsDelete(localFilePath));
} else {
logger.info({ movieMetadata: metadata, language }, 'Could not obtain subtitle data for movie.');
}
})
});
default:
throw new Error('Unknown media format');
}
};
const processMessages = async (messages) => {
const processedMessages = [];
const failedMessages = [];
logger.debug(`Processing ${messages.length} messages`);
if (messages.length > 0) {
await OpenSubtitles.login();
for (let i = 0; i < messages.length; i += 1) {
const e = messages[i];
try {
await findAndStoreSubtitles(e);
processedMessages.push(e)
} catch {
failedMessages.push(e)
}
}
}
if (failedMessages.length > 0 && process.env.PASS_SUBTITLES_NEEDED_QUEUE_DLQ) {
await Promise.all([
failedMessages.map((e) => qsClient.enqueueMessage(process.env.PASS_SUBTITLES_NEEDED_QUEUE_DLQ, JSON.parse(e.message))),
failedMessages.map((e) => qsClient.deleteMessage(process.env.PASS_SUBTITLES_NEEDED_QUEUE, e.id)),
]);
logger.warn(`Successfully DLQ'd ${failedMessages.length} messages.`)
}
return processedMessages;
};
const handle = () => Promise.resolve(logger.info('Fetching messages to process.'))
.then(() => process.env.PASS_SUBTITLES_NEEDED_QUEUE = 'pass-subtitles-needed-dlq')
.then(() => getQueueMessages())
.then((messages) => processMessages(messages))
.then((messages) => dequeueMessages(messages))
.then((count) => logger.info(`Successfully processed ${count} available messages.`))
.catch((e) => logger.fatal({ err: e }, 'Unexpected error occurred'))
.then(() => true);
if (process.env.LOCAL_DEBUG === 'true') {
(async () => { await handle(); })();
} else {
fdk.handle((input) => handle(input));
}
|
import React from 'react'
import { render, screen } from '@testing-library/react'
import { Provider } from 'react-redux'
import configureMockStore from 'redux-mock-store'
import HomeRoute from './HomeRoute'
import * as policyListDuck from '../store/policyList.duck'
const mockStore = configureMockStore()
describe('Home component tests', () => {
beforeEach(() => {
jest.spyOn(policyListDuck, 'fetchPoliciesFromServer').mockImplementation(() => {
return {type: 'anything', payload: []}
})
})
describe('after initial rendering', () => {
beforeEach(() => {
const store = mockStore({
privacy: { privacyCancelled: false, privacyAccepted: false},
policyList: { items: [] }
})
render(<Provider store={store}><HomeRoute/></Provider>)
})
it('should show the PrivacyNotice', () => {
expect(screen.queryByTestId('privacyNotice')).toBeInTheDocument()
})
it('should not show the pleaseAcceptPrivacyStatement notification', () => {
expect(screen.queryByTestId('pleaseAcceptPrivacyStatement')).toBeNull()
})
it('should not show the PolicyTable', () => {
expect(screen.queryByTestId('policyTable')).toBeNull()
})
})
describe('when user has accepted the PrivacyNotice', () => {
beforeEach(() => {
const store = mockStore({
privacy: { privacyCancelled: false, privacyAccepted: true},
// eslint-disable-next-line camelcase
policyList: { items: [{ id: 1, title: '', summary: '', date_introduced: '2016-11-03T04:47:00.000Z'}]},
})
render(<Provider store={store}><HomeRoute/></Provider>)
})
it('should not show the PrivacyNotice', () => {
expect(screen.queryByTestId('privacyNotice')).toBeNull()
})
it('should show the PolicyTable', () => {
expect(screen.queryByTestId('policyTable')).toBeInTheDocument()
})
})
describe('when user has cancelled the PrivacyNotice', () => {
beforeEach(() => {
const store = mockStore({
privacy: { privacyCancelled: true, privacyAccepted: false},
policyList: { items: [] },
})
render(<Provider store={store}><HomeRoute/></Provider>)
})
it('should show the pleaseAcceptPrivacyStatement notification', () => {
expect(screen.queryByTestId('pleaseAcceptPrivacyStatement')).toBeInTheDocument()
})
})
})
|
var Chart = function(params)
{
self = this;
self.container = params.container;
self.xValues = params.xValues;
self.yVal = params.yValues;
margin = {top: 50, right: 50, bottom: 90, left: 50};
self.width = 1000 - margin.left - margin.right;
self.height = 530 - margin.top - margin.bottom;
//setting up svg to add elements of the chart
var canvas = d3.select(self.container)
.append("svg")
.attr("width", self.width + margin.left + margin.right)
.attr("height", self.height + margin.top + margin.bottom);
self.histChart = canvas.append("g")
.attr("transform", "translate(" + margin.left + "," +
margin.top + ")");
self.myMap = {};
var i;
for(i=0; i<self.xValues.length ;i++) {
self.myMap[self.xValues[i]] = self.yVal[i];
}
self.xLabels = d3.keys(self.myMap);
self.yValues = d3.values(self.myMap);
console.log(self.yValues);
//setting up scales for x-axis and y-axis
self.xScale = d3.scaleBand().domain(self.xLabels).range([0, self.width]);
self.yScale = d3.scaleLinear().domain([0, 1]).range([self.height,0]);
var x = self.xScale;
var y = self.yScale;
//constructing bars for data
var bars = self.histChart.selectAll("rect").data(self.xLabels);
bars.enter().append('rect')
.attr("class", "bar")
.attr('x', d => {return self.xScale(d);})
.attr('y', d => {return self.yScale(self.myMap[d]);})
.attr('width',self.xScale.bandwidth())
.attr('height', d=> { return self.height - self.yScale(self.myMap[d])})
.style("fill", "#3182bd");
var xAxis = self.histChart.append("g")
.attr("class", "x-axis")
.attr("transform", "translate(0," + self.height + ")")
.call(d3.axisBottom(self.xScale))
.append("text")
.attr("class", "xAxisLabel")
.attr("y", self.height - 350)
.attr("x", self.width - 100)
.attr("text-anchor", "end")
.attr("stroke", "#333333")
.text("Principal Components");
var yAxis = self.histChart.append("g")
.attr("class", "y-axis")
.call(d3.axisLeft(self.yScale))
.append("text")
.attr("class", "yAxisLabel")
.attr("transform", "rotate(-90)")
.attr("y", 15)
.attr("dy", "-5.1em")
.attr("text-anchor", "end")
.attr("stroke", "#333333")
.text("Explained Variance");
var line = self.histChart.append("line")
.attr("x1", self.xScale("PC4")+self.xScale.bandwidth()/2)
.attr("x2", self.xScale("PC4")+self.xScale.bandwidth()/2)
.attr("y1", 0)
.attr("y2", self.height)
.attr("stroke-width", 2)
.attr("stroke", "black")
.attr("stroke-dasharray", "8,8");
}
var ScatterPlot = function(params) {
self = this;
self.container = params.container;
self.data = params.data;
self.columns = params.columns
self.xValues = [];
self.yValues = [];
self.data = JSON.parse(self.data);
console.log(self.data.length);
for (var i = 0; i < self.data.length; i++) {
self.xValues.push(self.data[i][self.columns[0]]);
self.yValues.push(self.data[i][self.columns[1]]);
}
var margin = {top: 10, right: 30, bottom: 30, left: 60};
self.width = 450 - margin.left - margin.right;
self.height = 350 - margin.top - margin.bottom;
//setting up svg to add elements of the chart
var canvas = d3.select(self.container)
.append("svg")
.attr("width", self.width + margin.left + margin.right)
.attr("height", self.height + margin.top + margin.bottom);
var scatterPlt = canvas.append("g")
.attr("transform", "translate(" + margin.left + "," +
margin.top + ")");
//setting up scales for x-axis and y-axis
var xScale = d3.scaleLinear().domain([d3.min(self.xValues), d3.max(self.xValues)]).range([0, self.width]);
var yScale = d3.scaleLinear().domain([d3.min(self.yValues), d3.max(self.yValues)]).range([self.height,0]);
//constructing bars for data
var dots = scatterPlt.append('g').selectAll("dot").data(self.data);
dots.enter().append('circle')
.attr("class", "point")
.attr('cx', d => {return xScale(d[self.columns[0]]);})
.attr('cy', d => {return yScale(d[self.columns[1]]);})
.attr("r", 1.5)
.style("fill", "#3182bd");
var xAxis = scatterPlt.append("g")
.attr("class", "x-axis")
.attr("transform", "translate(0," + self.height + ")")
.call(d3.axisBottom(xScale))
.append("text")
.attr("class", "xAxisLabel")
.attr("y", self.height - 283)
.attr("x", self.width - 100)
.attr("text-anchor", "end")
.attr("stroke", "#333333")
.text(self.columns[0]);
var yAxis = scatterPlt.append("g")
.attr("class", "y-axis")
.call(d3.axisLeft(yScale))
.append("text")
.attr("class", "yAxisLabel")
.attr("transform", "rotate(-90)")
.attr("y", 15)
.attr("dy", "-5.1em")
.attr("text-anchor", "end")
.attr("stroke", "#333333")
.text(self.columns[1]);
}
var ScatterPlotMatrix = function(params) {
self = this;
self.container = params.container;
self.data = params.data;
self.columns = params.columns
self.xValues = [];
self.yValues = [];
self.data = JSON.parse(self.data);
console.log(self.data.length);
self.columns[0] = d3.keys(self.data[0])[0];
self.columns[1] = d3.keys(self.data[0])[1];
for (var i = 0; i < self.data.length; i++) {
self.xValues.push(self.data[i][self.columns[0]]);
self.yValues.push(self.data[i][self.columns[1]]);
}
var margin = {top: 10, right: 20, bottom: 40, left: 40};
self.width = 250 - margin.left - margin.right;
self.height = 250 - margin.top - margin.bottom;
//setting up svg to add elements of the chart
var canvas = d3.select(self.container)
.append("svg")
.attr("width", self.width + margin.left + margin.right)
.attr("height", self.height + margin.top + margin.bottom);
var scatterPlt = canvas.append("g")
.attr("transform", "translate(" + margin.left + "," +
margin.top + ")");
//setting up scales for x-axis and y-axis
var xScale = d3.scaleLinear().domain([d3.min(self.xValues)-1, d3.max(self.xValues)]).range([0, self.width]);
var yScale = d3.scaleLinear().domain([d3.min(self.yValues)-1, d3.max(self.yValues)]).range([self.height,0]);
//constructing bars for data
var dots = scatterPlt.append('g').selectAll("dot").data(self.data);
dots.enter().append('circle')
.attr("class", "point")
.attr('cx', d => {return xScale(d[self.columns[0]]);})
.attr('cy', d => {return yScale(d[self.columns[1]]);})
.attr("r", 1.5)
.style("fill", "#3182bd");
var xAxis = scatterPlt.append("g")
.attr("class", "x-axis")
.attr("transform", "translate(0," + self.height + ")")
.call(d3.axisBottom(xScale));
// .append("text")
// .attr("class", "xAxisLabel")
// .attr("y", self.height - 283)
// .attr("x", self.width - 100)
// .attr("text-anchor", "end")
// .attr("stroke", "#333333")
// .text(self.columns[0]);
var yAxis = scatterPlt.append("g")
.attr("class", "y-axis")
.call(d3.axisLeft(yScale));
// .append("text")
// .attr("class", "yAxisLabel")
// .attr("transform", "rotate(-90)")
// .attr("y", 15)
// .attr("dy", "-5.1em")
// .attr("text-anchor", "end")
// .attr("stroke", "#333333")
// .text(self.columns[1]);
}
//REFERENCES
//https://www.d3-graph-gallery.com/graph/scatter_basic.html
//https://jakevdp.github.io/PythonDataScienceHandbook/05.10-manifold-learning.html
|
const BASE_URL = "https://jira-clone-pedja.herokuapp.com/";
function fetchData(path) {
return fetch(`${BASE_URL}`).then((data) => data.json());
// return fetch(`${BASE_URL}/${path}`).then((data) => data.json());
}
export default fetchData;
|
var fs = require('fs');
var png = require('../build/Release/node_png_encode')
var PngDecoder = png.PngDecoder;
var decoder = new PngDecoder(function(err, width, height, buffer) {
console.log('PngDecoder callback:',err,width,height,buffer);
});
console.log(decoder)
console.log(decoder.feedBuffer)
var wholeBuffer = fs.readFileSync('./mixed-unlit.png');
var chunks = [];
for (var i = 0; i < wholeBuffer.length; i+= 100) {
chunks.push(wholeBuffer.slice(i, Math.min(wholeBuffer.length, i+100)));
}
console.log(chunks);
var chunkIdx = 0;
var interval = setInterval(function() {
if (chunkIdx == chunks.length) return clearInterval(interval);
console.log('feeding chunk', chunkIdx);
console.log(decoder.data(chunks[chunkIdx]));
chunkIdx++;
}, 1000);
|
var baseName = "jstests_core_logging_options";
load('jstests/libs/command_line/test_parsed_options.js');
// Verbosity testing
jsTest.log("Testing \"verbose\" command line option with no args");
var expectedResult = {
"parsed": {"systemLog": {"verbosity": 1}}
};
testGetCmdLineOptsMongod({verbose: ""}, expectedResult);
jsTest.log("Testing \"verbose\" command line option with one \"v\"");
var expectedResult = {
"parsed": {"systemLog": {"verbosity": 1}}
};
testGetCmdLineOptsMongod({verbose: "v"}, expectedResult);
jsTest.log("Testing \"verbose\" command line option with two \"v\"s");
var expectedResult = {
"parsed": {"systemLog": {"verbosity": 2}}
};
testGetCmdLineOptsMongod({verbose: "vv"}, expectedResult);
jsTest.log("Testing \"v\" command line option");
var expectedResult = {
"parsed": {"systemLog": {"verbosity": 1}}
};
// Currently the test converts "{ v : 1 }" to "-v" when it spawns the binary.
testGetCmdLineOptsMongod({v: 1}, expectedResult);
jsTest.log("Testing \"vv\" command line option");
var expectedResult = {
"parsed": {"systemLog": {"verbosity": 2}}
};
// Currently the test converts "{ v : 2 }" to "-vv" when it spawns the binary.
testGetCmdLineOptsMongod({v: 2}, expectedResult);
jsTest.log("Testing \"systemLog.verbosity\" config file option");
expectedResult = {
"parsed":
{"config": "jstests/libs/config_files/set_verbosity.json", "systemLog": {"verbosity": 5}}
};
testGetCmdLineOptsMongod({config: "jstests/libs/config_files/set_verbosity.json"}, expectedResult);
// log component verbosity
jsTest.log("Testing \"systemLog.component.verbosity\" config file option");
expectedResult = {
"parsed": {
"config": "jstests/libs/config_files/set_component_verbosity.json",
"systemLog": {
"verbosity": 2,
"component": {
"accessControl": {"verbosity": 0},
"storage": {"verbosity": 3, "journal": {"verbosity": 5}}
}
}
}
};
testGetCmdLineOptsMongod({config: "jstests/libs/config_files/set_component_verbosity.json"},
expectedResult);
// Log output testing
var baseDir = MongoRunner.dataPath + baseName;
var logDir = MongoRunner.dataPath + baseName + "/logs/";
// ensure log directory exists
assert(mkdir(baseDir));
assert(mkdir(logDir));
jsTest.log("Testing \"logpath\" command line option");
var expectedResult = {
"parsed": {"systemLog": {"destination": "file", "path": logDir + "/mylog.log"}}
};
testGetCmdLineOptsMongod({logpath: logDir + "/mylog.log"}, expectedResult);
jsTest.log("Testing with no explicit logging setting");
expectedResult = {
"parsed": {}
};
testGetCmdLineOptsMongod({}, expectedResult);
resetDbpath(baseDir);
print(baseName + " succeeded.");
|
/* Guía http://easyautocomplete.com/guide */
/*
* Funciones del Plugin JavaScript EASYAUTOCOMPLETE
* Más información en http://easyautocomplete.com
*/
$(document).ready(function(){
var searchRequest = null;
var value = null ;
searchRequest = $.ajax({
type: "POST", // Método de envío
url: "/searchcity", // Url del controlador
data:{
'cityInformation' : value
}, // variable que enviaremos
dataType:"json",
success: function(response){
var options = {
data: response,
requestDelay: 500,
placeholder: "",
list: {
maxNumberOfElements: 6,
match: {
enabled: true
}
}
};
// console.log(response);
$("#medical_history_city").easyAutocomplete(options);
// eliminamos el atributo style que genera automáticamente el plugin
$('div.easy-autocomplete').removeAttr('style');
}
});
});
/***************************************************************************/
/*
$(document).ready(function(){
var searchRequest = null;
$("#medical_history_idAddressCity").keydown(function(){
var minlength = 0;
var that = this;
var value = $(this).val();
if (value.length >= minlength ) {
console.log('busqueda activada para' + value);
if (searchRequest != null)
searchRequest.abort();
searchRequest = $.ajax({
type: "POST", // Método de envío
url: "/searchcity", // Url del controlador
data:{ 'cityInformation' : value}, // variable que enviaremos
dataType:"json",
success: function(response){
var options = {
data: response,
requestDelay: 500,
placeholder: "Introduzca Código Postal",
list: {
maxNumberOfElements: 6,
match: {
enabled: true
}
}
};
optionsGlobal = options;
console.log(response);
$("#medical_history_idAddressCity").easyAutocomplete(options);
// Funciones del Plugin JavaScript EASYAUTOCOMPLETE, Más información en http://easyautocomplete.com
// eliminamos el atributo style que genera automáticamente el plugin
$('div.easy-autocomplete').removeAttr('style');
}
});
}
});
});
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.